-
Notifications
You must be signed in to change notification settings - Fork 46
/
layout.js
1254 lines (1053 loc) · 39.7 KB
/
layout.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
/**********/
/* LAYOUT */
/**********/
GW.layout = {
optionsCache: { },
blockContainersNeedingLayout: [ ],
layoutProcessors: [ ],
// Block containers
blockContainers: [
".markdownBody",
"section",
".collapse-block",
"blockquote",
".epigraph",
".admonition",
".sidenote",
"#x-of-the-day"
],
// Block elements get layout classes applied to them.
blockElements: [
"section",
".collapse-block",
"blockquote",
".epigraph",
"p",
".columns",
".footnote",
"figure",
"iframe",
"hr",
"div.sourceCode",
".table-wrapper",
".math.block",
".admonition",
".TOC",
".interview .exchange",
".interview .utterance"
],
// Wrappers are transparent at the top and bottom.
wrapperElements: [
"div",
"span",
".list",
"li",
".parsed-raw-block"
],
// Half-wrappers are transparent at the bottom only, not the top.
halfWrapperElements: [
"section"
],
// Elements which do not participate in block layout.
skipElements: [
".empty",
".empty-graf",
".hidden",
".float",
"noscript",
"button",
"a:empty",
".heading.collapse"
],
// Elements which always participate in block layout, even when empty.
nonEmptyElements: [
"hr"
],
// Do not apply block layout classes to or within these elements.
blockLayoutExclusionSelector: [
"#page-metadata",
".TOC > *",
".popframe"
].join(", "),
emptyNodeExclusionPredicate: (node) => {
if (node.nodeType != Node.ELEMENT_NODE)
return false;
/* Exclude elements that have any classes (discounting
classes added by the layout system).
*/
let classes = Array.from(node.classList);
[ "block",
"first-block",
"empty-graf",
"first-graf",
"list",
"in-list",
"float",
"has-floats",
"heading"
].forEach(layoutClass => {
classes.remove(layoutClass);
});
if (classes.length > 0)
return true;
// Exclude elements that have any data attributes.
if (Object.keys(node.dataset).length > 0)
return true;
return false;
},
blockSpacing: [
[ "body.page-index .abstract > p.first-block", 7, false ],
[ "body.page-index section", 7, false ],
[ "body.page-index section li p + p", 0, false ],
[ "section#see-also.first-block", 4, false ],
[ ".float.first-block", 2, false ],
[ ".first-block", 0, false ],
[ ".heading + section", 5, false ],
[ ".heading + *", 4, false ],
[ ".tweet .tweet-content", 3, false ],
[ ".tweet .tweet-content p", 3, false ],
[ ".tweet figure", 8, false ],
[ "p.data-field.title + p.data-field",
1, false ],
[ "p.data-field.title + .data-field",
3, false ],
[ ".annotation .data-field.file-includes .collapse + annotation .collapse",
5, false ],
[ ".annotation .data-field + .annotation .collapse",
5, false ],
[ ".annotation .collapse.bare-content + annotation .collapse.bare-content",
4, false ],
[ ".annotation * + annotation .collapse.bare-content",
6, false ],
[ ".aux-links-append + .aux-links-append",
0, false ],
[ ".collapse.expanded-not p.aux-links-list-label + *",
0, false ],
[ ".aux-links-append + .file-include-collapse",
0, false ],
[ ".interview .exchange", 4, false ],
[ ".interview .utterance", 2, false ],
[ ".admonition-title > p + p", 1, false ],
[ "p.footnote-back-block", 1, false ],
[ "p.in-list + p.data-field", 10 ],
[ "p.first-graf", 10 ],
[ "p.list-heading", 10 ],
[ "p", 0 ],
[ ".TOC", 10 ],
[ ".collapse-block", 10 ],
[ "section.level1", 15 ],
[ "section.level2", 13 ],
[ "section.level3", 11 ],
[ "section.level4", 10 ],
[ "section.level5", 9 ],
[ "section.level6", 8 ],
[ "section.footnotes", 14 ],
[ ".footnote", 6 ],
[ "hr", 10 ],
[ ".aux-links-append .columns", 4 ],
[ ".columns", 6 ],
[ "figure.outline-not", 9 ],
[ "figure", 10 ],
[ "iframe", 10 ],
[ "blockquote", 10 ],
[ ".epigraph", 6 ],
[ "div.table-wrapper", 10 ],
[ "div.sourceCode", 10 ],
[ ".math.block", 10 ],
[ ".admonition", 10 ],
],
blockSpacingAdjustments: [
[ "p + p", (bsm, block) => bsm - 6 ],
[ [ "p + :not(p)",
":not(p) + p"
], (bsm, block) => bsm - 2 ],
[ [ "p + blockquote",
"blockquote + p",
"blockquote + blockquote"
], (bsm, block) => bsm - 2 ],
[ [ "p + .math.block",
".math.block + p",
".math.block + .math.block"
], (bsm, block) => bsm - 2 ],
[ [ ".in-list + .in-list",
".list-heading + .in-list"
], (bsm, block) => bsm - 2 ],
[ ".aux-links-append p + .aux-links-append p.list-heading",
(bsm, block) => bsm + 2 ],
[ "figcaption *", (bsm, block) => bsm - 2 ],
[ ".TOC + .collapse-block", (bsm, block) => bsm - 4 ],
]
};
// Add support for .desktop-not and .mobile-not classes.
GW.layout.skipElements.push(GW.mediaQueries.mobileWidth.matches ? ".mobile-not" : ".desktop-not");
// Skip non-layout-containing blocks if they themselves appear in block flow.
GW.layout.skipElements.push(...(GW.layout.blockLayoutExclusionSelector.split(", ")));
// Default block sequence function options.
GW.layout.defaultOptions = processLayoutOptions({
blockContainers: GW.layout.blockContainers,
blockElements: GW.layout.blockElements,
skipElements: GW.layout.skipElements,
nonEmptyElements: GW.layout.nonEmptyElements,
wrapperElements: GW.layout.wrapperElements,
halfWrapperElements: GW.layout.halfWrapperElements
});
// Needed so that predicates (like isBlock()) can be called prior to layout.
GW.layout.currentPassBegin = 1;
/**********************************************************************/
/* Registers a layout processor function, which will be applied to all
rendered content as part of the dynamic layout process.
*/
function addLayoutProcessor(name, processor, options = { }) {
// Reference for easy direct calling.
GW.layout[name] = processor;
// Add to layout processor list.
GW.layout.layoutProcessors.push([ name, processor, options ]);
}
/******************************************************************************/
/* Applies given layout processor to given block container within the given
container.
If the layout processor’s options include a condition, tests the condition
against the block container and the base location, applying the processor
only if the test passes.
Fires didComplete event for each time a layout processor fires.
Optionally, specify a containing document different from the root document.
Optionally, specify a base location different from the root document’s.
(Useful for processing document fragments representing other pages or parts
thereof.)
*/
function applyLayoutProcessorToBlockContainer(processorSpec, blockContainer, container, containingDocument = document, baseLocation = location) {
let [ name, processor, options ] = processorSpec;
let info = {
container: blockContainer,
baseLocation: baseLocation
};
if (options.condition?.(info) == false)
return;
processor(blockContainer);
GW.notificationCenter.fireEvent("Layout.layoutProcessorDidComplete", {
document: containingDocument,
container: container,
processorName: name,
processorOptions: options,
blockContainer: blockContainer
});
}
/****************************************************/
/* Activates dynamic layout for the given container.
*/
function startDynamicLayoutInContainer(container) {
let containingDocument = container.getRootNode();
let baseDocumentLocation = baseLocationForDocument(containingDocument);
let selectorize = selectorizeForContainer(container);
let observer = new MutationObserver((mutationsList, observer) => {
// Construct list of all block containers affected by these mutations.
let affectedBlockContainers = [ ];
for (mutationRecord of mutationsList) {
// Find block container in which the mutated element is contained.
let nearestBlockContainer = mutationRecord.target.closest(selectorize(GW.layout.blockContainers));
// Avoid adding a container twice, and apply exclusions.
if ( nearestBlockContainer
&& affectedBlockContainers.includes(nearestBlockContainer) == false
&& nearestBlockContainer.closest(GW.layout.blockLayoutExclusionSelector) == null)
affectedBlockContainers.push(nearestBlockContainer);
}
/* Exclude block containers that are contained within other block
containers in the list, to prevent redundant processing.
*/
affectedBlockContainers = affectedBlockContainers.filter(c => affectedBlockContainers.findIndex(x =>
(c.compareDocumentPosition(x) & Node.DOCUMENT_POSITION_CONTAINS)
) == -1);
/* Add containers to list of containers needing layout processing, if
they are not there already.
*/
affectedBlockContainers.forEach(affectedBlockContainer => {
if (GW.layout.blockContainersNeedingLayout.includes(affectedBlockContainer) == false)
GW.layout.blockContainersNeedingLayout.push(affectedBlockContainer);
});
requestAnimationFrame(() => {
GW.layout.currentPassBegin = performance.now();
// Do layout in all waiting block containers.
while (GW.layout.blockContainersNeedingLayout.length > 0) {
let nextBlockContainer = GW.layout.blockContainersNeedingLayout.shift();
GW.layout.layoutProcessors.forEach(processorSpec => {
applyLayoutProcessorToBlockContainer(processorSpec, nextBlockContainer, container, containingDocument, baseDocumentLocation);
});
}
});
});
observer.observe(container, { subtree: true, childList: true });
}
/*************************************************/
/* Activate dynamic layout for the main document.
*/
doWhenBodyExists(() => {
startDynamicLayoutInContainer(document.body);
// Add listener to redo layout when orientation changes.
doWhenMatchMedia(GW.mediaQueries.portraitOrientation, "Layout.updateLayoutWhenOrientationChanges", (mediaQuery) => {
document.querySelectorAll(".markdownBody").forEach(blockContainer => {
GW.layout.layoutProcessors.forEach(processorSpec => {
applyLayoutProcessorToBlockContainer(processorSpec, blockContainer, document.body);
});
});
});
});
/*****************************************************************************/
/* Process layout options object, so that it contains all the appropriate
defaults (from GW.layout). (This must be done before the options object is
read or used in any way except being passed to another function.)
*/
function processLayoutOptions(options) {
if (options == null)
return GW.layout.defaultOptions;
if (options["blockElementsSelector"] != null)
return options;
let cacheKey = options.cacheKey;
if (cacheKey == null) {
cacheKey = "";
for (let [ key, value ] of Object.entries(options))
cacheKey += `| ${key}: ` + value.join(", ");
options.cacheKey = cacheKey;
}
if (GW.layout.optionsCache[cacheKey])
return GW.layout.optionsCache[cacheKey];
[ "blockContainers",
"blockElements",
"skipElements",
"nonEmptyElements",
"wrapperElements",
"halfWrapperElements"
].forEach(optionKey => {
let option = options[optionKey];
if (option == null) {
option = GW.layout[optionKey];
let capitalizedOptionKey = optionKey.slice(0, 1).toUpperCase() + optionKey.slice(1);
let alsoOption = options["also" + capitalizedOptionKey];
if (alsoOption != null)
option = option.concat(alsoOption);
let notOption = options["not" + capitalizedOptionKey];
if (notOption != null)
option = option.filter(x => notOption.includes(x) == false);
options[optionKey] = option;
}
if ([ "wrapperElements", "halfWrapperElements" ].includes(optionKey) == false)
options[optionKey + "Selector"] = option.join(", ");
});
options.wrapperOptions = { };
let topFilter = (x => [ ...options.wrapperElements, ...options.halfWrapperElements ].includes(x) == false);
options.wrapperOptions["downOut"] = {
blockElementsSelector: options.blockElements.filter(topFilter).join(", "),
blockContainersSelector: options.blockContainers.filter(topFilter).join(", "),
wrappersSelector: [ ...options.wrapperElements, ...options.halfWrapperElements ].join(", ")
};
options.wrapperOptions["upIn"] = options.wrapperOptions["downOut"];
let bottomFilter = (x => options.wrapperElements.includes(x) == false);
options.wrapperOptions["downIn"] = {
blockElementsSelector: options.blockElements.filter(bottomFilter).join(", "),
blockContainersSelector: options.blockContainers.filter(bottomFilter).join(", "),
wrappersSelector: options.wrapperElements.join(", ")
};
options.wrapperOptions["upOut"] = options.wrapperOptions["downIn"];
GW.layout.optionsCache[cacheKey] = options;
return options;
}
/******************************************************************/
/* Generate element layout cache key for given action and options.
(Or, just use provided cache key, if any.)
*/
function generateCacheKey(action, options) {
return `${action} ${options.cacheKey}`;
}
/***************************************************************************/
/* Retrieve desired result from element’s layout cache, or calculate it and
store in element’s layout cache; and, in any case, return.
*/
function useLayoutCache(element, uniqueKey, options, f) {
options = processLayoutOptions(options);
let cacheKey = generateCacheKey(uniqueKey, options);
if ( (element.layoutCache?.time ?? 0) < GW.layout.currentPassBegin
|| element.layoutCache[cacheKey] == null) {
if ((element.layoutCache?.time ?? 0) < GW.layout.currentPassBegin)
element.layoutCache = { time: GW.layout.currentPassBegin };
element.layoutCache[cacheKey] = f(element, options);
}
return element.layoutCache[cacheKey];
}
/***************************************************************************/
/* Returns true if element is a wrapper of the given type, false otherwise.
Types: upOut, downOut, upIn, downIn
*/
function isWrapper(element, wrapperType, options) {
if (element == null)
return null;
return useLayoutCache(element, "isWrapper", options, (element, options) => {
return ( element?.matches(options.wrapperOptions[wrapperType].wrappersSelector) == true
&& element?.matches(options.wrapperOptions[wrapperType].blockElementsSelector) != true
&& element?.matches(options.wrapperOptions[wrapperType].blockContainersSelector) != true);
});
}
/*****************************************************************/
/* Returns true if element is a skipped element, false otherwise.
*/
function isSkipped(element, options) {
if (element == null)
return null;
return useLayoutCache(element, "isSkipped", options, (element, options) => {
return (element?.matches(options.skipElementsSelector) == true);
});
}
/**************************************************************/
/* Returns true if element is a layout block, false otherwise.
*/
function isBlock(element, options) {
if (element == null)
return null;
return useLayoutCache(element, "isBlock", options, (element, options) => {
return (element?.matches(options.blockElementsSelector) == true);
});
}
/***************************************************************************/
/* Returns true if element is an always-not-empty element, false otherwise.
*/
function isNonEmpty(element, options) {
if (element == null)
return null;
return useLayoutCache(element, "isNonEmpty", options, (element, options) => {
return (element?.matches(options.nonEmptyElementsSelector) == true);
});
}
/******************************************************************/
/* Returns nearest enclosing block container of the given element.
(Might be null.)
*/
function blockContainerOf(element, options) {
if (element == null)
return null;
return useLayoutCache(element, "blockContainer", options, (element, options) => {
return element.parentElement?.closest(options.blockContainersSelector);
});
}
/**************************************************************************/
/* Returns layout block sequential (next or previous) to the given element
in the block flow.
*/
function sequentialBlockOf(element, direction, options) {
if (element == null)
return null;
options = processLayoutOptions(options);
let siblingKey = direction + "ElementSibling";
let wrapperDirection = (direction == "next" ? "down" : "up");
let wrapperInType = wrapperDirection + "In";
let wrapperOutType = wrapperDirection + "Out";
let terminus = (direction == "next" ? "first" : "last");
// Skip elements that don’t participate in block flow.
if (isSkipped(element[siblingKey], options))
return sequentialBlockOf(element[siblingKey], direction, options);
// Look inside “transparent” wrappers (that don’t affect layout).
if (isWrapper(element[siblingKey], wrapperInType, options)) {
let terminalBlock = terminalBlockOf(element[siblingKey], terminus, options);
if (terminalBlock)
return terminalBlock;
}
// Skip empty elements.
if ( isNodeEmpty_metadataAware(element[siblingKey]) == true
&& isNonEmpty(element[siblingKey], options) == false)
return sequentialBlockOf(element[siblingKey], direction, options);
// An actual block element (the base case).
if (isBlock(element[siblingKey], options))
return element[siblingKey];
/* If we’re asked for the sequential block of the terminal child of a
transparent wrapper, we return the sequential block of that wrapper
(recursively, of course).
*/
if (isWrapper(element.parentElement, wrapperOutType, options))
return sequentialBlockOf(element.parentElement, direction, options);
return null;
}
/************************************************************************/
/* Returns layout block previous to the given element in the block flow.
(Might be null.)
*/
function previousBlockOf(element, options) {
if (element == null)
return null;
return useLayoutCache(element, "previousBlock", options, (element, options) => {
return sequentialBlockOf(element, "previous", options);
});
}
/************************************************************************/
/* Returns layout block next from the given element in the block flow.
(Might be null.)
*/
function nextBlockOf(element, options) {
if (element == null)
return null;
return useLayoutCache(element, "nextBlock", options, (element, options) => {
return sequentialBlockOf(element, "next", options);
});
}
/***************************************************************/
/* Returns terminal (first or last) layout block of an element.
(Might be the element itself, or null.)
*/
function terminalBlockOf(element, terminus, options, strictDescent = false) {
if (element == null)
return null;
options = processLayoutOptions(options);
let wrapperType = (terminus == "first" ? "down" : "up") + "In";
// Look inside wrappers (or any block, if strictDescent is specified).
if ( strictDescent == true
|| isWrapper(element, wrapperType, options)) {
let childBlocks = childBlocksOf(element, options);
for (let i = (terminus == "first" ? 0 : childBlocks.length - 1);
i != (terminus == "first" ? childBlocks.length : -1);
i += (terminus == "first" ? 1 : -1)) {
let terminalBlock = terminalBlockOf(childBlocks[i], terminus, options);
if ( terminalBlock
&& isSkipped(terminalBlock, options) == false
&& ( isNodeEmpty_metadataAware(terminalBlock) == false
|| isNonEmpty(terminalBlock, options) == true))
return terminalBlock;
}
}
// The element itself is a layout block (only if no strictDescent).
if ( strictDescent == false
&& isBlock(element, options))
return element;
return null;
}
/*******************************************/
/* Returns last layout block of an element.
(Might be the element itself, or null.)
*/
function lastBlockOf(element, options, strictDescent) {
if (element == null)
return null;
if (strictDescent) {
return terminalBlockOf(element, "last", options, true);
} else {
return useLayoutCache(element, "lastBlock", options, (element, options) => {
return terminalBlockOf(element, "last", options);
});
}
}
/********************************************/
/* Returns first layout block of an element.
(Might be the element itself, or null.)
*/
function firstBlockOf(element, options, strictDescent) {
if (element == null)
return null;
if (strictDescent) {
return terminalBlockOf(element, "first", options, true);
} else {
return useLayoutCache(element, "firstBlock", options, (element, options) => {
return terminalBlockOf(element, "first", options);
});
}
}
/***************************************************************************/
/* Returns all “child” blocks of an element (blocks that are descended from
the given element with no other blocks in the chain of descent; wrappers
don’t count).
*/
function childBlocksOf(element, options) {
if (element == null)
return null;
return useLayoutCache(element, "childBlocks", options, (element, options) => {
options = processLayoutOptions(options);
let childBlocks = Array.from(element.children);
for (let i = 0; i < childBlocks.length; i++) {
if (isWrapper(childBlocks[i], "downIn", options)) {
childBlocks.splice(i, 1, ...childBlocks[i].children);
i--;
} else if (isBlock(childBlocks[i], options) == false) {
childBlocks.splice(i, 1);
i--;
}
}
return childBlocks;
});
}
/****************************************************************************/
/* Returns true if the element is a “bare wrapper”, i.e. a <div> or <span>
with no classes (or, in the <div> case, possibly just the ‘block’ class);
false otherwise.
*/
function isBareWrapper(element) {
return ( ( element.tagName == "DIV"
&& ( element.className.trim() == ""
|| element.className.trim() == "block"))
|| ( element.tagName == "SPAN"
&& element.className.trim() == ""));
}
/**************************************************************************/
/* Returns assembled and appropriately prefixed selector from given parts.
*/
function selectorizeForContainer(container) {
if (container instanceof DocumentFragment)
return (parts) => (parts);
else
return (parts) => (parts.map(part => (part == ".markdownBody" ? part : `.markdownBody ${part}`)).join(", "));
}
/***************************************************************/
/* Returns tag_name#id.class1.class2.class3 of a given element.
*/
function elementSummaryString(element) {
return ( element.tagName.toLowerCase()
+ (element.id ? `#${element.id}` : ``)
+ (Array.from(element.classList).map(x => `.${x}`).join("")));
}
/********************************************************/
/* Returns block spacing multiplier for the given block.
*/
function getBlockSpacingMultiplier(block, debug = false) {
let predicateFromSelector = (selector) => {
let parts = selector.match(/^(.+) \+ (.+)$/);
if (parts) {
/* Headings do not normally count as layout blocks, but they do
here (unless it’s a heading of a collapse section, in which case
it still doesn’t count as a layout block).
*/
return (block) => ( previousBlockOf(block, {
alsoBlockElements: [ "section:not(.collapse) > .heading" ],
cacheKey: "alsoBlocks_nonCollapseSectionHeadings"
})?.matches(parts[1])
&& block.matches(parts[2]));
} else {
return (block) => block.matches(selector);
}
};
let predicateMatches = (predicate, block) => {
if (typeof predicate == "string")
predicate = predicateFromSelector(predicate);
if ( typeof predicate == "object"
&& predicate instanceof Array) {
let predicateArray = predicate;
predicate = (block) => {
return (predicateArray.findIndex(x => predicateMatches(x, block)) != -1);
};
}
return (predicate(block) == true);
};
if (debug)
console.log(block);
for (let [ predicate, result, adjustable = true ] of GW.layout.blockSpacing) {
if (predicateMatches(predicate, block)) {
if (debug)
console.log(predicate);
let bsm = (typeof result == "function")
? result(block)
: result;
if (adjustable) {
for (let [ predicate, transform ] of GW.layout.blockSpacingAdjustments)
if (predicateMatches(predicate, block)) {
if (debug)
console.log(predicate);
bsm = Math.max(0, transform(bsm, block));
}
}
return bsm;
}
}
return undefined;
}
/*****************************************************************************/
/* Returns a block’s dropcap type (‘goudy’, ‘yinit’, etc.), or null if none.
*/
function dropcapTypeOf(block) {
return Array.from(block.classList).find(cssClass => /^dropcaps?-/.test(cssClass))?.replace(/^dropcaps-/, "dropcap-")?.slice("dropcap-".length);
}
/******************************************************************************/
/* Adds a dropcap class to a block. Dropcaps may be ‘kanzlei’, ‘de-zs’, etc.
(See default.css for the list.)
*/
function addDropcapClassTo(block, dropcapType) {
if (block.classList.contains("force-dropcap"))
return;
stripDropcapClassesFrom(block);
block.classList.add(`dropcap-${dropcapType}`);
}
/*************************************/
/* Strip dropcap classes from block.
*/
function stripDropcapClassesFrom(block) {
if (block.classList.contains("force-dropcap"))
return;
block.classList.remove(...(Array.from(block.classList).filter(className => className.startsWith("dropcap-"))));
}
/**************************************************************************/
/* Like paragraphizeTextNodesOfElement, but retains elements with metadata
(an ID, non-layout classes, or any data attributes), as well as links,
<br> elements, and lists.
*/
function paragraphizeTextNodesOfElementRetainingMetadata(element) {
paragraphizeTextNodesOfElement(element, {
nodeOmissionOptions: {
alsoExcludePredicate: GW.layout.emptyNodeExclusionPredicate,
alsoExcludeSelector: "a, br, ul, ol",
excludeIdentifiedElements: true
}
});
}
/*****************************************************************************/
/* Like isNodeEmpty, but does not count elements with metadata as being empty
(i.e., if they have an ID, or non-layout classes, or any data attributes).
*/
function isNodeEmpty_metadataAware(node) {
return isNodeEmpty(node, {
alsoExcludePredicate: GW.layout.emptyNodeExclusionPredicate,
excludeIdentifiedElements: true
});
}
/*********************/
/* LAYOUT PROCESSORS */
/*********************/
/*************************************************************************/
/* Apply block layout classes to appropriate elements in given container.
*/
addLayoutProcessor("applyBlockLayoutClassesInContainer", (container) => {
let selectorize = selectorizeForContainer(container);
// Designate headings.
container.querySelectorAll(selectorize(range(1, 6).map(x => `h${x}`))).forEach(heading => {
heading.classList.add("heading");
});
// Designate floats (on non-mobile layouts).
let floatClasses = [
".float-left",
".float-right"
];
if (GW.mediaQueries.mobileWidth.matches == false) {
container.querySelectorAll(selectorize(floatClasses)).forEach(floatBlock => {
floatBlock.classList.add("float");
});
} else {
container.querySelectorAll(selectorize(floatClasses)).forEach(floatBlock => {
floatBlock.classList.remove("float");
});
}
// Designate lists.
container.querySelectorAll(selectorize([
"ul",
"ol"
])).forEach(list => {
list.classList.add("list");
});
// Designate float-containing lists.
container.querySelectorAll(".markdownBody li .float").forEach(floatBlock => {
let options = {
alsoBlockContainers: [ ".list" ],
cacheKey: "alsoBlockContainers_lists"
};
let container = blockContainerOf(floatBlock, options);
while (container?.matches(".list")) {
container.classList.add("has-floats");
container = blockContainerOf(container, options);
}
});
// Designate “big lists”.
/* If any of a list’s list items have multiple non-list children, then
it is a “big list” (with consequences for block spacing).
*/
let listItemChildBlocksOptions = {
notWrapperElements: [ ".list" ],
cacheKey: "notWrappers_lists"
};
let isBigList = (list) => {
if (list.matches(".list") != true)
return false;
for (let listItem of list.children) {
if (childBlocksOf(listItem, listItemChildBlocksOptions).filter(x => x.matches(".list") != true).length > 1)
return true;
}
return false;
};
container.querySelectorAll(".list").forEach(list => {
let bigList = isBigList(list);
/* If this is a sub-list, and any other sub-lists on the same level as
this one are “big lists”, then this is also a “big list” (because
the designation of “bigness” is applied to *list levels within a
list tree*, not to individual lists).
*/
let container = blockContainerOf(list, {
alsoBlockContainers: [ "li" ],
cacheKey: "alsoBlockContainers_listItems"
});
if (container?.matches("li")) {
for (let listItem of container.parentElement.children) {
if (childBlocksOf(listItem, listItemChildBlocksOptions).findIndex(x => isBigList(x)) != -1) {
bigList = true;
break;
}
}
}
list.classList.toggle("big-list", bigList);
});
// Disable triptychs on mobile layouts.
container.querySelectorAll(selectorize([ ".triptych" ])).forEach(triptych => {
/* Why “aptych”? Because on mobile it is laid out in one column
instead of three, making it “un-folded”:
https://old.reddit.com/r/AncientGreek/comments/ypts2o/polyptychs_help_with_a_word/
*/
triptych.classList.toggle("aptych", GW.mediaQueries.mobileWidth.matches);
});
// Apply special block sequence classes.
container.querySelectorAll(selectorize(GW.layout.blockElements)).forEach(block => {
if (block.closest(GW.layout.blockLayoutExclusionSelector))
return;
/* Designate blocks preceded by nothing (not counting floats and other
elements that do not participate in block flow) in their block
container (the .first-block class).
Headings do not normally count as layout blocks, but they do here
(unless it’s a heading of a collapse section, in which case it still
doesn’t count as a layout block).
*/
block.classList.toggle("first-block", previousBlockOf(block, {
alsoBlockElements: [ "section:not(.collapse) > .heading" ],
cacheKey: "alsoBlocks_nonCollapseSectionHeadings"
}) == null);
// Designate blocks in lists (the .in-list class).
block.classList.toggle("in-list", blockContainerOf(block, {
alsoBlockContainers: [ "li" ],
cacheKey: "alsoBlockContainers_listItems"
})?.matches("li") == true);
// Apply special paragraph classes.
if (block.matches("p") == true) {
// Empty paragraphs (the .empty-graf class; not displayed).
let emptyGraf = isNodeEmpty_metadataAware(block);
block.classList.toggle("empty-graf", emptyGraf);
if (emptyGraf)
return;
/* Paragraphs not preceded directly by other paragraphs
(not in lists) (the .first-graf class).
*/
let firstGraf = false;
let previousBlockSelector = [
":not(p)",
".text-center",
".section-metadata",
".margin-notes-block",
".page-description-annotation",
".data-field",
".admonition-title > p"