All files / apps/wp-editor/app/utils htmlDiff.ts

100% Statements 69/69
96.55% Branches 28/29
100% Functions 9/9
100% Lines 60/60

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    1x 1x     1x 18x   18x 250028x 250028x   31x 31x 31x       1x           250051x 250051x 250051x 50003x 50003x 50003x     250049x 50002x 50002x     250048x 150023x 150023x     100025x 100025x       1x 9x   9x 9x   9x 250051x   250051x 150001x   100050x 100050x       9x     15x   1x 10x 10x   10x 21x 17x 21x     10x 15x 11x 11x   4x       10x   10x             1x 3x 3x   3x 16x 11x   6x 6x       3x    
import { diffArrays } from "diff";
 
const RAW_TEXT = /<(style|script)\b/iy;
const TEXT = /\s+|[^\s<]+/y;
 
/** `indexOf` that remembers each needle's last hit, so a scan whose `from` only grows stays linear. */
const finderIn = (haystack: string) => {
    const found = new Map<string, number>();
 
    return (needle: string, from: number): number => {
        const cached = found.get(needle);
        if (cached !== undefined && (cached === -1 || cached >= from)) return cached;
 
        const index = haystack.indexOf(needle, from);
        found.set(needle, index);
        return index;
    };
};
 
const tokenEnd = (
    html: string,
    at: number,
    find: ReturnType<typeof finderIn>,
    findFolded: ReturnType<typeof finderIn>,
): number | undefined => {
    RAW_TEXT.lastIndex = at;
    const raw = RAW_TEXT.exec(html);
    if (raw?.[1]) {
        const close = `</${raw[1].toLowerCase()}>`;
        const index = findFolded(close, at + raw[0].length);
        if (index !== -1) return index + close.length;
    }
 
    if (html.startsWith("<!--", at)) {
        const index = find("-->", at + 4);
        if (index !== -1) return index + 3;
    }
 
    if (html[at] === "<") {
        const index = find(">", at + 1);
        return index > at + 1 ? index + 1 : undefined;
    }
 
    TEXT.lastIndex = at;
    return TEXT.exec(html) ? TEXT.lastIndex : undefined;
};
 
/** Markup, raw-text elements, comments, whitespace runs and words; a stray `<` is dropped. */
export const htmlTokens = (html: string): string[] => {
    const find = finderIn(html);
    // ASCII only: a full toLowerCase can change the length and shift every index after it
    const findFolded = finderIn(html.replaceAll(/[A-Z]+/g, (letters) => letters.toLowerCase()));
    const tokens: string[] = [];
 
    for (let at = 0; at < html.length;) {
        const end = tokenEnd(html, at, find, findFolded);
 
        if (end === undefined) {
            at++;
        } else {
            tokens.push(html.slice(at, end));
            at = end;
        }
    }
 
    return tokens;
};
 
const isMarkup = (token: string): boolean => token.startsWith("<");
 
const wrap = (tokens: string[], tag: "ins" | "del"): string => {
    let out = "";
    let run = "";
 
    const flush = () => {
        if (run.trim()) out += `<${tag}>${run}</${tag}>`;
        else out += run;
        run = "";
    };
 
    for (const token of tokens) {
        if (isMarkup(token)) {
            flush();
            out += token;
        } else {
            run += token;
        }
    }
 
    flush();
 
    return out;
};
 
/**
 * Both sides keep their own markup untouched; only changed text runs are wrapped, so each side
 * stays exactly as balanced as its source.
 */
export const htmlDiff = (before: string, after: string): { before: string; after: string } => {
    let left = "";
    let right = "";
 
    for (const { added, removed, value } of diffArrays(htmlTokens(before), htmlTokens(after))) {
        if (removed) left += wrap(value, "del");
        else if (added) right += wrap(value, "ins");
        else {
            left += value.join("");
            right += value.join("");
        }
    }
 
    return { before: left, after: right };
};