/
misc.js
1815 lines (1478 loc) · 58.1 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" xmlns:xlink="http://www.w3.org/1999/xlink" 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);
}
/*****************************************************************************/
/* Return a random alternate asset pathname (not versioned), given a pathname
with ‘%R’ where a number should be, e.g.:
/static/img/logo/christmas/light/logo-christmas-light-%R-small-1x.png
will return
/static/img/logo/christmas/light/logo-christmas-light-1-small-1x.png
(or -2, -3, etc., selecting randomly from available numbered alternates).
Specified assets must be listed in the versioned asset database.
*/
function randomAsset(assetPathnamePattern) {
let assetPathnameRegExp = new RegExp(assetPathnamePattern);
let alternateAssetPathnames = [ ];
for (versionedAssetPathname of Object.keys(GW.assetVersions)) {
if (assetPathnameRegExp.test(versionedAssetPathname))
alternateAssetPathnames.push(versionedAssetPathname);
}
return (alternateAssetPathnames[rollDie(alternateAssetPathnames.length) - 1] ?? null);
}
/*******************/
/* IMAGE INVERSION */
/*******************/
GW.invertOrNot = { };
GW.invertOrNotAPIEndpoint = "https://invertornot.com/api/url";
/*******************************************************************/
/* Returns true if the given image should be inverted in dark mode.
*/
function shouldInvertImageInDarkMode(image) {
return (GW.invertOrNot[image.src].invert == true);
}
/*****************************************************************************/
/* Sends request to InvertOrNot for judgments about whether the images in the
given container ought to be inverted.
*/
function requestImageInversionDataForImagesInContainer(container) {
let imageURLs = Array.from(container.querySelectorAll("figure img")).map(image =>
( URLFromString(image.src).pathname.match(/\.(png|jpe?g$)/i)
&& GW.invertOrNot[image.src] == null)
? image.src
: 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)
};
});
},
onFailure: (event) => {
console.log(event);
}
});
}
/*********/
/* 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", "rewrite.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 = {
/* Get the (side|foot)note number from the URL hash (which might point to a
footnote, a sidenote, or a citation).
*/
noteNumberFromHash: (hash = location.hash) => {
if (hash.startsWith("#") == false)
hash = "#" + hash;
if (hash.match(/#[sf]n[0-9]/))
return hash.substr(3);
else if (hash.match(/#fnref[0-9]/))
return hash.substr(6);
else
return "";
},
noteNumber: (element) => {
return Notes.noteNumberFromHash(element.hash ?? element.id);
},
citationSelectorMatching: (element) => {
return ("#" + Notes.idForCitationNumber(Notes.noteNumberFromHash(element.hash)));
},
footnoteSelectorMatching: (element) => {
return ("#" + Notes.idForFootnoteNumber(Notes.noteNumberFromHash(element.hash)));
},
sidenoteSelectorMatching: (element) => {
return ("#" + Notes.idForSidenoteNumber(Notes.noteNumberFromHash(element.hash)));
},
idForCitationNumber: (number) => {
return `fnref${number}`;
},
idForFootnoteNumber: (number) => {
return `fn${number}`;
},
idForSidenoteNumber: (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.textContent.trim() == "☞")
return;
let section = marginNote.closest("section, .markdownBody, .annotation-abstract");
if (section == null)
return;
let marginNotesBlock = section.querySelector(`#${(CSS.escape(section.id))}-${marginNotesBlockClass}`);
if (marginNotesBlock == null) {
/* Construct the margin notes block. It should go after any
abstract and/or epigraph that opens the section.
*/
let firstBlock = firstBlockOf(section, {
alsoSkipElements: [
".abstract blockquote",
".epigraph",
"p.data-field"
]
}, true);
let marginNoteBlockContainerElementsSelector = [
"section",
".markdownBody",
".abstract-collapse:not(.abstract)",
".collapse-content-wrapper",
".annotation-abstract"
].join(", ");
while (firstBlock.parentElement.matches(marginNoteBlockContainerElementsSelector) == false)
firstBlock = firstBlock.parentElement;
// Inject the margin notes block.
marginNotesBlock = newElement("P", {
class: marginNotesBlockClass,
id: `${section.id}-${marginNotesBlockClass}`
});
firstBlock.parentElement.insertBefore(marginNotesBlock, firstBlock);
}
// Clone the note.
let clonedNote = marginNote.cloneNode(true);
// Set margin note type class.
clonedNote.swapClasses([ "inline", "sidenote" ], 0);
// Unwrap the inner wrapper (unneeded here).
unwrap(clonedNote.querySelector(".marginnote-inner-wrapper"));
// Remove dropcap, if any.
resetDropcapInBlock(clonedNote);
// Trim whitespace.
clonedNote.innerHTML = clonedNote.innerHTML.trim();
// Strip brackets.
/* Reason: we use brackets for editorial insertions & commentary,
particularly in annotations where the reader assumes the text is
written by the original authors.
Sometimes in long annotations where we wish to add ‘sections’
(because the original didn’t have them or they were inappropriate,
eg. long journalistic essays where the material is scattered rather
than organized by topic as necessary for a convenient annotation),
we use margin-notes as a substitute for original sections.
Such editorializing of course must be marked by brackets to avoid
misleading the reader; but then, when aggregated at the beginning
of the annotation like all margin notes, it looks bad:
‘[Foo] · [Bar] · [Baz] · [Quux]’.
So, although it risks misleading readers who do not read down
to the actual margin-note usage & see that it’s an editorial
insertion, we remove the brackets when aggregated.
(If it is necessary to override this feature & force brackets
displayed in aggregates - perhaps because the margin-note is some
exotic chemical name that starts with a bracket - one can use
alternate Unicode bracket-pairs, or possibly some sort of
non-printing non-whitespace character to block the match.
Although, since the match requires the text to both start *and* end
with a bracket, this should be an extremely rare edge-case not
worth thinking about further.)
*/
if ( clonedNote.textContent.startsWith("[")
&& clonedNote.textContent.endsWith("]")) {
clonedNote.firstTextNode.nodeValue = clonedNote.firstTextNode.nodeValue.slice(1);
clonedNote.lastTextNode.nodeValue = clonedNote.lastTextNode.nodeValue.slice(0, -1);
}
// Strip trailing period.
if (clonedNote.textContent.endsWith("."))
clonedNote.lastTextNode.nodeValue = clonedNote.lastTextNode.nodeValue.slice(0, -1);
// Prevent duplication.
if (Array.from(marginNotesBlock.children).findIndex(child => {
return clonedNote.textContent == child.textContent;
}) != -1)
return;
// Append.
marginNotesBlock.append(clonedNote);
// Process the new entries to activate pop-frame spawning.
Extracts.addTargetsWithin(marginNotesBlock);
});
// Update visibility of margin note blocks.
doc.querySelectorAll(`.${marginNotesBlockClass}`).forEach(marginNotesBlock => {
marginNotesBlock.classList.toggle("hidden", marginNotesBlock.children.length < GW.marginNotes.minimumAggregatedNotesCount);
});
}
/***************************************************************************/
/* Child nodes of a paragraph, excluding any margin notes in sidenote mode.
*/
function nodesOfGraf(graf) {
return Array.from(graf.childNodes).filter(node => ((node instanceof Element && node.matches(".marginnote.sidenote")) == false));
}
/*****************************************************************************/
/* Text content of a paragraph, excluding the contents of any margin notes in
sidenote mode.
*/
function textContentOfGraf(graf) {
return nodesOfGraf(graf).map(node => node.textContent).join("");
}
/******************************************************************************/
/* First text node of a paragraph, skipping any margin notes in sidenote mode.
*/
function firstTextNodeOfGraf(graf) {
return nodesOfGraf(graf).first.firstTextNode;
}
/*********************/
/* TABLE OF CONTENTS */
/*********************/
GW.TOC = {
containersToUpdate: [ ]
};
/*********************************************************************/
/* Update page TOC, on the next animation frame, if not already done.
*/
function updatePageTOCIfNeeded(container = document) {
if (container == document) {
GW.TOC.containersToUpdate = [ document ];
} else if (GW.TOC.containersToUpdate.includes(container) == false) {
GW.TOC.containersToUpdate.push(container);
}
requestAnimationFrame(() => {
while (GW.TOC.containersToUpdate.length > 0)
updatePageTOC(GW.TOC.containersToUpdate.shift());
});
}
/*****************************************************************************/
/* Updates the page TOC with any sections in the page that don’t already have
TOC entries.
*/
// Called by: updateMainPageTOC (rewrite.js)
// Called by: includeContent (transclude.js)
function updatePageTOC(container = document) {
GWLog("updatePageTOC", "misc.js", 2);
let TOC = document.querySelector("#TOC");
if (!TOC)
return;
// Don’t nest TOC entries any deeper than this.
let maxNestingDepth = 4;
// Collect new entries, for later processing (if need be).
let newEntries = [ ];
container.querySelectorAll("#markdownBody section").forEach(section => {
// If this section already has a TOC entry, return.
if (TOC.querySelector(`a[href$='#${(CSS.escape(fixedEncodeURIComponent(section.id)))}']`) != null)
return;
// If this section is too deeply nested, do not add it.
if (sectionLevel(section) > maxNestingDepth)
return;
/* Find where to insert the new TOC entry.
Any already-existing <section> should have a TOC entry.
(Unless the TOC entry has been removed or is missing for some reason,
in which case use the entry for the section after that, and so on.)
*/
let parentSection = section.parentElement.closest("section") ?? document.querySelector("#markdownBody");
let parentTOCElement = parentSection.id == "markdownBody"
? TOC
: TOC.querySelector(`#toc-${(CSS.escape(parentSection.id))}`).closest("li");
let nextSection = null;
let nextSectionTOCLink = null;
let followingSections = childBlocksOf(parentSection).filter(child =>
child.tagName == "SECTION"
&& child.compareDocumentPosition(section) == Node.DOCUMENT_POSITION_PRECEDING
);
do {
nextSection = followingSections.shift();
nextSectionTOCLink = nextSection
? parentTOCElement.querySelector(`#toc-${(CSS.escape(nextSection.id))}`)
: null;
} while ( nextSection
&& nextSectionTOCLink == null);
let followingTOCElement = nextSectionTOCLink
? nextSectionTOCLink.closest("li")
: null;
// Construct entry.
let entry = newElement("LI");
let entryText = section.id == "footnotes"
? "Footnotes"
: section.firstElementChild.querySelector("a").innerHTML;
entry.innerHTML = `<a
class='link-self decorate-not'
id='toc-${section.id}'
href='#${fixedEncodeURIComponent(section.id)}'
>${entryText}</a>`;
// Get or construct the <ul> element.
let subList = ( Array.from(parentTOCElement.childNodes).find(child => child.tagName == "UL")
?? parentTOCElement.appendChild(newElement("UL")));
// Insert and store.
subList.insertBefore(entry, followingTOCElement);
newEntries.push(entry);
});
// Process the new entries to activate pop-frame spawning.
newEntries.forEach(Extracts.addTargetsWithin);
// Rectify typography in new entries.
newEntries.forEach(entry => {
Typography.processElement(entry, Typography.replacementTypes.WORDBREAKS);
});
// Update visibility.
updateTOCVisibility(TOC);
}
/*************/
/* FOOTNOTES */
/*************/
/*****************************************************************************/
/* Mark hash-targeted footnote with ‘targeted’ class.
*/
function updateFootnoteTargeting() {
GWLog("updateFootnoteTargeting", "rewrite.js", 1);
if ( Sidenotes
&& Sidenotes.mediaQueries.viewportWidthBreakpoint.matches)
return;
// Clear any existing targeting.
let targetedElementSelector = [
".footnote-ref",
".footnote"
].map(x => x + ".targeted").join(", ");
document.querySelectorAll(targetedElementSelector).forEach(element => {
element.classList.remove("targeted");
});
// Identify and mark target footnote.
let target = location.hash.match(/^#(fn|fnref)[0-9]+$/)
? getHashTargetedElement()
: null;
if (target)
target.classList.add("targeted");
}
/*************/
/* DROPCAPS */
/*************/
GW.dropcaps = {
dropcapBlockSelector: "p[class*='dropcap-']:not(.dropcap-not)",
graphicalDropcapTypes: [
"dropcat",
"gene-wolfe",
"ninit"
]
};
/***************************************************************************/
/* Returns URL of a random graphical dropcap of the given type and letter,
appropriate for the current mode and the viewport’s device pixel ratio.
*/
function randomDropcapURL(dropcapType, letter) {
let mode = DarkMode.computedMode();
let scale = valMinMax(Math.ceil(window.devicePixelRatio), 1, 2);
let dropcapPathname = randomAsset(`/static/font/dropcap/${dropcapType}/(${mode}/)?${letter.toUpperCase()}(-.+)?-[0-9]+(\\.svg|-small-${scale}x\\.png)$`);
if (dropcapPathname == null)
return null;
return versionedAssetURL(dropcapPathname);
}
/*****************************************************************************/
/* Reset dropcap in the given block to initial state (as it was prior to the
handlers in this section being run, i.e. not implemented, only marked for
implementation).
This function is also used to strip dropcaps from blocks that shouldn’t
have them in the first place.
*/
function resetDropcapInBlock(block) {
let dropcapLink = block.querySelector(".link-dropcap");
if (dropcapLink == null)
return;
unwrap(dropcapLink);
// If this is a graphical dropcap block...
let dropcapImage = block.querySelector("img.dropcap");
if (dropcapImage) {
// Remove mode change handler.
GW.notificationCenter.removeHandlerForEvent(dropcapImage.modeChangeHandler, "DarkMode.computedModeDidChange");
// Remove graphical dropcap.
dropcapImage.remove();
}
// Text node surgery: reattach letter.
let letterSpan = block.querySelector("span.dropcap, span.hidden-initial-letter");
letterSpan.nextSibling.textContent = letterSpan.textContent + letterSpan.nextSibling.textContent;
letterSpan.remove();
// Text node surgery: reattach preceding punctuation (if any).
let precedingPunctuation = block.querySelector("span.initial-preceding-punctuation");
if (precedingPunctuation) {
precedingPunctuation.nextSibling.textContent = precedingPunctuation.textContent + precedingPunctuation.nextSibling.textContent;
precedingPunctuation.remove();
}
}
/******************************/
/* GENERAL ACTIVITY INDICATOR */
/******************************/
GW.activities = [ ];
function beginActivity() {
GW.activities.push({ });
if (GW.activityIndicator)
GW.activityIndicator.classList.add("on");
}
function endActivity() {
GW.activities.shift();
if ( GW.activityIndicator
&& GW.activities.length == 0)
GW.activityIndicator.classList.remove("on");
}
/********/
/* MISC */
/********/
/****************************************************************************/
/* Returns relevant scroll container for the given element. Null is returned
for elements whose scroll container is just the viewport.
*/
function scrollContainerOf(element) {
if ( Extracts
&& Extracts.popFrameProvider) {
let containingPopFrame = Extracts.popFrameProvider.containingPopFrame(element);
if (containingPopFrame)
return containingPopFrame.scrollView;
}
return null;