-
Notifications
You must be signed in to change notification settings - Fork 1
/
galkontinuum-debug.user.js
4590 lines (3729 loc) · 130 KB
/
galkontinuum-debug.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Galkontinuum
// @namespace 6930e44863619d3f19806f68f74dbf62
// @author Bipface
// @version 2020.04.26
// @description Enhanced browsing on Booru galleries
// @homepageURL .
// @downloadURL .
// @run-at document-end
// @grant none
// @match *://danbooru.donmai.us/*
// @match *://e621.net/*
// @match *://gelbooru.com/*
// @match *://realbooru.com/*
// @match *://rule34.xxx/*
// @match *://safebooru.org/*
// @match *://testbooru.donmai.us/*
// @match *://yande.re/*
// ==/UserScript==
'use strict';
const getReadmeMarkdown = (manif, {downloadHref}) =>
`# Galkontinuum
Galkontinuum is a [userscript][wiki userscript] which enables slideshow-style
browsing of search results on the Booru family of sites.
![Navigating results across pages][nav acrosspage anim]
It targets galleries running Gelbooru 0.2.x, Danbooru 2.x, Danbooru 1.x and
compatible forks such as e621 and Moebooru.
Check [dist/manifest.json][dist manif] for the current list of supported sites.
## Overview
### Thumbnail Overlay
Each post's thumbnail element will now have two buttons placed over it as shown
below. The upper button is the usual link to the post's page. The lower button
loads this post in the *media panel* (described in the next section), without
leaving the current page.
![Thumbnail overlay][thumb overlay anim]
### Media Panel
The media panel appears below the thumbnail list and provides controls to
navigate through the sequence of results for the current search.
Navigation is across the entire result set — not limited to the current page.
#### Toolbar Controls
![Media panel][media panel numbered]
1. Toggle notes overlay
2. Previous post
3. Toggle scale mode (fit-to-screen / full-size)
4. Next post
5. Close media panel and return to thumbnail
6. Unused
7. Unused
8. Link to post page
9. Unused
10. Toggle help/about panel
#### Overlay Controls
![Media overlay][media overlay numbered]
1. Previous post
2. Focus content (only appears over videos)
3. Next post
4. Release focus
When content is focused, hotkeys are disabled and overlay controls are hidden.
#### Notes Overlay
Notes appear as a set of transparent rectangles over the media.
Hovering or tapping on them will reveal the caption.
Note areas scale proportionally | Caption tooltips stick to bottom edge
--- | ---
![Scaling notes][notes scaley anim] | ![Sticky captions][notes sticky captions anim]
### Hotkeys
Key | Action
:---: | ---
\`⇦\` | Previous post
\`⇨\` | Next post
\`esc\` | Release focus / close media panel
\`num0\` | Toggle scale mode (fit-to-screen / full-size)
### History
Viewing any post in the media panel will cause its corresponding page to be
added/renewed in the browser's history.
For example, viewing post #1803204 on e621 will add
\`https://e621.net/post/show/1803204\` to history.
### Mobile Usage
Usability is good on Android running Firefox 68.0 (with Greasemonkey).
Other environments are yet to be tested.
Rule34.xxx | Safebooru | e621
--- | --- | ---
![][fennec r34xxx] | ![][fennec safebooru] | ![][fennec e621]
## Installation
### Requirements
- Firefox 56 or newer.
- Chrome 60 or newer.
Support for other browsers may be considered if requested.
### Userscript Manager
1. Install a userscript manager such as [Greasemonkey][greasemonkey] or
[Tampermonkey][tampermonkey].
2. Visit [dist/galkontinuum.user.js][dist galk].
You should be presented with an installation prompt.
### Chrome - standalone extension (Windows)
Be aware that the script will not update automatically when installed this way.
1. Download the files [dist/galkontinuum.user.js][dist galk] and
[dist/manifest.json][dist manif] into a new directory.
2. Visit \`chrome://extensions\`.
3. Enable the **Developer mode** option and choose **Load unpacked**.
![Load unpacked][chrome load unpacked]
4. Select the directory containing the downloaded files.
![Select Folder][chrome select folder]
## Limitations
- Navigating through results is only possible if they are ordered by ID
(ascending or descending). Note that on Moebooru-based sites, the default
order is by timestamp, not by ID — you can enable navigation by appending
\`order:id_desc\` to your search terms.
- On Gelbooru-based sites, posts added within the last few minutes may fail to
load due to the search database being out of sync with the main database.
- On Danbooru-based sites, [restricted posts][danbooru wiki censored tags]
might not be excluded when navigating through results, despite being hidden in
the thumbnail list on the page. These will most likely fail to load.
Working-around this issue is non-trival due to inadequacies in the
\`/post/index\` API.
- On Danbooru-based sites, navigation may be hindered or impossible when the
maximum number of search terms is used.
For example, searches on e621 containing more than 6 terms will result in an
error message stating "You can only search up to 6 tags at once". Therefore,
when 6 search terms are used, navigation in one or both directions may fail due
to inadequacies in the \`/post/index\` API requiring an additional tags to be
inserted.
- Markup is not supported in note text.
- On Danbooru-based sites, a maximum of 1000 notes will be shown on any single
post. Currently the only post known to have over 1000 notes is
[#951241][danbooru post 1k notes] on Danbooru.
- Posts with an ID less than zero or greater than 2147483647 will not be
recognised. It is unknown whether there are any boorus with IDs outside this
range.
[dist galk]: ${downloadHref}
[dist manif]: ${(new URL('manifest.json', downloadHref)).href}
[wiki userscript]: https://en.wikipedia.org/wiki/Userscript
[greasemonkey]: https://www.greasespot.net/
[tampermonkey]: https://tampermonkey.net/
[danbooru wiki censored tags]: https://danbooru.donmai.us/wiki_pages/84990
[danbooru post 1k notes]: https://danbooru.donmai.us/posts/951241
[nav acrosspage anim]: http://b.webpurr.com/x2EK.webp
[thumb overlay anim]: https://i.imgur.com/ueGF43J.gif
[notes sticky captions anim]: http://a.webpurr.com/EPLM.webp
[notes scaley anim]: http://b.webpurr.com/MMla.webp
[media panel numbered]: https://i.imgur.com/MtdHz9U.gif
[media overlay numbered]: https://i.imgur.com/0nxqIGF.png
[chrome load unpacked]: https://i.imgur.com/RDu11ts.png
[chrome select folder]: https://i.imgur.com/mvJnMHQ.png
[fennec r34xxx]: http://b.webpurr.com/nr70.webp
[fennec safebooru]: http://b.webpurr.com/avB7.webp
[fennec e621]: http://b.webpurr.com/dVBv.webp
`;
/*
known issues:
- danbooru dark theme
- file size unknwon on gelbooru-based sites
(do HEAD request to find out)
- full-size cropped on danbooru mobile layout
- bug in moebooru api yields deleted results if any id:<n / id:>n term
is specified; no `deleted:false` to override it with
- thumbnail may remain visible after the first frame of an animation is
fully rendered (noticible with alpha-transparent gifs)
doesn't affect swf/video
- player appears with wrong dimensions before video starts loading
- blacklist may interfere on moebooru
- buttons too small on e621 on mobile
- gelbooru: thumbnail overlay is exactly the size of the thumbnail itself
https://i.imgur.com/YJjIzxt.png
and icon doesn't scale:
https://gelbooru.com/index.php?page=post&s=list&tags=id%3a4730432
- browser history doesn't work well on danbooru since they append ?q=…
to the post page hrefs
- tryParsePostId() imposes a much stricter syntax than the sites
themselves seem to,
for example,
the following addresses resolve to post 158:
https://rule34.xxx/?page=post&s=view&id=%2b158
https://rule34.xxx/?page=post&s=view&id=0158
https://rule34.xxx/?page=post&s=view&id=%23158
https://rule34.xxx/?page=post&s=view&id=%09158
the following address resolves to post 159:
https://rule34.xxx/?page=post&s=view&id=%20++%23+00158.99999999999999++
danbooru is similarly lenient
planned enhancements:
- markup in notes
- rule34: use main-DB api for getting post info
- more hotkeys
- artist tags on footer
- navigation on current page without API requests?
- post pages: add a link back to the gallery page on which it appears (?)
- options page
- settings for showing fullsize/thumbnail/sample
loading full-size images may not always be desirable
(e.g. mobile browsing with small data allowance)
- reversed navigation ?
- api requ. page size / prefetch threshold
- history
- default video volume
test cases:
environments:
- firefox 56, greasemonkey 3
- firefox 56, greasemonkey 4
- firefox current, greasemonkey 4
- firefox current, tampermonkey
- firefox android, ?
- chrome current, content-script (manifest.json)
- chrome current, tampermonkey
media:
- jpeg / png (static) / gif (static) / webp?
- png (animated) / gif (animated) / webp?
- webm / mp4 (?)
- controls visible, loop enabled, volume?
- swf
- ugoira:
https://danbooru.donmai.us/posts/3471696
- sample may or may not exist
- tall:
https://e621.net/post/index/1/id:1363663
- wide:
https://e621.net/post/index/1/id:1848964
https://rule34.xxx/?page=post&s=list&tags=id%3a2386407
- nonexistent:
https://rule34.xxx/?page=post&s=list#galkontinuum:{"currentPostId":59391120}
- inaccessible:
https://danbooru.donmai.us/posts#galkontinuum:{"currentPostId":3453471}
sites:
- rule34 (special-case for thumbnail urls,
special-case for getSlideViewParent)
- gelbooru (special-case for getSlideViewParent)
- yandere (special-case for thumbnail layout)
- e621 (special-case for thumbnail layout,
special-case for svgHref, special-case for api responses)
navigation:
- navigating before/after current search results list (across pages)
- attempting to navigate before first item or after last item
- id: / sort: / order: search terms
on gel, last sort: applies, all id: apply
on dan, last order: applies, last id: applies
- 2 or more search terms (danbooru limitation)
- 6 or more search terms (e621 limitation)
- attempting to navigate with posts which aren't in solr database yet
(on gelbooru-type sites)
notes overlay:
- desktop
- mobile
test:
https://danbooru.donmai.us/posts?tags=id:3339117
https://e621.net/post/index/?tags=id:1843616
https://rule34.xxx/?page=post&s=list&tags=id:2269258
over 500 notes:
https://danbooru.donmai.us/posts?tags=id%3A71230
over 1000 notes:
https://danbooru.donmai.us/posts?tags=id%3A951241
danbooru post statuses:
- visible: active, unmoderated, flagged, modqueue, pending
- hidden: banned (dmca)
https://danbooru.donmai.us/posts?tags=id:3482400
- hidden: deleted
https://danbooru.donmai.us/posts?tags=id:3464546
- hidden: restricted (not an actual status)
https://danbooru.donmai.us/posts?tags=id:3453471
note: on danbooru, status:deleted and -status:deleted are exempt from
the search term limit
by default, searches seem to assume an implicit -status:deleted
moebooru:
has an `is_held` flag where the post doesn't appear in gallery searches
but is returned by api searches
(apparently can use search term `holds:false`)
https://yande.re/forum/show/26190
https://yande.re/wiki/show?title=howto%3Ahold
https://github.com/moebooru/moebooru/blob/master/app/models/post/sql_methods.rb
note: `index_timestamp` does not exist in danbooru codebase
...
intrinsics in chrome standalone userscript:
- GM_log → console.log(…)
- GM_openInTab → open(href, ``)
- GM_addStyle → head.appendChild(<style>)
- GM_xmlhttpRequest → ordinary XMLHttpRequest, without bypassing CORS
not supported:
- GM_registerMenuCommand
- GM_getValue
- GM_setValue
references:
danbooru search term limit:
/danbooru/blob/master/config/danbooru_default_config.rb
→ is_unlimited_tag?(tag)
moebooru hide_pending_posts config:
https://github.com/moebooru/moebooru/blob/
5236247847294d70a70cd9d6589d647c3df922bf/config/init_config.rb#L263
danbooru restricted tags:
https://danbooru.donmai.us/wiki_pages/84990
easylist generic element hiding rules on gelbooru/r34xxx:
https://github.com/easylist/easylist/blob/
a19a5324bfb8be835c6361162c51c87b07603bfe/
easylist/easylist_specific_hide.txt#L10241
*/
const dbg = true; /* will be assigned false in release-mode */
const manifest = null; /* will be assigned manfiest object in release-mode */
/* note: in chrome, standalone userscripts don't have access to `GM_info` */
const globalObj =
typeof self !== `undefined` ? self :
typeof global !== `undefined` ? global :
Function(`return this`)();
/* don't use `globalThis` - not assigned correctly in some environments */
if (typeof globalObj !== `object`) {
throw new Error(`failed to obtain global object`);};
const runtime =
(typeof globalObj.document === `object`
&& globalObj.document.defaultView === globalObj)
? `browser`
: (typeof globalObj.process === `object`
&& typeof globalObj.process.release === `object`
&& globalObj.process.release.name === `node`)
? `nodejs`
: undefined;
const TypedArray = Object.getPrototypeOf(Uint8Array.prototype).constructor;
if (!((new Uint8Array) instanceof TypedArray)) {
throw new Error(`failed to obtain TypedArray class`);};
/* workaround for prototype.js (which redefines `window.Element`): */
const Element =
runtime === `browser`
? ((document.documentElement instanceof globalObj.Element)
? globalObj.Element
: Object.getPrototypeOf(HTMLElement.prototype).constructor)
: undefined;
if (runtime === `browser` && !(document.documentElement instanceof Element)) {
throw new Error(`tampered Element class`);};
/* -------------------------------------------------------------------------- */
const unittests = dbg ? [] : null;
const test =
dbg
? f => {unittests.push(f);}
: () => {};
const nodejsEntrypoint = async function(command, argJson) {
log(`launching as command-line operation …`);
let arg = tryParseJson(argJson);
enforce(typeof arg === `object`,
`invalid parameter "${argJson}" - expected json object`);
let fs = require(`fs`);
let readline = require(`readline`);
let path = require(`path`);
enforce(typeof process.mainModule === `object`);
let selfFilePath = process.mainModule.filename;
let reflectLines = function() {
return readline.createInterface({
input : fs.createReadStream(selfFilePath),
crlfDelay : Infinity,});
};
let reflectManifest = async function() {
return await createManifest(reflectLines(), {
filename : path.basename(selfFilePath),
...arg});
};
switch (command) {
case undefined :
case `run-unittests` : {
if (dbg) {
runUnittests(unittests);
} else {
logWarn(`no tests defined (debug mode disabled)`);};
return;
};
case `create-readme` : {
process.stdout.write(
getReadmeMarkdown(
await reflectManifest(), arg));
return;
};
case `create-release` : {
/* reads the current source file and applies
alterations for release-mode:
- populate @description and @downloadURL
- populate `manifest` object
- assign `dbg = false`
parameters: see `create-manifest`
result is written to stdout */
let manif = await reflectManifest();
let segs = createReleaseSegments(
reflectLines(), manif, arg);
/* note: `for await (…)` isn't supported in firefox 56 */
for (let value, iter = segs[Symbol.asyncIterator]();
!({value} = await iter.next()).done;)
{
process.stdout.write(value+`\n`);
};
return;
};
case `create-manifest` : {
/* generate a json manifest from ==UserScript== block
parameters:
- "filename" : filename for `js : […]` section
- "homepageHref" : address for `@homepageURL` field
- "downloadHref" : address for `@downloadURL` field
result is written to stdout */
let manif = await reflectManifest()
process.stdout.write(
JSON.stringify(manif, null, `\t`));
return;
};
default :
throw new Error(`unrecognised command "${command}"`);
};
};
const runUnittests = function(xs) {
assert(Array.isArray(xs));
let totalCount = xs.length;
let failCount = totalCount;
for (let f of xs) {
try {
f();
--failCount;
} catch (err) {
logError(`unittest failure:`, err.message, `-`, err.stack);};
};
logInfo(`${totalCount - failCount}/${totalCount} unittests passed`);
if (failCount !== 0) {
throw new Error(`${failCount} unittest(s) failed`);};
};
const createReleaseSegments = function(
srcLines, manif, {downloadHref, homepageHref})
{
dbg && assert(typeof srcLines[Symbol.asyncIterator] === `function`);
dbg && assert(typeof manif === `object`);
let homepageUrl = null;
if (typeof homepageHref === `string`) {
homepageUrl = tryParseHref(homepageHref);};
enforce(homepageUrl !== null || homepageHref === undefined,
`invalid url "${homepageHref}"`);
let downloadUrl = null;
if (typeof downloadHref === `string`) {
downloadUrl = tryParseHref(downloadHref);};
enforce(downloadUrl !== null || downloadHref === undefined,
`invalid url "${downloadHref}"`);
let next = async function() {
let {value, done} = await this.linesIter.next();
if (done) {
;
} else if (downloadUrl !== null
&& /^\s*\/\/\s*@downloadURL(\s.*)?$/.test(value))
{
value = `// @downloadURL ${downloadUrl.href}`;
} else if (homepageUrl !== null
&& /^\s*\/\/\s*@homepageURL(\s.*)?$/.test(value))
{
value = `// @homepageURL ${homepageUrl.href}`;
} else if (/^const\s+dbg\s*=[^;]*;.*$/.test(value)) {
value = `const dbg = false;`;
} else if (/^const\s+manifest\s*=[^;]*;.*$/.test(value)) {
value = `const manifest = ${JSON.stringify(manif, null, '\t')};`;
};
return {value, done};
};
return {
[Symbol.asyncIterator]() {
return {
next,
manif,
linesIter : srcLines[Symbol.asyncIterator](),};
},
};
};
const createManifest = async function(srcLines,
{commitId, filename, homepageHref})
{
/* https://developer.chrome.com/extensions/manifest */
dbg && assert(typeof srcLines[Symbol.asyncIterator] === `function`);
enforce(typeof filename === `string`,
`invalid filename "${filename}" - expected string`);
let homepageUrl = null;
if (typeof homepageHref === `string`) {
homepageUrl = tryParseHref(homepageHref);};
enforce(homepageUrl !== null || homepageHref === undefined,
`invalid url "${homepageHref}"`);
let name = filename;
let version = `0000.00.00`;
let runAt = undefined;
let matches = [];
let foundHeader = false;
let userscriptHeader = `==UserScript==`;
let userscriptFooter = `==/UserScript==`;
/* note: `for await (…)` isn't supported in firefox 56 */
for (let value, iter = srcLines[Symbol.asyncIterator]();
!({value} = await iter.next()).done;)
{
let {1 : k, 2 : v} = {.../^\s*\/\/\s*(\S+)(.*)$/.exec(value)};
v = typeof v === `string` ? v.trim() : ``;
if (typeof k !== `string`
|| k === ``
|| k === userscriptFooter)
{
break;};
if (!foundHeader) {
enforce(k === userscriptHeader,
`expected userscript header "// ${userscriptHeader}"`);
foundHeader = true;
};
if (k === `@name`) {
name = v;
} else if (k === `@version`) {
version = v;
} else if (k === `@match`) {
matches.push(v);
} else if (k === `@run-at`) {
runAt = v.replace('-', '_');};
};
/* note: `download_url` is a non-standard field;
corresponds to the `@downloadURL` field in the metadata block */
return {
manifest_version : 2,
name,
author : `Bipface`,
key : `u+fV2D5ukOQp8yXOpGU2itSBKYT22tnFu5Nbn5u12nI=`,
homepage_url : (homepageUrl ? homepageUrl.href : undefined),
version, /* note: must consist of digits and dots */
version_name :
(typeof commitId === `string`
? `${version} (${commitId})`
: `${version}`),
minimum_chrome_version : `60`, /* suspected */
converted_from_user_script : true,
content_scripts : [
{
js : [filename],
run_at : runAt,
matches,
exclude_matches : [],
include_globs : [`*`],
exclude_globs : [],}]};
};
const userscriptEntrypoint = function(doc) {
log(`launching as userscript …`);
dbg && runUnittests(unittests);
let url = tryParseHref(doc.location.href);
if (!(doc instanceof HTMLDocument) || !isGalleryUrl(url))
{
logInfo(`document does not appear to be a gallery; aborting`);
return;
} else {
let d = getDomain({origin : url.origin});
logInfo(`document appears to be a gallery`,
`(domain: ${d.name}, kind: ${d.kind}, subkind: ${d.subkind})`);
};
onReadyStateChange({currentTarget : doc});
};
const onReadyStateChange = function f(ev) {
/* userscripts aren't reliably executed at the correct readyState … */
let doc = ev.currentTarget;
doc.removeEventListener(`readystatechange`, f, false);
if ([`interactive`, `complete`].includes(doc.readyState)) {
log(`document loaded (readyState: ${doc.readyState})`);
onDocumentReady(doc);
} else {
log(`document not loaded (readyState: ${doc.readyState})`);
doc.addEventListener(`readystatechange`, f, false);};
};
let userscriptInitialised = false;
const onDocumentReady = function(doc) {
if (userscriptInitialised) {return;};
userscriptInitialised = true;
enforce([`interactive`, `complete`].includes(doc.readyState),
`document not loaded`);
doc.defaultView.addEventListener(
/* must use capture to override danbooru's hotkeys: */
`keydown`, onKeyDownGlobal, true);
doc.defaultView.addEventListener(
`hashchange`, ev => {applyToDocument(doc);}, false);
applyToDocument(doc);
};
/* -------------------------------------------------------------------------- */
const namespace = `galkontinuum`;
const galk = new Proxy({}, {get : (_, name) => `${namespace}-${name}`});
const hostnameDomainTbl = {
[`danbooru.donmai.us`] :
{kind : `danbooru`, subkind : `danbooru`, name : `danbooru`},
[`gelbooru.com`] :
{kind : `gelbooru`, name : `gelbooru`},
[`e621.net`] :
{kind : `danbooru`, subkind : `danbooru`, name : `e621`},
[`realbooru.com`] :
{kind : `gelbooru`, name : `realbooru`},
[`rule34.xxx`] :
{kind : `gelbooru`, name : `r34xxx`},
[`safebooru.org`] :
{kind : `gelbooru`, name : `safebooru`},
[`testbooru.donmai.us`] :
{kind : `danbooru`, subkind : `danbooru`, name : `danbooru`},
[`yande.re`] :
{kind : `danbooru`, subkind : `moebooru`, name : `yandere`},
};
const globalBoundKeyNames = new Set([
`Escape`, `0`, `ArrowRight`, `Right`, `ArrowLeft`, `Left`,]);
const onKeyDownGlobal = function(ev) {
/* hotkeys: */
if (!globalBoundKeyNames.has(ev.key)
|| !(ev.target instanceof Element))
{
return;};
let doc = ev.target.ownerDocument;
let view = getSlideView(doc.documentElement);
if (view === null) {
/* no hotkeys are active unless the view exists */
} else if (!nodesAreHierarchicallyCoaxial(view, ev.target)
&& ev.target.closest(`.${galk.thumbOverlay}`) === null)
{
/* hotkeys are only active in the view's axis or thumbnail overlay */
} else if (ev.key === `Escape`) {
if (trySelectAndClickDisplayedElem(view,
`.${galk.svPanel}.${galk.helpVisible}
.${galk.svCtrlBar} > .${galk.help}`)
|| trySelectAndClickDisplayedElem(view,
`.${galk.svCtrlBar} > .${galk.close}`)
|| trySelectAndClickDisplayedElem(view,
`.${galk.svCtrlBar} > .${galk.defocus}`))
{
ev.stopImmediatePropagation();
ev.stopPropagation();};
} else if (mediaIsFocused(doc)) {
/* no further hotkeys are active when media is focused */
} else if (ev.key === `ArrowRight` || ev.key === `Right`) {
if (trySelectAndClickDisplayedElem(
view, `.${galk.svCtrlBar} > .${galk.next}`))
{
ev.stopImmediatePropagation();
ev.stopPropagation();};
} else if (ev.key === `ArrowLeft` || ev.key === `Left`) {
if (trySelectAndClickDisplayedElem(
view, `.${galk.svCtrlBar} > .${galk.prev}`))
{
ev.stopImmediatePropagation();
ev.stopPropagation();};
} else if (ev.key === `0`
&& ev.location === KeyboardEvent.DOM_KEY_LOCATION_NUMPAD)
{
if (trySelectAndClickDisplayedElem(
view, `.${galk.svCtrlBar} > .${galk.scale}`))
{
ev.stopImmediatePropagation();
ev.stopPropagation();};
};
};
const trySelectAndClickDisplayedElem = function(scope, selector) {
let el = scope.querySelector(selector);
if (el instanceof HTMLElement && el.offsetParent !== null) {
el.click();
return true;
} else {
return false;};
};
const applyToDocument = function(doc) {
dbg && assert(doc instanceof HTMLDocument);
let url = tryParseHref(doc.location.href);
if (!isGalleryUrl(url)) {
logInfo(`document does not appear to be a gallery; aborting`);
return;};
let state = Object.freeze(stateFromUrl(url));
if (state === null) {
logError(`failed to derive state from url "${url.href}"; aborting`);
return;};
dbg && logDebug(`state:`, JSON.stringify(state, null, `\t`));
ensureApplyGlobalStyleRules(state, doc,
() => getGlobalStyleRules(getDomain(state)));
let viewParent = getSlideViewParent(state, doc);
let view = ensureSlideView(state, doc, viewParent);
if (view !== null) {
view.addEventListener(galk.mediaViewing, onMediaViewing, false);
bindSlideView(state, doc, view);
} else {
logError(`failed to create slide-view panel`);};
let thumbsElem = getThumbnailsListElem(state, doc);
if (thumbsElem !== null) {
bindThumbnailsList(state, doc, thumbsElem);
} else {
logError(`failed to find thumbnail list element`);};
if (getDomain(state).name === `danbooru`) {
ensureForwardDanbooruTooltipEvents(state, doc);};
};
const onMediaViewing = function({detail : {state, postId}}) {
let postUrl = postPageUrl(state, postId);
if (postUrl === null) {
return;};
/* add the post page to the browser's history:
(a relatively expensive synchronous operation — deferred execution) */
setTimeout(() => {
let s = history.state;
let loc = location.href;
history.replaceState({}, ``, postUrl.href);
history.replaceState(s, ``, loc);
});
};
const getSlideViewParent = function(state, doc) {
return getSingleElemByClass(doc, `content-post`) /* r34xxx */
|| getSingleElemByClass(doc, `content`) /* safebooru */
|| doc.getElementById(`content`) /* danbooru */
|| getSingleElemByClass(doc, `contain-push`) /* gelbooru */;
};
const getSlideView = function(scopeElem) {
let view = getSingleElemByClass(scopeElem, galk.svPanel);
if (!(view instanceof HTMLElement)) {
return null;};
return view;
};
const ensureSlideView = function(state, doc, parentElem) {
let view = getSlideView(parentElem);
if (view !== null) {
return view;};
if (parentElem === null) {
return null;};
log(`creating slide-view panel …`);
view = doc.createElement(`section`);
view.classList.add(galk.svPanel);
view.hidden = true;
let manif = manifest || {};
view.insertAdjacentHTML(`beforeend`,
`<header class='${galk.svCtrlBar}'>
<a title='Toggle Notes' class='${galk.notes} ${galk.disabled}'>
<figure class='${galk.btnIcon}'></figure></a>
<a title='Previous' class='${galk.nav} ${galk.prev}'>
<figure class='${galk.btnIcon}'></figure></a>
<a title='Toggle Size' class='${galk.scale} ${galk.disabled}'>
<figure class='${galk.btnIcon}'></figure></a>
<a title='Next' class='${galk.nav} ${galk.next}'>
<figure class='${galk.btnIcon}'></figure></a>
<a title='Close' class='${galk.close}'>
<figure class='${galk.btnIcon}'></figure></a>
<a title='Release Focus' class='${galk.defocus}'>
<figure class='${galk.btnIcon}'></figure></a>
</header>
<section class='${galk.svContentPanel}'>
<section class='${galk.svContentStack}'>
<aside class='${galk.helpOverlay}'>
<section>
<header>Galkontinuum</header>
<span>Version ${manif.version_name}</span>
<a href='${encodeURI(manif.homepage_url)}'>User Guide</a>
</section>
</aside>
<aside class='${galk.notesOverlay}'></aside>
<nav class='${galk.ctrlOverlay}'>
<a class='${galk.focus}'>
<figure class='${galk.btnIcon}'></figure></a>
<a class='${galk.nav} ${galk.prev}'>
<figure class='${galk.btnIcon}'></figure></a>
<a class='${galk.nav} ${galk.next}'>
<figure class='${galk.btnIcon}'></figure></a>
</nav>
<img class='${galk.media}' hidden=''/>
<video class='${galk.media}' hidden=''
controls='' loop='' muted=''></video>
<object class='${galk.media}' hidden=''
type='application/x-shockwave-flash'
typemustmatch='' width='0' height='0'>
<param name='wmode' value='transparent'/>
</object>
<img class='${galk.mediaSample}' hidden=''/>
<img class='${galk.mediaThumbnail}' hidden=''/>
<img class='${galk.mediaPlaceholder}'/>
<figure class='${galk.mediaUnavailable}' hidden=''>
<img/></figure>
</section>
</section>
<footer class='${galk.svCtrlBar}'>
<a class='${galk.disabled}'>
<figure class='${galk.btnIcon}'></figure></a>
<a class='${galk.disabled}'>
<figure class='${galk.btnIcon}'></figure></a>
<a class='${galk.postPage}'>
<figure class='${galk.btnIcon}'></figure></a>
<a title='Direct Link' class='${galk.mediaAttr} ${galk.disabled}'>
<span class='${galk.btnLabel}'>
<span>
<span class='${galk.mediaFileExt}'></span>
<span class='${galk.mediaDims}'></span>
</span>
<span>
<span class='${galk.mediaFileSize}'></span>
<span class='${galk.mediaStatus}'></span>
</span>
</span>
</a>
<a title='Help' class='${galk.help}'>
<figure class='${galk.btnIcon}'></figure></a>
</footer>`);
/* note: avoid using
<div> <p> <h1…h6> <ul> <li> <dd> <dt>
due to global !important styles in safebooru's mobile layout stylesheet */
parentElem.append(view);
return view;
};
const getSlideViewElements = function(view) {
return {
stackElem : enforce(getSingleElemByClass(view, galk.svContentStack)),
notesOvr : enforce(getSingleElemByClass(view, galk.notesOverlay)),
imgElem : enforce(querySingleElem(view, `img.${galk.media}`)),
vidElem : enforce(querySingleElem(view, `video.${galk.media}`)),
swfElem : enforce(querySingleElem(view, `object.${galk.media}`)),
sampleElem : enforce(getSingleElemByClass(view, galk.mediaSample)),
thumbElem : enforce(getSingleElemByClass(view, galk.mediaThumbnail)),
unavElem : enforce(getSingleElemByClass(view, galk.mediaUnavailable)),
phldrElem : enforce(getSingleElemByClass(view, galk.mediaPlaceholder)),
prevBtns : view.querySelectorAll(`a.${galk.prev}`),