In this section
- Verify Mobile UI Browser interaction · pipelinenews / atman/202608271656-verify-mobile-ui-browser.mjs lines 701–1400
Verify Mobile UI Browser
A JavaScript module in the atman folder of PipelineNews that applies area (`applySafeArea`), attaches diagnostics (`attachDiagnostics`) and selects full page capture (`selectFullPageCapture`), using SHA-256.
interactionpipelinenews / atman/202608271656-verify-mobile-ui-browser.mjs · lines 701–1400 of 1963 · version 2026-08-27 16:56 (continued from section 1003) · Entry point · pattern sha256File (shared by 4 files)
- What it does
- It draws its content. Defines 55 functions or classes, including selectedIds, slug, serialiseError, relativeEvidencePath, writeJson. Uses libraries node:crypto, node:fs, node:fs/promises, node:path, node:module. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file run.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: PipelineNews Mobile CSS Repair Workflow (pipelinenews).
- What it achieves
- It serialises error (`serialiseError`), writes JSON (`writeJson`) and applies safe area (`applySafeArea`). Its name says it verifies mobile UI browser. Defines `selectedIds`, `slug`, `serialiseError` and 52 more.
- Why it matters
- Run by PipelineNews Mobile CSS Repair Workflow.
- Application
- pipelinenews · atman · JavaScript module
- Uses
- Mobile UI Invariants (import), node:crypto, node:fs, node:fs/promises, node:path, node:module, playwright, sharp, playwright/package.json
- Used by
- run by PipelineNews Mobile CSS Repair Workflow (workflow run)
- Produces
- selectedIds, slug, serialiseError, relativeEvidencePath, writeJson, sha256File, invariantResult, emptyInvariantResults, applySafeArea, attachDiagnostics, favicon, retain
- Defines here
- stickySnapshot, safeAreaSnapshot, considerEdge, staticInvariantResults, detachedDomSnapshot, nodeSnapshot, observeRotationGeometry
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/202608271656-verify-mobile-ui-browser.mjs:701-1400 · blob fcba98c5336221df52e233d5acc0f42a15c188f8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
const rect = element.getBoundingClientRect();
if (!inViewport(rect)) return false;
const x = Math.min(innerWidth - 1, Math.max(0, rect.left + rect.width / 2));
const y = Math.min(innerHeight - 1, Math.max(0, rect.top + rect.height / 2));
const hit = document.elementFromPoint(x, y);
return Boolean(hit && (element === hit || element.contains(hit) || hit.contains(element)));
};
const root = document.scrollingElement || document.documentElement;
const overflowOffenders = [];
for (const element of document.querySelectorAll("body *")) {
if (overflowOffenders.length >= 20 || !rendered(element)) continue;
const rect = element.getBoundingClientRect();
if (rect.right <= innerWidth + thresholds.root_overflow_tolerance_px && rect.left >= -thresholds.root_overflow_tolerance_px) continue;
const whitelisted = selectors.internal_x_scroll_whitelist.some((selector) => {
const owner = element.closest(selector);
if (!owner) return false;
const ownerRect = owner.getBoundingClientRect();
return ownerRect.left >= -thresholds.root_overflow_tolerance_px
&& ownerRect.right <= innerWidth + thresholds.root_overflow_tolerance_px;
});
if (!whitelisted) overflowOffenders.push({ element: elementLabel(element), rect: rectData(rect) });
}
const i1 = {
viewport_width: innerWidth,
root_scroll_width: root.scrollWidth,
body_scroll_width: document.body?.scrollWidth || 0,
tolerance_px: thresholds.root_overflow_tolerance_px,
whitelist: selectors.internal_x_scroll_whitelist,
unwhitelisted_offenders: overflowOffenders,
};
i1.pass = root.scrollWidth <= innerWidth + thresholds.root_overflow_tolerance_px
&& overflowOffenders.length === 0;
const originalRootScroll = { left: root.scrollLeft, top: root.scrollTop };
const bodyScrollHeight = document.body?.scrollHeight || 0;
const rootScrollHeight = root.scrollHeight;
const scrollDemand = Math.max(bodyScrollHeight, rootScrollHeight);
const maximumRootScroll = Math.max(0, rootScrollHeight - innerHeight);
const probeDistance = Math.min(thresholds.body_scroll_probe_px, maximumRootScroll);
let probedScrollY = scrollY;
if (scrollDemand > innerHeight + 1 && probeDistance > 0) {
root.scrollTop = Math.min(maximumRootScroll, originalRootScroll.top + probeDistance);
await nextFrame();
await nextFrame();
probedScrollY = scrollY;
root.scrollTo(originalRootScroll.left, originalRootScroll.top);
await nextFrame();
}
const i2 = {
viewport_height: innerHeight,
body_scroll_height: bodyScrollHeight,
root_scroll_height: rootScrollHeight,
maximum_root_scroll: maximumRootScroll,
probe_px: probeDistance,
initial_scroll_y: originalRootScroll.top,
probed_scroll_y: probedScrollY,
overflow_y: getComputedStyle(document.body).overflowY,
};
i2.pass = scrollDemand <= innerHeight + 1
|| (probeDistance > 0 && Math.abs(probedScrollY - originalRootScroll.top) >= 1);
const panelLimit = innerHeight * thresholds.panel_viewport_height_ratio;
const panels = [];
for (const selector of selectors.panels) {
const elements = [...document.querySelectorAll(selector)];
elements.forEach((element, index) => {
if (!rendered(element)) return;
const rect = element.getBoundingClientRect();
const style = getComputedStyle(element);
const typedStyle = typeof element.computedStyleMap === "function"
? element.computedStyleMap()
: null;
const typedHeight = typedStyle?.get("height")?.toString() || null;
const typedMinimumHeight = typedStyle?.get("min-height")?.toString() || null;
const minimumHeight = Number.parseFloat(style.minHeight);
const usedHeight = Number.parseFloat(style.height);
const declaredHeightIsAuto = typedHeight === "auto";
const declaredMinimumIsAutoOrZero = typedMinimumHeight === "auto"
|| typedMinimumHeight === "0px"
|| typedMinimumHeight === "0";
const fixedHeightExceeds = typedHeight !== null
&& !declaredHeightIsAuto
&& rect.height > panelLimit + 0.5;
const minimumHeightExceeds = typedMinimumHeight !== null
&& !declaredMinimumIsAutoOrZero
&& Number.isFinite(minimumHeight)
&& minimumHeight > panelLimit + 0.5;
panels.push({
selector,
index,
element: elementLabel(element),
rect: rectData(rect),
used_height_px: Number.isFinite(usedHeight) ? usedHeight : null,
minimum_height_px: Number.isFinite(minimumHeight) ? minimumHeight : null,
declared_height: typedHeight,
declared_minimum_height: typedMinimumHeight,
declared_height_is_auto: declaredHeightIsAuto,
declared_minimum_is_auto_or_zero: declaredMinimumIsAutoOrZero,
overflow_y: style.overflowY,
exceeds: fixedHeightExceeds || minimumHeightExceeds,
});
});
}
const i3 = {
viewport_height: innerHeight,
maximum_panel_height: Number(panelLimit.toFixed(2)),
panels,
pass: panels.every((panel) => !panel.exceeds),
};
const stickySnapshot = (label) => {
const stickyBands = [];
for (const element of document.querySelectorAll("body *")) {
if (!rendered(element)) continue;
const rect = element.getBoundingClientRect();
if (!inViewport(rect)) continue;
const position = getComputedStyle(element).position;
if (position !== "sticky" && position !== "fixed") continue;
stickyBands.push({
top: Math.max(0, rect.top),
bottom: Math.min(innerHeight, rect.bottom),
position,
element: elementLabel(element),
});
}
stickyBands.sort((a, b) => a.top - b.top || a.bottom - b.bottom);
const mergedBands = [];
for (const band of stickyBands) {
if (band.bottom <= band.top) continue;
const previous = mergedBands.at(-1);
if (!previous || band.top > previous.bottom) {
mergedBands.push({ top: band.top, bottom: band.bottom });
} else {
previous.bottom = Math.max(previous.bottom, band.bottom);
}
}
const occupiedPixels = mergedBands.reduce((sum, band) => sum + band.bottom - band.top, 0);
return {
label,
occupied_pixels: Number(occupiedPixels.toFixed(2)),
occupied_ratio: Number((occupiedPixels / innerHeight).toFixed(4)),
union_bands: mergedBands.map((band) => ({
top: Number(band.top.toFixed(2)),
bottom: Number(band.bottom.toFixed(2)),
})),
contributors: stickyBands.slice(0, 20).map((band) => ({
...band,
top: Number(band.top.toFixed(2)),
bottom: Number(band.bottom.toFixed(2)),
})),
contributor_count: stickyBands.length,
};
};
const stickyScrollState = [];
const stickyScrollElements = new Set([root]);
for (const selector of [
...Object.values(selectors.controls),
selectors.table_wrap,
".main",
".paper",
]) {
const element = document.querySelector(selector);
for (let current = element; current; current = current.parentElement) {
const style = getComputedStyle(current);
if (current === root || (/(auto|scroll)/u.test(style.overflowY) && current.scrollHeight > current.clientHeight + 1)) {
stickyScrollElements.add(current);
}
}
}
for (const element of stickyScrollElements) {
stickyScrollState.push({ element, top: element.scrollTop, left: element.scrollLeft });
}
const stickySamples = [stickySnapshot("initial")];
const controlsAnchor = document.querySelector(selectors.controls.search);
if (controlsAnchor) {
controlsAnchor.scrollIntoView({ block: "center", inline: "nearest", behavior: "auto" });
await nextFrame();
await nextFrame();
stickySamples.push(stickySnapshot("controls"));
}
for (const state of stickyScrollState) state.element.scrollTo(state.left, state.top);
await nextFrame();
const tableAnchor = document.querySelector(selectors.table_wrap);
if (tableAnchor) {
tableAnchor.scrollIntoView({ block: "start", inline: "nearest", behavior: "auto" });
await nextFrame();
await nextFrame();
stickySamples.push(stickySnapshot("table"));
}
for (const state of stickyScrollState) state.element.scrollTo(state.left, state.top);
await nextFrame();
const worstStickySample = stickySamples.reduce((worst, sample) => (
sample.occupied_pixels > worst.occupied_pixels ? sample : worst
));
const stickyLimit = innerHeight * thresholds.sticky_viewport_height_ratio;
const i4 = {
viewport_height: innerHeight,
maximum_sticky_pixels: Number(stickyLimit.toFixed(2)),
occupied_pixels: worstStickySample.occupied_pixels,
occupied_ratio: worstStickySample.occupied_ratio,
worst_sample: worstStickySample.label,
union_bands: worstStickySample.union_bands,
contributors: worstStickySample.contributors,
samples: stickySamples,
pass: worstStickySample.occupied_pixels <= stickyLimit + 0.5,
};
const controls = {};
for (const [name, selector] of Object.entries(selectors.controls)) {
const element = document.querySelector(selector);
if (!element) {
controls[name] = { selector, present: false, pass: false };
continue;
}
const scrollChain = [];
const seenScrollers = new Set();
for (let ancestor = element.parentElement; ancestor; ancestor = ancestor.parentElement) {
const style = getComputedStyle(ancestor);
if (/(auto|scroll)/u.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight + 1) {
scrollChain.push({ element: ancestor, top: ancestor.scrollTop, left: ancestor.scrollLeft });
seenScrollers.add(ancestor);
}
}
if (!seenScrollers.has(root)) scrollChain.push({ element: root, top: root.scrollTop, left: root.scrollLeft });
const beforeRect = element.getBoundingClientRect();
const initiallyHitTestable = hitTestable(element);
let deliberateScrollAction = false;
if (!initiallyHitTestable) {
element.scrollIntoView({ block: "center", inline: "nearest", behavior: "auto" });
deliberateScrollAction = true;
await nextFrame();
await nextFrame();
}
const rect = element.getBoundingClientRect();
const scrollDeltas = scrollChain.map((entry) => ({
owner: entry.element === root ? "document" : elementLabel(entry.element),
delta_x: Number((entry.element.scrollLeft - entry.left).toFixed(2)),
delta_y: Number((entry.element.scrollTop - entry.top).toFixed(2)),
})).filter(({ delta_x: x, delta_y: y }) => x !== 0 || y !== 0);
const disabled = Boolean(element.disabled) || element.getAttribute("aria-disabled") === "true";
const finalHitTestable = hitTestable(element);
const pass = rendered(element) && !disabled && finalHitTestable;
controls[name] = {
selector,
present: true,
rendered: rendered(element),
disabled,
initially_hit_testable: initiallyHitTestable,
deliberate_scroll_into_view: deliberateScrollAction,
scroll_actions: deliberateScrollAction ? 1 : 0,
scroll_chain_deltas: scrollDeltas,
hit_testable: finalHitTestable,
before_rect: rectData(beforeRect),
rect: rectData(rect),
pass,
};
for (const entry of scrollChain.reverse()) entry.element.scrollTo(entry.left, entry.top);
await nextFrame();
}
const i5 = { controls, pass: Object.values(controls).every((control) => control.pass) };
const tapFailures = [];
let tapFailureCount = 0;
let interactiveCount = 0;
let exceptionCount = 0;
for (const element of document.querySelectorAll(selectors.interactives)) {
if (!rendered(element)) continue;
if (Boolean(element.disabled) || element.getAttribute("aria-disabled") === "true") continue;
interactiveCount += 1;
const rect = element.getBoundingClientRect();
const exception = contract.tap_target_exceptions.find((selector) => {
try { return element.matches(selector); } catch { return false; }
}) || null;
if (exception) exceptionCount += 1;
const minimum = exception
? thresholds.exception_tap_target_px
: thresholds.primary_tap_target_px;
if (rect.width + 0.5 < minimum || rect.height + 0.5 < minimum) {
tapFailureCount += 1;
if (tapFailures.length < 30) {
tapFailures.push({
element: elementLabel(element),
text: (element.textContent || element.getAttribute("aria-label") || "").trim().slice(0, 80),
rect: rectData(rect),
exception,
required_px: minimum,
});
}
}
}
const i6 = {
interactive_count: interactiveCount,
explicit_exception_count: exceptionCount,
failure_count: tapFailureCount,
failures_truncated: tapFailureCount > tapFailures.length,
failures: tapFailures,
pass: tapFailureCount === 0,
};
const viewportMeta = document.querySelector("meta[name='viewport']")?.getAttribute("content") || "";
const viewportFitCover = /(?:^|,)\s*viewport-fit\s*=\s*cover\s*(?:,|$)/iu.test(viewportMeta);
const insets = safeAreaState.requested;
const safeAreaProbe = document.createElement("div");
safeAreaProbe.setAttribute("data-mobile-ui-safe-area-probe", "");
safeAreaProbe.style.cssText = [
"position:fixed",
"visibility:hidden",
"pointer-events:none",
"padding-top:env(safe-area-inset-top)",
"padding-right:env(safe-area-inset-right)",
"padding-bottom:env(safe-area-inset-bottom)",
"padding-left:env(safe-area-inset-left)",
].join(";");
document.body.appendChild(safeAreaProbe);
const probeStyle = getComputedStyle(safeAreaProbe);
const computedInsets = {
top: Number.parseFloat(probeStyle.paddingTop) || 0,
right: Number.parseFloat(probeStyle.paddingRight) || 0,
bottom: Number.parseFloat(probeStyle.paddingBottom) || 0,
left: Number.parseFloat(probeStyle.paddingLeft) || 0,
};
safeAreaProbe.remove();
const envValuesMatch = Object.entries(insets)
.every(([edge, value]) => Math.abs(computedInsets[edge] - value) <= 0.5);
const safeAreaSnapshot = (label) => {
const intersections = [];
let count = 0;
for (const element of document.querySelectorAll(selectors.interactives)) {
if (!rendered(element)) continue;
if (Boolean(element.disabled) || element.getAttribute("aria-disabled") === "true") continue;
const rawRect = element.getBoundingClientRect();
const rect = visibleHitRect(element);
if (!rect || !visibleHitWithin(element, rect)) continue;
const edges = [];
const edgeClips = [];
const considerEdge = (edge, clip) => {
const overlap = intersectRect(rect, clip);
if (!overlap || !visibleHitWithin(element, overlap)) return;
edges.push(edge);
edgeClips.push({ edge, overlap: rectData(overlap) });
};
if (insets.top > 0) considerEdge("top", {
left: 0, top: 0, right: innerWidth, bottom: insets.top,
});
if (insets.right > 0) considerEdge("right", {
left: innerWidth - insets.right, top: 0, right: innerWidth, bottom: innerHeight,
});
if (insets.bottom > 0) considerEdge("bottom", {
left: 0, top: innerHeight - insets.bottom, right: innerWidth, bottom: innerHeight,
});
if (insets.left > 0) considerEdge("left", {
left: 0, top: 0, right: insets.left, bottom: innerHeight,
});
if (!edges.length) continue;
count += 1;
if (intersections.length < 20) {
intersections.push({
element: elementLabel(element),
edges,
raw_rect: rectData(rawRect),
visible_hit_rect: rectData(rect),
safe_area_overlaps: edgeClips,
});
}
}
return { label, count, intersections, truncated: count > intersections.length };
};
const safeAreaSamples = [safeAreaSnapshot("initial")];
if (controlsAnchor) {
controlsAnchor.scrollIntoView({ block: "center", inline: "nearest", behavior: "auto" });
await nextFrame();
await nextFrame();
safeAreaSamples.push(safeAreaSnapshot("controls"));
}
for (const state of stickyScrollState) state.element.scrollTo(state.left, state.top);
await nextFrame();
if (tableAnchor) {
tableAnchor.scrollIntoView({ block: "start", inline: "nearest", behavior: "auto" });
await nextFrame();
await nextFrame();
safeAreaSamples.push(safeAreaSnapshot("table"));
}
for (const state of stickyScrollState) state.element.scrollTo(state.left, state.top);
await nextFrame();
const safeAreaIntersectionCount = safeAreaSamples.reduce((sum, sample) => sum + sample.count, 0);
const safeAreaIntersections = safeAreaSamples.flatMap((sample) => sample.intersections).slice(0, 30);
const i7 = {
cdp_override_supported: safeAreaState.supported,
cdp_override_error: safeAreaState.error,
requested_insets: insets,
computed_env_insets: computedInsets,
computed_env_matches_request: envValuesMatch,
computed_env_matches_requested: envValuesMatch,
env_match: envValuesMatch,
viewport_meta: viewportMeta,
viewport_fit_cover: viewportFitCover,
intersection_count: safeAreaIntersectionCount,
intersections_truncated: safeAreaIntersectionCount > safeAreaIntersections.length,
intersections: safeAreaIntersections,
samples: safeAreaSamples,
pass: safeAreaState.supported
&& envValuesMatch
&& viewportFitCover
&& safeAreaIntersectionCount === 0,
};
const menu = document.querySelector(selectors.release_menu);
let i8;
if (menuExerciseState.opener_visible) {
i8 = {
applicable: true,
selector: selectors.release_menu,
branch: "overlay-menu",
...menuExerciseState,
};
i8.pass = Boolean(
menuExerciseState.exercised
&& !menuExerciseState.open_error
&& menuExerciseState.overlay_open
&& (menuExerciseState.fits_viewport || menuExerciseState.internally_scrollable)
&& menuExerciseState.outside_dismiss
&& menuExerciseState.underlying_scroll_locked
);
} else if (!menu || !rendered(menu)) {
i8 = {
applicable: true,
selector: selectors.release_menu,
branch: "hidden-without-opener",
reason: menu ? "release menu is hidden and has no visible opener" : "release menu absent",
...menuExerciseState,
pass: false,
};
} else {
const rect = menu.getBoundingClientRect();
const style = getComputedStyle(menu);
const fitsViewport = rect.top >= -0.5 && rect.bottom <= innerHeight + 0.5;
const internallyScrollable = /(auto|scroll)/u.test(style.overflowY)
&& menu.scrollHeight > menu.clientHeight + 1
&& rect.height <= innerHeight + 0.5;
const overlayOpen = menu.matches(":popover-open")
|| (menu instanceof HTMLDialogElement && menu.open)
|| menu.getAttribute("aria-modal") === "true";
const opener = document.querySelector(selectors.release_menu_opener);
i8 = {
applicable: true,
selector: selectors.release_menu,
branch: "persistent-navigation",
opener_present: Boolean(opener),
overlay_open: overlayOpen,
rect: rectData(rect),
viewport_height: innerHeight,
scroll_height: menu.scrollHeight,
client_height: menu.clientHeight,
overflow_y: style.overflowY,
fits_viewport: fitsViewport,
internally_scrollable: internallyScrollable,
outside_dismiss: overlayOpen ? false : null,
underlying_scroll_locked: overlayOpen ? getComputedStyle(document.body).overflowY === "hidden" : null,
};
i8.pass = !overlayOpen && (fitsViewport || internallyScrollable);
}
let i10 = { applicable: cellSpec.orientation === "landscape", pass: null };
if (i10.applicable) {
const wrap = document.querySelector(selectors.table_wrap);
const table = document.querySelector(selectors.table);
const rows = [...document.querySelectorAll(selectors.table_rows)];
if (!wrap || !table || rows.length === 0) {
i10 = { applicable: true, present: false, pass: false };
} else {
const scrollOwners = [];
for (let ancestor = wrap.parentElement; ancestor; ancestor = ancestor.parentElement) {
const style = getComputedStyle(ancestor);
if (/(auto|scroll)/u.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight + 1) {
scrollOwners.push({ element: ancestor, top: ancestor.scrollTop, left: ancestor.scrollLeft });
}
}
scrollOwners.push({ element: root, top: root.scrollTop, left: root.scrollLeft });
wrap.scrollIntoView({ block: "start", inline: "nearest" });
await nextFrame();
await nextFrame();
const wrapRect = wrap.getBoundingClientRect();
const paneTop = Math.max(0, wrapRect.top);
const paneBottom = Math.min(innerHeight, wrapRect.bottom);
const visibleRows = rows.filter((row) => {
const rect = row.getBoundingClientRect();
const visibleHeight = Math.max(0, Math.min(rect.bottom, paneBottom) - Math.max(rect.top, paneTop));
return rect.height > 0 && visibleHeight >= rect.height * 0.5;
});
const originalLeft = wrap.scrollLeft;
const maximumLeft = Math.max(0, wrap.scrollWidth - wrap.clientWidth);
wrap.scrollLeft = maximumLeft;
await nextFrame();
await nextFrame();
const reachedFinalPosition = Math.abs(wrap.scrollLeft - maximumLeft) <= 1;
const finalCells = visibleRows.map((row) => row.lastElementChild).filter(Boolean);
const finalColumnVisible = finalCells.some((cellElement) => {
const rect = cellElement.getBoundingClientRect();
const currentWrap = wrap.getBoundingClientRect();
return rect.left >= currentWrap.left - 1 && rect.right <= currentWrap.right + 1;
});
i10 = {
applicable: true,
present: true,
wrap_rect: rectData(wrapRect),
pane_top: Number(paneTop.toFixed(2)),
pane_bottom: Number(paneBottom.toFixed(2)),
visible_row_count: visibleRows.length,
minimum_visible_rows: thresholds.minimum_visible_table_rows,
client_width: wrap.clientWidth,
scroll_width: wrap.scrollWidth,
maximum_scroll_left: maximumLeft,
reached_scroll_left: wrap.scrollLeft,
reached_final_position: reachedFinalPosition,
final_column_visible: finalColumnVisible,
pass: visibleRows.length >= thresholds.minimum_visible_table_rows
&& maximumLeft > 0
&& reachedFinalPosition
&& finalColumnVisible,
};
wrap.scrollLeft = originalLeft;
for (const owner of scrollOwners) owner.element.scrollTo(owner.left, owner.top);
await nextFrame();
}
}
const bodyCopies = [...document.querySelectorAll(selectors.body_copy)].filter((element) => cssVisible(element));
const allCopyFonts = bodyCopies.map((element) => ({
element: elementLabel(element),
font_size_px: Number.parseFloat(getComputedStyle(element).fontSize),
}));
const clippedText = [];
for (const element of document.querySelectorAll("body *")) {
const directText = [...element.childNodes]
.some((node) => node.nodeType === Node.TEXT_NODE && /\S/u.test(node.textContent || ""));
if (!directText) continue;
const style = getComputedStyle(element);
if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) continue;
if (typeof element.checkVisibility === "function"
&& !element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) continue;
const rect = element.getBoundingClientRect();
if ((rect.height <= 0 || element.getClientRects().length === 0) && clippedText.length < 20) {
clippedText.push({
element: elementLabel(element),
text: (element.textContent || "").trim().slice(0, 80),
rect: rectData(rect),
});
}
}
const htmlStyle = getComputedStyle(document.documentElement);
const bodyStyle = getComputedStyle(document.body);
const textSizeAdjust = htmlStyle.webkitTextSizeAdjust || bodyStyle.webkitTextSizeAdjust || "";
const numericTextAdjust = Number.parseFloat(textSizeAdjust);
const explicitTextAdjust = textSizeAdjust !== "auto"
&& textSizeAdjust !== "none"
&& Number.isFinite(numericTextAdjust)
&& numericTextAdjust >= 100;
const minimumCopyFont = allCopyFonts.length
? Math.min(...allCopyFonts.map(({ font_size_px: size }) => size))
: null;
const copyFonts = allCopyFonts
.map((record, index) => ({ ...record, index }))
.sort((left, right) => left.font_size_px - right.font_size_px || left.index - right.index)
.slice(0, 50);
const i11 = {
body_copy_selector: selectors.body_copy,
copy_font_count: allCopyFonts.length,
copy_fonts: copyFonts,
copy_fonts_truncated: allCopyFonts.length > copyFonts.length,
minimum_copy_font_px: minimumCopyFont,
required_minimum_px: thresholds.minimum_body_copy_px,
webkit_text_size_adjust: textSizeAdjust,
text_size_adjust_explicit: explicitTextAdjust,
clipped_text_count: clippedText.length,
clipped_text: clippedText,
pass: minimumCopyFont !== null
&& minimumCopyFont >= thresholds.minimum_body_copy_px
&& explicitTextAdjust
&& clippedText.length === 0,
};
return { I1: i1, I2: i2, I3: i3, I4: i4, I5: i5, I6: i6, I7: i7, I8: i8, I10: i10, I11: i11 };
}, {
contract: CONTRACT,
cellSpec: cell,
safeAreaState: safeArea,
menuExerciseState: menuExercise,
});
}
function staticInvariantResults(measurements, cell) {
return CONTRACT.invariants
.filter(({ id }) => id !== "I12")
.map((descriptor) => {
if (descriptor.id === "I9") {
return invariantResult("I9", false, null, { reason: "rotation-only invariant" });
}
const measurement = measurements[descriptor.id];
if (!measurement) throw new Error(`Verifier omitted ${descriptor.id}`);
const landscapeOnly = descriptor.id === "I10";
const applicable = descriptor.id === "I8"
? measurement.applicable
: (!landscapeOnly || cell.orientation === "landscape");
return invariantResult(descriptor.id, applicable, measurement.pass, measurement);
});
}
async function detachedDomSnapshot(cdp) {
try {
const result = await cdp.send("DOM.getDetachedDomNodes");
const retainedIds = result.detachedNodes.flatMap((entry) => entry.retainedNodeIds || []);
return {
supported: true,
detached_tree_count: result.detachedNodes.length,
retained_node_count: retainedIds.length,
detached_total: result.detachedNodes.length + retainedIds.length,
retained_node_ids: retainedIds.slice(0, 50),
retained_ids_truncated: retainedIds.length > 50,
tree_backend_node_ids: result.detachedNodes
.map((entry) => entry.treeNode?.backendNodeId)
.filter(Number.isFinite)
.slice(0, 50),
error: null,
};
} catch (error) {
return {
supported: false,
detached_tree_count: null,
retained_node_count: null,
detached_total: null,
retained_node_ids: [],
retained_ids_truncated: false,
tree_backend_node_ids: [],
error: serialiseError(error),
};
}
}
async function nodeSnapshot(page, cdp, phase, expectedViewport) {
await cdp.send("HeapProfiler.collectGarbage");
const counters = await cdp.send("Memory.getDOMCounters");
const detached = await detachedDomSnapshot(cdp);
const pageState = await page.evaluate(() => ({
connected_elements: document.getElementsByTagName("*").length,
inner_width: innerWidth,
inner_height: innerHeight,
screen_width: screen.width,
screen_height: screen.height,
portrait: matchMedia("(orientation: portrait)").matches,
landscape: matchMedia("(orientation: landscape)").matches,
screen_orientation_type: screen.orientation?.type || null,
screen_orientation_angle: screen.orientation?.angle ?? null,
}));
const expectedOrientationMatches = expectedViewport.orientation === "landscape"
? pageState.landscape
: pageState.portrait;
if (
pageState.inner_width !== expectedViewport.width
|| pageState.inner_height !== expectedViewport.height
|| !expectedOrientationMatches
) {
throw new Error(
`Rotation snapshot ${phase} layout viewport does not match `
+ `${expectedViewport.width}x${expectedViewport.height} ${expectedViewport.orientation}`,
);
}
return {
phase,
...pageState,
expected_viewport: expectedViewport,
layout_viewport_matches_expected: true,
cdp_documents: counters.documents,
cdp_nodes: counters.nodes,
cdp_js_event_listeners: counters.jsEventListeners,
detached,
};
}
async function observeRotationGeometry(page) {
const playwrightViewport = page.viewportSize();
try {
const browser = await page.evaluate(() => ({
inner_width: innerWidth,
inner_height: innerHeight,
outer_width: outerWidth,
outer_height: outerHeight,
visual_viewport_width: visualViewport?.width ?? null,
visual_viewport_height: visualViewport?.height ?? null,
visual_viewport_scale: visualViewport?.scale ?? null,
screen_width: screen.width,
screen_height: screen.height,
device_pixel_ratio: devicePixelRatio,
portrait: matchMedia("(orientation: portrait)").matches,
landscape: matchMedia("(orientation: landscape)").matches,
screen_orientation_type: screen.orientation?.type || null,
screen_orientation_angle: screen.orientation?.angle ?? null,
}));
return {
captured_at: new Date().toISOString(),