All files / roosterjs-content-model-core/lib/coreApi/announce announce.ts

100% Statements 27/27
90% Branches 27/30
100% Functions 3/3
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 511x     1x               1x 40x 10x 10x 10x   10x 5x     10x 9x 9x 5x     9x 4x     9x 9x           10x 1x     9x 4x 4x 4x     9x    
import { createAriaLiveElement } from '../../utils/createAriaLiveElement';
import type { Announce } from 'roosterjs-content-model-types';
 
const DOT_STRING = '.';
 
/**
 * @internal
 * Announce the given data
 * @param core The EditorCore object
 * @param announceData Data to announce
 */
export const announce: Announce = (core, announceData) => {
    const { text, defaultStrings, formatStrings = [], ariaLiveMode = 'assertive' } = announceData;
    const { announcerStringGetter } = core.lifecycle;
    const template = defaultStrings && announcerStringGetter?.(defaultStrings);
    let textToAnnounce = formatString(template || text, formatStrings);
 
    if (!core.lifecycle.announceContainer) {
        core.lifecycle.announceContainer = createAriaLiveElement(core.physicalRoot.ownerDocument);
    }
 
    if (textToAnnounce && core.lifecycle.announceContainer) {
        const { announceContainer } = core.lifecycle;
        if (announceContainer.ariaLive != ariaLiveMode) {
            announceContainer.ariaLive = ariaLiveMode;
        }
 
        if (textToAnnounce == announceContainer.textContent) {
            textToAnnounce += DOT_STRING;
        }
 
        Eif (announceContainer) {
            announceContainer.textContent = textToAnnounce;
        }
    }
};
 
function formatString(text: string | undefined, formatStrings: string[]) {
    if (text == undefined) {
        return text;
    }
 
    text = text.replace(/\{(\d+)\}/g, (_, sub: string) => {
        const index = parseInt(sub);
        const replace = formatStrings[index];
        return replace ?? '';
    });
 
    return text;
}