Skip to content

Truly independent web browser

18.5 KB
Raw Blame
<!DOCTYPE html>
<script src="include.js"></script>
<script src="layout-optimization-test-matrix.js"></script>
<script src="work-test.js"></script>
<style>
    body { margin: 0; }
    .cache-root { box-sizing: border-box; overflow: hidden; }
    .inline-matrix { display: inline-block; font-size: 0; vertical-align: top; }
    .inline-item { display: inline-block; width: 10px; height: 10px; }
</style>
<script>
    const formattingContexts = {
        block: "display: block",
        inlineBlock: "display: inline-block",
        flex: "display: flex",
        grid: "display: grid",
    };

    function makeElement(style = "", className = "") {
        const element = document.createElement("div");
        element.className = className;
        element.style.cssText = style;
        return element;
    }

    function makeCacheChain(format, depth, leaf) {
        let inner = leaf;
        for (let level = depth - 1; level >= 0; --level) {
            const width = 100 - level * 10;
            const height = 50 - level * 5;
            const root = makeElement(
                `${formattingContexts[format]}; width: ${width}px; height: ${height}px`,
                "cache-root");
            root.id = `chain${level}`;
            root.appendChild(inner);
            inner = root;
        }
        return inner;
    }

    function chainRun(format) {
        const context = format === "block" || format === "inlineBlock" ? "block" : format;
        const kind = context === "block" ? "BlockContainer" : "Box";
        return `${kind}<DIV>#chain0.cache-root/${context}`;
    }

    function escapedWork(testCase) {
        // A changed inline basis reruns the shell. Its child's fixed width still
        // allows replay. A changed block basis can replay the shell itself.
        const shell = testCase.axis === "inline"
            ? `BlockContainer<DIV>#shell/block RUN (cache=miss)\n        ${chainRun(testCase.format)} REPLAY FRAGMENTS`
            : "BlockContainer<DIV>#shell/block REPLAY FRAGMENTS";
        return `layout FULL
  @viewport/block RUN (cache=bypass)
    BlockContainer<HTML>/block RUN (cache=miss)
      ${shell}
      BlockContainer<DIV>#target/block RUN (cache=miss)`;
    }

    function movementWork(testCase) {
        // The chain lays out its out-of-flow child itself, so it retains the committed subtree including that child.
        // An inline-block chain sits in an anonymous block, whose subtree is reused as it is.
        const work = testCase.format === "inlineBlock"
            ? "BlockContainer(anonymous) REUSE IN-FLOW SUBTREE"
            : `${chainRun(testCase.format)} REUSE SUBTREE`;
        return `layout FULL
  @viewport/block RUN (cache=bypass)
    BlockContainer<HTML>/block RUN (cache=miss)
      ${work}`;
    }

    function flushLayout() {
        internals.updateLayoutForTesting();
    }

    function runEscapedOutOfFlowMatrix(matrix) {
        const cases = matrixCases({
            position: ["absolute", "fixed"],
            format: Object.keys(formattingContexts),
            depth: [1, 2, 3],
            axis: ["inline", "block"],
        });
        for (const testCase of cases) {
            const label = `escaped ${JSON.stringify(testCase)}`;
            matrix.run(label, () => {
                const containingBlock = makeElement("width: 300px; height: 200px");
                containingBlock.id = "host";
                if (testCase.position === "absolute")
                    containingBlock.style.position = "relative";
                else
                    containingBlock.style.transform = "translateX(0px)";

                const outOfFlow = makeElement("width: 10px; height: 10px");
                outOfFlow.id = "target";
                outOfFlow.style.position = testCase.position;
                if (testCase.axis === "inline") {
                    outOfFlow.style.right = "10px";
                    outOfFlow.style.top = "5px";
                } else {
                    outOfFlow.style.left = "5px";
                    outOfFlow.style.bottom = "10px";
                }
                const stableShell = makeElement("width: 110px; height: 60px; overflow: hidden");
                stableShell.id = "shell";
                stableShell.appendChild(makeCacheChain(testCase.format, testCase.depth, outOfFlow));
                containingBlock.appendChild(stableShell);
                document.body.appendChild(containingBlock);
                try {
                    flushLayout();

                    const before = relativeRect(outOfFlow, containingBlock);
                    runLayoutTestStep({
                        name: label,
                        mutate: () => {
                            if (testCase.axis === "inline")
                                containingBlock.style.width = "200px";
                            else
                                containingBlock.style.height = "120px";
                        },
                        expect: escapedWork(testCase),
                        check: () => {
                            const after = relativeRect(outOfFlow, containingBlock);
                            const expectedBefore = testCase.axis === "inline" ? [280, 5, 10, 10] : [5, 180, 10, 10];
                            const expectedAfter = testCase.axis === "inline" ? [180, 5, 10, 10] : [5, 100, 10, 10];
                            matrix.expect("geometry before", before, expectedBefore);
                            matrix.expect("geometry after", after, expectedAfter);
                        },
                    });
                } finally {
                    containingBlock.remove();
                }
            });
        }
    }

    function runCommittedMovementMatrix(matrix) {
        const cases = matrixCases({
            format: Object.keys(formattingContexts),
            depth: [1, 2, 3],
            descendant: ["inFlow", "absolute", "fixed"],
        });
        for (const testCase of cases) {
            const label = `movement ${JSON.stringify(testCase)}`;
            matrix.run(label, () => {
                const host = makeElement("width: 300px");
                const spacer = makeElement("height: 10px");
                const descendant = makeElement("width: 10px; height: 10px");
                descendant.id = "target";
                const chain = makeCacheChain(testCase.format, testCase.depth, descendant);
                let containingRoot = chain;
                while (containingRoot.firstElementChild !== descendant)
                    containingRoot = containingRoot.firstElementChild;
                if (testCase.descendant !== "inFlow") {
                    descendant.style.position = testCase.descendant;
                    descendant.style.left = "7px";
                    descendant.style.top = "9px";
                    if (testCase.descendant === "absolute")
                        containingRoot.style.position = "relative";
                    else
                        containingRoot.style.transform = "translateX(0px)";
                }
                host.append(spacer, chain);
                document.body.appendChild(host);
                try {
                    flushLayout();

                    const before = descendant.getBoundingClientRect();
                    const beforeTuple = [rounded(before.left), rounded(before.top), rounded(before.width), rounded(before.height)];
                    runLayoutTestStep({
                        name: label,
                        mutate: () => { spacer.style.height = "40px"; },
                        expect: movementWork(testCase),
                        check: () => {
                            const after = descendant.getBoundingClientRect();
                            const afterTuple = [rounded(after.left), rounded(after.top), rounded(after.width), rounded(after.height)];
                            matrix.expect("movement", afterTuple, [beforeTuple[0], beforeTuple[1] + 30, 10, 10]);
                        },
                    });
                } finally {
                    host.remove();
                }
            });
        }
    }

    function makeInlineContainer(keys, width, ancestorDepth) {
        const container = document.createElement("div");
        container.className = "inline-matrix";
        container.style.width = `${width}px`;
        let parent = container;
        for (let level = 0; level < ancestorDepth; ++level) {
            const wrapper = document.createElement("span");
            parent.appendChild(wrapper);
            parent = wrapper;
        }
        for (const key of keys) {
            const item = document.createElement("span");
            item.className = "inline-item";
            item.dataset.key = key;
            parent.appendChild(item);
        }
        container.itemParent = parent;
        return container;
    }

    function inlineGeometry(container) {
        const result = { container: [rounded(container.offsetWidth), rounded(container.offsetHeight)], items: {} };
        for (const item of container.querySelectorAll(".inline-item"))
            result.items[item.dataset.key] = relativeRect(item, container);
        return result;
    }

    function runInlineDamageMatrix(matrix) {
        const cases = matrixCases({
            mutation: ["insert", "remove", "moveEarlier", "moveLater"],
            width: [30, 40, 50],
            position: [1, 6, 10],
            ancestorDepth: [0, 1, 2],
        });
        for (const testCase of cases) {
            const label = `inline damage ${JSON.stringify(testCase)}`;
            matrix.run(label, () => {
                const initialKeys = Array.from({ length: 12 }, (_, index) => String(index));
                const subject = makeInlineContainer(initialKeys, testCase.width, testCase.ancestorDepth);
                let control = null;
                document.body.appendChild(subject);
                try {
                    flushLayout();

                    const finalKeys = [...initialKeys];
                    if (testCase.mutation === "insert") {
                        finalKeys.splice(testCase.position, 0, "inserted");
                        const item = document.createElement("span");
                        item.className = "inline-item";
                        item.dataset.key = "inserted";
                        subject.itemParent.insertBefore(item, subject.itemParent.children[testCase.position]);
                    } else if (testCase.mutation === "remove") {
                        finalKeys.splice(testCase.position, 1);
                        subject.itemParent.children[testCase.position].remove();
                    } else {
                        const [movedKey] = finalKeys.splice(testCase.position, 1);
                        const movedItem = subject.itemParent.children[testCase.position];
                        if (testCase.mutation === "moveEarlier") {
                            finalKeys.unshift(movedKey);
                            subject.itemParent.prepend(movedItem);
                        } else {
                            finalKeys.push(movedKey);
                            subject.itemParent.append(movedItem);
                        }
                    }

                    control = makeInlineContainer(finalKeys, testCase.width, testCase.ancestorDepth);
                    document.body.appendChild(control);
                    flushLayout();
                    matrix.expect("fresh-control geometry", inlineGeometry(subject), inlineGeometry(control));
                } finally {
                    subject.remove();
                    control?.remove();
                }
            });
        }
    }

    const intrinsicSequences = {
        two: { widths: [20, 30], min: 30, max: 50 },
        three: { widths: [10, 20, 30], min: 30, max: 60 },
        one: { widths: [35], min: 35, max: 35 },
    };

    function appendIntrinsicContent(target, widths, content) {
        let parent = target;
        if (content === "atomicPair") {
            const fixed = document.createElement("span");
            fixed.style.cssText = "display: inline-block; width: 10px; height: 10px";
            target.appendChild(fixed);
        }
        if (content !== "direct") {
            const wrapper = document.createElement("span");
            wrapper.style.whiteSpace = "normal";
            if (content === "atomic" || content === "atomicPair")
                wrapper.style.display = "inline-block";
            target.appendChild(wrapper);
            parent = wrapper;
        }
        for (const width of widths) {
            const item = document.createElement("span");
            item.style.cssText = `display: inline-block; width: ${width}px; height: 10px`;
            parent.appendChild(item);
        }
    }

    function makeIntrinsicProbe(width, sequence, content, wrapping) {
        const probe = makeElement(
            `display: inline-block; width: ${width}; overflow: hidden; font-size: 0; white-space: ${wrapping}`);
        appendIntrinsicContent(probe, sequence.widths, content);
        return probe;
    }

    function runIntrinsicSizingMatrix(matrix) {
        const cases = matrixCases({
            atomic: ["inlineBlock", "float", "absolute"],
            available: [25, 40, 70],
            sequence: Object.keys(intrinsicSequences),
            content: ["direct", "inline", "atomic", "atomicPair"],
            wrapping: ["normal", "nowrap"],
        });
        for (const testCase of cases) {
            const label = `intrinsic ${JSON.stringify(testCase)}`;
            matrix.run(label, () => {
                const sequence = intrinsicSequences[testCase.sequence];
                const host = makeElement(`position: relative; width: ${testCase.available}px; height: 30px; font-size: 0`);
                const target = makeElement(`overflow: hidden; font-size: 0; white-space: ${testCase.wrapping}`);
                if (testCase.atomic === "inlineBlock")
                    target.style.display = "inline-block";
                else if (testCase.atomic === "float")
                    target.style.float = "left";
                else {
                    target.style.position = "absolute";
                    target.style.left = "0";
                }
                appendIntrinsicContent(target, sequence.widths, testCase.content);
                host.appendChild(target);

                const minProbe = makeIntrinsicProbe("min-content", sequence, testCase.content, testCase.wrapping);
                const maxProbe = makeIntrinsicProbe("max-content", sequence, testCase.content, testCase.wrapping);
                document.body.append(host, minProbe, maxProbe);
                try {
                    flushLayout();

                    const maximum = sequence.max + (testCase.content === "atomicPair" ? 10 : 0);
                    let minimum = sequence.min;
                    if (testCase.wrapping === "nowrap") {
                        // NB: Boxes in a span that wraps can break apart, since the span is their nearest common
                        //     ancestor, and only the nowrap container's own children can't.
                        if (testCase.content === "direct")
                            minimum = sequence.max;
                        else if (testCase.content === "atomicPair")
                            minimum += 10;
                    }
                    const expected = Math.min(maximum, Math.max(minimum, testCase.available));
                    matrix.expect("shrink-to-fit width", rounded(target.getBoundingClientRect().width), expected);
                    matrix.expect("min-content width", rounded(minProbe.getBoundingClientRect().width), minimum);
                    matrix.expect("max-content width", rounded(maxProbe.getBoundingClientRect().width), maximum);
                } finally {
                    host.remove();
                    minProbe.remove();
                    maxProbe.remove();
                }
            });
        }
    }

    const emptyVariants = {
        auto: "",
        fixed: "width: 25px; height: 15px",
        minimum: "min-width: 12px; min-height: 8px",
        boxModel: "box-sizing: content-box; width: 0; height: 0; padding: 3px; border: 2px solid",
    };

    function makeEmptyAtomic(kind, variant, withZeroChild) {
        const target = makeElement(`${emptyVariants[variant]}; overflow: hidden`);
        if (kind === "inlineBlock")
            target.style.display = "inline-block";
        else if (kind === "float")
            target.style.float = "left";
        else {
            target.style.position = "absolute";
            target.style.left = "0";
            target.style.top = "0";
        }
        if (withZeroChild)
            target.appendChild(makeElement("width: 0; height: 0"));
        return target;
    }

    function runEmptyAtomicMatrix(matrix) {
        const cases = matrixCases({
            parent: ["block", "flex", "grid"],
            atomic: ["inlineBlock", "float", "absolute"],
            variant: Object.keys(emptyVariants),
        });
        for (const testCase of cases) {
            const label = `empty atomic ${JSON.stringify(testCase)}`;
            matrix.run(label, () => {
                const emptyParent = makeElement(`${formattingContexts[testCase.parent]}; position: relative; width: 100px; height: 50px; font-size: 0`);
                const controlParent = makeElement(`${formattingContexts[testCase.parent]}; position: relative; width: 100px; height: 50px; font-size: 0`);
                const empty = makeEmptyAtomic(testCase.atomic, testCase.variant, false);
                const control = makeEmptyAtomic(testCase.atomic, testCase.variant, true);
                emptyParent.appendChild(empty);
                controlParent.appendChild(control);
                document.body.append(emptyParent, controlParent);
                try {
                    flushLayout();
                    matrix.expect("zero-child control", relativeRect(empty, emptyParent), relativeRect(control, controlParent));
                } finally {
                    emptyParent.remove();
                    controlParent.remove();
                }
            });
        }
    }

    promiseTest(async () => {
        if (document.readyState !== "complete")
            await new Promise(resolve => window.addEventListener("load", resolve, { once: true }));
        await document.fonts.ready;
        __outputElement.style.display = "none";
        const matrix = new LayoutTestMatrix("layout optimization scenarios");
        runEscapedOutOfFlowMatrix(matrix);
        runCommittedMovementMatrix(matrix);
        runInlineDamageMatrix(matrix);
        runIntrinsicSizingMatrix(matrix);
        runEmptyAtomicMatrix(matrix);
        __outputElement.style.display = "";
        matrix.print();
    });
</script>