Skip to content

Commit

Permalink
fix: stop tracking unmounted elements
Browse files Browse the repository at this point in the history
  • Loading branch information
AriPerkkio committed Sep 6, 2021
1 parent 098a731 commit 07f4c40
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/capture-announcements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export default function CaptureAnnouncements(options: Options): Restore {
// prettier-ignore
const cleanups: Restore[] = [
interceptMethod(Element.prototype, 'setAttribute', onSetAttribute),
interceptMethod(Element.prototype, 'removeAttribute', onRemoveAttribute),
interceptMethod(Element.prototype, 'removeChild', onRemoveChild),
interceptMethod(Element.prototype, 'insertAdjacentElement', onInsertAdjacent),
interceptMethod(Element.prototype, 'insertAdjacentHTML', onInsertAdjacent),
interceptMethod(Element.prototype, 'insertAdjacentText', onInsertAdjacent),
Expand Down Expand Up @@ -212,6 +212,25 @@ function onRemoveAttribute(
}
}

function onRemoveChild(
this: Element,
...args: Parameters<Element['removeChild']>
) {
if (args[0] == null || !isElement(args[0])) return;

const elementAndItsLiveRegionChildren = [
args[0],
...args[0].querySelectorAll(LIVE_REGION_QUERY),
];

// Check whether removed element or any of its children were tracked
for (const element of elementAndItsLiveRegionChildren) {
if (liveRegions.has(element)) {
liveRegions.delete(element);
}
}
}

function trimWhiteSpace(text: string): string | null {
const trimmed = text.trim().replace(WHITE_SPACE_REGEXP, ' ');
return trimmed.length > 0 ? trimmed : null;
Expand Down
31 changes: 31 additions & 0 deletions test/capture-announcements.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,4 +416,35 @@ describe('element tracking', () => {
expect(liveRegions.size).toBe(0);
expect(liveRegions.has(element)).toBe(false);
});

test('element is removed from tracked elements when unmounted', () => {
element.setAttribute('role', 'status');
appendToRoot(element);
element.textContent = 'Hello world';

expect(liveRegions.size).toBe(1);
expect(liveRegions.has(element)).toBe(true);

element.parentElement!.removeChild(element);

expect(liveRegions.size).toBe(0);
expect(liveRegions.has(element)).toBe(false);
});

test('element is removed from tracked elements when ancestor is unmounted', () => {
const child = document.createElement('div');
child.setAttribute('role', 'status');
element.appendChild(child);

appendToRoot(element);
child.textContent = 'Hello world';

expect(liveRegions.size).toBe(1);
expect(liveRegions.has(child)).toBe(true);

element.parentElement!.removeChild(element);

expect(liveRegions.size).toBe(0);
expect(liveRegions.has(element)).toBe(false);
});
});

0 comments on commit 07f4c40

Please sign in to comment.