Last modified by wiki admin on 2026/08/26 01:04

From version 6.1
edited by wiki admin
on 2026/08/24 22:13
Change comment: There is no comment for this version
To version 7.1
edited by wiki admin
on 2026/08/24 22:31
Change comment: There is no comment for this version

Summary

Details

XWiki.JavaScriptExtension[0]
Code
... ... @@ -56,12 +56,33 @@
56 56   var content = document.getElementById('xwikicontent');
57 57   if (!content) { return; }
58 58  
59 - // Only top-level headings. An h2 nested inside a table or a macro box is
60 - // part of that structure and must not be torn out of it.
61 - var headings = [];
62 - for (var i = 0; i < content.children.length; i++) {
63 - if (content.children[i].tagName === 'H2') { headings.push(content.children[i]); }
59 + // Find the element the section headings actually live in. XWiki wraps
60 + // rendered content in its own container (.f-accordion-panel on this
61 + // instance), so the headings are NOT direct children of #xwikicontent --
62 + // an earlier version of this script looked only at content.children, found
63 + // nothing on every real article, and silently did nothing. The Preview
64 + // page hid that, because hand-written wiki markup does put headings at the
65 + // top level.
66 + var found = content.querySelectorAll('h2');
67 + if (found.length < MIN_SECTIONS) { return; }
68 +
69 + // Group headings that share a parent, using the parent holding the most of
70 + // them. Taking every h2 regardless of depth would tear headings out of
71 + // tables and macro boxes they belong to.
72 + var byParent = [];
73 + for (var f = 0; f < found.length; f++) {
74 + var parent = found[f].parentNode;
75 + var slot = null;
76 + for (var b = 0; b < byParent.length; b++) {
77 + if (byParent[b].parent === parent) { slot = byParent[b]; break; }
78 + }
79 + if (!slot) { slot = { parent: parent, items: [] }; byParent.push(slot); }
80 + slot.items.push(found[f]);
64 64   }
82 + byParent.sort(function (a, b) { return b.items.length - a.items.length; });
83 +
84 + var container = byParent[0].parent;
85 + var headings = byParent[0].items;
65 65   if (headings.length < MIN_SECTIONS) { return; }
66 66  
67 67   var made = [];
... ... @@ -86,7 +86,7 @@
86 86   // the table-of-contents macro still resolve to something.
87 87   if (h2.id) { details.id = h2.id; h2.removeAttribute('id'); }
88 88  
89 - content.insertBefore(details, h2);
110 + container.insertBefore(details, h2);
90 90  
91 91   // Move the heading and everything up to the next h2 into the body.
92 92   var node = h2;
... ... @@ -105,7 +105,7 @@
105 105   tools.className = 'alder-tools';
106 106   tools.appendChild(button('Expand all', true, made));
107 107   tools.appendChild(button('Collapse all', false, made));
108 - content.insertBefore(tools, made[0]);
129 + container.insertBefore(tools, made[0]);
109 109  
110 110   openFromHash();
111 111   window.addEventListener('hashchange', openFromHash);