Skip to content

Commit f2552b4

Browse files
feat: improve DOM observer
1 parent 2f36833 commit f2552b4

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed

src/Virtual.ts

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,39 @@ import {
77
ERR_VIRTUAL_MISSING_CONTAINER,
88
ERR_VIRTUAL_NOT_STARTED,
99
} from "./errors";
10+
import { aria } from "aria-query";
11+
import { isElement } from "./isElement";
1012
import { notImplemented } from "./notImplemented";
1113
import userEvent from "@testing-library/user-event";
1214

1315
export interface StartOptions extends CommandOptions {
1416
container: HTMLElement;
1517
}
1618

19+
const observedAttributes = [
20+
...aria.keys(),
21+
"type",
22+
"control",
23+
"for",
24+
"labels",
25+
"style",
26+
"class",
27+
"title",
28+
"alt",
29+
"label",
30+
"value",
31+
"hidden",
32+
"disabled",
33+
];
34+
1735
// TODO: monitor focus change and update the screen reader active element.
1836
// TODO: handle aria-live, role="polite", role="alert", and other interruptions.
1937

2038
const observeDOM = (function () {
21-
const MutationObserver: typeof window.MutationObserver =
22-
// @ts-expect-error WebKitMutationObserver is non-standard WebKit fallback for old implementations
23-
window.MutationObserver || window.WebKitMutationObserver;
39+
const MutationObserver = window.MutationObserver;
2440

2541
return function observeDOM(node: Node, onChange: () => void): () => void {
26-
if (!node || node.nodeType !== 1) {
42+
if (!isElement(node)) {
2743
return;
2844
}
2945

@@ -32,20 +48,22 @@ const observeDOM = (function () {
3248
if (MutationObserver) {
3349
const mutationObserver = new MutationObserver(callback);
3450

35-
mutationObserver.observe(node, { childList: true, subtree: true });
51+
mutationObserver.observe(node, {
52+
attributes: true,
53+
attributeFilter: observedAttributes,
54+
childList: true,
55+
subtree: true,
56+
});
3657

3758
return () => {
3859
mutationObserver.disconnect();
3960
};
40-
} else if (window.addEventListener) {
41-
node.addEventListener("DOMNodeInserted", callback, false);
42-
node.addEventListener("DOMNodeRemoved", callback, false);
43-
44-
return () => {
45-
node.removeEventListener("DOMNodeInserted", callback, false);
46-
node.removeEventListener("DOMNodeRemoved", callback, false);
47-
};
4861
}
62+
63+
return () => {
64+
// gracefully fallback to not supporting Accessibility Tree refreshes if
65+
// the DOM changes.
66+
};
4967
};
5068
})();
5169

0 commit comments

Comments
 (0)