-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathheadingoffset-polyfill.js
274 lines (247 loc) · 8.2 KB
/
headingoffset-polyfill.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
// @ts-check
// Track headings with polyfill-managed 'aria-level' attributes
const managedHeadings = new WeakSet();
// Track observed roots
const observedRoots = new WeakSet();
/** Handle 'aria-level' attribute changes */
const ariaLevelObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (!(mutation.target instanceof HTMLHeadingElement)) continue;
if (mutation.type !== "attributes") continue;
const heading = mutation.target;
if (heading.hasAttribute("aria-level")) {
// Attribute was added or modified - stop managing unless we did it
managedHeadings.delete(heading);
} else {
// Attribute was removed - start managing and reapply
updateAriaLevel(heading);
}
}
});
/** Handle changes to 'headingoffset' and 'headingreset' attributes and DOM structure */
const headingObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === "childList") {
// Handle added nodes
for (const node of mutation.addedNodes) {
if (!(node instanceof HTMLElement)) {
continue;
}
// If a heading is added (or a node with heading children), update its 'aria-level' attribute
if (node instanceof HTMLHeadingElement) {
updateAriaLevel(node);
} else if (
node.querySelector(
"h1, h2, h3, h4, h5, h6, [headingoffset], [headingreset]"
)
) {
getHeadings(node).forEach((heading) => updateAriaLevel(heading));
}
// If a shadow root is added, observe it
if (node.shadowRoot) {
observeRoot(node.shadowRoot);
}
}
} else if (
mutation.type === "attributes" &&
mutation.target instanceof HTMLElement
) {
// If a container's attributes change, update child headings’ 'aria-level' attributes
getHeadings(mutation.target).forEach((heading) =>
updateAriaLevel(heading)
);
}
}
});
/**
* Watch a document or shadow root for changes
* @param {Document|ShadowRoot} root A document or shadow root
*/
function observeRoot(root) {
// Early-return if the root is already observed
if (observedRoots.has(root)) {
return;
}
observedRoots.add(root);
ariaLevelObserver.observe(root, {
attributeFilter: ["aria-level"],
subtree: true,
});
headingObserver.observe(root, {
attributeFilter: ["headingoffset", "headingreset"],
childList: true,
subtree: true,
});
getHeadings(root).forEach((heading) => updateAriaLevel(heading));
}
/**
* Get a container’s child headings
* @param {Element|Document|ShadowRoot} container
* @returns {HTMLHeadingElement[]} An array of heading elements
*/
function getHeadings(container) {
/** Get child headings @type {HTMLHeadingElement[]} */
const headings = Array.from(
container.querySelectorAll("h1, h2, h3, h4, h5, h6")
);
// Add headings in shadow roots
for (const element of container.querySelectorAll("*")) {
if (element.shadowRoot) {
/** @type {HTMLHeadingElement[]} */
const shadowHeadings = Array.from(
element.shadowRoot.querySelectorAll("h1, h2, h3, h4, h5, h6")
);
headings.push(...shadowHeadings);
}
}
return headings;
}
/**
* Updates a heading’s 'aria-level' attribute, based on its offset
* @param {HTMLHeadingElement} heading
*/
function updateAriaLevel(heading) {
// Early-return if 'aria-level' was not set by the polyfill
if (heading.hasAttribute("aria-level") && !managedHeadings.has(heading)) {
return;
}
const tagLevel = Number(heading.tagName[1]);
const offset = computeHeadingOffset(heading, 9 - tagLevel);
const ariaLevel = tagLevel + offset;
// Don’t set 'aria-level' if it’s redundant
if (ariaLevel === tagLevel) {
heading.removeAttribute("aria-level");
return;
}
heading.setAttribute("aria-level", String(ariaLevel));
ariaLevelObserver.takeRecords(); // Prevent observer loop
managedHeadings.add(heading);
}
/**
* Determines whether an element is explicitly (via the 'headingreset' attribute)
* or implicitly (as a modal dialog) a 'headingoffset' accumulation boundary.
* @param {Element} element
* @returns {boolean}
*/
function isOffsetBoundary(element) {
// Modal dialogs implicitly reset heading levels
if (element instanceof HTMLDialogElement) {
return (
element.open && element.hasAttribute("open") && element.matches(":modal")
);
}
return element.hasAttribute("headingreset");
}
/**
* Compute the heading’s offset (from its 'tagName' level) by summing its ancestors’
* 'headingoffset' attributes, up to a 'headingreset' boundary.
* @param {Element} heading A heading element.
* @param {number} maxOffset Maximum offset to apply (0-9).
* @returns {number} Number of levels (0 to 'maxOffset') to offset the heading.
*/
function computeHeadingOffset(heading, maxOffset) {
// Early-return if the heading is (itself) a boundary
if (isOffsetBoundary(heading)) {
return Math.min(heading.headingOffset || 0, maxOffset);
}
// Accumulate 'headingoffset' values upwards, handling shadow boundaries and slots
let offset = heading.headingOffset || 0;
let ancestor = heading;
while (ancestor) {
// Move to parent (or assigned slot, or shadow host)
if (ancestor.assignedSlot) {
ancestor = ancestor.assignedSlot;
} else if (ancestor.parentElement) {
ancestor = ancestor.parentElement;
} else if (ancestor.getRootNode() instanceof ShadowRoot) {
ancestor = ancestor.getRootNode().host;
} else {
break;
}
// Add this element's offset
offset += ancestor.headingOffset || 0;
// Early-return if the ancestor is a boundary
if (isOffsetBoundary(ancestor)) {
return Math.min(offset, maxOffset);
}
// Early-return if the maximum offset is reached
if (offset >= maxOffset) {
return maxOffset;
}
}
return Math.min(offset, maxOffset);
}
// Initialize the polyfill
(() => {
/* c8 ignore start */
// Early-return (without polyfilling) if 'headingoffset' is natively-supported
if ("headingOffset" in Element.prototype) {
return;
}
/* c8 ignore stop */
// Define 'headingOffset' IDL attribute
Object.defineProperty(Element.prototype, "headingOffset", {
get() {
const value = Number(this.getAttribute("headingoffset"));
return Math.min(Math.max(value || 0, 0), 9);
},
set(value) {
if (value === undefined || value === null || value === "") {
this.removeAttribute("headingoffset");
} else {
if (!isNaN(Number(value))) {
this.setAttribute("headingoffset", value);
}
}
},
enumerable: true,
});
// Define 'headingReset' IDL attribute
Object.defineProperty(Element.prototype, "headingReset", {
get() {
return this.hasAttribute("headingreset");
},
set(value) {
if (value === undefined || value === null || value === "") {
this.removeAttribute("headingreset");
} else {
this.setAttribute("headingreset", "");
}
},
enumerable: true,
});
// Patch 'attachShadow' to handle (future) shadow roots
const originalAttachShadow = Element.prototype.attachShadow;
Object.defineProperty(Element.prototype, "attachShadow", {
value: function (...args) {
const shadowRoot = originalAttachShadow.call(this, ...args);
observeRoot(shadowRoot);
return shadowRoot;
},
});
// Patch 'attachInternals' to handle (future) closed declarative shadow roots
const originalAttachInternals = HTMLElement.prototype.attachInternals;
Object.defineProperty(HTMLElement.prototype, "attachInternals", {
value: function () {
const internals = originalAttachInternals.call(this);
if (internals.shadowRoot) {
window.setTimeout(() => {
observeRoot(internals.shadowRoot);
}, 0);
}
return internals;
},
});
// Handle document and current shadow roots
function findAndObserveShadowRoots(root) {
const elements = root.querySelectorAll("*");
for (const element of elements) {
if (element.shadowRoot) {
observeRoot(element.shadowRoot);
findAndObserveShadowRoots(element.shadowRoot);
}
}
}
observeRoot(document);
findAndObserveShadowRoots(document);
})();