Theme engine v3 step 8: the layer guard

themeGuards.ts: watches the site's layer container; every new popover (and one that the
site moves or that grows) is measured in an idle callback and shifted into the viewport
minus the bar insets with a translate (data-wb-clamped, --wb-clamp-x/y); taller than the
viewport it scrolls. Bounded: only nodes that hold a popover are measured, at most 4 per
pass; a moved popover is seen through its own style attribute and a ResizeObserver.
clampShift/viewportBox are pure and unit tested.
This commit is contained in:
CRTkafa 2026-10-02 05:46:52 +07:00
parent 9606c2a86e
commit a9c48c5d35
2 changed files with 167 additions and 0 deletions

View file

@ -0,0 +1,140 @@
// Theme engine v3, step 8 (.omc/plans/theme-engine-v3.md 3.5, 4.2): the layer guard. A site positions
// its popovers (menus, hover cards, tooltips) from an anchor; a theme that moves the anchor (a bottom
// taskbar, a top bar) moves them past the window edge. Static CSS cannot see where a portal lands, so
// this guard measures each new layer root once and shifts it back inside the viewport minus the bar
// insets. Bounded: it watches only the layer container's children (no subtree attribute observation
// of the page), measures in an idle callback, at most a few layers per frame, never timeline cells.
/** The viewport box popovers must stay in. */
export type Box = { left: number; top: number; right: number; bottom: number };
export type Rect = { left: number; top: number; width: number; height: number };
/** Attribute on a shifted layer (a static rule hides its caret, which points at the old anchor). */
export const CLAMPED_ATTR = 'data-wb-clamped';
export const CLAMP_X = '--wb-clamp-x';
export const CLAMP_Y = '--wb-clamp-y';
/**
* Pure: the shift that brings `rect` inside `box`. A rect larger than the box keeps its start edge
* inside (left/top) and reports `overflowY`, so the caller can cap its height and let it scroll.
*/
export function clampShift(rect: Rect, box: Box): { dx: number; dy: number; overflowY: boolean } {
const shift = (start: number, size: number, min: number, max: number) => {
if (size >= max - min) return min - start;
if (start < min) return min - start;
if (start + size > max) return max - (start + size);
return 0;
};
return {
dx: Math.round(shift(rect.left, rect.width, box.left, box.right)),
dy: Math.round(shift(rect.top, rect.height, box.top, box.bottom)),
overflowY: rect.height > box.bottom - box.top,
};
}
/** The box: the viewport less `margin` on every side and the bar insets top and bottom. */
export function viewportBox(width: number, height: number, insets: { top: number; bottom: number }, margin = 8): Box {
return { left: margin, top: margin + insets.top, right: width - margin, bottom: height - margin - insets.bottom };
}
/** The static rules the guard relies on (part of the theme sheet). */
export function layerGuardCss(): string {
return `[${CLAMPED_ATTR}]{translate:var(${CLAMP_X},0px) var(${CLAMP_Y},0px) !important}\n[${CLAMPED_ATTR}="scroll"]{max-height:var(--wb-clamp-h) !important;overflow-y:auto !important}`;
}
export type LayerGuardOptions = {
/** The container the site renders its portals into (X: `#layers`). */
root: string;
/** Inside a new layer, the element that is positioned and should be shifted (first match wins). */
targets: string[];
/** Bar insets in px (read from the theme's `--wb-bar-inset-top/bottom` by default). */
insets?: () => { top: number; bottom: number };
};
const px = (value: string) => { const n = parseFloat(value); return Number.isFinite(n) ? n : 0; };
/** Watches the layer root; returns a stop function. Off in safe mode (the host never installs it then). */
export function installLayerGuard(win: Window, options: LayerGuardOptions): () => void {
const doc = win.document;
const insets = options.insets ?? (() => {
const style = win.getComputedStyle(doc.documentElement);
return { top: px(style.getPropertyValue('--wb-bar-inset-top')), bottom: px(style.getPropertyValue('--wb-bar-inset-bottom')) };
});
const selector = options.targets.join(',');
const pending = new Set<Element>();
let scheduled = false;
const measure = () => {
scheduled = false;
let budget = 4;
for (const layer of [...pending]) {
if (budget-- <= 0) break;
pending.delete(layer);
if (!layer.isConnected) continue;
for (const target of layer.matches(selector) ? [layer] : [...layer.querySelectorAll(selector)].slice(0, 2)) clamp(target as HTMLElement);
}
if (pending.size) schedule();
};
// A measured popover is watched for the site moving it again (its inline position): only its own
// style attribute, and only position changes count (our own clamp variables change it too).
const placed = new WeakMap<HTMLElement, string>();
const position = (el: HTMLElement) => `${el.style.left}|${el.style.top}|${el.style.right}|${el.style.bottom}|${el.style.transform}`;
const Observer = (win as Window & { MutationObserver: typeof MutationObserver }).MutationObserver;
const moved = new Observer((records: MutationRecord[]) => {
for (const record of records) {
const el = record.target as HTMLElement;
if (el.isConnected && placed.get(el) !== position(el)) { pending.add(el); schedule(); }
}
});
// A popover that grows (a theme's font, content loading in) is measured again too.
const Resize = (win as Window & { ResizeObserver?: typeof ResizeObserver }).ResizeObserver;
const sized = Resize ? new Resize(entries => { for (const entry of entries) { const el = entry.target as HTMLElement; if (el.isConnected) { pending.add(el); schedule(); } } }) : null;
const clamp = (el: HTMLElement) => {
if (!placed.has(el)) { moved.observe(el, { attributes: true, attributeFilter: ['style'] }); sized?.observe(el); }
placed.set(el, position(el));
// Measure without our own shift.
el.style.removeProperty(CLAMP_X); el.style.removeProperty(CLAMP_Y);
const r = el.getBoundingClientRect();
if (r.width < 1 || r.height < 1) return;
const box = viewportBox(win.innerWidth, win.innerHeight, insets());
const { dx, dy, overflowY } = clampShift({ left: r.left, top: r.top, width: r.width, height: r.height }, box);
if (!dx && !dy && !overflowY) { el.removeAttribute(CLAMPED_ATTR); return; }
el.style.setProperty(CLAMP_X, `${dx}px`); el.style.setProperty(CLAMP_Y, `${dy}px`);
if (overflowY) el.style.setProperty('--wb-clamp-h', `${Math.max(80, box.bottom - box.top)}px`);
el.setAttribute(CLAMPED_ATTR, overflowY ? 'scroll' : '');
};
const schedule = () => {
if (scheduled) return;
scheduled = true;
const idle = (win as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number }).requestIdleCallback;
if (idle) idle.call(win, measure, { timeout: 120 }); else win.setTimeout(measure, 16);
};
// Only a node that is or holds a popover is worth a measurement (typing in a dialog inserts nodes too).
const queue = (node: Node | null) => {
if (!node || node.nodeType !== 1) return;
const el = node as Element;
if (!el.matches(selector) && !el.querySelector(selector)) return;
pending.add(el); schedule();
// The site positions a portal after it mounts (a layout effect, a measured anchor): measure again
// once it has settled. Two late passes, no observer on the page's style attributes.
for (const delay of [120, 450]) win.setTimeout(() => { if (el.isConnected) { pending.add(el); schedule(); } }, delay);
};
let observer: MutationObserver | null = null;
let layers: Element | null = null;
const attach = () => {
const found = doc.querySelector(options.root);
if (found === layers) return;
observer?.disconnect();
layers = found;
if (!found) return;
// Children of the layer root and their children: a portal mounts its positioned box a level or two down.
const next = new Observer((records: MutationRecord[]) => { for (const record of records) for (const node of record.addedNodes) queue(node.nodeType === 1 ? ((node as Element).closest(selector) ?? node) : null); });
next.observe(found, { childList: true, subtree: true });
observer = next;
for (const child of found.children) queue(child);
};
attach();
const retry = win.setInterval(attach, 2000);
const onResize = () => { if (layers) for (const child of layers.children) queue(child); };
win.addEventListener('resize', onResize);
return () => { observer?.disconnect(); moved.disconnect(); sized?.disconnect(); win.clearInterval(retry); win.removeEventListener('resize', onResize); };
}

View file

@ -0,0 +1,27 @@
// Theme engine v3, step 8: the layer guard's geometry (pure part).
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { clampShift, viewportBox } from '../src/themeGuards.ts';
const box = viewportBox(2000, 1000, { top: 0, bottom: 56 });
test('the account menu that ran 52px past a 2000px window comes back inside, 8px from the edge', () => {
// Live 1.0.2: left 1737, width 300 in a 1985px viewport.
const shift = clampShift({ left: 1737, top: 822, width: 300, height: 108 }, viewportBox(1985, 1000, { top: 0, bottom: 56 }));
assert.equal(1737 + shift.dx + 300, 1985 - 8);
assert.equal(shift.dy, 0);
});
test('a hover card cut at the bottom moves up above the bar inset', () => {
const shift = clampShift({ left: 400, top: 900, width: 300, height: 200 }, box);
assert.equal(900 + shift.dy + 200, 1000 - 8 - 56);
});
test('inside stays put; taller than the box keeps its top edge and asks to scroll', () => {
assert.deepEqual(clampShift({ left: 100, top: 100, width: 200, height: 200 }, box), { dx: 0, dy: 0, overflowY: false });
const tall = clampShift({ left: 100, top: 300, width: 200, height: 2000 }, box);
assert.equal(300 + tall.dy, 8);
assert.ok(tall.overflowY);
const left = clampShift({ left: -40, top: 100, width: 200, height: 100 }, box);
assert.equal(-40 + left.dx, 8);
});