Skip to content

Commit

Permalink
fix: detect appended text nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
AriPerkkio committed Mar 3, 2021
1 parent ac5fa5e commit 8d55459
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 15 deletions.
13 changes: 6 additions & 7 deletions src/to-be-announced.ts
@@ -1,4 +1,5 @@
import {
getClosestElement,
getParentLiveRegion,
isElement,
isInDOM,
Expand Down Expand Up @@ -34,7 +35,10 @@ const incorrectlyUsedStatusMessages: string[] = [];
* - `textContent` of live region should have changed
*/
function updateAnnouncements(node: Node) {
const parentLiveRegion = getParentLiveRegion(node);
const element = getClosestElement(node);
if (!element) return;

const parentLiveRegion = getParentLiveRegion(element);

if (parentLiveRegion) {
const politenessSetting = resolvePolitenessSetting(parentLiveRegion);
Expand Down Expand Up @@ -85,12 +89,7 @@ function onTextContentChange(this: Node) {

// https://github.com/facebook/react/blob/9198a5cec0936a21a5ba194a22fcbac03eba5d1d/packages/react-dom/src/client/setTextContent.js#L12-L35
function onNodeValueChange(this: Node) {
// This should be a TEXT_NODE
const element = isElement(this) ? this : this.parentElement;

if (element) {
updateAnnouncements(element);
}
updateAnnouncements(this);
}

function onAppendChild(newChild: Node) {
Expand Down
24 changes: 16 additions & 8 deletions src/utils.ts
Expand Up @@ -16,8 +16,20 @@ export const LIVE_REGION_QUERY = [
// '[role="timer"]',
].join(', ');

export function isElement(node: Node): node is Element {
return node && 'closest' in node;
export function isElement(node: Node | null): node is Element {
return node != null && 'closest' in node;
}

export function getClosestElement(node: Node): Element | null {
if (isElement(node)) {
return node;
}

if (node.parentNode) {
return getClosestElement(node.parentNode);
}

return null;
}

export function isLiveRegionAttribute(
Expand All @@ -33,12 +45,8 @@ export function isInDOM(node: Node): boolean {
return isElement(node) && node.closest('html') != null;
}

export function getParentLiveRegion(node: Node): Element | null {
if (isElement(node)) {
return node.closest(LIVE_REGION_QUERY);
}

return null;
export function getParentLiveRegion(element: Element): Element | null {
return element.closest(LIVE_REGION_QUERY);
}

function isPolitenessSetting(
Expand Down
8 changes: 8 additions & 0 deletions test/to-be-announced.dom.test.ts
Expand Up @@ -70,6 +70,14 @@ import { appendToRoot, Tag } from './utils';
expect('First').not.toBeAnnounced();
expect('Second').toBeAnnounced();
});

test('should announce when text node is appended into existing container', () => {
appendToRoot(element);

element.appendChild(document.createTextNode('Hello world'));

expect('Hello world').toBeAnnounced();
});
});
});

Expand Down

0 comments on commit 8d55459

Please sign in to comment.