-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathmisc.js
2762 lines (2288 loc) · 97 KB
/
misc.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
/*******************/
/* INJECT TRIGGERS */
/*******************/
GW.elementInjectTriggers = { };
GW.defunctElementInjectTriggers = { };
/****************************************************************************/
/* Register element inject trigger for the given uuid. (In other words, when
element with `data-uuid` attribute with value equal to the given uuid is
injected into the document, run the given function on the element.)
Returns the uuid.
(If null is passed for the uuid, one will be generated automatically.)
Each entry thus added triggers only once per uuid, then deletes itself.
*/
function onInject(uuid, f) {
uuid = uuid ?? crypto.randomUUID();
GW.elementInjectTriggers[uuid] = f;
return uuid;
}
/***********************************************************************/
/* Watch for element injections in the given document. Process injected
elements through registered inject triggers.
*/
function observeInjectedElementsInDocument(doc) {
let observer = new MutationObserver((mutationsList, observer) => {
if (Object.entries(GW.elementInjectTriggers).length == 0)
return;
let doTrigger = (element, f) => {
GW.defunctElementInjectTriggers[element.dataset.uuid] = f;
delete GW.elementInjectTriggers[element.dataset.uuid];
f(element);
};
for (mutationRecord of mutationsList) {
for (let [ uuid, f ] of Object.entries(GW.elementInjectTriggers)) {
for (node of mutationRecord.addedNodes) {
if (node instanceof HTMLElement) {
if (node.dataset.uuid == uuid) {
doTrigger(node, f);
break;
} else {
let nestedNode = node.querySelector(`[data-uuid='${uuid}']`);
if (nestedNode) {
doTrigger(nestedNode, f);
break;
}
}
}
}
}
}
});
observer.observe(doc, { subtree: true, childList: true });
}
observeInjectedElementsInDocument(document);
/******************************************************************************/
/* Returns a placeholder element that, when injected, replaces itself with the
return value of the provided replacement function (to which the placeholder
is passed).
If an optional wrapper function is given, replacement is done within an
anonymous closure which is passed to the wrapper function. (This can be
used to, e.g., delay replacement, by passing a suitable doWhen function
as the wrapper.)
*/
function placeholder(replaceFunction, wrapperFunction) {
let transform = wrapperFunction
? (element) => { wrapperFunction(() => { element.replaceWith(replaceFunction(element)); }); }
: (element) => { element.replaceWith(replaceFunction(element)); }
let uuid = onInject(null, transform);
return `<span class="placeholder" data-uuid="${uuid}"></span>`;
}
/*****************************************************************************/
/* Generate new UUIDs for any placeholder elements in the given container.
(Necessary when using a DocumentFragment to make a copy of a subtree;
otherwise - since inject triggers are deleted after triggering once -
any placeholders in the copied subtree will never get replaced.)
*/
function regeneratePlaceholderIds(container) {
container.querySelectorAll(".placeholder").forEach(placeholder => {
placeholder.dataset.uuid = onInject(null, ( GW.elementInjectTriggers[placeholder.dataset.uuid]
?? GW.defunctElementInjectTriggers[placeholder.dataset.uuid]));
});
}
/**********/
/* ASSETS */
/**********/
doAjax({
location: versionedAssetURL("/static/img/icon/icons.svg"),
onSuccess: (event) => {
GW.svgIconFile = newDocument(event.target.response);
GW.notificationCenter.fireEvent("GW.SVGIconsLoaded");
}
});
function doWhenSVGIconsLoaded(f) {
if (GW.svgIconFile != null)
f();
else
GW.notificationCenter.addHandlerForEvent("GW.SVGIconsLoaded", (info) => {
f();
}, { once: true });
}
GW.svg = (icon) => {
if (GW.svgIconFile == null)
return placeholder(element => elementFromHTML(GW.svg(icon)), doWhenSVGIconsLoaded);
let iconView = GW.svgIconFile.querySelector(`#${icon}`);
if (iconView == null)
return null;
let viewBox = iconView.getAttribute("viewBox").split(" ").map(x => parseFloat(x));
let g = iconView.nextElementSibling;
let xOffset = parseFloat(g.getAttribute("transform").match(/translate\((.+?), .+\)/)[1]);
viewBox[0] -= xOffset;
viewBox = viewBox.join(" ");
return ( `<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="${viewBox}"
>`
+ g.innerHTML
+ `</svg>`);
};
/******************/
/* ASSET VERSIONS */
/******************/
GW.assetVersions = (GW.assetVersions ?? { });
/*****************************************************************************/
/* Return fully qualified, versioned (if possible) URL for asset at the given
path.
*/
function versionedAssetURL(pathname) {
let version = GW.assetVersions[pathname];
let versionString = (version ? `?v=${version}` : ``);
return URLFromString(pathname + versionString);
}
/***************************************************************************/
/* Convenience function for shared code between uses of getAssetPathname().
*/
function processAssetSequenceOptions(options, metaOptions) {
metaOptions = Object.assign({
currentAssetURL: null,
assetSavedIndexKey: null
}, metaOptions);
let sequenceIndex, sequenceCurrent;
if (GW.allowedAssetSequencingModes.includes(options.sequence) == false) {
sequenceIndex = null;
sequenceCurrent = null;
} else if (options.sequence.endsWith("Current")) {
for (let prefix of [ "next", "previous" ])
if (options.sequence.startsWith(prefix))
sequenceIndex = prefix;
sequenceCurrent = metaOptions.currentAssetURL.pathname;
} else {
let savedIndexKey = metaOptions.assetSavedIndexKey;
let savedIndex = localStorage.getItem(savedIndexKey);
if ( savedIndex == null
&& options.randomize) {
sequenceIndex = rollDie(1E6);
localStorage.setItem(savedIndexKey, sequenceIndex);
} else if (options.sequence.startsWith("next")) {
sequenceIndex = savedIndex == null
? 1
: parseInt(savedIndex) + 1;
localStorage.setItem(savedIndexKey, sequenceIndex);
} else {
sequenceIndex = savedIndex == null
? 0
: parseInt(savedIndex) - 1;
localStorage.setItem(savedIndexKey, sequenceIndex);
}
sequenceCurrent = null;
}
return { sequenceIndex, sequenceCurrent };
}
/*****************************************************************************/
/* Return an asset pathname (not versioned), given a pathname regular
expression pattern (in string form, not a RegExp object), with ‘%R’ where
a number should be, e.g.:
/static/img/logo/christmas/light/logo-christmas-light-%R(\\.svg|-small-1x\\.(png|jpg|webp))
will return files with pathnames like:
/static/img/logo/christmas/light/logo-christmas-light-1-small-1x.png
/static/img/logo/christmas/light/logo-christmas-light-1-small-1x.jpg
/static/img/logo/christmas/light/logo-christmas-light-1-small-1x.webp
/static/img/logo/christmas/light/logo-christmas-light-1.svg
(Or -2, -3, etc.)
Specified assets must be listed in the versioned asset database.
By default, selects uniform-randomly from all available asset pathnames
matching the provided pattern. (But see option fields, below.)
Available option fields:
sequenceIndex (integer)
sequenceIndex (string)
If this field is set to an integer value, then, instead of returning a
random asset pathname out of the asset pathnames matching the provided
pattern, selects the i’th one, where i is equal to (sequenceIndex - 1)
modulo the number of matching asset pathnames.
If this field is set to a string value, then it must be either “next”
or “previous”, and the `sequenceCurrent` field must also be set; if
these conditions are not met, null is returned. (See the
`sequenceCurrent` field, below, for details on this option.)
sequenceCurrent (string)
If the `sequenceIndex` field is not set to a string value of either
“next” or “previous”, this field is ignored.
If `sequenceIndex` is set to “next”, and the value of this field is
equal to a value of one of the asset pathnames that match the provided
pattern, then the next pattern in the set of matching patterns is
returned (wrapping around to the first value after the last one).
If `sequenceIndex` is set to “previous”, and the value of this field
is equal to a value of one of the asset pathnames that match the
provided pattern, then the previous pattern in the set of matching
patterns is returned (wrapping around to the last value after the
first).
If the value of this field does not match any of the asset pathnames
that match the provided pattern (including if it is null), then, if
`sequenceIndex` is set to “next”, it behaves as if `sequenceIndex` had
been set to 1; and if `sequenceIndex` is set to “previous”, it behaves
as if `sequenceIndex` had been set to 0 (i.e., the first or the last
pattern in the set of matching patterns is returned).
*/
function getAssetPathname(assetPathnamePattern, options) {
options = Object.assign({
sequenceIndex: null,
sequenceCurrent: null
}, options);
let assetPathnameRegExp = new RegExp(assetPathnamePattern.replace("%R", "[0-9]+"));
let matchingAssetPathnames = [ ];
for (versionedAssetPathname of Object.keys(GW.assetVersions)) {
if (assetPathnameRegExp.test(versionedAssetPathname))
matchingAssetPathnames.push(versionedAssetPathname);
}
if (matchingAssetPathnames.length == 0) {
return null;
} else if (options.sequenceIndex == null) {
return matchingAssetPathnames[rollDie(matchingAssetPathnames.length) - 1];
} else if (typeof options.sequenceIndex == "number") {
return matchingAssetPathnames[modulo(options.sequenceIndex - 1, matchingAssetPathnames.length)];
} else if (typeof options.sequenceIndex == "string") {
if ([ "next", "previous" ].includes(options.sequenceIndex) == false)
return null;
let currentIndex = matchingAssetPathnames.indexOf(options.sequenceCurrent);
if (currentIndex == -1) {
return (options.sequenceIndex == "next"
? matchingAssetPathnames.first
: matchingAssetPathnames.last);
} else {
return (options.sequenceIndex == "next"
? matchingAssetPathnames[modulo(currentIndex + 1, matchingAssetPathnames.length)]
: matchingAssetPathnames[modulo(currentIndex - 1, matchingAssetPathnames.length)]);
}
} else {
return null;
}
}
/*******************/
/* IMAGE OUTLINING */
/*******************/
GW.outlineOrNot = { };
GW.outlineOrNotAPIEndpoint = "https://api.obormot.net/outlineornot/url";
/******************************************************************************/
/* Returns true if the given image’s outlining status has been set (i.e., if
it has one of the classes [ "outline", "outline-auto", "outline-not",
"outline-not-auto" ]), false otherwise.
*/
function outliningJudgmentHasBeenAppliedToImage(image) {
return (image.classList.containsAnyOf([ "outline", "outline-auto", "outline-not", "outline-not-auto" ]) == true);
}
/*****************************************************************************/
/* Returns true if the given image should be outlined (i.e., the outlineOrNot
API has judged this image to be outline-requiring), false if the image
should not be outlined (i.e., the outlineOrNot API has judged this image
to be non-outline-requiring, null if no judgment is available.
*/
function outliningJudgmentForImage(image) {
return (GW.outlineOrNot[Images.smallestAvailableImageSizeURLForImage(image).href]?.outline ?? null);
}
/*****************************************************************************/
/* Applies available (i.e., requested and received from the outlineOrNot API)
image outlining judgment data to the given image, and returns true if this
was done successfully. If no such data is available for the given image,
does nothing (and returns false). Likewise does nothing (and returns null)
for images which already have their outlining status specified.
*/
function applyImageOutliningJudgment(image) {
if (outliningJudgmentHasBeenAppliedToImage(image))
return null;
let outliningJudgment = outliningJudgmentForImage(image);
if (outliningJudgment != null) {
image.classList.add(outliningJudgment == true ? "outline-auto" : "outline-not-auto");
return true;
} else {
return false;
}
}
/*****************************************************************************/
/* Sends request to outlineOrNot for judgments about whether the images in the
given container ought to be outlined.
*/
function requestImageOutliningJudgmentsForImagesInContainer(container) {
/* Disable, for now.
—SA 2024-12-18
*/
return;
let imageURLs = Array.from(container.querySelectorAll("figure img")).map(image => {
let imageURL = Images.smallestAvailableImageSizeURLForImage(image);
return ( imageURL.pathname.match(/\.(png|jpe?g$)/i)
&& GW.invertOrNot[imageURL.href] == null)
? imageURL.href
: null;
}).filter(x => x);
if (imageURLs.length == 0)
return;
doAjax({
location: GW.outlineOrNotAPIEndpoint,
method: "POST",
serialization: "JSON",
responseType: "json",
params: imageURLs,
onSuccess: (event) => {
event.target.response.forEach(imageInfo => {
GW.outlineOrNot[imageInfo.url] = {
outline: (imageInfo.outline == 1)
};
});
GW.notificationCenter.fireEvent("GW.imageOutliningJudgmentsAvailable", { judgments: event.target.response });
},
onFailure: (event) => {
console.log(event);
}
});
}
/*******************/
/* IMAGE INVERSION */
/*******************/
GW.invertOrNot = { };
GW.invertOrNotAPIEndpoint = "https://invertornot.com/api/url";
/******************************************************************************/
/* Returns true if the given image’s inversion status has been set (i.e., if
it has one of the classes [ "invert", "invert-auto", "invert-not",
"invert-not-auto" ]), false otherwise.
*/
function inversionJudgmentHasBeenAppliedToImage(image) {
return (image.classList.containsAnyOf([ "invert", "invert-auto", "invert-not", "invert-not-auto" ]) == true);
}
/****************************************************************************/
/* Returns true if the given image should be inverted in dark mode (i.e.,
the invertOrNot API has judged this image to be invertible), false if the
image should not be inverted (i.e., the invertOrNot API has judged this
image to be non-invertible, null if no judgment is available.
*/
function inversionJudgmentForImage(image) {
return (GW.invertOrNot[Images.smallestAvailableImageSizeURLForImage(image).href]?.invert ?? null);
}
/*****************************************************************************/
/* Applies available (i.e., requested and received from the invertOrNot API)
image inversion judgment data to the given image, and returns true if this
was done successfully. If no such data is available for the given image,
does nothing (and returns false). Likewise does nothing (and returns null)
for images which already have their inversion status specified.
*/
function applyImageInversionJudgment(image) {
if (inversionJudgmentHasBeenAppliedToImage(image))
return null;
let inversionJudgment = inversionJudgmentForImage(image);
if (inversionJudgment != null) {
image.classList.add(inversionJudgment == true ? "invert-auto" : "invert-not-auto");
return true;
} else {
return false;
}
}
/*****************************************************************************/
/* Sends request to invertOrNot for judgments about whether the images in the
given container ought to be inverted.
*/
function requestImageInversionJudgmentsForImagesInContainer(container) {
let imageURLs = Array.from(container.querySelectorAll("figure img")).map(image => {
let imageURL = Images.smallestAvailableImageSizeURLForImage(image);
return ( imageURL.pathname.match(/\.(png|jpe?g$)/i)
&& GW.invertOrNot[imageURL.href] == null)
? imageURL.href
: null;
}).filter(x => x);
if (imageURLs.length == 0)
return;
doAjax({
location: GW.invertOrNotAPIEndpoint,
method: "POST",
serialization: "JSON",
responseType: "json",
params: imageURLs,
onSuccess: (event) => {
event.target.response.forEach(imageInfo => {
GW.invertOrNot[imageInfo.url] = {
invert: (imageInfo.invert == 1)
};
});
GW.notificationCenter.fireEvent("GW.imageInversionJudgmentsAvailable", { judgments: event.target.response });
},
onFailure: (event) => {
console.log(event);
}
});
}
/**********/
/* IMAGES */
/**********/
Images = {
thumbnailBasePath: "/metadata/thumbnail/",
thumbnailDefaultSize: "256",
thumbnailSizeFromURL: (url) => {
if (typeof url == "string")
url = URLFromString(url);
return parseInt(url.pathname.slice(Images.thumbnailBasePath.length).split("/")[0]);
},
smallestAvailableImageSizeURLForImage: (image) => {
return (Images.thumbnailURLForImage(image) ?? Images.fullSizeURLForImage(image));
},
fullSizeURLForImage: (image) => {
return URLFromString(image.dataset.srcSizeFull ?? image.src);
},
thumbnailURLForImageURL: (imageSrcURL, size = Images.thumbnailDefaultSize) => {
if (imageSrcURL.hostname != location.hostname)
return null;
return URLFromString( Images.thumbnailBasePath
+ size + "px/"
+ fixedEncodeURIComponent(fixedEncodeURIComponent(imageSrcURL.pathname)));
},
thumbnailURLForImage: (image, size = Images.thumbnailDefaultSize) => {
if (Images.isSVG(image))
return null;
return (Images.isThumbnail(image)
? URLFromString(image.src)
: Images.thumbnailURLForImageURL(URLFromString(image.src)));
},
thumbnailifyImage: (image) => {
if (Images.isSVG(image))
return;
if (Images.isThumbnail(image))
return;
let thumbnailURL = Images.thumbnailURLForImage(image);
if (thumbnailURL) {
image.dataset.srcSizeFull = image.src;
image.src = thumbnailURL.href;
}
},
isSVG: (image) => {
return (URLFromString(image.src).pathname.toLowerCase().endsWith(".svg"));
},
isThumbnail: (image) => {
return (image.dataset.srcSizeFull > "");
},
unthumbnailifyImage: (image) => {
if (Images.isThumbnail(image)) {
image.src = image.dataset.srcSizeFull;
delete image.dataset.srcSizeFull;
}
}
};
/***********************/
/* PROGRESS INDICATORS */
/***********************/
/**************************************************************************/
/* Returns SVG source for a progress-indicator SVG icon, given a specified
progress percentage (in [0,100]).
*/
function arcSVGForProgressPercent (percent) {
let svgOpeningTagSrc = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">`;
let svgClosingTagSrc = `</svg>`;
let strokeWidth = GW.isMobile() ? 64.0 : 56.0;
let boxRadius = 256.0;
let radius = boxRadius - (strokeWidth * 0.5);
let backdropCircleGray = (GW.isMobile() ? 110.0 : 170.0) + (percent * 0.64);
let backdropCircleColor = Color.hexStringFromRGB({
red: backdropCircleGray,
green: backdropCircleGray,
blue: backdropCircleGray
});
let backdropCircleSrc = `<circle cx="${boxRadius}" cy="${boxRadius}" r="${radius}"`
+ ` stroke-width="${strokeWidth}" stroke="${backdropCircleColor}" fill="none"/>`;
let arcAttributesSrc = `fill="none" stroke="#000" stroke-width="${strokeWidth}" stroke-linecap="round"`;
let arcSrc;
if (percent == 100) {
arcSrc = `<circle cx="${boxRadius}" cy="${boxRadius}" r="${radius}" ${arcAttributesSrc}/>`;
} else {
let angle = 2.0 * Math.PI * ((percent / 100.0) - 0.25);
let y = (radius * Math.sin(angle)) + boxRadius;
let x = (radius * Math.cos(angle)) + boxRadius;
let largeArc = percent > 50 ? "1" : "0";
arcSrc = `<path
d="M ${boxRadius} ${strokeWidth * 0.5} A ${radius} ${radius} 0 ${largeArc} 1 ${x} ${y}"
${arcAttributesSrc}/>`;
}
return (svgOpeningTagSrc + backdropCircleSrc + arcSrc + svgClosingTagSrc);
}
/*****************************************************************************/
/* Given an element with a `data-progress-percentage` attribute, injects an
inline icon displaying the specified progress percentage. (The icon will
automatically be further processed for display by the inline icon system.)
*/
function renderProgressPercentageIcon(progressIndicator) {
let svgSrc = arcSVGForProgressPercent(parseInt(progressIndicator.dataset.progressPercentage));
progressIndicator.querySelector(".progress-indicator-icon")?.remove();
progressIndicator.appendChild(newElement("SPAN", {
class: "progress-indicator-icon icon-special",
style: `--icon-url: url("data:image/svg+xml;utf8,${encodeURIComponent(svgSrc)}")`
}));
}
/*********/
/* LINKS */
/*********/
/******************************************************************************/
/* Returns true if the link is an annotated link, OR if it is an include-link
which transclude.js treats as an annotation transclude. (This is relevant
because in either case, the link hash should be ignored, when deciding what
to do with a link on the basis of it having or not having a link hash.)
*/
function isAnnotationLink(link) {
return (Annotations.isAnnotatedLinkFull(link) || Transclude.isAnnotationTransclude(link));
}
/****************************************************************************/
/* Return the element, in the target document, pointed to by the hash of the
given link (which may be a URL object or an HTMLAnchorElement).
*/
function targetElementInDocument(link, doc) {
if (isAnchorLink(link) == false)
return null;
let anchor = anchorsForLink(link)[0];
let element = null;
if (anchor.startsWith("#"))
element = doc.querySelector(selectorFromHash(anchor));
if ( element == null
&& link instanceof HTMLAnchorElement
&& link.dataset.backlinkTargetUrl > "") {
// HAX. (Remove when link IDs are fixed. —SA 2023-03-22)
/* Disabling this hack, hopefully it’s no longer needed.
(See also line below.) —SA 2023-04-29
*/
// let exactBacklinkSelector = null;
// if (anchor.startsWith("#gwern")) {
// let targetID = "#" + anchor.slice(("#gwern" + link.dataset.backlinkTargetUrl.slice(1).replace("/", "-") + "-").length);
// if (targetID > "")
// exactBacklinkSelector = `a[href*='${CSS.escape(link.dataset.backlinkTargetUrl + targetID)}']`;
// }
let backlinkSelector = `a[href*='${CSS.escape(link.dataset.backlinkTargetUrl)}']:not(.backlink-not)`;
let exclusionSelector = [
"#page-metadata a",
".aux-links-list a"
].join(", ");
/* Disabling this hack, hopefully it’s no longer needed.
(See also lines above.) —SA 2023-04-29
*/
element = /* doc.querySelector(exactBacklinkSelector) ?? */ (Array.from(doc.querySelectorAll(backlinkSelector)).filter(backlink => {
return ( (link.dataset.backlinkTargetUrl.startsWith("/")
? backlink.pathname == link.dataset.backlinkTargetUrl
: backlink.href == link.dataset.backlinkTargetUrl)
&& backlink.closest(exclusionSelector) == null);
}).first);
}
return element;
}
/*****************************************************************************/
/* Returns true if the given link (a URL or an HTMLAnchorElement) points to a
specific element within a page, rather than to a whole page. (This is
usually because the link has a URL hash, but may also be because the link
is a backlink, in which case it implicitly points to that link in the
target page which points back at the target page for the backlink; or it
may be because the link is a link with a value for the `data-target-id`
or `data-backlink-target-url` attributes.)
*/
function isAnchorLink(link) {
return (anchorsForLink(link).length == 1);
}
/***********************************************/
/* Removes all anchor data from the given link.
*/
function stripAnchorsFromLink(link) {
if (link instanceof HTMLAnchorElement) {
link.removeAttribute("data-target-id");
link.removeAttribute("data-backlink-target-url");
}
link.hash = "";
}
/****************************************************************************/
/* Returns an array of anchors for the given link. This array may have zero,
one, or two elements.
*/
function anchorsForLink(link) {
if (link instanceof HTMLAnchorElement) {
if (link.dataset.targetId > "") {
return link.dataset.targetId.split(" ").map(x => `#${x}`);
} else if ( isAnnotationLink(link) == false
&& link.hash > "") {
return link.hash.match(/#[^#]*/g);
} else if ( isAnnotationLink(link) == false
&& link.dataset.backlinkTargetUrl > "") {
return [ link.dataset.backlinkTargetUrl ];
} else {
return [ ];
}
} else {
return link.hash.match(/#[^#]*/g) ?? [ ];
}
}
/************/
/* SECTIONS */
/************/
/******************************************************************************/
/* Returns the heading level of a <section> element. (Given by a class of the
form ‘levelX’ where X is a positive integer. Defaults to 1 if no such class
is present.)
*/
function sectionLevel(section) {
if ( !section
|| section.tagName != "SECTION")
return null;
// Note: ‘m’ is a regexp matches array.
let m = Array.from(section.classList).map(c => c.match(/^level([0-9]*)$/)).find(m => m);
return (m ? parseInt(m[1]) : 1);
}
/*************/
/* CLIPBOARD */
/*************/
/*******************************************/
/* Copy the provided text to the clipboard.
*/
function copyTextToClipboard(text) {
let scratchpad = document.querySelector("#scratchpad");
// Perform copy operation.
scratchpad.innerText = text;
selectElementContents(scratchpad);
document.execCommand("copy");
scratchpad.innerText = "";
}
/***************************************************/
/* Create scratchpad for synthetic copy operations.
*/
doWhenDOMContentLoaded(() => {
document.body.append(newElement("SPAN", { "id": "scratchpad" }));
});
/*****************************************************************************/
/* Adds the given copy processor, appending it to the existing array thereof.
Each copy processor should take two arguments: the copy event, and the
DocumentFragment which holds the selection as it is being processed by each
successive copy processor.
A copy processor should return true if processing should continue after it’s
done, false otherwise (e.g. if it has entirely replaced the contents of the
selection object with what the final clipboard contents should be).
*/
function addCopyProcessor(processor) {
if (GW.copyProcessors == null)
GW.copyProcessors = [ ];
GW.copyProcessors.push(processor);
}
/******************************************************************************/
/* Set up the copy processor system by registering a ‘copy’ event handler to
call copy processors. (Must be set up for the main document, and separately
for any shadow roots.)
*/
function registerCopyProcessorsForDocument(doc) {
GWLog("registerCopyProcessorsForDocument", "misc.js", 1);
doc.addEventListener("copy", (event) => {
if ( GW.copyProcessors == null
|| GW.copyProcessors.length == 0)
return;
event.preventDefault();
event.stopPropagation();
let selection = getSelectionAsDocument(doc);
let i = 0;
while ( i < GW.copyProcessors.length
&& GW.copyProcessors[i++](event, selection));
event.clipboardData.setData("text/plain", selection.textContent);
event.clipboardData.setData("text/html", selection.innerHTML);
});
}
/*************/
/* AUX-LINKS */
/*************/
AuxLinks = {
auxLinksLinkTypes: {
"/metadata/annotation/backlink/": "backlinks",
"/metadata/annotation/similar/": "similars",
"/metadata/annotation/link-bibliography/": "link-bibliography"
},
auxLinksLinkType: (link) => {
for (let [ pathnamePrefix, linkType ] of Object.entries(AuxLinks.auxLinksLinkTypes))
if (link.pathname.startsWith(pathnamePrefix))
return linkType;
return null;
},
/* Page or document for whom the aux-links are.
*/
targetOfAuxLinksLink: (link) => {
for (let [ pathnamePrefix, linkType ] of Object.entries(AuxLinks.auxLinksLinkTypes)) {
if (link.pathname.startsWith(pathnamePrefix)) {
if (link.pathname.endsWith(".html")) {
let start = pathnamePrefix.length;
let end = (link.pathname.length - ".html".length);
return decodeURIComponent(decodeURIComponent(link.pathname.slice(start, end)));
} else {
let start = (pathnamePrefix.length - 1);
return link.pathname.slice(start);
}
}
}
return null;
}
};
/*********/
/* NOTES */
/*********/
Notes = {
hashForCitationRegexp: new RegExp("^#fnref[0-9]+$"),
hashMatchesCitation: (hash = location.hash) => {
return Notes.hashForCitationRegexp.test(hash);
},
hashForFootnoteRegexp: new RegExp("^#fn[0-9]+$"),
hashMatchesFootnote: (hash = location.hash) => {
return Notes.hashForFootnoteRegexp.test(hash);
},
hashForSidenoteRegexp: new RegExp("^#sn[0-9]+$"),
hashMatchesSidenote: (hash = location.hash) => {
return Notes.hashForSidenoteRegexp.test(hash);
},
/* Get the (side|foot)note number from a URL hash (which might point to a
footnote, a sidenote, or a citation).
*/
noteNumberFromHash: (hash = location.hash) => {
if ( Notes.hashMatchesFootnote(hash)
|| Notes.hashMatchesSidenote(hash))
return hash.substr(3);
else if (Notes.hashMatchesCitation(hash))
return hash.substr(6);
else
return "";
},
noteNumber: (element) => {
return Notes.noteNumberFromHash(element.hash ?? ("#" + element.id));
},
citationIdForNumber: (number) => {
return `fnref${number}`;
},
footnoteIdForNumber: (number) => {
return `fn${number}`;
},
sidenoteIdForNumber: (number) => {
return `sn${number}`;
},
setCitationNumber: (citation, number) => {
// #fnN
citation.hash = citation.hash.slice(0, 3) + number;
// fnrefN
citation.id = citation.id.slice(0, 5) + number;
// Link text.
citation.firstElementChild.textContent = number;
},
setFootnoteNumber: (footnote, number) => {
// fnN
footnote.id = footnote.id.slice(0, 2) + number;
// #fnrefN
let footnoteBackLink = footnote.querySelector("a.footnote-back");
if (footnoteBackLink) {
footnoteBackLink.hash = footnoteBackLink.hash.slice(0, 6) + number;
}
// #fnN
let footnoteSelfLink = footnote.querySelector("a.footnote-self-link");
if (footnoteSelfLink) {
footnoteSelfLink.hash = footnoteSelfLink.hash.slice(0, 3) + number;
footnoteSelfLink.title = "Link to footnote " + number;
}
// Footnote backlinks.
let backlinksListLabelLink = footnote.querySelector(".section-backlinks .backlinks-list-label a");
if (backlinksListLabelLink) {
// #fnN
backlinksListLabelLink.hash = backlinksListLabelLink.hash.slice(0, 3) + number;
// N
backlinksListLabelLink.querySelector("span.footnote-number").innerText = number;
}
},
/**************************************************************************/
/* Return all {side|foot}note elements associated with the given citation.
*/
allNotesForCitation: (citation) => {
if (!citation.classList.contains("footnote-ref"))
return null;
let citationNumber = Notes.noteNumber(citation);
let selector = `#fn${citationNumber}, #sn${citationNumber}`;
let allNotes = Array.from(document.querySelectorAll(selector)
).concat(Array.from(citation.getRootNode().querySelectorAll(selector))
).concat(Extracts.popFrameProvider.allSpawnedPopFrames().flatMap(popFrame =>
Array.from(popFrame.document.querySelectorAll(selector)))
).unique();
/* We must check to ensure that the note in question is from the same
page as the citation (to distinguish between main document and any
full-page embeds that may be spawned).
*/
return allNotes.filter(note => (note.querySelector(".footnote-back")?.pathname == citation.pathname));
}
};
/****************/
/* MARGIN NOTES */
/****************/
GW.marginNotes = {
// Don’t show margin notes block if there are fewer notes than this.
minimumAggregatedNotesCount: 3,
aggregationNeededInDocuments: [ ]
};
/****************************************************************************/
/* Aggregate margin notes, on the next animation frame, if not already done.
*/
function aggregateMarginNotesIfNeededInDocument(doc) {
if (GW.marginNotes.aggregationNeededInDocuments.includes(doc) == false)
GW.marginNotes.aggregationNeededInDocuments.push(doc);
requestAnimationFrame(() => {
if (GW.marginNotes.aggregationNeededInDocuments.includes(doc) == false)
return;
GW.marginNotes.aggregationNeededInDocuments.remove(doc);
aggregateMarginNotesInDocument(doc);
});
}
/**************************/
/* Aggregate margin notes.
*/
function aggregateMarginNotesInDocument(doc) {
GWLog("aggregateMarginNotesInDocument", "misc.js", 2);
let marginNotesBlockClass = "margin-notes-block";
doc.querySelectorAll(".marginnote").forEach(marginNote => {
if (marginNote.classList.contains("only-icon"))
return;
let section = marginNote.closest("section, .markdownBody, .annotation-abstract");
if (section == null)
return;