All files / roosterjs-content-model-core/lib/editor/core DOMHelperImpl.ts

90.53% Statements 86/95
80.16% Branches 101/126
95.65% Functions 22/23
90.43% Lines 85/94

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 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 275 276 2771x 1x                                             2x                                   1x         381x 381x 380x 380x   380x 380x     1x 445x     1x 1x     1x 944x     1x 327x 327x   327x         1x 2x 1x   1x       1x 1x     1x 4x     1x 491x     491x       491x                       1x 7x   7x 12x 5x     7x     2x     1x 3145x     3145x           1x 254x 254x   254x           1x 300x 300x 300x 300x 300x           1x 1x 1x   1x               1x       4x   4x   4x                                                                         1x 1x     1x 546x 546x 2x     544x                             544x     75x 70x 70x 70x 2x     272x 68x 67x   1x       1x 171x 1x   170x     1x         1x   623x   381x    
import { areSameRanges } from '../../utils/areSameRanges';
import {
    getColor,
    getRangesByText,
    isBlockElement,
    isNodeOfType,
    parseValueWithUnit,
    toArray,
} from 'roosterjs-content-model-dom';
import type {
    ContentModelSegmentFormat,
    DarkColorHandler,
    DOMHelper,
} from 'roosterjs-content-model-types';
 
interface SelectionWithComposedRanges extends Selection {
    getComposedRanges(options: { shadowRoots: ShadowRoot[] }): StaticRange[];
}
 
function isSelectionWithComposedRanges(sel: Selection): sel is SelectionWithComposedRanges {
    return 'getComposedRanges' in sel;
}
 
function isShadowRoot(node: Node): node is ShadowRoot {
    return 'host' in node;
}
 
/**
 * @internal
 */
export interface DOMHelperImplOption {
    /**
     * @deprecated This is always treated as true now
     */
    cloneIndependentRoot?: boolean;
 
    /**
     * When true, enable shadow root detection so the editor works inside a Shadow DOM.
     */
    useShadowDom?: boolean;
}
 
class DOMHelperImpl implements DOMHelper {
    private shadowRoot: ShadowRoot | null;
    private doc: Document;
    private useComposedRanges: boolean;
 
    constructor(private contentDiv: HTMLElement, options?: DOMHelperImplOption) {
        const rootNode = contentDiv.getRootNode();
        this.shadowRoot = options?.useShadowDom && isShadowRoot(rootNode) ? rootNode : null;
        this.doc = contentDiv.ownerDocument;
 
        const sel = this.doc.defaultView?.getSelection();
        this.useComposedRanges = !!(this.shadowRoot && sel && 'getComposedRanges' in sel);
    }
 
    queryElements(selector: string): HTMLElement[] {
        return toArray(this.contentDiv.querySelectorAll(selector)) as HTMLElement[];
    }
 
    getTextContent(): string {
        return this.contentDiv.textContent || '';
    }
 
    isNodeInEditor(node: Node, excludeRoot?: boolean): boolean {
        return excludeRoot && node == this.contentDiv ? false : this.contentDiv.contains(node);
    }
 
    calculateZoomScale(): number {
        const originalWidth = this.contentDiv.getBoundingClientRect()?.width || 0;
        const visualWidth = this.contentDiv.offsetWidth;
 
        return visualWidth > 0 && originalWidth > 0
            ? Math.round((originalWidth / visualWidth) * 100) / 100
            : 1;
    }
 
    setDomAttribute(name: string, value: string | null) {
        if (value === null) {
            this.contentDiv.removeAttribute(name);
        } else {
            this.contentDiv.setAttribute(name, value);
        }
    }
 
    getDomAttribute(name: string): string | null {
        return this.contentDiv.getAttribute(name);
    }
 
    getDomStyle<T extends keyof CSSStyleDeclaration>(style: T): CSSStyleDeclaration[T] {
        return this.contentDiv.style[style];
    }
 
    findClosestElementAncestor(startFrom: Node, selector?: string): HTMLElement | null {
        const startElement = isNodeOfType(startFrom, 'ELEMENT_NODE')
            ? startFrom
            : startFrom.parentElement;
        const closestElement = selector
            ? (startElement?.closest(selector) as HTMLElement | null)
            : startElement;
 
        return closestElement &&
            this.isNodeInEditor(closestElement) &&
            closestElement != this.contentDiv
            ? closestElement
            : null;
    }
 
    /**
     * Find the closest block element ancestor from the given node within current editing scope
     * @param startFrom The node to start the search from
     * @returns The closest block element ancestor
     */
    findClosestBlockElement(startFrom: Node): HTMLElement {
        let node: Node | null = startFrom;
 
        while (node && this.isNodeInEditor(node)) {
            if (isNodeOfType(node, 'ELEMENT_NODE') && isBlockElement(node)) {
                return node;
            }
 
            node = node.parentElement;
        }
 
        return this.contentDiv;
    }
 
    hasFocus(): boolean {
        const activeElement = this.shadowRoot
            ? this.shadowRoot.activeElement
            : this.doc.activeElement;
        return !!(activeElement && this.contentDiv.contains(activeElement));
    }
 
    /**
     * Check if the root element is in RTL mode
     */
    isRightToLeft(): boolean {
        const contentDiv = this.contentDiv;
        const style = contentDiv.ownerDocument.defaultView?.getComputedStyle(contentDiv);
 
        return style?.direction == 'rtl';
    }
 
    /**
     * Get the width of the editable area of the editor content div
     */
    getClientWidth(): number {
        const contentDiv = this.contentDiv;
        const style = contentDiv.ownerDocument.defaultView?.getComputedStyle(contentDiv);
        const paddingLeft = parseValueWithUnit(style?.paddingLeft);
        const paddingRight = parseValueWithUnit(style?.paddingRight);
        return this.contentDiv.clientWidth - (paddingLeft + paddingRight);
    }
 
    /**
     * Get a deep cloned root element
     */
    getClonedRoot(): HTMLElement {
        const doc = this.contentDiv.ownerDocument.implementation.createHTMLDocument();
        const clone = doc.importNode(this.contentDiv, true /*deep*/);
 
        return clone;
    }
 
    /**
     * Get format of the container element
     * @param isInDarkMode Optional flag to indicate if the environment is in dark mode
     * @param darkColorHandler Optional DarkColorHandler to retrieve dark mode colors
     */
    getContainerFormat(
        isInDarkMode?: boolean,
        darkColorHandler?: DarkColorHandler
    ): ContentModelSegmentFormat {
        const window = this.contentDiv.ownerDocument.defaultView;
 
        const style = window?.getComputedStyle(this.contentDiv);
 
        return style
            ? {
                  fontSize: style.fontSize,
                  fontFamily: style.fontFamily,
                  fontWeight: style.fontWeight,
                  textColor: getColor(
                      this.contentDiv,
                      false /*isBackgroundColor*/,
                      !!isInDarkMode,
                      darkColorHandler,
                      style.color
                  ),
                  backgroundColor: getColor(
                      this.contentDiv,
                      true /*isBackgroundColor*/,
                      !!isInDarkMode,
                      darkColorHandler,
                      style.backgroundColor
                  ),
                  italic: style.fontStyle == 'italic',
                  letterSpacing: style.letterSpacing,
                  lineHeight: style.lineHeight,
                  strikethrough: style.textDecoration?.includes('line-through'),
                  superOrSubScriptSequence: style.verticalAlign,
                  underline: style.textDecoration?.includes('underline'),
              }
            : {};
    }
 
    /**
     * Get text ranges by searching for a specific text, with options to match case and whole word.
     * This will only search within editable elements.
     * @param text The text to search for
     * @param matchCase Whether to match case
     * @param wholeWord Whether to match whole word
     * @returns An array of Ranges that match the search criteria
     */
    getRangesByText(text: string, matchCase: boolean, wholeWord: boolean): Range[] {
        return getRangesByText(this.contentDiv, text, matchCase, wholeWord, true /*editableOnly*/);
    }
 
    getSelectionRange(): Range | null {
        const sel = this.doc.defaultView?.getSelection();
        if (!sel) {
            return null;
        }
 
        Iif (this.useComposedRanges && this.shadowRoot && isSelectionWithComposedRanges(sel)) {
            const staticRanges = sel.getComposedRanges({
                shadowRoots: [this.shadowRoot],
            });
 
            if (staticRanges?.length > 0) {
                const sr = staticRanges[0];
                const range = this.doc.createRange();
                range.setStart(sr.startContainer, sr.startOffset);
                range.setEnd(sr.endContainer, sr.endOffset);
                return range;
            }
            return null;
        }
 
        return sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
    }
 
    setSelectionRange(range: Range, isReverted: boolean = false): void {
        const sel = this.doc.defaultView?.getSelection();
        const currentRange = this.getSelectionRange();
        if (!sel || (currentRange && areSameRanges(range, currentRange))) {
            return;
        }
 
        const { startContainer, startOffset, endContainer, endOffset } = range;
        if (!isReverted) {
            sel.setBaseAndExtent(startContainer, startOffset, endContainer, endOffset);
        } else {
            sel.setBaseAndExtent(endContainer, endOffset, startContainer, startOffset);
        }
    }
 
    appendToRoot(element: HTMLElement): void {
        if (this.shadowRoot) {
            this.shadowRoot.appendChild(element);
        } else {
            this.doc.body.appendChild(element);
        }
    }
}
 
/**
 * @internal Create new instance of DOMHelper
 */
export function createDOMHelper(
    contentDiv: HTMLElement,
    options: DOMHelperImplOption = {}
): DOMHelper {
    return new DOMHelperImpl(contentDiv, options);
}