Files
hyperframes/packages/studio/src/utils/sourceScopedSelectorIndex.ts
T
Miguel Ángel ac27b1534f perf(studio): resolve a selector's occurrence index once per layer walk (#3831)
The preview flattens several composition files into one DOM, so a layer's
identity is its selector plus its occurrence index WITHIN its own source
file. `getSourceScopedSelectorIndex` derived that per element: a whole
-document `querySelectorAll(selector)`, `resolveSourceFile` on every match,
then `indexOf`. Every element sharing a class paid for all of them, so a
walk over n such elements did n whole-document queries and n^2 source-file
resolutions — the shape a composition of repeated cards or tiles has by
construction.

Build the occurrence index ONCE per selector instead and share it across
one walk. `withSelectorIndexPass(doc, run)` opens that scope; outside it
the helper behaves exactly as before, per call.

The pass lives in `collectDomEditLayerItems`, which owns the loop, rather
than at a call site — its four callers (off-canvas indicators, the layers
panel, the marquee hit-test and the agent look tool) all walked the same
way and all paid the same cost.

Behaviour is unchanged. The occurrence indices are identical, including
the misses: an element outside the requested source file, or one not
matching the selector, still yields undefined, as do `#`-prefixed and
`[data-composition-id=` selectors and an invalid selector.

Measured on a 1689-element preview over 80 single-frame seeks, per rebuild:
class-selector document queries 171.6 -> 10.8, and the walk's self-timed
cost 15.25ms -> 5.37ms. Elements walked per rebuild is unchanged at 973.7,
so the two arms did the same work.

Tests assert complexity invariance rather than a threshold: the query count
must be IDENTICAL at n and 4n elements sharing a selector, which a fixture
-sized threshold would not catch. Both fail on the previous algorithm.
2026-09-09 19:11:22 -07:00

88 lines
3.2 KiB
TypeScript

/**
* Occurrence index for a selector within its source document.
*
* The preview flattens multiple composition files into one DOM, so a raw
* `querySelectorAll` index is not a stable source-file identity. Callers supply
* their existing source resolver; this helper alone owns occurrence scoping.
*/
/** Every element matching one selector, mapped to the source file it belongs to
* and its occurrence index within that file. One document query fills it. */
type SelectorOccurrences = Map<Element, { scope: string; index: number }>;
interface SelectorIndexPass {
doc: Document;
bySelector: Map<string, SelectorOccurrences>;
}
let activePass: SelectorIndexPass | null = null;
/**
* Share one occurrence index per selector across every
* `getSourceScopedSelectorIndex` call made synchronously inside `run`.
*
* Unshared, each call runs its own whole-document `querySelectorAll(selector)`
* and resolves the source file of every match. A rebuild that walks n elements
* sharing a selector therefore does n whole-document queries and n² resolver
* calls — a composition of repeated cards or tiles is exactly that shape. One
* index per selector makes the same pass linear.
*
* Correctness rests on the pass being ONE synchronous walk of a document that
* does not change under it: nothing invalidates the index, so `run` must not
* mutate `doc`, and every call inside it must resolve source files the same way
* (the resolver may be a fresh closure per call, as long as it answers the
* same). Outside a pass the index is per-call, exactly as before.
*/
export function withSelectorIndexPass<T>(doc: Document, run: () => T): T {
const previous = activePass;
activePass = { doc, bySelector: new Map() };
try {
return run();
} finally {
activePass = previous;
}
}
function buildOccurrences(
doc: Document,
selector: string,
resolveSourceFile: (candidate: Element) => string | undefined,
): SelectorOccurrences {
const occurrences: SelectorOccurrences = new Map();
const counts = new Map<string, number>();
for (const candidate of doc.querySelectorAll(selector)) {
const scope = resolveSourceFile(candidate) ?? "index.html";
const index = counts.get(scope) ?? 0;
counts.set(scope, index + 1);
occurrences.set(candidate, { scope, index });
}
return occurrences;
}
export function getSourceScopedSelectorIndex(
doc: Document,
el: Element,
selector: string | undefined,
sourceFile: string | undefined,
resolveSourceFile: (candidate: Element) => string | undefined,
): number | undefined {
if (!selector || selector.startsWith("#") || selector.startsWith("[data-composition-id=")) {
return undefined;
}
try {
const pass = activePass?.doc === doc ? activePass : null;
let occurrences = pass?.bySelector.get(selector);
if (!occurrences) {
occurrences = buildOccurrences(doc, selector, resolveSourceFile);
pass?.bySelector.set(selector, occurrences);
}
// An element outside the requested scope is not in that scope's occurrence
// run at all, which is the `indexOf` miss the filtered form returned before.
const hit = occurrences.get(el);
return hit && hit.scope === (sourceFile ?? "index.html") ? hit.index : undefined;
} catch {
return undefined;
}
}