Skip to content

Truly independent web browser

Tests/LibWeb: Add layoutWork() to query layout traces

Aliaksandr Kalenik6d97e67bd143
diff --git a/Tests/LibWeb/Text/expected/layout-test-harness.txt b/Tests/LibWeb/Text/expected/layout-test-harness.txt
index 5cf74e72daf..7a6093235f8 100644
--- a/Tests/LibWeb/Text/expected/layout-test-harness.txt
+++ b/Tests/LibWeb/Text/expected/layout-test-harness.txt
@@ -15,3 +15,12 @@ PASS: stops tracing after a failed check
PASS: requires expectations before mutating
PASS: rejects asynchronous mutations
PASS: rejects asynchronous checks
+PASS: parses every kind of trace line
+PASS: rejects unknown trace lines
+PASS: work lays out pending changes before tracing the mutation
+PASS: work stops tracing after a throwing mutation
+PASS: work rejects asynchronous mutations
+PASS: work counts the events a filter object matches
+PASS: work counts the events a filter function matches
+PASS: work names each matching box once, in trace order
+PASS: work keeps the trace text
diff --git a/Tests/LibWeb/Text/input/layout-test-harness.html b/Tests/LibWeb/Text/input/layout-test-harness.html
index 8722475c478..2861d4f9e42 100644
--- a/Tests/LibWeb/Text/input/layout-test-harness.html
+++ b/Tests/LibWeb/Text/input/layout-test-harness.html
@@ -63,5 +63,83 @@ test(() => {
exercise("rejects asynchronous checks", () => ({
name: "async", expect: "", check: () => Promise.resolve(),
}), "begin,flush,take", "check must be synchronous");
+
+ const trace = [
+ "layout FULL",
+ " @viewport/block RUN (cache=bypass)",
+ " Box<DIV>#flex/flex RUN (cache=miss)",
+ " BlockContainer(anonymous) MEASURE max-content inline (cache=miss) FROM ITEMS",
+ " BlockContainer(anonymous) MEASURE min-content inline (cache=hit) FROM MAX-CONTENT",
+ " Box<DIV>#item MEASURE max-content block (cache=miss)",
+ " Box<DIV>#item/flex (measurement, intrinsic) RUN (cache=bypass)",
+ " BlockContainer<P> INLINE SIZE FROM ITEMS",
+ " Box<TABLE>#table/table (intrinsic) RUN (cache=bypass)",
+ " BlockContainer<TD>.cell MEASURE CELL (cache=miss)",
+ " BlockContainer<TD>.cell/block RUN AHEAD OF INTRINSIC BLOCK PADDING",
+ " BlockContainer<TD>.cell MEASURE CELL (cache=hit)",
+ " BlockContainer<DIV> REUSE IN-FLOW SUBTREE",
+ "layout PARTIAL Box<DIV>#flex",
+ " Box<DIV>#flex/flex REPLAY FRAGMENTS",
+ "",
+ ].join("\n");
+ const expectedEvents = [
+ { depth: 0, event: "layout", partial: false },
+ { depth: 1, event: "run", box: "@viewport", formattingContext: "block", measurement: false, intrinsic: false, action: "RUN", cache: "bypass" },
+ { depth: 2, event: "run", box: "Box<DIV>#flex", formattingContext: "flex", measurement: false, intrinsic: false, action: "RUN", cache: "miss" },
+ { depth: 3, event: "measure", box: "BlockContainer(anonymous)", size: "max-content inline", cache: "miss", from: "items" },
+ { depth: 3, event: "measure", box: "BlockContainer(anonymous)", size: "min-content inline", cache: "hit", from: "max-content" },
+ { depth: 3, event: "measure", box: "Box<DIV>#item", size: "max-content block", cache: "miss" },
+ { depth: 4, event: "run", box: "Box<DIV>#item", formattingContext: "flex", measurement: true, intrinsic: true, action: "RUN", cache: "bypass" },
+ { depth: 5, event: "inline size from items", box: "BlockContainer<P>" },
+ { depth: 3, event: "run", box: "Box<TABLE>#table", formattingContext: "table", measurement: false, intrinsic: true, action: "RUN", cache: "bypass" },
+ { depth: 4, event: "measure cell", box: "BlockContainer<TD>.cell", cache: "miss" },
+ { depth: 5, event: "run", box: "BlockContainer<TD>.cell", formattingContext: "block", measurement: false, intrinsic: false, action: "RUN AHEAD OF INTRINSIC BLOCK PADDING" },
+ { depth: 4, event: "measure cell", box: "BlockContainer<TD>.cell", cache: "hit" },
+ { depth: 4, event: "reuse in-flow subtree", box: "BlockContainer<DIV>" },
+ { depth: 0, event: "layout", partial: true, box: "Box<DIV>#flex" },
+ { depth: 1, event: "run", box: "Box<DIV>#flex", formattingContext: "flex", measurement: false, intrinsic: false, action: "REPLAY FRAGMENTS" },
+ ];
+ // JSON leaves out the properties a line does not have.
+ const parsedEvents = parseLayoutTrace(trace);
+ println(`${JSON.stringify(parsedEvents) === JSON.stringify(expectedEvents) ? "PASS" : "FAIL"}: parses every kind of trace line`);
+ try {
+ parseLayoutTrace(" Box<DIV>#item SOMETHING NEW");
+ println("FAIL: rejects unknown trace lines");
+ } catch (error) {
+ println(`${String(error).includes("unrecognized layout trace line") ? "PASS" : "FAIL"}: rejects unknown trace lines`);
+ }
+
+ function exerciseWork(name, mutate, expectedCalls, errorText, inspect) {
+ const calls = [];
+ const fakeInternals = {
+ beginLayoutTrace: () => calls.push("begin"),
+ updateLayoutForTesting: () => calls.push("flush"),
+ takeLayoutTrace: () => { calls.push("take"); return trace; },
+ };
+ let error = "";
+ let work;
+ try {
+ work = layoutWork(() => mutate(calls), fakeInternals);
+ } catch (caught) {
+ error = String(caught);
+ }
+ const passed = calls.join(",") === expectedCalls
+ && (errorText ? error.includes(errorText) : !error)
+ && (!inspect || inspect(work));
+ println(`${passed ? "PASS" : "FAIL"}: ${name}`);
+ }
+ exerciseWork("work lays out pending changes before tracing the mutation", calls => { calls.push("mutate"); },
+ "flush,begin,mutate,flush,take");
+ exerciseWork("work stops tracing after a throwing mutation", () => { throw new Error("mutation failed"); },
+ "flush,begin,take", "mutation failed");
+ exerciseWork("work rejects asynchronous mutations", () => Promise.resolve(),
+ "flush,begin,take", "mutate must be synchronous");
+ exerciseWork("work counts the events a filter object matches", () => {}, "flush,begin,flush,take", null,
+ work => work.count({ event: "measure", cache: "miss" }) === 2 && work.count({ event: "measure cell" }) === 2);
+ exerciseWork("work counts the events a filter function matches", () => {}, "flush,begin,flush,take", null,
+ work => work.count(event => event.depth === 0) === 2);
+ exerciseWork("work names each matching box once, in trace order", () => {}, "flush,begin,flush,take", null,
+ work => work.boxes({ event: "measure" }).join() === "BlockContainer(anonymous),Box<DIV>#item");
+ exerciseWork("work keeps the trace text", () => {}, "flush,begin,flush,take", null, work => work.text === trace);
});
</script>
diff --git a/Tests/LibWeb/Text/input/layout-test.js b/Tests/LibWeb/Text/input/layout-test.js
index 831a5763fe9..b7af90f75a5 100644
--- a/Tests/LibWeb/Text/input/layout-test.js
+++ b/Tests/LibWeb/Text/input/layout-test.js
@@ -1,5 +1,6 @@
-// Exact formatting-context work expectations. Keep measured steps synchronous and
-// buffer output: writing test results into the document can invalidate later steps.
+// Layout work expectations: exact traces with layoutTest(), or queries over the traced events
+// with layoutWork(). Keep measured steps synchronous and buffer output: writing test results
+// into the document can invalidate later steps.
function normalizeLayoutTrace(text) {
const lines = text.replace(/\r/g, "").split("\n");
@@ -18,6 +19,88 @@ function layoutTraceDifference(expected, actual) {
return `line ${line + 1}: expected ${JSON.stringify(left[line] ?? "<end>")}, got ${JSON.stringify(right[line] ?? "<end>")}`;
}
+// The kinds of layout trace lines, each as a pattern and the event that its groups make.
+const layoutTraceLines = (() => {
+ const box = String.raw`(\S+)`;
+ const cache = String.raw`\(cache=(\w+)\)`;
+ const runFlags = String.raw`(?: \((measurement)?(?:, )?(intrinsic)?\))?`;
+ return [
+ ["layout FULL", () => ({ event: "layout", partial: false })],
+ [`layout PARTIAL ${box}`, box => ({ event: "layout", partial: true, box })],
+ [`${box} MEASURE CELL ${cache}`, (box, cache) => ({ event: "measure cell", box, cache })],
+ [
+ `${box} MEASURE ((?:min|max)-content (?:inline|block)) ${cache}(?: FROM (ITEMS|MAX-CONTENT))?`,
+ (box, size, cache, from) => ({ event: "measure", box, size, cache, from: from?.toLowerCase() }),
+ ],
+ [`${box} INLINE SIZE FROM ITEMS`, box => ({ event: "inline size from items", box })],
+ [`${box} REUSE IN-FLOW SUBTREE`, box => ({ event: "reuse in-flow subtree", box })],
+ [
+ `${box}/([a-z-]+)${runFlags} ([A-Z][A-Z -]*[A-Z])(?: ${cache})?`,
+ (box, formattingContext, measurement, intrinsic, action, cache) => ({
+ event: "run",
+ box,
+ formattingContext,
+ measurement: !!measurement,
+ intrinsic: !!intrinsic,
+ action,
+ cache,
+ }),
+ ],
+ ].map(([pattern, makeEvent]) => [new RegExp(`^${pattern}$`), makeEvent]);
+})();
+
+// Parses a layout trace into one event per line. Each event has its depth, its kind in `event`, and the
+// name of the box it is about in `box`, except for a full layout pass:
+// layout `partial`
+// run `formattingContext`, `measurement`, `intrinsic`, `action`, `cache`
+// reuse in-flow subtree
+// measure `size` ("min-content inline", ...), `cache`, `from` ("items", "max-content")
+// measure cell `cache`
+// inline size from items
+function parseLayoutTrace(text) {
+ const events = [];
+ for (const line of text.replace(/\r/g, "").split("\n")) {
+ if (!line.trim()) continue;
+ const depth = line.match(/^ */)[0].length / 2;
+ const content = line.trim();
+ const kind = layoutTraceLines.find(([pattern]) => pattern.test(content));
+ if (!kind) throw new Error(`unrecognized layout trace line: ${JSON.stringify(line)}`);
+ const [pattern, makeEvent] = kind;
+ events.push({ depth, ...makeEvent(...content.match(pattern).slice(1)) });
+ }
+ return events;
+}
+
+// Whether `event` has every property of `filter`, or passes it where it is a function.
+function layoutEventMatches(event, filter) {
+ if (typeof filter === "function") return filter(event);
+ return Object.entries(filter).every(([key, value]) => event[key] === value);
+}
+
+// Lays out what is pending, then runs `mutate` and lays out again, tracing only the layout work the
+// mutation causes. Output printed before the call is laid out first, so it is never counted. Answers
+// the trace and its events, with queries over the events that match a filter (see layoutEventMatches).
+function layoutWork(mutate, testInternals = internals) {
+ testInternals.updateLayoutForTesting();
+ testInternals.beginLayoutTrace();
+ let text;
+ try {
+ if (mutate()?.then) throw new Error("mutate must be synchronous");
+ testInternals.updateLayoutForTesting();
+ } finally {
+ text = testInternals.takeLayoutTrace();
+ }
+ const events = parseLayoutTrace(text);
+ const matching = filter => events.filter(event => layoutEventMatches(event, filter));
+ return {
+ text,
+ events,
+ count: filter => matching(filter).length,
+ // The names of the boxes of the matching events, each once, in the order they first appear.
+ boxes: filter => [...new Set(matching(filter).map(event => event.box))],
+ };
+}
+
// Match the display-list helper's optional block-fixture preparation.
function removeBodyWhitespace() {
for (const node of [...document.body.childNodes]) {