-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathcollapse.js
979 lines (827 loc) · 35.3 KB
/
collapse.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
/*************************/
/* Configuration / state.
*/
GW.collapse = {
/* Visibility of block collapse labels depends on how many times the user
has used them already.
*/
alwaysShowCollapseInteractionHints: (getSavedCount("clicked-to-expand-collapse-block-count") < (GW.isMobile() ? 6 : 3)),
showCollapseInteractionHintsOnHover: ( GW.isMobile() == false
&& getSavedCount("clicked-to-expand-collapse-block-count") < 6),
/* Hover events (see below).
*/
hoverEventsEnabled: (GW.isMobile() == false),
hoverEventsActive: (GW.isMobile() == false)
};
/****************************************************************************/
/* On desktop, disable hover events on scroll; re-enable them on mouse move.
*/
if (GW.collapse.hoverEventsEnabled) {
// Disable on scroll.
addScrollListener(GW.collapse.disableCollapseHoverEventsOnScroll = (event) => {
GW.collapse.hoverEventsActive = false;
}, {
name: "disableCollapseHoverEventsOnScrollListener"
});
/* Add event handler to add scroll listener to spawned popups, to
disable hover events when scrolling within a popup.
*/
GW.notificationCenter.addHandlerForEvent("Popups.popupDidSpawn", GW.collapse.addDisableHoverEventsOnScrollListenerOnPopupSpawned = (info) => {
addScrollListener(GW.collapse.disableCollapseHoverEventsOnScroll, {
target: info.popup.scrollView
});
});
// Enable on mousemove.
addMousemoveListener(GW.collapse.enableCollapseHoverEventsOnMousemove = (event) => {
GW.collapse.hoverEventsActive = true;
}, {
name: "enableCollapseHoverEventsOnMousemoveListener"
});
}
/******************************************************************************/
/* Expand all collapse blocks containing the given node, if any (including the
node itself, if it is a collapse block). Returns true if any such expansion
occurred.
Available option fields:
fireStateChangedEvent (boolean)
Fire a `Collapse.collapseStateDidChange` event after all (possibly
recursive) expansion is completed. (Only one event fired per
non-recursive call to expandCollapseBlocksToReveal(), even if recursive
expansion occurred.)
*/
function expandCollapseBlocksToReveal(node, options) {
GWLog("expandCollapseBlocksToReveal", "collapse.js", 2);
options = Object.assign({
fireStateChangedEvent: true
}, options);
if (node == null)
return;
// If the node is not an element (e.g. a text node), get its parent element.
let element = node instanceof HTMLElement ? node : node.parentElement;
/* If the given element is not within any collapsed block, there is nothing
to do.
*/
if (isWithinCollapsedBlock(element) == false)
return false;
// Determine if nearest collapse block needs expanding.
let collapseBlock = element.closest(".collapse");
let expand = (isCollapsed(collapseBlock) == true);
/* Expand any higher-level collapse blocks.
Fire state change event only if we will not have to expand this block
(otherwise we’ll do redundant layout).
*/
let expandedAncestor = expandCollapseBlocksToReveal(collapseBlock.parentElement, {
fireStateChangedEvent: (expand == false)
});
if (expand) {
// Expand nearest collapse block.
toggleCollapseBlockState(collapseBlock, expand);
/* Fire state change event only if we will not have to do any more
expansion (otherwise we’ll do redundant layout).
*/
if (options.fireStateChangedEvent) {
GW.notificationCenter.fireEvent("Collapse.collapseStateDidChange", {
source: "expandCollapseBlocksToReveal",
collapseBlock: collapseBlock
});
}
}
// Report whether we had to expand a collapse block.
return (expand || expandedAncestor);
}
/******************************************************************************/
/* Collapse the specified collapse block and all collapse blocks nested within
it, if any.
Available option fields:
fireStateChangedEvent (boolean)
Fire a `Collapse.collapseStateDidChange` event after all (possibly
recursive) collapsing is completed. (Only one event fired per
non-recursive call to expandCollapseBlocksToReveal(), even if recursive
collapsing occurred.)
*/
function collapseCollapseBlock(collapseBlock, options) {
GWLog("collapseCollapseBlock", "collapse.js", 2);
options = Object.assign({
fireStateChangedEvent: true
}, options);
if (isCollapsed(collapseBlock))
return;
/* Collapse any nested collapse blocks. Fire no state change events when
doing so; we will fire a single event, once we’ve collapsed the
specified collapse block, after all of its nested collapse blocks are
collapsed.
*/
collapseBlock.querySelectorAll(".collapse").forEach(nestedCollapseBlock => {
collapseCollapseBlock(nestedCollapseBlock, {
fireStateChangedEvent: false
});
});
// Collapse block.
toggleCollapseBlockState(collapseBlock, false);
// Fire event, if need be.
if (options.fireStateChangedEvent) {
GW.notificationCenter.fireEvent("Collapse.collapseStateDidChange", {
source: "collapseCollapseBlock",
collapseBlock: collapseBlock
});
}
}
/*******************************************************************/
/* Returns true if the given collapse block is currently collapsed.
*/
function isCollapsed(collapseBlock) {
if (collapseBlock.classList.contains("expanded"))
return false;
if (collapseBlock.classList.contains("expanded-not"))
return true;
return undefined;
}
/*****************************************************************************/
/* Returns true if the given element is within a currently-collapsed collapse
block.
*/
function isWithinCollapsedBlock(element) {
/* If the element is not within a collapse block at all, it obviously can't
be within a *currently-collapsed* collapse block.
*/
let collapseParent = element.closest(".collapse");
if (collapseParent == null)
return false;
/* If the element is within a collapse block and that collapse block is
currently collapsed, then the condition is satisfied...
*/
if ( isCollapsed(collapseParent) == true
|| isCollapsed(collapseParent) == undefined)
return true;
/* BUT the collapse block that the element is in, even if *it* is not
itself collapsed, could be *within* another collapse block!
*/
return isWithinCollapsedBlock(collapseParent.parentElement);
}
/************************************************************************/
/* Returns true iff element’s immediate children include any block-level
elements.
*/
function containsBlockChildren(element) {
for (child of element.children) {
if ([ "DIV", "P", "UL", "LI", "SECTION", "BLOCKQUOTE", "FIGURE" ].includes(child.tagName))
return true;
if ( child.tagName == "A"
&& Transclude.isIncludeLink(child))
return true;
}
return false
}
/****************************************************************************/
/* Constructs and returns a disclosure button.
Available option fields:
block (boolean)
If `true`, the constructed button is for a block collapse; otherwise,
the button is for an inline collapse.
start (boolean)
If `true`, the button is for placement at the start of an inline
collapse; otherwise, the button is for placement at the end of an
inline collapse. (Ignored for block collapse buttons.)
*/
function newDisclosureButton(options) {
options = Object.assign({
block: true,
start: true
}, options);
let className = "disclosure-button" + (options.block ? "" : (" " + (options.start ? "start" : "end")));
let disclosureButtonHTML = `<button type="button" class="${className}" tabindex="-1" aria-label="Open/close collapsed section">`;
if (options.block) {
disclosureButtonHTML += `<span class="part top">`
+ `<span class="label"></span>`
+ `<span class="icon">`
+ GW.svg("chevron-left-solid")
+ `</span>`
+ `</span>`
+ `<span class="part bottom">`
+ `<span class="label"></span>`
+ `<span class="icon">`
+ GW.svg("chevron-left-solid")
+ `</span>`
+ `</span>`;
} else {
disclosureButtonHTML += `<span class="icon">`
+ (options.start
? GW.svg("bracket-square-left-sharp-light")
: ( GW.svg("angle-right-regular")
+ GW.svg("bracket-square-right-sharp-light")))
+ `</span>`;
}
disclosureButtonHTML += `</button>`;
return elementFromHTML(disclosureButtonHTML);
}
/****************************************************************************/
/* Before preparing collapse blocks, rectify collapse abstract tag mismatch,
namely cases where a div.abstract (or a section.abstract, etc.) has a
span.abstract-collapse; also fix erroneous HTML structure caused by
well-meaning but misguided Pandoc HTML structure rectification (namely,
wrapping a span.collapse in a <p>) applied to such cases.
*/
addContentLoadHandler(GW.contentLoadHandlers.preprocessMismatchedCollapseHTML = (eventInfo) => {
GWLog("preprocessMismatchedCollapseHTML", "collapse.js", 1);
let possiblyMismatchedAbstractCollapseBlockTags = [
"div",
"section"
];
let possiblyMismatchedAbstractSelector = possiblyMismatchedAbstractCollapseBlockTags.map(tagSelector =>
`${tagSelector}.collapse span.abstract-collapse`
).join(", ");
eventInfo.container.querySelectorAll(possiblyMismatchedAbstractSelector).forEach(possiblyMismatchedAbstract => {
let containingCollapse = possiblyMismatchedAbstract.closest(".collapse");
if (possiblyMismatchedAbstractCollapseBlockTags.includes(containingCollapse.tagName.toLowerCase())) {
possiblyMismatchedAbstract.parentElement.parentElement.insertBefore(possiblyMismatchedAbstract, possiblyMismatchedAbstract.parentElement);
rewrapContents(possiblyMismatchedAbstract, "div", {
moveClasses: true
});
}
});
}, "rewrite");
/***********************************************************************/
/* Inject disclosure buttons and otherwise prepare the collapse blocks.
*/
addContentLoadHandler(GW.contentLoadHandlers.prepareCollapseBlocks = (eventInfo) => {
GWLog("prepareCollapseBlocks", "collapse.js", 1);
// Construct all collapse blocks (in correct final state).
eventInfo.container.querySelectorAll(".collapse").forEach(collapseBlock => {
// Compensate for Pandoc putting .collapse class on headings.
if ([ "H1", "H2", "H3", "H4", "H5", "H6" ].includes(collapseBlock.tagName)) {
collapseBlock.classList.remove("collapse");
if (collapseBlock.className == "")
collapseBlock.removeAttribute("class");
return;
}
let startExpanded = (collapseBlock.contains(getHashTargetedElement()) == true);
// The collapse block might already be prepared.
if (isCollapsed(collapseBlock) != undefined) {
if (isCollapsed(collapseBlock) == startExpanded)
collapseWrapper.swapClasses([ "expanded", "expanded-not" ], startExpanded ? 0 : 1);
return;
}
if (GW.collapse.hoverEventsEnabled)
collapseBlock.classList.add("expand-on-hover");
let collapseWrapper;
let wrapOptions = {
useExistingWrapper: true,
moveClasses: [ "collapse", "expand-on-hover" ]
};
let bareContentSelector = [
"p",
".list"
].join(", ");
if ([ "DIV", "SECTION", "SPAN", "A" ].includes(collapseBlock.tagName)) {
// Handle collapse-inducing include-links.
if (collapseBlock.tagName == "A")
collapseBlock = wrapElement(wrapElement(collapseBlock, "p", wrapOptions), "div", wrapOptions);
// No additional wrapper needed for these tag types.
collapseWrapper = collapseBlock;
// Check for empty collapses; if empty, log error and do nothing.
if (isNodeEmpty(collapseWrapper)) {
let collapseWrapperTagName = collapseWrapper.tagName.toLowerCase()
GWServerLogError(eventInfo.loadLocation.href + `--empty-collapse-${collapseWrapperTagName}`,
`empty collapse element (${collapseWrapperTagName})`);
return;
}
/* Rewrap spans that are NOT inline collapses (i.e., those that
are, for some reason, wrapping block-level content).
*/
if ( collapseWrapper.tagName == "SPAN"
&& containsBlockChildren(collapseWrapper))
collapseWrapper = rewrapContents(collapseWrapper, "div", {
useExistingWrapper: true,
moveClasses: true
});
// Designate collapse type (block or inline).
if ([ "SPAN" ].includes(collapseWrapper.tagName))
collapseWrapper.classList.add("collapse-inline");
else
collapseWrapper.classList.add("collapse-block");
/* Abstracts (the .abstract class) can end up in collapses
without this being known in advance, so may not have the
.abstract-collapse class, as they should.
*/
let collapseAbstract = collapseWrapper.querySelector(".collapse > .abstract");
if (collapseAbstract?.closest(".collapse") == collapseWrapper)
collapseAbstract.classList.add("abstract-collapse");
// Ensure correct structure and classes of abstracts.
collapseAbstract = collapseWrapper.querySelector(".collapse > .abstract-collapse");
if (collapseAbstract?.closest(".collapse") == collapseWrapper) {
// Mark those collapse blocks that have abstracts.
collapseWrapper.classList.add("has-abstract");
// Wrap bare text nodes and inline elements in <p> elements.
if (collapseWrapper.classList.contains("collapse-block"))
paragraphizeTextNodesOfElementRetainingMetadata(collapseAbstract);
// Make sure “real” abstracts are marked as such.
if ( collapseWrapper.classList.contains("collapse-block")
&& collapseAbstract.firstElementChild?.tagName == "BLOCKQUOTE")
collapseAbstract.classList.add("abstract");
} else {
if (collapseWrapper.classList.contains("collapse-inline")) {
/* Add default abstract (just an ellipsis) to inline
collapses that have no abstract.
*/
collapseWrapper.insertBefore(collapseAbstract = newElement("span", {
class: "abstract-collapse-only"
}, {
innerHTML: " …"
}), collapseWrapper.firstChild);
// Mark with a special class.
collapseWrapper.classList.add("collapse-inline-special");
} else {
// Mark those collapse blocks that have no abstracts.
collapseWrapper.classList.add("no-abstract");
}
}
// Designate “bare content” collapse blocks.
if ( collapseWrapper.classList.contains("collapse-block") == true
&& collapseWrapper.classList.contains("bare-content-not") == false) {
if ( collapseWrapper.firstElementChild.matches(bareContentSelector)
|| ( collapseWrapper.classList.contains("has-abstract")
&& collapseWrapper.querySelector(".abstract-collapse").firstElementChild.matches(bareContentSelector)))
collapseWrapper.classList.add("bare-content");
}
} else {
/* Additional wrapper is required for most tag types. We use a
block collapse here. Collapse blocks of this type never have
abstracts.
*/
collapseWrapper = wrapElement(collapseBlock, "div.collapse-block.no-abstract", wrapOptions);
// Designate “bare content” collapse blocks.
if (collapseWrapper.firstElementChild.matches(bareContentSelector))
collapseWrapper.classList.add("bare-content");
}
// Slight HTML structure rectification.
if ( collapseWrapper.parentElement
&& [ "P" ].includes(collapseWrapper.parentElement.tagName) == true
&& [ "SPAN" ].includes(collapseWrapper.tagName) == false
&& isOnlyChild(collapseWrapper))
unwrap(collapseWrapper.parentElement);
// Construct collapse content wrapper.
let collapseContentWrapperTagName = collapseWrapper.tagName == "SPAN" ? "SPAN" : "DIV";
let collapseContentWrapper = newElement(collapseContentWrapperTagName, { "class": "collapse-content-wrapper" });
let childNodesArray = Array.from(collapseWrapper.childNodes);
collapseContentWrapper.append(...childNodesArray.slice(childNodesArray.findLastIndex(node => {
return ( node instanceof Element
&& node.matches(".heading, .abstract-collapse, .abstract-collapse-only"));
}) + 1));
collapseWrapper.append(collapseContentWrapper);
// Inject the disclosure button.
if (collapseWrapper.classList.contains("collapse-inline")) {
// Additional wrapper for inline collapses.
let collapseContentOuterWrapper = wrapElement(collapseContentWrapper, "span.collapse-content-outer-wrapper");
// Button at start.
collapseContentOuterWrapper.insertBefore(newDisclosureButton({ block: false, start: true }),
collapseContentOuterWrapper.firstChild);
// Button at end.
collapseContentOuterWrapper.insertBefore(newDisclosureButton({ block: false, start: false }),
null);
} else {
collapseWrapper.insertBefore(newDisclosureButton({ block: true }),
collapseContentWrapper);
}
// Inject the size indicator.
let icebergWhere = collapseWrapper.classList.contains("collapse-block")
? collapseWrapper.querySelector(".disclosure-button")
: collapseWrapper.querySelector(".disclosure-button.end");
icebergWhere.appendChild(newElement("SPAN", {
"class": "collapse-iceberg-indicator graf-content-not"
}));
// Mark as expanded, if need be.
collapseWrapper.swapClasses([ "expanded", "expanded-not" ], startExpanded ? 0 : 1)
// Fire event.
if (startExpanded) {
GW.notificationCenter.fireEvent("Collapse.collapseStateDidChange", {
source: "prepareCollapseBlocks",
collapseBlock: collapseWrapper
});
}
});
}, "rewrite");
/*****************************************************************************/
/* Ensure that top part of disclosure button (including chevron icon) matches
height of section heading text, for section collapses.
*/
addContentInjectHandler(GW.contentInjectHandlers.rectifySectionCollapseLayout = (eventInfo) => {
GWLog("rectifySectionCollapseLayout", "collapse.js", 1);
eventInfo.container.querySelectorAll("section.collapse").forEach(section => {
section.style.removeProperty("--collapse-toggle-top-height");
section.style.removeProperty("--collapse-toggle-top-icon-size");
requestIdleCallback(() => {
let rects = Array.from(section.firstElementChild.querySelector("a").getClientRects());
let oneLineHeight = rects.first?.height ?? 0;
let totalHeight = rects.reduce((h, r) => h + r.height, 0);
if ( oneLineHeight == 0
|| totalHeight == 0)
return;
section.style.setProperty("--collapse-toggle-top-height", Math.round(totalHeight + oneLineHeight * 0.15) + "px");
section.style.setProperty("--collapse-toggle-top-icon-size", Math.round(oneLineHeight * 1.15) + "px");
GW.notificationCenter.fireEvent("Collapse.collapseStateDidChange", {
source: "Collapse.rectifySectionCollapseLayout",
collapseBlock: section
});
});
});
}, ">rewrite");
/******************************************************************************/
/* Collapse all expanded collapse blocks. (Mostly relevant when popping up
sections of an already-displayed full page, which may have collapses in it,
which have already been expanded, but which we do not want to be expanded
when the sections containing them appear in a new context.)
*/
addContentInjectHandler(GW.contentInjectHandlers.collapseExpandedCollapseBlocks = (eventInfo) => {
GWLog("collapseExpandedCollapseBlocks", "collapse.js", 1);
eventInfo.container.querySelectorAll(".collapse.expanded").forEach(collapseCollapseBlock);
}, "<eventListeners");
/*****************************************************************************/
/* Updates disclosure button label for current UI state.
Available option fields:
showLabels (boolean)
If `true`, disclosure button labels are visible by default. (Applies
only to block collapses, as inline collapses have no disclosure button
labels.)
NOTE: This option is ignored if
GW.collapse.alwaysShowCollapseInteractionHints is `true`.
*/
function updateDisclosureButtonState(collapseBlock, options) {
GWLog("updateDisclosureButtonState", "collapse.js", 2);
options = Object.assign({
showLabels: false
}, options);
let action = GW.isMobile() ? "Tap" : "Click";
let labelText = isCollapsed(collapseBlock)
? `${action} to expand`
: `${action} to collapse`;
if (collapseBlock.classList.contains("collapse-block")) {
let disclosureButton = collapseBlock.querySelector(".disclosure-button");
disclosureButton.querySelectorAll(".part .label").forEach(label => {
label.innerHTML = labelText;
});
disclosureButton.classList.toggle("labels-visible", options.showLabels || GW.collapse.alwaysShowCollapseInteractionHints);
} else { // Inline collapse.
collapseBlock.querySelectorAll(".disclosure-button").forEach(disclosureButton => {
disclosureButton.title = labelText;
});
}
let icebergIndicator = collapseBlock.querySelector(".collapse-iceberg-indicator");
let progressPercentage = 100;
if (isCollapsed(collapseBlock)) {
if (collapseBlock.classList.contains("collapse-block")) {
if (collapseBlock.classList.contains("no-abstract")) {
let collapsedContentHeight = collapseBlock.querySelector(".collapse-content-wrapper").clientHeight;
let contentHeight = Array.from(collapseBlock.querySelector(".collapse-content-wrapper").children).reduce((h, c) => h + c.clientHeight, 0);
progressPercentage = Math.round(100 * Math.min(1, collapsedContentHeight / contentHeight));
} else {
let abstractHeight = collapseBlock.querySelector(".abstract-collapse").clientHeight;
let contentHeight = Array.from(collapseBlock.querySelector(".collapse-content-wrapper").children).reduce((h, c) => h + c.clientHeight, 0);
progressPercentage = Math.round(100 * abstractHeight / (abstractHeight + contentHeight));
}
} else {
let abstractLength = collapseBlock.querySelector(".abstract-collapse, .abstract-collapse-only").textContent.length;
let contentLength = collapseBlock.querySelector(".collapse-content-wrapper").textContent.length;
progressPercentage = Math.round(100 * abstractLength / (abstractLength + contentLength));
}
}
icebergIndicator.dataset.progressPercentage = progressPercentage;
renderProgressPercentageIcon(icebergIndicator);
}
/***************************************/
/* Expand or collapse a collapse block.
*/
function toggleCollapseBlockState(collapseBlock, expanding) {
// Set proper classes.
collapseBlock.swapClasses([ "expanded", "expanded-not" ], expanding ? 0 : 1);
// Update label text and other HTML-based UI state.
updateDisclosureButtonState(collapseBlock, {
showLabels: GW.collapse.showCollapseInteractionHintsOnHover
});
/* Compensate for block indentation due to nesting (e.g., lists).
(Don’t do this for full-width collapses, as the full-width code will
already apply suitable side margins.)
(Also don’t do this for collapses in blockquotes, which get treated
specially.)
*/
if ( collapseBlock.classList.contains("collapse-block")
&& collapseBlock.closest("blockquote") == null
&& collapseBlock.querySelector(".collapse-content-wrapper").classList.contains("width-full") == false) {
if (expanding) {
let collapseContentWrapper = collapseBlock.querySelector(".collapse-content-wrapper");
let contentColumn = collapseBlock.closest(".sidenote, .markdownBody");
if (contentColumn.matches(".sidenote"))
return;
let contentRect = collapseContentWrapper.getBoundingClientRect();
let enclosingContentRect = contentColumn.getBoundingClientRect();
let collapseLeftOffsetPx = getComputedStyle(collapseBlock).getPropertyValue("--collapse-left-offset");
let floatOffset = 0;
// Compensate for TOC.
if ( collapseBlock.tagName != "SECTION"
&& contentColumn.id == "markdownBody") {
let TOC = document.querySelector("#TOC");
if (TOC) {
let TOCRect = TOC.getBoundingClientRect();
if (TOCRect.bottom > contentRect.top) {
floatOffset = Math.round( TOCRect.width
+ parseInt(getComputedStyle(TOC).marginRight)
+ parseInt(getComputedStyle(collapseBlock).paddingLeft));
}
}
}
collapseBlock.style.marginLeft = `calc(${(enclosingContentRect.x - contentRect.x)}px - ${collapseLeftOffsetPx} + ${floatOffset}px)`;
} else { // if (collapsing)
collapseBlock.style.marginLeft = "";
}
}
}
/*************************************************/
/* Add event listeners to the disclosure buttons.
*/
addContentInjectHandler(GW.contentInjectHandlers.activateCollapseBlockDisclosureButtons = (eventInfo) => {
GWLog("activateCollapseBlockDisclosureButtons", "collapse.js", 1);
// Add listeners to collapse block disclosure buttons.
eventInfo.container.querySelectorAll(".disclosure-button").forEach(disclosureButton => {
if (disclosureButton.actionHandler)
return;
let collapseBlock = disclosureButton.closest(".collapse");
updateDisclosureButtonState(collapseBlock);
disclosureButton.addActivateEvent(disclosureButton.actionHandler = (event) => {
GWLog("Collapse.collapseBlockDisclosureButtonActivated", "collapse.js", 2);
// Nullify accidental late clicks in block collapses.
if ( collapseBlock.classList.contains("collapse-block")
&& collapseBlock.classList.contains("just-auto-expanded"))
return;
// Expanding? Collapsing? (For readability and consistency.)
let expanding = (isCollapsed(collapseBlock) == true);
let collapsing = (isCollapsed(collapseBlock) == false);
// Keep count of clicks to uncollapse.
if ( expanding
&& collapseBlock.classList.contains("collapse-block")
&& event.type == "click")
incrementSavedCount("clicked-to-expand-collapse-block-count");
// Expand or collapse.
toggleCollapseBlockState(collapseBlock, expanding);
/* If a collapse block was collapsed from the bottom, it might now
be up off the screen. Scroll it into view.
*/
if ( collapsing
&& isOnScreen(collapseBlock) == false)
scrollElementIntoView(collapseBlock);
/* If a collapse block was expanded from the bottom, the top of the
collapse block might be up off the screen. Scroll it into view.
*/
else if ( expanding
&& collapseBlock.getBoundingClientRect().top < 0)
scrollElementIntoView(collapseBlock);
// Update temporary state.
if ( collapseBlock.classList.contains("expand-on-hover")
&& GW.collapse.hoverEventsEnabled) {
let tempClass = null;
switch (event.type) {
case "click":
tempClass = "just-clicked"; break;
case "mouseenter":
tempClass = "just-auto-expanded"; break;
}
if (tempClass) {
collapseBlock.classList.add(tempClass);
collapseBlock.addEventListener("mouseleave", (event) => {
collapseBlock.classList.remove(tempClass);
}, { once: true });
}
}
GW.notificationCenter.fireEvent("Collapse.collapseStateDidChange", {
source: "Collapse.collapseBlockDisclosureButtonStateChanged",
collapseBlock: collapseBlock
});
});
// Collapse block expand-on-hover.
if ( collapseBlock.classList.contains("expand-on-hover")
&& GW.collapse.hoverEventsEnabled) {
collapseBlock.addEventListener("mouseenter", (event) => {
if (GW.collapse.hoverEventsActive == false) {
collapseBlock.classList.add("hover-not");
} else {
collapseBlock.classList.remove("hover-not");
}
});
onEventAfterDelayDo(collapseBlock, "mouseenter", 1000, (event) => {
if (GW.collapse.hoverEventsActive == false)
return;
if (isCollapsed(collapseBlock) == false)
return;
if (collapseBlock.classList.contains("just-clicked"))
return;
disclosureButton.actionHandler(event);
}, {
cancelOnEvents: [ "mouseleave", "mousedown" ]
});
}
// On-hover state changes.
if (GW.collapse.hoverEventsEnabled) {
// Add listener to show labels on hover, if need be.
if ( collapseBlock.classList.contains("collapse-block")
&& GW.collapse.showCollapseInteractionHintsOnHover == true
&& GW.collapse.alwaysShowCollapseInteractionHints == false) {
disclosureButton.addEventListener("mouseenter", (event) => {
if (GW.collapse.hoverEventsActive == false)
return;
updateDisclosureButtonState(collapseBlock, {
showLabels: true
});
});
disclosureButton.addEventListener("mouseleave", (event) => {
if (GW.collapse.hoverEventsActive == false)
return;
updateDisclosureButtonState(collapseBlock);
});
}
// Add listeners to highlight counterpart at other end.
if ( collapseBlock.classList.contains("collapse-inline")
&& disclosureButton.classList.containsAnyOf([ "start", "end" ])) {
let counterpart = disclosureButton.classList.contains("end")
? collapseBlock.querySelector(".disclosure-button")
: collapseBlock.querySelector(".collapse-content-wrapper").nextElementSibling;
disclosureButton.addEventListener("mouseenter", (event) => {
if (GW.collapse.hoverEventsActive == false)
return;
counterpart.classList.add("hover");
});
disclosureButton.addEventListener("mouseleave", (event) => {
if (GW.collapse.hoverEventsActive == false)
return;
counterpart.classList.remove("hover");
});
}
}
});
}, "eventListeners");
/************************************************************************/
/* Permanently expand a collapse block and remove its disclosure button.
*/
function expandLockCollapseBlock(collapseBlock) {
// Remove disclosure button.
collapseBlock.querySelector(".disclosure-button").remove();
// Expand.
let wasCollapsed = (isCollapsed(collapseBlock) == true);
// Strip collapse-specific classes.
collapseBlock.classList.remove("collapse", "collapse-block", "collapse-inline", "expanded", "expanded-not", "expand-on-hover", "has-abstract", "no-abstract", "bare-content", "file-include-collapse", "expanded", "expanded-not");
if (collapseBlock.className == "")
collapseBlock.removeAttribute("class");
// Strip collapse-specific styles.
collapseBlock.style.removeProperty("margin");
collapseBlock.style.removeProperty("--collapse-toggle-top-height");
collapseBlock.style.removeProperty("--collapse-toggle-top-icon-size");
if (collapseBlock.style == "")
collapseBlock.removeAttribute("style");
// Unwrap subordinate containers.
Array.from(collapseBlock.children).filter(x => x.matches([
".collapse-content-outer-wrapper",
".collapse-content-wrapper",
".abstract-collapse:not(.abstract)"
].join(", "))).forEach(unwrap);
// Unwrap collapse block itself if it’s a bare wrapper.
if ( isBareWrapper(collapseBlock)
&& isOnlyChild(collapseBlock.firstElementChild))
unwrap(collapseBlock);
// Fire event.
if (wasCollapsed) {
GW.notificationCenter.fireEvent("Collapse.collapseStateDidChange", {
source: "Collapse.expandLockCollapseBlocks",
collapseBlock: collapseBlock
});
}
}
/**********************************************************/
/* Removes disclosure buttons and expands collapse blocks.
*/
addContentInjectHandler(GW.contentInjectHandlers.expandLockCollapseBlocks = (eventInfo) => {
GWLog("expandLockCollapseBlocks", "collapse.js", 2);
// Permanently expand collapse blocks (by making them into regular blocks).
eventInfo.container.querySelectorAll(".collapse").forEach(expandLockCollapseBlock);
}, "<rewrite", (info) => info.stripCollapses);
/*******************************************************************************/
/* Ensure that the given element is scrolled into view when layout is complete.
NOTE: In most cases when this function would be used, it is better to use
the revealElement() function instead, as otherwise, if the element is inside
a collapsed block, it will be scrolled into view but not actually visible on
the screen, frustrating the user.
Outside of this file (where scrollElementIntoView() is used in the
collapse code itself), this function should generally be called directly
only if (a) expansion of any collapse blocks involved is explicitly *not*
desired, or (b) expansion is being done separately (i.e., by calling
revealElement() and passing `false` as the value of the `scrollIntoView`
option; generally, this should be done *before* scrolling an element into
view!), with some other operations intervening between revealing and
scrolling into view.
Available option fields:
offset (float)
If element is in the base page (and not in a pop-frame, etc.), then,
after scrolling the element into view, scroll the page down by the given
offset. (If the element is in a pop-frame or similar, `offset` is
ignored.)
*/
function scrollElementIntoView(element, options) {
GWLog("scrollElementIntoView", "collapse.js", 2);
options = Object.assign({
offset: 0
}, options);
if ( Extracts
&& Extracts.popFrameProvider
&& Extracts.popFrameProvider.containingPopFrame(element)) {
Extracts.popFrameProvider.scrollElementIntoViewInPopFrame(element);
} else {
doWhenPageLayoutComplete(() => {
element.scrollIntoView();
if (options.offset != 0)
window.scrollBy(0, options.offset);
updateScrollState();
});
}
}
/****************************************************************************/
/* Expand collapse blocks to reveal the given element.
Available option fields:
scrollIntoView (boolean)
After expanding collapse blocks to reveal the element, scroll it into
view.
offset (float)
If `scrollIntoView` is `true`, then `offset` is passed to
scrollElementIntoView() as an option.
*/
function revealElement(element, options) {
GWLog("revealElement", "collapse.js", 2);
options = Object.assign({
scrollIntoView: true,
offset: 0
}, options);
let didExpandCollapseBlocks = expandCollapseBlocksToReveal(element);
if (options.scrollIntoView) {
if (didExpandCollapseBlocks) {
requestAnimationFrame(() => {
scrollElementIntoView(element, {
offset: options.offset
});
});
} else {
scrollElementIntoView(element, {
offset: options.offset
});
}
}
return didExpandCollapseBlocks;
}
/***********************************************/
/* Reveal the element targeted by the URL hash.
Available option fields:
offset (float)
Passed to revealElement() as an option.
*/
function revealTarget(options) {
GWLog("revealTarget", "collapse.js", 1);
options = Object.assign({
offset: 0
}, options);
let target = getHashTargetedElement();
if (target == null)
return;
let didReveal = revealElement(target, {
offset: options.offset
});
// Fire notification event.
if (didReveal)
GW.notificationCenter.fireEvent("Collapse.targetDidReveal");
}
/***************************************************************/
/* On load and on hash change, reveal element targeted by hash.
*/
GW.notificationCenter.addHandlerForEvent("GW.hashHandlingSetupDidComplete", GW.revealTargetOnPageLayoutComplete = (info) => {
GWLog("GW.revealTargetOnPageLayoutComplete", "collapse.js", 1);
revealTarget();
GW.notificationCenter.addHandlerForEvent("GW.hashDidChange", GW.revealTargetOnHashChange = (info) => {
GWLog("GW.revealTargetOnHashChange", "collapse.js", 1);
revealTarget();
});
});
/*******************************************************************************/
/* What happens when a user C-fs on a page and there is a hit *inside* a
collapse block? Just navigating to the collapsed section is not useful,
especially when there may be multiple collapses inside a frame. So we must
specially handle searches and pop open collapse sections with matches. We do
this by watching for selection changes. (We don’t bother checking for window
focus/blur because that is unreliable and in any case doesn’t work for
“Search Again” key command.)
*/
document.addEventListener("selectionchange", GW.selectionChangedRevealElement = (event) => {
GWLog("GW.selectionChangedRevealElement", "collapse.js", 3);
let newSelection = document.getSelection();
if ( newSelection
&& newSelection.rangeCount > 0
&& newSelection.getRangeAt(0).toString().length > 0) {
let element = (newSelection.anchorNode.nodeType === Node.ELEMENT_NODE
? newSelection.anchorNode
: newSelection.anchorNode.parentElement);
if (isWithinCollapsedBlock(element))
revealElement(element);
}
});