@hyperframes/studio 0.8.143 → 0.8.144

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/assets/{hyperframes-player-BXSuksFh.js → hyperframes-player-Bw_jIaSX.js} +3 -3
  2. package/dist/assets/{index-J7jpL4pj.js → index-BVM9NuWl.js} +141 -141
  3. package/dist/assets/{index-BgOVCqjo.js → index-Cj7W_c7p.js} +1 -1
  4. package/dist/assets/{index-FgyO_5Kv.js → index-DyH9dT7b.js} +1 -1
  5. package/dist/{chunk-TFLU2MGI.js → chunk-3GHTHPZD.js} +8 -1
  6. package/dist/chunk-3GHTHPZD.js.map +1 -0
  7. package/dist/{chunk-H2DUOXTF.js → chunk-G3EDKRZH.js} +3 -3
  8. package/dist/{chunk-UYWON5AX.js → chunk-PEAKCOUW.js} +7 -3
  9. package/dist/chunk-PEAKCOUW.js.map +1 -0
  10. package/dist/{chunk-LOVBLSMR.js → chunk-Y2OHHNM2.js} +35 -19
  11. package/dist/chunk-Y2OHHNM2.js.map +1 -0
  12. package/dist/{domEditingLayers-KBTPQKGA.js → domEditingLayers-PYST4G45.js} +3 -3
  13. package/dist/index.html +1 -1
  14. package/dist/index.js +139 -70
  15. package/dist/index.js.map +1 -1
  16. package/dist/player.js +3 -3
  17. package/dist/ui.d.ts +4 -5
  18. package/dist/ui.js +1 -1
  19. package/package.json +8 -8
  20. package/src/components/editor/DomEditSelectionChrome.test.tsx +103 -0
  21. package/src/components/editor/DomEditSelectionChrome.tsx +42 -16
  22. package/src/components/editor/anchoredResizeCommitFeedsOffset.test.ts +36 -0
  23. package/src/components/editor/domEditOverlayGestures.ts +1 -0
  24. package/src/components/editor/domEditOverlayStartGesture.ts +5 -0
  25. package/src/components/editor/domEditResizeLocal.test.ts +81 -1
  26. package/src/components/editor/domEditResizeLocal.ts +27 -3
  27. package/src/components/editor/domEditingLayers.ts +4 -1
  28. package/src/components/editor/domEditingTextFields.test.ts +18 -0
  29. package/src/components/editor/manualEditsDom.ts +12 -12
  30. package/src/components/editor/previewGestureStarts.ts +14 -5
  31. package/src/components/editor/resizeDraft.ts +13 -4
  32. package/src/components/editor/useDomEditOverlayGestures.ts +5 -3
  33. package/src/components/ui/Menu.test.tsx +67 -5
  34. package/src/components/ui/Menu.tsx +21 -4
  35. package/src/components/ui/Popover.tsx +11 -5
  36. package/src/hooks/gsapResizeIntercept.test.ts +46 -11
  37. package/src/hooks/gsapResizeIntercept.ts +25 -20
  38. package/src/hooks/useThumbnailStripSize.test.tsx +123 -0
  39. package/src/hooks/useThumbnailStripSize.ts +19 -8
  40. package/src/player/components/CompositionThumbnail.test.ts +3 -0
  41. package/src/player/components/ImageThumbnail.test.tsx +4 -1
  42. package/src/player/components/VideoThumbnail.test.tsx +13 -2
  43. package/src/player/hooks/timelineSyncHydration.ts +2 -1
  44. package/src/utils/authoredSource.test.ts +25 -0
  45. package/src/utils/authoredSource.ts +3 -5
  46. package/src/utils/rounding.ts +7 -0
  47. package/dist/chunk-LOVBLSMR.js.map +0 -1
  48. package/dist/chunk-TFLU2MGI.js.map +0 -1
  49. package/dist/chunk-UYWON5AX.js.map +0 -1
  50. /package/dist/{chunk-H2DUOXTF.js.map → chunk-G3EDKRZH.js.map} +0 -0
  51. /package/dist/{domEditingLayers-KBTPQKGA.js.map → domEditingLayers-PYST4G45.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/sourceScopedSelectorIndex.ts","../src/components/editor/domEditingDom.ts","../src/components/editor/domEditingTypes.ts","../src/player/lib/timelineText.ts","../src/utils/rounding.ts","../src/components/editor/colorValue.ts","../src/player/lib/playbackAdapter.ts","../src/player/lib/timelineElementHelpers.ts","../src/player/lib/storedVolume.ts","../src/utils/projectRouting.ts"],"sourcesContent":["/**\n * Occurrence index for a selector within its source document.\n *\n * The preview flattens multiple composition files into one DOM, so a raw\n * `querySelectorAll` index is not a stable source-file identity. Callers supply\n * their existing source resolver; this helper alone owns occurrence scoping.\n */\n\n/** Every element matching one selector, mapped to the source file it belongs to\n * and its occurrence index within that file. One document query fills it. */\ntype SelectorOccurrences = Map<Element, { scope: string; index: number }>;\n\ninterface SelectorIndexPass {\n doc: Document;\n bySelector: Map<string, SelectorOccurrences>;\n}\n\nlet activePass: SelectorIndexPass | null = null;\n\n/**\n * Share one occurrence index per selector across every\n * `getSourceScopedSelectorIndex` call made synchronously inside `run`.\n *\n * Unshared, each call runs its own whole-document `querySelectorAll(selector)`\n * and resolves the source file of every match. A rebuild that walks n elements\n * sharing a selector therefore does n whole-document queries and n² resolver\n * calls — a composition of repeated cards or tiles is exactly that shape. One\n * index per selector makes the same pass linear.\n *\n * Correctness rests on the pass being ONE synchronous walk of a document that\n * does not change under it: nothing invalidates the index, so `run` must not\n * mutate `doc`, and every call inside it must resolve source files the same way\n * (the resolver may be a fresh closure per call, as long as it answers the\n * same). Outside a pass the index is per-call, exactly as before.\n */\nexport function withSelectorIndexPass<T>(doc: Document, run: () => T): T {\n const previous = activePass;\n activePass = { doc, bySelector: new Map() };\n try {\n return run();\n } finally {\n activePass = previous;\n }\n}\n\nfunction buildOccurrences(\n doc: Document,\n selector: string,\n resolveSourceFile: (candidate: Element) => string | undefined,\n): SelectorOccurrences {\n const occurrences: SelectorOccurrences = new Map();\n const counts = new Map<string, number>();\n for (const candidate of doc.querySelectorAll(selector)) {\n const scope = resolveSourceFile(candidate) ?? \"index.html\";\n const index = counts.get(scope) ?? 0;\n counts.set(scope, index + 1);\n occurrences.set(candidate, { scope, index });\n }\n return occurrences;\n}\n\nexport function getSourceScopedSelectorIndex(\n doc: Document,\n el: Element,\n selector: string | undefined,\n sourceFile: string | undefined,\n resolveSourceFile: (candidate: Element) => string | undefined,\n): number | undefined {\n if (!selector || selector.startsWith(\"#\") || selector.startsWith(\"[data-composition-id=\")) {\n return undefined;\n }\n\n try {\n const pass = activePass?.doc === doc ? activePass : null;\n let occurrences = pass?.bySelector.get(selector);\n if (!occurrences) {\n occurrences = buildOccurrences(doc, selector, resolveSourceFile);\n pass?.bySelector.set(selector, occurrences);\n }\n // An element outside the requested scope is not in that scope's occurrence\n // run at all, which is the `indexOf` miss the filtered form returned before.\n const hit = occurrences.get(el);\n return hit && hit.scope === (sourceFile ?? \"index.html\") ? hit.index : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * Low-level DOM primitives: type guards, style getters, CSS escaping,\n * selector utilities, and composition source resolution.\n * No imports from other domEditing* modules — safe to import from anywhere.\n */\nimport { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from \"@hyperframes/core/color-grading\";\nimport { getSourceScopedSelectorIndex } from \"../../utils/sourceScopedSelectorIndex\";\nimport { CURATED_STYLE_PROPERTIES } from \"./domEditingTypes\";\n\n// ─── Type guard ───────────────────────────────────────────────────────────────\n\nexport function isHtmlElement(value: unknown): value is HTMLElement {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"nodeType\" in value &&\n typeof (value as { nodeType?: unknown }).nodeType === \"number\" &&\n (value as { nodeType: number }).nodeType === 1\n );\n}\n\n// ─── Style parsing ────────────────────────────────────────────────────────────\n\n// Single source of truth lives in @hyperframes/core/editing so the studio\n// callers and the core resolver can't drift. Re-exported here to keep this\n// module's public surface (6 studio callers import parsePx from it).\nexport { parsePx } from \"@hyperframes/core/editing\";\n\nexport function isTextBearingTag(tagName: string): boolean {\n return [\"div\", \"span\", \"p\", \"strong\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"].includes(tagName);\n}\n\nexport function isEditableTextLeaf(el: HTMLElement): boolean {\n return isTextBearingTag(el.tagName.toLowerCase()) && el.children.length === 0;\n}\n\n/** Does this node render AT ALL, ignoring what it inherits? Sole owner of the\n * rule; the walk below only decides which nodes to ask it about. */\nfunction elementRendersItself(win: Window, el: HTMLElement): boolean {\n const computed = win.getComputedStyle(el);\n if (computed.display === \"none\" || computed.visibility === \"hidden\") return false;\n const opacity = Number.parseFloat(computed.opacity);\n return !(\n Number.isFinite(opacity) &&\n opacity <= 0.01 &&\n !el.hasAttribute(COLOR_GRADING_SOURCE_HIDDEN_ATTR)\n );\n}\n\n/**\n * Does `el` render, given everything above it?\n *\n * `memo` is for a caller asking this about MANY elements in one synchronous\n * pass. Answers are a function of the node and its ancestors, and siblings\n * share almost all of their chain, so memoizing per node turns a walk per\n * element into one style read per node in the tree. It is only ever valid for\n * the length of one pass — the DOM cannot change under a pass, and every read\n * here is a read — so the caller creates it and drops it, and nothing survives\n * to be invalidated. Omitted, every call walks the chain itself.\n *\n * The ANSWER is what it always was. Which nodes get a style read is not: this\n * resolves top-down and stops at the first node that is out, where the previous\n * version resolved bottom-up and stopped at the first one that is out going the\n * other way. Same boolean for every input, a different (and, for a subtree\n * hidden near the root, smaller) set of reads.\n */\nexport function isElementVisibleThroughAncestors(\n el: HTMLElement,\n memo?: Map<HTMLElement, boolean>,\n): boolean {\n const win = el.ownerDocument.defaultView;\n if (!win) return true;\n // Up to the first node already answered for, then back down: a node's answer\n // needs its ancestors' first, and the topmost unanswered node is where the\n // chain of unknowns starts.\n const pending: HTMLElement[] = [];\n let inherited = true;\n for (let node: HTMLElement | null = el; node; node = node.parentElement) {\n const answered = memo?.get(node);\n if (answered !== undefined) {\n inherited = answered;\n break;\n }\n pending.push(node);\n }\n for (let i = pending.length - 1; i >= 0; i -= 1) {\n const node = pending[i]!;\n // Once an ancestor is out, its descendants are out with it, and asking the\n // platform about them would be a style read for an answer already known.\n inherited = inherited && elementRendersItself(win, node);\n memo?.set(node, inherited);\n }\n return inherited;\n}\n\n// ─── Style accessors ──────────────────────────────────────────────────────────\n\nexport function getCuratedComputedStyles(el: HTMLElement): Record<string, string> {\n const styles: Record<string, string> = {};\n const computed = el.ownerDocument.defaultView?.getComputedStyle(el);\n if (!computed) return styles;\n\n for (const prop of CURATED_STYLE_PROPERTIES) {\n const value = computed.getPropertyValue(prop);\n if (value) styles[prop] = value;\n }\n\n return styles;\n}\n\nexport function getInlineStyles(el: HTMLElement): Record<string, string> {\n const styles: Record<string, string> = {};\n for (const property of CURATED_STYLE_PROPERTIES) {\n const value = el.style.getPropertyValue(property);\n if (value) styles[property] = value;\n }\n return styles;\n}\n\nexport function getDataAttributes(el: HTMLElement): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of el.attributes) {\n if (attr.name.startsWith(\"data-\")) {\n attrs[attr.name.slice(5)] = attr.value;\n }\n }\n return attrs;\n}\n\n// ─── DOM traversal ────────────────────────────────────────────────────────────\n\nexport function findClosestByAttribute(\n el: HTMLElement,\n attributeNames: string[],\n): HTMLElement | null {\n let current: HTMLElement | null = el;\n while (current) {\n const candidate = current;\n if (attributeNames.some((attribute) => candidate.hasAttribute(attribute))) {\n return candidate;\n }\n current = current.parentElement;\n }\n return null;\n}\n// ─── Composition source resolution ───────────────────────────────────────────\n\n// The runtime INLINES subcompositions and strips the source-file linkage from the\n// mounted root (it keeps `data-composition-id` but drops `data-composition-src`/\n// `-file`), so a subcomp element's DOM ancestors no longer say which file it came\n// from. This project-global map (composition-id → source file, built once from\n// index.html's clips — see NLEContext/EditorShell) recovers it. The studio loads one project at a\n// time, so module scope is the right lifetime; it's empty until set, in which case\n// resolution falls back to the historical attribute-only behavior.\nlet compositionSourceMap: Map<string, string> = new Map();\n// Bumped on every replacement so a consumer that memoizes a resolved source file\n// can tell that the map it resolved against is gone. The map is module state\n// with no DOM footprint, so nothing else can observe the change.\nlet compositionSourceMapRevision = 0;\n\nexport function setCompositionSourceMap(map: Map<string, string>): void {\n compositionSourceMap = map;\n compositionSourceMapRevision += 1;\n}\n\nexport function getCompositionSourceMapRevision(): number {\n return compositionSourceMapRevision;\n}\n\nfunction sourceFromCompositionId(ownerRoot: HTMLElement | null): string | undefined {\n if (!ownerRoot || compositionSourceMap.size === 0) return undefined;\n // The runtime may rename the mounted id to a runtime-unique one, preserving the\n // authored id on `data-hf-original-composition-id` — prefer that, then the current id.\n const authored = ownerRoot.getAttribute(\"data-hf-original-composition-id\");\n const current = ownerRoot.getAttribute(\"data-composition-id\");\n return (\n (authored ? compositionSourceMap.get(authored) : undefined) ??\n (current ? compositionSourceMap.get(current) : undefined)\n );\n}\n\nexport function getSourceFileForElement(\n el: HTMLElement,\n activeCompositionPath: string | null,\n): { sourceFile: string; compositionPath: string } {\n const sourceHost = findClosestByAttribute(el, [\"data-composition-file\", \"data-composition-src\"]);\n const ownerRoot = findClosestByAttribute(el, [\"data-composition-id\"]);\n const sourceFile =\n sourceHost?.getAttribute(\"data-composition-file\") ??\n sourceHost?.getAttribute(\"data-composition-src\") ??\n ownerRoot?.getAttribute(\"data-composition-file\") ??\n ownerRoot?.getAttribute(\"data-composition-src\") ??\n sourceFromCompositionId(ownerRoot) ??\n activeCompositionPath ??\n \"index.html\";\n\n return {\n sourceFile,\n compositionPath: sourceFile,\n };\n}\n\nexport function normalizeTimelineCompositionSource(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n if (!trimmed) return undefined;\n if (!/^([a-z][a-z0-9+.-]*:|\\/)/i.test(trimmed)) return trimmed;\n\n let pathname = trimmed;\n try {\n pathname = new URL(trimmed, \"http://studio.local\").pathname;\n } catch {\n pathname = trimmed;\n }\n\n for (const marker of [\"/preview/comp/\", \"/preview/\"]) {\n const markerIndex = pathname.indexOf(marker);\n if (markerIndex < 0) continue;\n const sourcePath = pathname.slice(markerIndex + marker.length).replace(/^\\/+/, \"\");\n return sourcePath || trimmed;\n }\n\n return trimmed;\n}\n\n// ─── CSS escaping ─────────────────────────────────────────────────────────────\n\nfunction escapeCssIdentifier(value: string): string {\n const css = globalThis.CSS as { escape?: (input: string) => string } | undefined;\n if (typeof css?.escape === \"function\") return css.escape(value);\n\n if (value === \"-\") return \"\\\\-\";\n\n let escaped = \"\";\n for (let index = 0; index < value.length; index += 1) {\n const char = value[index] ?? \"\";\n const code = char.charCodeAt(0);\n if (code === 0) {\n escaped += \"�\";\n continue;\n }\n\n const isDigit = code >= 48 && code <= 57;\n const isUpperAlpha = code >= 65 && code <= 90;\n const isLowerAlpha = code >= 97 && code <= 122;\n const isControl = (code >= 1 && code <= 31) || code === 127;\n const isLeadingDigit = index === 0 && isDigit;\n const isSecondDigitAfterDash = index === 1 && value.startsWith(\"-\") && isDigit;\n if (isControl || isLeadingDigit || isSecondDigitAfterDash) {\n escaped += `\\\\${code.toString(16)} `;\n continue;\n }\n if (isUpperAlpha || isLowerAlpha || isDigit || char === \"-\" || char === \"_\" || code >= 128) {\n escaped += char;\n continue;\n }\n escaped += `\\\\${char}`;\n }\n return escaped;\n}\n\nexport function escapeCssString(value: string): string {\n return value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\a \")\n .replace(/\\r/g, \"\\\\d \")\n .replace(/\\f/g, \"\\\\c \");\n}\n\nexport function querySelectorAllSafely(doc: Document, selector: string): Element[] {\n try {\n return Array.from(doc.querySelectorAll(selector));\n } catch {\n return [];\n }\n}\n\nfunction humanizeIdentifier(value: string): string {\n return (\n value\n .replace(/\\.html$/i, \"\")\n .replace(/^compositions\\//i, \"\")\n .split(\"/\")\n .at(-1)\n ?.replace(/[-_]+/g, \" \")\n .replace(/\\b\\w/g, (char) => char.toUpperCase()) ?? value\n );\n}\n\n// ─── CSS selector building ────────────────────────────────────────────────────\n\nexport function buildStableSelector(el: HTMLElement): string | undefined {\n if (el.id) return `#${escapeCssIdentifier(el.id)}`;\n\n const compositionId = el.getAttribute(\"data-composition-id\");\n if (compositionId) return `[data-composition-id=\"${escapeCssString(compositionId)}\"]`;\n\n // Group wrappers carry no id/class; their data-hf-group value is the unique,\n // stable handle the source mutations write — use it so the wrapper is\n // selectable, patchable (move/scale), and addressable for ungroup.\n const group = el.getAttribute(\"data-hf-group\");\n if (group) return `[data-hf-group=\"${escapeCssString(group)}\"]`;\n\n return getPreferredClassSelector(el);\n}\n\nfunction getPreferredClassSelector(el: HTMLElement): string | undefined {\n const classes = Array.from(el.classList)\n .map((value) => value.trim())\n .filter(Boolean);\n if (classes.length === 0) return undefined;\n const preferred =\n classes.find((value) => value !== \"clip\" && !value.startsWith(\"__hf-\")) ?? classes[0];\n return preferred ? `.${escapeCssIdentifier(preferred)}` : undefined;\n}\n\n// fallow-ignore-next-line complexity\nexport function buildElementLabel(el: HTMLElement): string {\n const compositionId =\n el.getAttribute(\"data-hf-original-composition-id\") ?? el.getAttribute(\"data-composition-id\");\n if (compositionId && compositionId !== \"main\") {\n return humanizeIdentifier(compositionId);\n }\n\n const compositionSrc =\n el.getAttribute(\"data-composition-src\") ?? el.getAttribute(\"data-composition-file\");\n if (compositionSrc) {\n return humanizeIdentifier(compositionSrc);\n }\n\n const group = el.getAttribute(\"data-hf-group\");\n if (group) return group;\n\n if (el.id) return humanizeIdentifier(el.id);\n\n const preferredClass = getPreferredClassSelector(el);\n if (preferredClass) {\n return humanizeIdentifier(preferredClass.replace(/^\\./, \"\"));\n }\n\n const text = (el.textContent ?? \"\").trim().replace(/\\s+/g, \" \");\n if (text) return text.length > 40 ? `${text.slice(0, 39)}…` : text;\n return el.tagName.toLowerCase();\n}\n\nexport function getSelectorIndex(\n doc: Document,\n el: HTMLElement,\n selector: string | undefined,\n sourceFile: string,\n activeCompositionPath: string | null,\n): number | undefined {\n if (!selector?.startsWith(\".\")) return undefined;\n\n return getSourceScopedSelectorIndex(doc, el, selector, sourceFile, (candidate) =>\n isHtmlElement(candidate)\n ? getSourceFileForElement(candidate, activeCompositionPath).sourceFile\n : undefined,\n );\n}\n","import type { PatchTarget } from \"../../utils/sourcePatcher\";\nimport type { GsapAnimation } from \"@hyperframes/parsers/gsap-parser\";\n\nexport const CURATED_STYLE_PROPERTIES = [\n \"position\",\n \"display\",\n \"top\",\n \"left\",\n \"right\",\n \"bottom\",\n \"inset\",\n \"width\",\n \"height\",\n \"gap\",\n \"justify-content\",\n \"align-items\",\n \"flex-direction\",\n \"font-size\",\n \"font-style\",\n \"font-weight\",\n \"font-family\",\n \"line-height\",\n \"letter-spacing\",\n \"text-align\",\n \"text-transform\",\n \"color\",\n \"background-color\",\n \"background-image\",\n \"opacity\",\n \"mix-blend-mode\",\n \"border-radius\",\n \"border-width\",\n \"border-style\",\n \"border-color\",\n \"border-top-width\",\n \"border-top-style\",\n \"border-top-color\",\n \"outline-color\",\n \"overflow\",\n \"clip-path\",\n \"box-shadow\",\n \"filter\",\n \"backdrop-filter\",\n \"z-index\",\n \"transform\",\n \"object-fit\",\n \"object-position\",\n] as const;\n\nexport interface DomEditCapabilities {\n canSelect: boolean;\n canEditStyles: boolean;\n /** Can take a non-destructive `clip-path: inset()` crop — broader than\n * canEditStyles (a sub-composition host is croppable from the parent view). */\n canCrop: boolean;\n /** Directly editable authored left/top style fields. Canvas drag uses manual edits instead. */\n canMove: boolean;\n /** Directly editable authored width/height style fields. Canvas resize uses manual edits instead. */\n canResize: boolean;\n canApplyManualOffset: boolean;\n canApplyManualSize: boolean;\n canApplyManualRotation: boolean;\n reasonIfDisabled?: string;\n commitCheckPending?: boolean;\n}\n\nexport interface DomEditTextField {\n key: string;\n label: string;\n value: string;\n tagName: string;\n attributes: Array<{ name: string; value: string }>;\n inlineStyles: Record<string, string>;\n computedStyles: Record<string, string>;\n source: \"self\" | \"child\" | \"text-node\";\n sourceChildIndex?: number;\n}\n\nexport interface DomEditSelection extends PatchTarget {\n element: HTMLElement;\n label: string;\n tagName: string;\n sourceFile: string;\n compositionPath: string;\n compositionSrc?: string;\n isCompositionHost: boolean;\n isInsideLockedComposition: boolean;\n boundingBox: { x: number; y: number; width: number; height: number };\n textContent: string | null;\n dataAttributes: Record<string, string>;\n inlineStyles: Record<string, string>;\n computedStyles: Record<string, string>;\n textFields: DomEditTextField[];\n capabilities: DomEditCapabilities;\n existsInSource?: boolean;\n gsapAnimations?: GsapAnimation[];\n}\n\nexport interface DomEditLayerItem {\n key: string;\n element: HTMLElement;\n label: string;\n tagName: string;\n depth: number;\n childCount: number;\n id?: string;\n hfId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile: string;\n}\n\nexport interface DomEditContextOptions {\n activeCompositionPath: string | null;\n isMasterView: boolean;\n preferClipAncestor?: boolean;\n /** The group wrapper the user has drilled into (null = top level). Selection\n * resolution treats groups as a unit unless drilled into one. */\n activeGroupElement?: HTMLElement | null;\n}\n\nexport interface DomEditViewport {\n width: number;\n height: number;\n}\n\nexport interface TimelineElementDomTarget {\n id?: string;\n domId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile?: string;\n compositionSrc?: string;\n}\n\nexport interface TimelineElementDomTargetOptions {\n activeCompositionPath: string | null;\n compIdToSrc?: ReadonlyMap<string, string>;\n isMasterView: boolean;\n}\n","import { isHtmlElement } from \"@hyperframes/core/runtime/dom-realm\";\nimport { parseCssColor } from \"../../components/editor/colorValue\";\nimport type { TimelineText } from \"../store/timelineElement\";\nimport {\n getCuratedComputedStyles,\n isEditableTextLeaf,\n isTextBearingTag,\n} from \"../../components/editor/domEditingDom\";\n\n/** A layer that paints only text and a flat colour (a text tag whose children are all text leaves,\n * no background image): its words and look. Anything painted beyond that keeps its picture. */\nexport function readTimelineText(el: Element): TimelineText | undefined {\n if (!isHtmlElement(el) || !isTextBearingTag(el.localName)) return undefined;\n const children = Array.from(el.children);\n if (!children.every((child) => isHtmlElement(child) && isEditableTextLeaf(child)))\n return undefined;\n const value = el.textContent?.replace(/\\s+/g, \" \").trim();\n if (!value) return undefined;\n const style = getCuratedComputedStyles(el);\n if ((style[\"background-image\"] ?? \"none\") !== \"none\") return undefined;\n const background = style[\"background-color\"];\n return {\n value,\n fontFamily: style[\"font-family\"],\n fontWeight: style[\"font-weight\"],\n color: style.color,\n background: background && parseCssColor(background)?.alpha === 1 ? background : undefined,\n };\n}\n\nexport function sameTimelineText(a?: TimelineText, b?: TimelineText): boolean {\n if (!a || !b) return a === b;\n return (\n a.value === b.value &&\n a.fontFamily === b.fontFamily &&\n a.fontWeight === b.fontWeight &&\n a.color === b.color &&\n a.background === b.background\n );\n}\n","/** Round to 3 decimal places (millisecond precision for GSAP values). */\nexport function roundTo3(val: number): number {\n return Math.round(val * 1000) / 1000;\n}\n\n/** Whole CSS px: GSAP parses a -50% translate against the integer offsetWidth/Height. */\nexport function roundToLayoutPx(val: number): number {\n return Math.round(val);\n}\n\n/** Round to 2 decimal places (centisecond precision for timeline values). */\nexport function roundToCenti(val: number): number {\n return Math.round(val * 100) / 100;\n}\n","import { roundToCenti } from \"../../utils/rounding\";\n\nexport interface ParsedColor {\n red: number;\n green: number;\n blue: number;\n alpha: number;\n}\n\nexport interface HsvColor {\n hue: number;\n saturation: number;\n value: number;\n}\n\nfunction clampChannel(value: number): number {\n return Math.max(0, Math.min(255, Math.round(value)));\n}\n\nfunction clampAlpha(value: number): number {\n return Math.max(0, Math.min(1, value));\n}\n\nfunction toHex(value: number): string {\n return clampChannel(value).toString(16).padStart(2, \"0\");\n}\n\nfunction formatAlpha(value: number): string {\n return `${roundToCenti(clampAlpha(value))}`;\n}\n\nfunction parseComponent(value: string, scale: number): number {\n return value.endsWith(\"%\") ? (Number(value.slice(0, -1)) * scale) / 100 : Number(value);\n}\n\nconst NUMBER = String.raw`(?:\\d+(?:\\.\\d+)?|\\.\\d+)`;\nconst COMMA_RGB = new RegExp(\n String.raw`^rgba?\\(\\s*(${NUMBER})\\s*,\\s*(${NUMBER})\\s*,\\s*(${NUMBER})(?:\\s*,\\s*(${NUMBER}))?\\s*\\)$`,\n);\nconst SPACE_RGB = new RegExp(\n String.raw`^rgba?\\(\\s*(${NUMBER}%?)\\s+(${NUMBER}%?)\\s+(${NUMBER}%?)(?:\\s*\\/\\s*(${NUMBER}%?))?\\s*\\)$`,\n);\n\nfunction parseSerializedColor(value: string): ParsedColor | null {\n const trimmed = value.trim().toLowerCase();\n if (!trimmed) return null;\n if (trimmed === \"transparent\") {\n return { red: 0, green: 0, blue: 0, alpha: 0 };\n }\n\n const hex = trimmed.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);\n if (hex) {\n const digits = hex[1].length <= 4 ? [...hex[1]].map((digit) => digit + digit).join(\"\") : hex[1];\n return {\n red: Number.parseInt(digits.slice(0, 2), 16),\n green: Number.parseInt(digits.slice(2, 4), 16),\n blue: Number.parseInt(digits.slice(4, 6), 16),\n alpha: digits.length === 8 ? Number.parseInt(digits.slice(6, 8), 16) / 255 : 1,\n };\n }\n\n const rgba = trimmed.match(COMMA_RGB) ?? trimmed.match(SPACE_RGB);\n if (rgba) {\n return {\n red: clampChannel(parseComponent(rgba[1], 255)),\n green: clampChannel(parseComponent(rgba[2], 255)),\n blue: clampChannel(parseComponent(rgba[3], 255)),\n alpha: clampAlpha(rgba[4] != null ? parseComponent(rgba[4], 1) : 1),\n };\n }\n\n return null;\n}\n\nlet colorContext: CanvasRenderingContext2D | null = null;\n\nfunction canResolveInBrowser(value: string): boolean {\n return (\n typeof document !== \"undefined\" &&\n typeof CSS !== \"undefined\" &&\n CSS.supports(\"color\", value) &&\n !/\\bcurrentcolor\\b|\\bvar\\s*\\(|\\blight-dark\\s*\\(/i.test(value)\n );\n}\n\nfunction parseBrowserColor(value: string): ParsedColor | null {\n try {\n if (!canResolveInBrowser(value)) return null;\n colorContext ??= document.createElement(\"canvas\").getContext(\"2d\");\n if (!colorContext) return null;\n return (\n parseCanvasColor(\n colorContext,\n `color(from ${value} srgb r g b / alpha)`,\n parseSrgbSerialization,\n ) ?? parseCanvasColor(colorContext, value, parseSerializedColor)\n );\n } catch {\n return null;\n }\n}\n\nfunction parseCanvasColor(\n context: CanvasRenderingContext2D,\n value: string,\n parse: (serialized: string) => ParsedColor | null,\n): ParsedColor | null {\n const serialized = readCanvasColor(context, value);\n return serialized === null ? null : parse(serialized);\n}\n\nfunction readCanvasColor(context: CanvasRenderingContext2D, value: string): string | null {\n context.fillStyle = \"transparent\";\n context.fillStyle = value;\n const first = context.fillStyle;\n context.fillStyle = \"white\";\n context.fillStyle = value;\n return typeof first === \"string\" && first === context.fillStyle ? first : null;\n}\n\nfunction parseSrgbSerialization(serialized: string): ParsedColor | null {\n const match = serialized.match(/^color\\(srgb ([^ ]+) ([^ ]+) ([^ /)]+)(?: \\/ ([^)]+))?\\)$/);\n if (!match) return null;\n const channels = match.slice(1, 4).map(Number);\n const alpha = match[4] === undefined ? 1 : Number(match[4]);\n if (!channels.every(Number.isFinite) || !Number.isFinite(alpha)) return null;\n return {\n red: clampChannel(channels[0] * 255),\n green: clampChannel(channels[1] * 255),\n blue: clampChannel(channels[2] * 255),\n alpha: clampAlpha(alpha),\n };\n}\n\nexport function parseCssColor(value: string): ParsedColor | null {\n return parseSerializedColor(value) ?? parseBrowserColor(value.trim());\n}\n\nexport function resolvePickerColor(\n value: string | undefined,\n element: Element | null,\n fallback: string,\n): string {\n const view = element?.ownerDocument.defaultView;\n const parsed =\n (value ? parseCssColor(value) : null) ??\n (element && view ? parseCssColor(view.getComputedStyle(element).color) : null);\n return parsed ? toHexColor(parsed) : fallback;\n}\n\nexport function toColorPickerValue(value: string): string {\n const parsed = parseCssColor(value);\n if (!parsed) return \"#000000\";\n return toHexColor(parsed);\n}\n\nexport function toHexColor(color: Pick<ParsedColor, \"red\" | \"green\" | \"blue\">): string {\n return `#${toHex(color.red)}${toHex(color.green)}${toHex(color.blue)}`;\n}\n\nexport function formatCssColor(color: ParsedColor): string {\n const red = clampChannel(color.red);\n const green = clampChannel(color.green);\n const blue = clampChannel(color.blue);\n const alpha = clampAlpha(color.alpha);\n\n if (alpha >= 1) {\n return `rgb(${red}, ${green}, ${blue})`;\n }\n\n return `rgba(${red}, ${green}, ${blue}, ${formatAlpha(alpha)})`;\n}\n\nexport function rgbToHsv(color: Pick<ParsedColor, \"red\" | \"green\" | \"blue\">): HsvColor {\n const red = clampChannel(color.red) / 255;\n const green = clampChannel(color.green) / 255;\n const blue = clampChannel(color.blue) / 255;\n const max = Math.max(red, green, blue);\n const min = Math.min(red, green, blue);\n const delta = max - min;\n\n let hue = 0;\n if (delta !== 0) {\n if (max === red) {\n hue = 60 * (((green - blue) / delta) % 6);\n } else if (max === green) {\n hue = 60 * ((blue - red) / delta + 2);\n } else {\n hue = 60 * ((red - green) / delta + 4);\n }\n }\n\n if (hue < 0) hue += 360;\n\n return {\n hue,\n saturation: max === 0 ? 0 : delta / max,\n value: max,\n };\n}\n\nexport function hsvToRgb(color: HsvColor): Pick<ParsedColor, \"red\" | \"green\" | \"blue\"> {\n const hue = (((color.hue % 360) + 360) % 360) / 60;\n const saturation = Math.max(0, Math.min(1, color.saturation));\n const value = Math.max(0, Math.min(1, color.value));\n const chroma = value * saturation;\n const x = chroma * (1 - Math.abs((hue % 2) - 1));\n const m = value - chroma;\n\n let red = 0;\n let green = 0;\n let blue = 0;\n\n if (hue >= 0 && hue < 1) {\n red = chroma;\n green = x;\n } else if (hue >= 1 && hue < 2) {\n red = x;\n green = chroma;\n } else if (hue >= 2 && hue < 3) {\n green = chroma;\n blue = x;\n } else if (hue >= 3 && hue < 4) {\n green = x;\n blue = chroma;\n } else if (hue >= 4 && hue < 5) {\n red = x;\n blue = chroma;\n } else {\n red = chroma;\n blue = x;\n }\n\n return {\n red: clampChannel((red + m) * 255),\n green: clampChannel((green + m) * 255),\n blue: clampChannel((blue + m) * 255),\n };\n}\n\nexport function mergeColorWithExistingAlpha(nextHex: string, previousValue: string): string {\n const hex = nextHex.trim();\n const match = hex.match(/^#([0-9a-f]{6})$/i);\n if (!match) return previousValue;\n\n const previous = parseCssColor(previousValue);\n const red = Number.parseInt(match[1].slice(0, 2), 16);\n const green = Number.parseInt(match[1].slice(2, 4), 16);\n const blue = Number.parseInt(match[1].slice(4, 6), 16);\n const alpha = previous?.alpha ?? 1;\n\n return formatCssColor({ red, green, blue, alpha });\n}\n","/**\n * Playback adapter utilities: factory for the static-seek adapter used when a\n * composition exposes only a `renderSeek` / `seek` API (no native play/pause\n * support), plus a thin wrapper that normalises GSAP-style `TimelineLike`\n * objects to the `PlaybackAdapter` interface.\n */\n\nimport type {\n PlaybackAdapter,\n RuntimePlaybackAdapter,\n StaticSeekPlaybackClock,\n TimelineLike,\n} from \"./playbackTypes\";\n\n// ---------------------------------------------------------------------------\n// Pure numeric helpers\n// ---------------------------------------------------------------------------\n\nexport function isFinitePositive(value: number): boolean {\n return Number.isFinite(value) && value > 0;\n}\n\nfunction clampTime(time: number, duration: number): number {\n const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);\n const safeTime = Math.max(0, Number.isFinite(time) ? time : 0);\n return safeDuration > 0 ? Math.min(safeTime, safeDuration) : safeTime;\n}\n\nexport function getAdapterDuration(adapter: PlaybackAdapter | null | undefined): number {\n if (!adapter) return 0;\n try {\n const duration = Number(adapter.getDuration());\n return isFinitePositive(duration) ? duration : 0;\n } catch {\n return 0;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Clock factory\n// ---------------------------------------------------------------------------\n\nexport function getDefaultStaticSeekPlaybackClock(win: Window): StaticSeekPlaybackClock {\n return {\n now: () => win.performance.now(),\n requestAnimationFrame: (callback) => win.requestAnimationFrame(callback),\n cancelAnimationFrame: (handle) => win.cancelAnimationFrame(handle),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Static-seek adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps a render-only player (exposes `renderSeek`/`seek` but no native\n * play/pause) and drives playback via `requestAnimationFrame`.\n */\nexport function createStaticSeekPlaybackAdapter(\n player: Pick<RuntimePlaybackAdapter, \"getTime\"> &\n Partial<Pick<RuntimePlaybackAdapter, \"renderSeek\" | \"seek\">>,\n duration: number,\n clock: StaticSeekPlaybackClock,\n getPlaybackRate: () => number = () => 1,\n): PlaybackAdapter {\n const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);\n let currentTime = clampTime(Number(player.getTime?.() ?? 0), safeDuration);\n let playing = false;\n let rafId = 0;\n let playStartTime = currentTime;\n let playStartNow = clock.now();\n\n const renderSeek = (time: number) => {\n currentTime = clampTime(time, safeDuration);\n if (typeof player.renderSeek === \"function\") {\n player.renderSeek(currentTime);\n return;\n }\n player.seek?.(currentTime);\n };\n\n const stopTicker = () => {\n if (rafId) {\n clock.cancelAnimationFrame(rafId);\n rafId = 0;\n }\n };\n\n const tick: FrameRequestCallback = (now) => {\n if (!playing) return;\n const playbackRate = Math.max(0.1, Number(getPlaybackRate()) || 1);\n const elapsed = ((now - playStartNow) / 1000) * playbackRate;\n renderSeek(playStartTime + elapsed);\n if (currentTime >= safeDuration) {\n playing = false;\n rafId = 0;\n return;\n }\n rafId = clock.requestAnimationFrame(tick);\n };\n\n return {\n play: () => {\n if (playing || safeDuration <= 0) return;\n if (currentTime >= safeDuration) renderSeek(0);\n playing = true;\n playStartTime = currentTime;\n playStartNow = clock.now();\n stopTicker();\n rafId = clock.requestAnimationFrame(tick);\n },\n pause: () => {\n playing = false;\n stopTicker();\n },\n seek: (time, options) => {\n renderSeek(time);\n if (options?.keepPlaying) {\n if (playing) {\n playStartTime = currentTime;\n playStartNow = clock.now();\n }\n return;\n }\n // Default seek aligns with wrapTimeline: stop the RAF ticker so the\n // adapter's `playing` flag matches the public seek contract instead of\n // silently driving renderSeek in the background.\n playing = false;\n stopTicker();\n },\n getTime: () => currentTime,\n getDuration: () => safeDuration,\n isPlaying: () => playing,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Static-seek fallback cache\n// ---------------------------------------------------------------------------\n\nexport type StaticSeekCacheEntry = {\n player: RuntimePlaybackAdapter | PlaybackAdapter;\n duration: number;\n adapter: PlaybackAdapter;\n};\n\ntype StaticSeekCacheRef = { current: StaticSeekCacheEntry | null };\ntype WarnedRef = { current: boolean };\n\n/**\n * Pause and drop the cached static-seek adapter. Must be called whenever\n * adapter selection switches to a native adapter — a cached static-seek\n * adapter that was mid-play keeps its private rAF loop seeking the player\n * forever otherwise, fighting the native transport. Also re-arms the\n * downgrade warning so a later re-downgrade is surfaced again.\n */\nexport function releaseStaticSeekCache(cache: StaticSeekCacheRef, warned: WarnedRef): void {\n cache.current?.adapter.pause();\n cache.current = null;\n warned.current = false;\n}\n\n/**\n * Resolve (with caching) the seek-driven fallback adapter. Warns once per\n * downgrade streak: seek-driven playback never starts media elements or\n * WebAudio, so without the warning the downgrade silently loses audio.\n */\nexport function resolveStaticSeekFallback(opts: {\n cache: StaticSeekCacheRef;\n warned: WarnedRef;\n bestAdapter: RuntimePlaybackAdapter | PlaybackAdapter;\n effectiveDuration: number;\n docDuration: number;\n clock: StaticSeekPlaybackClock;\n getPlaybackRate: () => number;\n}): PlaybackAdapter {\n const { cache, warned, bestAdapter, effectiveDuration, docDuration } = opts;\n const cached = cache.current;\n if (cached?.player === bestAdapter && cached.duration === effectiveDuration) {\n return cached.adapter;\n }\n cached?.adapter.pause();\n if (!warned.current) {\n warned.current = true;\n console.warn(\n `[useTimelinePlayer] Selected adapter duration (${getAdapterDuration(bestAdapter)}s) does not cover the document duration (${docDuration}s); falling back to seek-driven playback, which never starts media elements or WebAudio. Audio will not play in preview — extend the GSAP timeline to cover the declared data-duration.`,\n );\n }\n const adapter = createStaticSeekPlaybackAdapter(\n bestAdapter,\n effectiveDuration,\n opts.clock,\n opts.getPlaybackRate,\n );\n cache.current = { player: bestAdapter, duration: effectiveDuration, adapter };\n return adapter;\n}\n\n// ---------------------------------------------------------------------------\n// GSAP timeline wrapper\n// ---------------------------------------------------------------------------\n\nexport function wrapTimeline(tl: TimelineLike): PlaybackAdapter {\n return {\n play: () => tl.play(),\n pause: () => tl.pause(),\n seek: (t, options) => {\n const shouldPause = !options?.keepPlaying;\n if (shouldPause) tl.pause();\n tl.seek(t);\n if (shouldPause) tl.pause();\n },\n getTime: () => tl.time(),\n getDuration: () => tl.duration(),\n isPlaying: () => tl.isActive(),\n };\n}\n","/**\n * Low-level helpers for building and identifying TimelineElement objects.\n *\n * Covers: duration reading, media-element metadata extraction, selector/key/\n * identity builders, and DOM node lookup. These are\n * intentionally dependency-free (no store, no hooks) so they can be used in\n * both the React hook and test environments.\n */\n\nimport type { TimelineElement } from \"../store/playerStore\";\nimport { readTimelineText } from \"./timelineText\";\nimport type { ClipManifestClip } from \"./playbackTypes\";\nimport { isFinitePositive } from \"./playbackAdapter\";\nimport { getSourceScopedSelectorIndex } from \"../../utils/sourceScopedSelectorIndex\";\nimport { HF_AUDIO_GROUP_TAG } from \"@hyperframes/core/audio-groups\";\nimport { readElementFades } from \"@hyperframes/core/audio-fade\";\nimport { isHtmlElement, isImageElement, isMediaElement } from \"@hyperframes/core/runtime/dom-realm\";\nimport { elementVolume } from \"./storedVolume\";\nimport {\n type AttrReader,\n clampPlaybackRate,\n readMediaOffsetSeconds,\n} from \"@hyperframes/parsers/media-duration\";\n\n// ---------------------------------------------------------------------------\n// Layer-reveal lift transparency\n// ---------------------------------------------------------------------------\n\n/**\n * Attributes carrying the pre-lift state of a Layers-panel selection reveal\n * (useLayerRevealOverride): while a layer is selected it PAINTS on top via a\n * temporary inline z-index, but the lift is a purely visual, ephemeral studio\n * affordance — every z reader must keep reporting the element's TRUE z\n * (stored here) so menus, badges, the lane mirror, and the panel sort never\n * reason on the lifted value. A z-reorder commit removes the attributes (the\n * commit is the new truth).\n */\nexport const LAYER_REVEAL_PRIOR_Z_ATTR = \"data-hf-reveal-prior-z\";\nexport const LAYER_REVEAL_PRIOR_POSITION_ATTR = \"data-hf-reveal-prior-pos\";\n\n/** The lifted element's true (pre-lift) z, or null when no lift is active. */\nexport function readLayerRevealPriorZ(el: Element): number | null {\n const raw = el.getAttribute(LAYER_REVEAL_PRIOR_Z_ATTR);\n if (raw == null) return null;\n const n = Number.parseInt(raw, 10);\n return Number.isFinite(n) ? n : null;\n}\n\n// ---------------------------------------------------------------------------\n// Duration attribute helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read a host element's effective CSS stacking order for the timeline's reverse\n * z→lane mapping. Prefers the inline `style.zIndex` (what the canvas context\n * menu and LayersPanel z-edits write via handleDomZIndexReorderCommit), falls\n * back to computed style; \"auto\" / empty / unparseable ⇒ 0. Works with a\n * detached parse Document (no defaultView) as well as a live iframe. Mirrors\n * canvasContextMenuZOrder.parseZIndex semantics so the two directions agree.\n * Reveal-lift transparent: an active lift reports the stored TRUE z.\n */\nexport function readTimelineElementZIndex(el: Element): number {\n const prior = readLayerRevealPriorZ(el);\n if (prior != null) return prior;\n const html = el as HTMLElement;\n const parseZ = (value: string | null | undefined): number | null => {\n if (value == null || value === \"\" || value === \"auto\") return null;\n const n = Number.parseInt(value, 10);\n return Number.isFinite(n) ? n : null;\n };\n const fromInline = parseZ(html.style?.zIndex);\n if (fromInline != null) return fromInline;\n const view = el.ownerDocument?.defaultView;\n if (view?.getComputedStyle) {\n const fromComputed = parseZ(view.getComputedStyle(html).zIndex);\n if (fromComputed != null) return fromComputed;\n }\n return 0;\n}\n\nfunction readDurationAttribute(el: Element | null | undefined): number {\n if (!el) return 0;\n const duration =\n Number.parseFloat(el.getAttribute(\"data-duration\") ?? \"\") ||\n Number.parseFloat(el.getAttribute(\"data-hf-authored-duration\") ?? \"\");\n return isFinitePositive(duration) ? duration : 0;\n}\n\nexport function isTimelineIgnoredElement(el: Element): boolean {\n // An `<hf-audio-group>` is a mixer bus with no timing of its own, drawn as a group row, never a clip.\n if (el.tagName.toLowerCase() === HF_AUDIO_GROUP_TAG) return true;\n return Boolean(\n el.closest(\n [\n \"[data-hyperframes-ignore]\",\n \"[data-hyperframes-picker-ignore]\",\n \"[data-hf-ignore]\",\n \"[data-hf-color-grading-canvas]\",\n ].join(\",\"),\n ),\n );\n}\n\n/**\n * Furthest clip end (start + RAW `data-duration`) over every non-root clip in the\n * document. Reads the authored attribute, NOT any runtime-computed value — so it\n * is immune to the runtime's clamp that truncates a clip's live duration to the\n * composition length. This is the source of truth for content-driven duration:\n * computing it from the store instead would feed the truncated value back in and\n * make the composition length ratchet down (research HANDOFF-3 §6.1 feedback loop).\n */\nexport function furthestClipEndFromDocument(doc: Document | null | undefined): number {\n if (!doc) return 0;\n const root = doc.querySelector(\"[data-composition-id]\");\n let maxEnd = 0;\n for (const node of Array.from(doc.querySelectorAll(\"[data-start]\"))) {\n if (node === root || isTimelineIgnoredElement(node)) continue;\n const start = Number.parseFloat(node.getAttribute(\"data-start\") ?? \"\");\n const duration = readDurationAttribute(node);\n if (!Number.isFinite(start) || start < 0 || duration <= 0) continue;\n maxEnd = Math.max(maxEnd, start + duration);\n }\n return maxEnd;\n}\n\nexport function readTimelineDurationFromDocument(doc: Document | null | undefined): number {\n if (!doc) return 0;\n const rootDuration = readDurationAttribute(doc.querySelector(\"[data-composition-id]\"));\n if (rootDuration > 0) return rootDuration;\n return furthestClipEndFromDocument(doc);\n}\n\n// ---------------------------------------------------------------------------\n// DOM element type guards\n// ---------------------------------------------------------------------------\n\nfunction isCompositionHost(el: Element): boolean {\n return (\n el.hasAttribute(\"data-composition-id\") ||\n el.hasAttribute(\"data-composition-src\") ||\n el.hasAttribute(\"data-composition-file\")\n );\n}\n\nexport function resolveMediaElement(el: Element): HTMLMediaElement | HTMLImageElement | null {\n if (isMediaElement(el) || isImageElement(el)) return el;\n // A composition's media belongs to its own timeline, not the clip's: its length would cap a trim.\n if (isCompositionHost(el)) return null;\n const candidate = el.querySelector(\"video, audio, img\");\n return isMediaElement(candidate) || isImageElement(candidate) ? candidate : null;\n}\n\n/** The in-point as playback reads it, and the attribute holding it; empty when neither is authored. */\nexport function readPlaybackStartAttributes(\n getAttr: AttrReader,\n): Pick<TimelineElement, \"playbackStart\" | \"playbackStartAttr\"> {\n const playbackStartAttr =\n getAttr(\"data-playback-start\") != null\n ? \"playback-start\"\n : getAttr(\"data-media-start\") != null\n ? \"media-start\"\n : undefined;\n return playbackStartAttr\n ? { playbackStart: readMediaOffsetSeconds(getAttr), playbackStartAttr }\n : {};\n}\n\nexport function playbackStartAttributeForElement(\n element: Pick<TimelineElement, \"kind\" | \"playbackStartAttr\">,\n): \"data-media-start\" | \"data-playback-start\" {\n return element.playbackStartAttr === \"playback-start\" || element.kind === \"composition\"\n ? \"data-playback-start\"\n : \"data-media-start\";\n}\n\nfunction applyPlaybackMetadataFromElement(entry: TimelineElement, el: Element): void {\n Object.assign(\n entry,\n readPlaybackStartAttributes((n) => el.getAttribute(n)),\n );\n\n const authoredPlaybackRate = Number.parseFloat(el.getAttribute(\"data-playback-rate\") ?? \"\");\n if (Number.isFinite(authoredPlaybackRate) && authoredPlaybackRate > 0) {\n entry.playbackRate = clampPlaybackRate(authoredPlaybackRate);\n }\n}\n\n/** Sets or clears an optional field, so a re-parse after the attribute is removed drops it. */\nfunction setOptional<K extends keyof TimelineElement>(\n entry: TimelineElement,\n key: K,\n value: TimelineElement[K] | undefined,\n): void {\n if (value === undefined) delete entry[key];\n else entry[key] = value;\n}\n\n/** The compiler's rule (timingCompiler): explicit data-has-audio wins; otherwise an unmuted <video> is audible. */\nexport function isVideoAudible(opts: {\n tag: string;\n hasAudioAttr: string | null | undefined;\n muted: boolean;\n}): boolean {\n if (opts.hasAudioAttr === \"true\") return true;\n if (opts.hasAudioAttr === \"false\" || opts.hasAudioAttr === \"\") return false;\n return opts.tag.toLowerCase() === \"video\" && !opts.muted;\n}\n\nexport function isAudibleVideoNode(el: Element): boolean {\n if (el.tagName.toLowerCase() !== \"video\" || el.hasAttribute(\"muted\")) return false;\n return isVideoAudible({\n tag: \"video\",\n hasAudioAttr: el.getAttribute(\"data-has-audio\"),\n muted: false,\n });\n}\n\n/** What the mixer gets: the compiler's `data-has-audio` rule, muted and volume. */\nfunction applyAudioMetadataFromElement(entry: TimelineElement, el: Element): void {\n const media = resolveMediaElement(el) ?? el;\n const muted = el.hasAttribute(\"muted\") || media.hasAttribute(\"muted\");\n const sound = isVideoAudible({\n tag: el.tagName,\n hasAudioAttr: el.getAttribute(\"data-has-audio\"),\n muted,\n });\n setOptional(entry, \"hasAudio\", sound ? true : undefined);\n setOptional(entry, \"muted\", muted ? true : undefined);\n setOptional(entry, \"volume\", elementVolume(el, media));\n}\n\nfunction applyFadeMetadataFromElement(entry: TimelineElement, el: Element): void {\n const fades = readElementFades(el);\n setOptional(entry, \"fadeIn\", fades.fadeIn > 0 ? fades.fadeIn : undefined);\n setOptional(entry, \"fadeOut\", fades.fadeOut > 0 ? fades.fadeOut : undefined);\n}\n\nexport function applyMediaMetadataFromElement(entry: TimelineElement, el: Element): void {\n setOptional(entry, \"text\", readTimelineText(el));\n applyPlaybackMetadataFromElement(entry, el);\n applyAudioMetadataFromElement(entry, el);\n applyFadeMetadataFromElement(entry, el);\n\n const mediaEl = resolveMediaElement(el);\n if (!mediaEl) return;\n\n entry.tag = mediaEl.tagName.toLowerCase();\n const src = mediaEl.getAttribute(\"src\");\n if (src) entry.src = src;\n\n if (!isMediaElement(mediaEl)) return;\n\n const sourceDurationAttr =\n el.getAttribute(\"data-source-duration\") ?? mediaEl.getAttribute(\"data-source-duration\");\n const sourceDuration = sourceDurationAttr ? parseFloat(sourceDurationAttr) : mediaEl.duration;\n if (Number.isFinite(sourceDuration) && sourceDuration > 0) {\n entry.sourceDuration = sourceDuration;\n }\n\n const playbackRate = mediaEl.defaultPlaybackRate;\n if (entry.playbackRate == null && Number.isFinite(playbackRate) && playbackRate > 0) {\n entry.playbackRate = clampPlaybackRate(playbackRate);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Label helpers\n// ---------------------------------------------------------------------------\n\nexport function getTimelineElementDisplayLabel(input: {\n id?: string | null;\n label?: string | null;\n tag?: string | null;\n}): string {\n const label = input.label?.trim();\n if (label) return label;\n const id = input.id?.trim();\n if (id) return id;\n const tag = input.tag?.trim().toLowerCase();\n return tag ? `${tag} clip` : \"Timeline clip\";\n}\n\n// ---------------------------------------------------------------------------\n// Selector / identity / key builders\n// ---------------------------------------------------------------------------\n\nexport function getTimelineElementSelector(el: Element): string | undefined {\n if (isHtmlElement(el) && el.id) return `#${CSS.escape(el.id)}`;\n const compId = el.getAttribute(\"data-composition-id\");\n if (compId) return `[data-composition-id=\"${CSS.escape(compId)}\"]`;\n if (isHtmlElement(el)) {\n const classes = el.className.split(/\\s+/).filter(Boolean);\n const firstClass = classes.find((className) => className !== \"clip\") ?? classes[0];\n if (firstClass) return `.${CSS.escape(firstClass)}`;\n }\n return undefined;\n}\n\nexport function getTimelineElementSourceFile(el: Element): string | undefined {\n const ownerRoot = el.parentElement?.closest(\"[data-composition-id]\");\n return (\n ownerRoot?.getAttribute(\"data-composition-file\") ??\n ownerRoot?.getAttribute(\"data-composition-src\") ??\n undefined\n );\n}\n\nexport function getTimelineElementSelectorIndex(\n doc: Document,\n el: Element,\n selector: string | undefined,\n): number | undefined {\n return getSourceScopedSelectorIndex(\n doc,\n el,\n selector,\n getTimelineElementSourceFile(el),\n getTimelineElementSourceFile,\n );\n}\n\nexport function buildTimelineElementKey(params: {\n id: string;\n fallbackIndex: number;\n domId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile?: string;\n}): string {\n const scope = params.sourceFile ?? \"index.html\";\n if (params.domId) return `${scope}#${params.domId}`;\n if (params.selector) return `${scope}:${params.selector}:${params.selectorIndex ?? 0}`;\n return `${scope}:${params.id}:${params.fallbackIndex}`;\n}\n\n/**\n * Inverse of {@link buildTimelineElementKey} for the `sourceFile#domId` form.\n * A key with no `#` is a bare dom id and carries no source file of its own, so\n * the caller supplies the scope it wants to look that id up in.\n */\nexport function splitTimelineElementKey(key: string): {\n sourceFile: string | null;\n domId: string;\n} {\n const hashIndex = key.lastIndexOf(\"#\");\n if (hashIndex < 0) return { sourceFile: null, domId: key };\n return { sourceFile: key.slice(0, hashIndex), domId: key.slice(hashIndex + 1) };\n}\n\nexport function buildTimelineElementIdentity(params: {\n preferredId?: string | null;\n label: string;\n fallbackIndex: number;\n domId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile?: string;\n}): { id: string; key: string } {\n const id =\n params.preferredId?.trim() ||\n buildTimelineElementKey({\n id: params.label,\n fallbackIndex: params.fallbackIndex,\n domId: params.domId,\n selector: params.selector,\n selectorIndex: params.selectorIndex,\n sourceFile: params.sourceFile,\n });\n const key = buildTimelineElementKey({\n id,\n fallbackIndex: params.fallbackIndex,\n domId: params.domId,\n selector: params.selector,\n selectorIndex: params.selectorIndex,\n sourceFile: params.sourceFile,\n });\n return { id, key };\n}\n\nexport function getTimelineElementIdentity(element: { key?: string | null; id: string }): string {\n return element.key ?? element.id;\n}\n\n/**\n * The id space the RUNTIME matches on — a bare DOM id, never a store key.\n *\n * Studio addresses rows by `buildTimelineElementKey`'s composite\n * `<sourceFile>#<domId>`, but everything audio in `@hyperframes/core` keys off\n * the live document: `resolveAudioGroups` collects `member.id`,\n * `resolveCarveSourceIds` goes through `getElementById`. Anything crossing into\n * that space — a group membership list, a carve source — has to be\n * converted here first; a composite key silently matches nothing.\n *\n * `null` for a row with no DOM id at all (selector-addressed elements): such an\n * element cannot be grouped, because `resolveAudioGroups` skips\n * members without an `id` and would build a group that is half there.\n */\nexport function runtimeAudioId(element: { domId?: string | null }): string | null {\n return element.domId || null;\n}\n\n/**\n * Timeline store key for a z-reorder entry built OUTSIDE the timeline\n * expansion (canvas context menu / LayersPanel), so the reorder commit can\n * update the store's zIndex synchronously. Matches buildTimelineElementKey's\n * stable branches (`sourceFile#domId`, else the selector-based key). Undefined\n * when the element has neither a DOM id nor a selector — the timeline's\n * fallback branch needs its own fallbackIndex, which these callers don't have,\n * so such an entry simply skips the synchronous store update.\n */\nexport function deriveTimelineStoreKey(params: {\n domId?: string;\n selector?: string;\n selectorIndex?: number;\n sourceFile?: string;\n}): string | undefined {\n if (!params.domId && !params.selector) return undefined;\n return buildTimelineElementKey({ id: \"\", fallbackIndex: 0, ...params });\n}\n\n/**\n * {@link deriveTimelineStoreKey} for a caller that already has a DOM id in\n * hand (e.g. one it just minted), so the undefined branch never applies.\n */\nexport function deriveTimelineStoreKeyForDomId(domId: string, sourceFile?: string): string {\n return deriveTimelineStoreKey({ domId, sourceFile })!;\n}\n\n// ---------------------------------------------------------------------------\n// DOM node querying\n// ---------------------------------------------------------------------------\n\nfunction getTimelineDomNodes(doc: Document): Element[] {\n const rootComp = doc.querySelector(\"[data-composition-id]\");\n return Array.from(doc.querySelectorAll(\"[data-start]\")).filter(\n (node) => node !== rootComp && !isTimelineIgnoredElement(node),\n );\n}\n\nfunction numbersNearlyEqual(a: number, b: number): boolean {\n return Math.abs(a - b) < 0.001;\n}\n\nconst MANIFEST_CLIP_ATTRS: ReadonlyArray<[string, (clip: ClipManifestClip) => number]> = [\n [\"data-start\", (clip) => clip.start],\n [\"data-duration\", (clip) => clip.duration],\n [\"data-track-index\", (clip) => clip.track],\n];\n\nfunction nodeMatchesClipTag(node: Element, clip: ClipManifestClip): boolean {\n return !clip.tagName || node.tagName.toLowerCase() === clip.tagName.toLowerCase();\n}\n\nfunction nodeMatchesManifestClip(node: Element, clip: ClipManifestClip): boolean {\n if (!nodeMatchesClipTag(node, clip)) return false;\n // An attribute only constrains the match when it parses to a finite number:\n // missing or garbled reads as \"unknown\", not \"mismatch\".\n return MANIFEST_CLIP_ATTRS.every(([attr, expected]) => {\n const actual = Number.parseFloat(node.getAttribute(attr) ?? \"\");\n return !Number.isFinite(actual) || numbersNearlyEqual(actual, expected(clip));\n });\n}\n\n/** Whether `node` sits in the composition the clip was read from, the chain the runtime records outermost first\n * (`resolveNearestCompositionContext` in core's runtime/timeline.ts). A clip without that scope accepts any node. */\nfunction nodeInClipScope(node: Element, clip: ClipManifestClip): boolean {\n const scope = clip.compositionAncestors;\n if (!scope) return true;\n const ids: string[] = [];\n for (let cursor = node.parentElement; cursor; cursor = cursor.parentElement) {\n const id = cursor.getAttribute(\"data-composition-id\");\n if (id) ids.unshift(id);\n }\n return ids.length === scope.length && ids.every((id, index) => id === scope[index]);\n}\n\n/** The first match in the clip's composition across `selectors`; a lone match stands only when none is in scope, as a\n * healed host can stale the clip's chain for a pass. An id can repeat in a sub-composition earlier in the document. */\nfunction findInClipScope(\n doc: Document,\n clip: ClipManifestClip,\n selectors: string[],\n): Element | null {\n let lone: Element | null = null;\n for (const selector of selectors) {\n const nodes = Array.from(doc.querySelectorAll(selector));\n const scoped = nodes.find((node) => nodeInClipScope(node, clip));\n if (scoped) return scoped;\n if (nodes.length === 1) lone ??= nodes[0];\n }\n return lone;\n}\n\nexport type PreviewTarget = Pick<TimelineElement, \"hfId\" | \"domId\" | \"id\" | \"sourceFile\">;\n\n/** Finds a row's preview element by `data-hf-id`, then id, preferring one in the row's own file: both repeat across\n * files. Indexes the document once, so a pass over every row costs one scan. */\nexport function previewElementFinder(\n doc: Document,\n selector = \"[data-hf-id], [id]\",\n): (target: PreviewTarget) => Element | null {\n const byKey = new Map<string, Element[]>();\n const add = (key: string, node: Element) => {\n const nodes = byKey.get(key);\n if (nodes) nodes.push(node);\n else byKey.set(key, [node]);\n };\n for (const node of doc.querySelectorAll(selector)) {\n const hfId = node.getAttribute(\"data-hf-id\");\n const id = node.getAttribute(\"id\");\n if (hfId) add(`hf:${hfId}`, node);\n if (id) add(`id:${id}`, node);\n }\n return (target) => {\n const matches = [\n ...((target.hfId && byKey.get(`hf:${target.hfId}`)) || []),\n ...(byKey.get(`id:${target.domId ?? target.id}`) ?? []),\n ];\n return (\n matches.find((node) => getTimelineElementSourceFile(node) === target.sourceFile) ??\n matches[0] ??\n null\n );\n };\n}\n\nexport function findClipElementById(doc: Document, clip: ClipManifestClip): Element | null {\n if (!clip.id) return null;\n const first = doc.getElementById(clip.id);\n if (!first || nodeInClipScope(first, clip)) return first;\n return findInClipScope(doc, clip, [`[id=\"${CSS.escape(clip.id)}\"]`]);\n}\n\nfunction findTimelineDomNode(doc: Document, clip: ClipManifestClip): Element | null {\n if (!clip.id) return null;\n const first = doc.getElementById(clip.id);\n if (first && nodeInClipScope(first, clip)) return first;\n const id = CSS.escape(clip.id);\n const byOtherKeys = [`[data-hf-id=\"${id}\"]`, `[data-composition-id=\"${id}\"]`, `.${id}`];\n return findInClipScope(doc, clip, first ? [`[id=\"${id}\"]`, ...byOtherKeys] : byOtherKeys);\n}\n\nexport function findTimelineDomNodeForClip(\n doc: Document,\n clip: ClipManifestClip,\n fallbackIndex: number,\n usedNodes = new Set<Element>(),\n getCandidates = () => getTimelineDomNodes(doc),\n): Element | null {\n const byIdentity = findTimelineDomNode(doc, clip);\n if (byIdentity && !usedNodes.has(byIdentity) && nodeMatchesClipTag(byIdentity, clip))\n return byIdentity;\n\n const candidates = getCandidates().filter((node) => !usedNodes.has(node));\n const exact = candidates.find((node) => nodeMatchesManifestClip(node, clip));\n if (exact) return exact;\n\n const positional = candidates[fallbackIndex];\n return positional && nodeMatchesClipTag(positional, clip) ? positional : null;\n}\n\n/** One synchronous hydration pass: snapshot only on a miss, never across reloads. */\nexport function createTimelineDomNodeResolver(doc: Document) {\n let candidates: Element[] | undefined;\n const usedNodes = new Set<Element>();\n const getCandidates = () => (candidates ??= getTimelineDomNodes(doc));\n return (clip: ClipManifestClip, index: number): Element | null => {\n const node = findTimelineDomNodeForClip(doc, clip, index, usedNodes, getCandidates);\n if (node) usedNodes.add(node);\n return node;\n };\n}\n","export function parseStoredVolume(text: string | null): number | undefined {\n const volume = Number.parseFloat(text ?? \"\");\n return Number.isFinite(volume) ? volume : undefined;\n}\n\nexport const elementVolume = (el: Element, media: Element) =>\n parseStoredVolume(el.getAttribute(\"data-volume\") ?? media.getAttribute(\"data-volume\"));\n","const PROJECT_HASH_PREFIX = \"#project/\";\n\nexport interface ProjectHashRoute {\n projectId: string;\n params: URLSearchParams;\n}\n\nconst WINDOWS_DRIVE_PREFIX = /^[a-z]:/i;\n\n/** Project names are single path segments, including when received from a hash or server. */\nexport function isValidProjectId(value: string): boolean {\n return (\n value.length > 0 &&\n value !== \".\" &&\n value !== \"..\" &&\n !WINDOWS_DRIVE_PREFIX.test(value) &&\n !value.includes(\"/\") &&\n !value.includes(\"\\\\\") &&\n !Array.from(value).some((char) => char.charCodeAt(0) < 32)\n );\n}\n\nfunction decodeHashProjectId(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction normalizeHashParams(\n params?: URLSearchParams | Record<string, string | null | undefined>,\n): URLSearchParams {\n if (!params) return new URLSearchParams();\n if (params instanceof URLSearchParams) return params;\n\n const next = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (!key || value == null || value === \"\") continue;\n next.set(key, value);\n }\n return next;\n}\n\nexport function encodeProjectId(projectId: string): string {\n if (!isValidProjectId(projectId)) throw new Error(\"Invalid project ID\");\n return encodeURIComponent(projectId);\n}\n\nexport function buildProjectHash(\n projectId: string,\n params?: URLSearchParams | Record<string, string | null | undefined>,\n): string {\n const search = normalizeHashParams(params).toString();\n return `${PROJECT_HASH_PREFIX}${encodeProjectId(projectId)}${search ? `?${search}` : \"\"}`;\n}\n\nexport function parseProjectHashRoute(hash: string): ProjectHashRoute | null {\n if (!hash.startsWith(PROJECT_HASH_PREFIX)) return null;\n\n const route = hash.slice(PROJECT_HASH_PREFIX.length);\n const queryIndex = route.indexOf(\"?\");\n const encodedProjectId = queryIndex >= 0 ? route.slice(0, queryIndex) : route;\n if (!encodedProjectId || encodedProjectId.includes(\"/\")) return null;\n\n const projectId = decodeHashProjectId(encodedProjectId);\n if (!isValidProjectId(projectId)) return null;\n\n const rawParams = queryIndex >= 0 ? route.slice(queryIndex + 1) : \"\";\n return {\n projectId,\n params: new URLSearchParams(rawParams),\n };\n}\n\nexport function parseProjectIdFromHash(hash: string): string | null {\n return parseProjectHashRoute(hash)?.projectId ?? null;\n}\n\nexport function buildProjectApiPath(projectId: string, suffix = \"\"): string {\n const normalizedSuffix = suffix && !suffix.startsWith(\"/\") ? `/${suffix}` : suffix;\n return `/api/projects/${encodeProjectId(projectId)}${normalizedSuffix}`;\n}\n"],"mappings":";AAiBA,IAAI,aAAuC;AAkBpC,SAAS,sBAAyB,KAAe,KAAiB;AACvE,QAAM,WAAW;AACjB,eAAa,EAAE,KAAK,YAAY,oBAAI,IAAI,EAAE;AAC1C,MAAI;AACF,WAAO,IAAI;AAAA,EACb,UAAE;AACA,iBAAa;AAAA,EACf;AACF;AAEA,SAAS,iBACP,KACA,UACA,mBACqB;AACrB,QAAM,cAAmC,oBAAI,IAAI;AACjD,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,aAAa,IAAI,iBAAiB,QAAQ,GAAG;AACtD,UAAM,QAAQ,kBAAkB,SAAS,KAAK;AAC9C,UAAM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M,YAAY,oBAAoB,gBAAgB;AACtD,MAAI,CAAC,iBAAiB,SAAS,EAAG,QAAO;AAEzC,QAAM,YAAY,cAAc,IAAI,MAAM,MAAM,aAAa,CAAC,IAAI;AAClE,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,IAAI,gBAAgB,SAAS;AAAA,EACvC;AACF;AAEO,SAAS,uBAAuB,MAA6B;AAClE,SAAO,sBAAsB,IAAI,GAAG,aAAa;AACnD;AAEO,SAAS,oBAAoB,WAAmB,SAAS,IAAY;AAC1E,QAAM,mBAAmB,UAAU,CAAC,OAAO,WAAW,GAAG,IAAI,IAAI,MAAM,KAAK;AAC5E,SAAO,iBAAiB,gBAAgB,SAAS,CAAC,GAAG,gBAAgB;AACvE;","names":["isHtmlElement","isHtmlElement","isHtmlElement","isHtmlElement"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/editor/manualEditingAvailability.ts","../src/utils/sdkCutoverPolicy.ts","../src/utils/studioApiFetch.ts","../src/components/editor/probeSourceElement.ts","../src/components/editor/domEditingLayers.ts","../src/components/editor/domEditingGroups.ts","../src/components/editor/domEditingElement.ts","../src/components/editor/domEditingRootLayer.ts","../src/components/editor/domEditLayerWalkCache.ts"],"sourcesContent":["export type StudioFeatureFlagEnv = Record<string, boolean | string | undefined>;\n\nconst TRUTHY_ENV_VALUES = new Set([\"1\", \"true\", \"yes\", \"on\", \"enabled\"]);\nconst FALSY_ENV_VALUES = new Set([\"0\", \"false\", \"no\", \"off\", \"disabled\"]);\n\nexport function resolveStudioBooleanEnvFlag(\n env: StudioFeatureFlagEnv,\n names: string[],\n fallback: boolean,\n): boolean {\n for (const name of names) {\n const value = env[name];\n if (typeof value === \"boolean\") return value;\n if (typeof value !== \"string\") continue;\n\n const normalized = value.trim().toLowerCase();\n if (!normalized) continue;\n if (TRUTHY_ENV_VALUES.has(normalized)) return true;\n if (FALSY_ENV_VALUES.has(normalized)) return false;\n }\n\n return fallback;\n}\n\n// `import.meta.env` is a Vite-only extension. In non-Vite ESM hosts\n// (Next.js / Turbopack, Node, jest in some configs) it's undefined,\n// and downstream `env[name]` reads would crash. Fall back to `{}` so\n// every flag resolves to its declared default outside Vite. Direct\n// property access keeps Vite's compile-time transform happy.\n//\n// When the studio is served as a pre-built SPA by the embedded Hono server,\n// `import.meta.env` values were baked at build time. The server injects\n// `window.__HF_STUDIO_ENV__` with any `VITE_STUDIO_*` env vars from the\n// user's shell, so runtime overrides take precedence over baked defaults.\nconst runtimeEnv =\n typeof window !== \"undefined\"\n ? ((window as Window & { __HF_STUDIO_ENV__?: StudioFeatureFlagEnv }).__HF_STUDIO_ENV__ ?? {})\n : {};\nconst env = { ...(import.meta.env ?? {}), ...runtimeEnv } as StudioFeatureFlagEnv;\n\n// Stage 7 SDK cutover — routes Studio edits through SDK dispatch instead of the\n// server patch/mutation routes. Default TRUE as of the flip release (spec:\n// 2026-09-17-studio-sdk-cutover-flip-design.md). Kill switch:\n// VITE_STUDIO_SDK_CUTOVER_ENABLED=false (works at runtime via __HF_STUDIO_ENV__).\nexport const STUDIO_SDK_CUTOVER_ENABLED = resolveStudioBooleanEnvFlag(\n env,\n [\"VITE_STUDIO_SDK_CUTOVER_ENABLED\"],\n true,\n);\n\n/**\n * Per-family selection. Unset = every family (the master alone enables all).\n * Set `VITE_STUDIO_SDK_CUTOVER_FAMILIES=dom,timing` to RESTRICT to a subset.\n */\nexport const STUDIO_SDK_CUTOVER_FAMILIES = resolveEnabledSdkFamilies(\n env,\n STUDIO_SDK_CUTOVER_ENABLED,\n);\n\n// Resolver-parity tripwire (telemetry-only, decoupled from cutover).\n// Runs the SDK resolver alongside any edit and emits sdk_resolver_shadow on\n// divergence. Default true; disable via VITE_STUDIO_SDK_RESOLVER_SHADOW_ENABLED=false.\n// Soak gate: retire once zero element_not_found divergences over a clean window.\nexport const STUDIO_SDK_RESOLVER_SHADOW_ENABLED = resolveStudioBooleanEnvFlag(\n env,\n [\"VITE_STUDIO_SDK_RESOLVER_SHADOW_ENABLED\"],\n true,\n);\n\n// Studio inspector redesign (\"Ledger, flat\" — design_handoff_studio_inspector):\n// flat identity header/footer/groups. Default true as of v0.7.59+ bug-fix pass\n// (right-aligned values, Stroke select-only, promote-badge overlap, Layout/\n// Style section gating); disable via VITE_STUDIO_FLAT_INSPECTOR_ENABLED=false\n// to fall back to the legacy panel.\nexport const STUDIO_FLAT_INSPECTOR_ENABLED = resolveStudioBooleanEnvFlag(\n env,\n [\"VITE_STUDIO_ENABLE_FLAT_INSPECTOR\", \"VITE_STUDIO_FLAT_INSPECTOR_ENABLED\"],\n true,\n);\n\n// A host whose mounted API authenticates with same-origin cookies sets this; studioApiFetch then sends them, and its\n// requests share the preview media's sockets again.\nexport const STUDIO_API_SAME_ORIGIN_CREDENTIALS = resolveStudioBooleanEnvFlag(\n env,\n [\"VITE_STUDIO_API_SAME_ORIGIN_CREDENTIALS\"],\n false,\n);\n\nimport { resolveEnabledSdkFamilies } from \"../../utils/sdkCutoverPolicy\";\n","export const STUDIO_SDK_OPERATION_FAMILIES = [\n \"dom\",\n \"timing\",\n \"gsap-animation\",\n \"gsap-keyframe\",\n \"lifecycle\",\n] as const;\n\nexport type StudioSdkOperationFamily = (typeof STUDIO_SDK_OPERATION_FAMILIES)[number];\n\ninterface StudioSdkFamilyStatus {\n owner: string;\n deadline: string;\n parityEvidence: string;\n graduated: boolean;\n}\n\nconst STUDIO_SDK_FAMILY_STATUS = {\n dom: {\n owner: \"studio-foundations\",\n deadline: \"2026-09-30\",\n parityEvidence: \"sdkCutoverParity.test.ts\",\n graduated: false,\n },\n timing: {\n owner: \"studio-foundations\",\n deadline: \"2026-10-15\",\n parityEvidence: \"sdkCutover.test.ts timing corpus\",\n graduated: false,\n },\n \"gsap-animation\": {\n owner: \"studio-foundations\",\n deadline: \"2026-10-31\",\n parityEvidence: \"sdkCutover.test.ts GSAP animation corpus\",\n graduated: false,\n },\n \"gsap-keyframe\": {\n owner: \"studio-foundations\",\n deadline: \"2026-11-15\",\n parityEvidence: \"sdkCutover.test.ts GSAP keyframe corpus\",\n graduated: false,\n },\n lifecycle: {\n owner: \"studio-foundations\",\n deadline: \"2026-11-30\",\n parityEvidence: \"sdkCutover.test.ts lifecycle corpus\",\n graduated: false,\n },\n} as const satisfies Record<StudioSdkOperationFamily, StudioSdkFamilyStatus>;\n\nexport function resolveEnabledSdkFamilies(\n env: Record<string, boolean | string | undefined>,\n masterEnabled: boolean,\n): ReadonlySet<StudioSdkOperationFamily> {\n if (!masterEnabled) return new Set();\n const raw = env[\"VITE_STUDIO_SDK_CUTOVER_FAMILIES\"];\n // Unset/blank = every family. The list exists to RESTRICT (kill switch per family).\n if (typeof raw !== \"string\" || raw.trim() === \"\") return new Set(STUDIO_SDK_OPERATION_FAMILIES);\n const requested = raw\n .split(\",\")\n .map((family) => family.trim())\n .filter(Boolean);\n const known = new Set<string>(STUDIO_SDK_OPERATION_FAMILIES);\n const unknown = requested.filter((family) => !known.has(family));\n if (unknown.length > 0) {\n throw new Error(`Unknown Studio SDK cutover families: ${unknown.join(\", \")}`);\n }\n return new Set(requested as StudioSdkOperationFamily[]);\n}\n\nexport function isSdkFamilyEnabled(\n masterEnabled: boolean,\n configured: ReadonlySet<StudioSdkOperationFamily> | undefined,\n family: StudioSdkOperationFamily,\n): boolean {\n // `undefined` preserves compatibility for isolated tests/embedders that mock\n // only the historical master flag. Production always supplies an explicit set.\n return masterEnabled && (configured?.has(family) ?? true);\n}\n\nexport function renderStudioSdkCutoverReport(): string {\n const rows = STUDIO_SDK_OPERATION_FAMILIES.map((family) => {\n const status = STUDIO_SDK_FAMILY_STATUS[family];\n return `| ${family} | ${status.owner} | ${status.deadline} | ${status.parityEvidence} | ${status.graduated ? \"yes\" : \"no\"} |`;\n });\n return [\n \"# Studio SDK cutover report\",\n \"\",\n \"Default: SDK persist ON for every family. Kill switches:\",\n \" `VITE_STUDIO_SDK_CUTOVER_ENABLED=false` (all families → server path)\",\n \" `VITE_STUDIO_SDK_CUTOVER_FAMILIES=dom,timing` (only listed families → SDK; rest → server)\",\n \"\",\n \"A family graduates only after zero unexplained resolver/serialization divergences over its agreed corpus and soak window.\",\n \"\",\n \"| Family | Owner | Deadline | Parity evidence | Graduated |\",\n \"| --- | --- | --- | --- | --- |\",\n ...rows,\n \"\",\n ].join(\"\\n\");\n}\n","import { STUDIO_API_SAME_ORIGIN_CREDENTIALS } from \"../components/editor/manualEditingAvailability\";\n\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\nfunction studioApiCredentials(): RequestCredentials {\n if (STUDIO_API_SAME_ORIGIN_CREDENTIALS) return \"same-origin\";\n const host = globalThis.location?.hostname;\n return !host || LOOPBACK_HOSTS.has(host) ? \"omit\" : \"same-origin\";\n}\n\nexport function studioApiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n return globalThis.fetch(input, { ...init, credentials: studioApiCredentials() });\n}\n","import { buildProjectApiPath } from \"../../utils/projectRouting\";\nimport { studioApiFetch } from \"../../utils/studioApiFetch\";\nimport type { DomEditSelection } from \"./domEditingTypes\";\n\nexport type ProbeTarget = { id?: string; hfId?: string; selector?: string; selectorIndex?: number };\n\nexport function knownSourceAnswer(\n previous: DomEditSelection | null | undefined,\n element: HTMLElement,\n sourceFile: string,\n target: ProbeTarget,\n): boolean | undefined {\n if (!previous || previous.element !== element || previous.sourceFile !== sourceFile) return;\n const same =\n previous.id === target.id &&\n previous.hfId === target.hfId &&\n previous.selector === target.selector &&\n previous.selectorIndex === target.selectorIndex;\n return same ? previous.existsInSource : undefined;\n}\n\ninterface PendingProbe {\n target: ProbeTarget;\n resolve: (exists: boolean) => void;\n}\n\nconst pending = new Map<string, PendingProbe[]>();\n\nasync function sendBatch(projectId: string, sourceFile: string, probes: PendingProbe[]) {\n let exists: boolean[] = [];\n try {\n const response = await studioApiFetch(\n buildProjectApiPath(\n projectId,\n `/file-mutations/probe-elements/${encodeURIComponent(sourceFile)}`,\n ),\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ targets: probes.map((probe) => probe.target) }),\n },\n );\n if (response.ok) {\n const data = await response.json();\n if (Array.isArray(data?.exists)) exists = data.exists;\n }\n } catch {}\n probes.forEach((probe, index) => probe.resolve(exists[index] !== false));\n}\n\nexport function probeSourceElement(\n projectId: string,\n sourceFile: string,\n target: ProbeTarget,\n): Promise<boolean> {\n return new Promise((resolve) => {\n const key = `${projectId}\\0${sourceFile}`;\n let probes = pending.get(key);\n if (!probes) {\n const batch: PendingProbe[] = [];\n probes = batch;\n pending.set(key, batch);\n setTimeout(() => {\n pending.delete(key);\n void sendBatch(projectId, sourceFile, batch);\n }, 0);\n }\n probes.push({ target, resolve });\n });\n}\n","import { knownSourceAnswer, probeSourceElement, type ProbeTarget } from \"./probeSourceElement\";\nimport { isAudibleVideoNode } from \"../../player/lib/timelineElementHelpers\";\nimport type { PatchOperation } from \"../../utils/sourcePatcher\";\nimport {\n resolveEditingAffordances,\n resolveEditingSections,\n type EditableElementFacts,\n} from \"@hyperframes/core/editing\";\nimport { groupScopedLayerRoots, resolveGroupCapture } from \"./domEditingGroups\";\nimport type {\n DomEditCapabilities,\n DomEditContextOptions,\n DomEditLayerItem,\n DomEditSelection,\n DomEditTextField,\n} from \"./domEditingTypes\";\nimport {\n buildElementLabel,\n buildStableSelector,\n findClosestByAttribute,\n getCuratedComputedStyles,\n getDataAttributes,\n getInlineStyles,\n getSelectorIndex,\n getSourceFileForElement,\n isEditableTextLeaf,\n isHtmlElement,\n} from \"./domEditingDom\";\nimport {\n findElementForSelection,\n getSelectionCandidate,\n isDomLayerElement,\n} from \"./domEditingElement\";\nimport { isCompositionRootLayer } from \"./domEditingRootLayer\";\nimport { withSelectorIndexPass } from \"../../utils/sourceScopedSelectorIndex\";\nimport { type DomEditLayerWalkCache, readDomEditLayerWalkEntry } from \"./domEditLayerWalkCache\";\n\nfunction sameTagChildIndex(el: HTMLElement): number {\n let index = 0;\n let sibling = el.previousElementSibling;\n while (sibling) {\n if (sibling.tagName === el.tagName) index += 1;\n sibling = sibling.previousElementSibling;\n }\n return index;\n}\n\nfunction getTextFieldLabel(\n _tagName: string,\n index: number,\n total: number,\n source: \"self\" | \"child\",\n): string {\n if (source === \"self\" || total === 1) return \"Content\";\n return `Text ${index + 1}`;\n}\n\nfunction buildTextField(\n el: HTMLElement,\n index: number,\n total: number,\n source: \"self\" | \"child\",\n sourceChildIndex?: number,\n): DomEditTextField {\n const tagName = el.tagName.toLowerCase();\n const key = el.getAttribute(\"data-hf-text-key\") ?? `${source}:${index}:${tagName}`;\n return {\n key,\n label: getTextFieldLabel(tagName, index, total, source),\n value: el.textContent ?? \"\",\n tagName,\n attributes: Array.from(el.attributes)\n .filter((attribute) => attribute.name !== \"style\")\n .map((attribute) => ({\n name: attribute.name,\n value: attribute.value,\n })),\n inlineStyles: getInlineStyles(el),\n computedStyles: getCuratedComputedStyles(el),\n source,\n ...(sourceChildIndex == null ? {} : { sourceChildIndex }),\n };\n}\n\n// fallow-ignore-next-line complexity\nexport function collectDomEditTextFields(el: HTMLElement): DomEditTextField[] {\n const childElements = Array.from(el.children).filter(isHtmlElement).filter(isEditableTextLeaf);\n\n if (childElements.length > 0) {\n const hasMixedContent = Array.from(el.childNodes).some(\n (node) => node.nodeType === 3 && node.textContent?.trim(),\n );\n\n if (hasMixedContent) {\n const fields: DomEditTextField[] = [];\n let childIdx = 0;\n for (const node of el.childNodes) {\n if (node.nodeType === 3) {\n const text = node.textContent ?? \"\";\n if (!text.trim()) continue;\n fields.push({\n key: `text-node:${childIdx}`,\n label: `Text ${childIdx + 1}`,\n value: text,\n tagName: \"#text\",\n attributes: [],\n inlineStyles: {},\n computedStyles: {},\n source: \"text-node\",\n });\n childIdx++;\n } else if (isHtmlElement(node) && isEditableTextLeaf(node)) {\n fields.push(\n buildTextField(node, childIdx, childElements.length, \"child\", sameTagChildIndex(node)),\n );\n childIdx++;\n }\n }\n return fields;\n }\n\n return childElements.map((child, index) =>\n buildTextField(child, index, childElements.length, \"child\", sameTagChildIndex(child)),\n );\n }\n\n if (isEditableTextLeaf(el)) {\n return [buildTextField(el, 0, 1, \"self\")];\n }\n\n return [];\n}\n\nfunction escapeHtmlText(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction serializeTextFieldStyle(field: DomEditTextField): string {\n const entries = Object.entries(field.inlineStyles).filter(([, value]) => Boolean(value));\n if (entries.length === 0) return \"\";\n return entries.map(([key, value]) => `${key}: ${value}`).join(\"; \");\n}\n\nexport function serializeDomEditTextFields(fields: DomEditTextField[]): string {\n return fields\n .filter((field) => field.source === \"child\" || field.source === \"text-node\")\n .map((field) => {\n if (field.source === \"text-node\") {\n return escapeHtmlText(field.value);\n }\n const attrs = [\n ...field.attributes.filter((attribute) => attribute.name !== \"data-hf-text-key\"),\n { name: \"data-hf-text-key\", value: field.key },\n ]\n .map((attribute) => ` ${attribute.name}=\"${attribute.value.replace(/\"/g, \"&quot;\")}\"`)\n .join(\"\");\n const style = serializeTextFieldStyle(field);\n const styleAttr = style ? ` style=\"${style.replace(/\"/g, \"&quot;\")}\"` : \"\";\n return `<${field.tagName}${attrs}${styleAttr}>${escapeHtmlText(field.value)}</${field.tagName}>`;\n })\n .join(\"\");\n}\n\nexport function buildDefaultDomEditTextField(base?: Partial<DomEditTextField>): DomEditTextField {\n return {\n key: `child:new:${Date.now()}`,\n label: \"Text\",\n value: \"New text\",\n tagName: \"span\",\n attributes: [],\n inlineStyles: {\n \"font-family\": base?.computedStyles?.[\"font-family\"] ?? \"inherit\",\n \"font-size\": base?.computedStyles?.[\"font-size\"] ?? \"16px\",\n \"font-weight\": base?.computedStyles?.[\"font-weight\"] ?? \"400\",\n color: base?.computedStyles?.color ?? \"inherit\",\n },\n computedStyles: {},\n source: \"child\",\n };\n}\n\nexport interface DomEditChildLocator {\n childSelector: string;\n childIndex: number;\n}\n\nexport function buildTextFieldChildLocator(\n fields: DomEditTextField[],\n fieldKey: string,\n): DomEditChildLocator | null {\n const field = fields.find((candidate) => candidate.key === fieldKey);\n if (!field || field.source !== \"child\") return null;\n // sourceChildIndex is only absent for a synthetic field that was never read\n // back from the live DOM (e.g. one built by buildDefaultDomEditTextField).\n // Guessing its position by counting same-tag \"child\" fields elsewhere in\n // the array is unreliable and can silently locate the wrong element — fail\n // closed instead so the caller falls back to the unsupported-structure path.\n if (field.sourceChildIndex == null) return null;\n\n return {\n childSelector: `:scope > ${field.tagName}`,\n childIndex: field.sourceChildIndex,\n };\n}\n\nfunction capabilityFacts(geometry: {\n hasStableTarget: boolean;\n tag: string;\n inlineStyles: Record<string, string>;\n computedStyles: Record<string, string>;\n isCompositionHost: boolean;\n isCompositionRoot: boolean;\n isInsideLockedComposition: boolean;\n isMasterView: boolean;\n existsInSource: boolean;\n}): EditableElementFacts {\n return {\n ...geometry,\n hasEditableText: false,\n hasTimingStart: false,\n animationCount: 0,\n };\n}\n\n/**\n * Build core EditableElementFacts from a fully-resolved DomEditSelection.\n * `animationCount` is supplied by the caller because live GSAP tweens arrive on\n * a separate channel (the PropertyPanel `gsapAnimations` prop), not on the\n * selection — `selection.gsapAnimations` is never populated.\n */\nexport function domEditSelectionToFacts(\n selection: DomEditSelection,\n animationCount = selection.gsapAnimations?.length ?? 0,\n): EditableElementFacts {\n return {\n hasStableTarget: Boolean(selection.selector || selection.hfId),\n tag: selection.tagName,\n inlineStyles: selection.inlineStyles,\n computedStyles: selection.computedStyles,\n isCompositionHost: selection.isCompositionHost,\n isCompositionRoot: false,\n isInsideLockedComposition: selection.isInsideLockedComposition,\n isMasterView: false,\n existsInSource: true,\n hasEditableText: selection.textFields.length > 0,\n hasTimingStart: selection.dataAttributes.start != null,\n animationCount,\n hasAudio: isAudibleVideoNode(selection.element),\n };\n}\n\n/**\n * Resolve DOM edit capabilities for a given element.\n * Thin wrapper over core resolveEditingAffordances — kept for backward\n * compatibility (tests and the barrel import this signature directly).\n */\nexport function resolveDomEditCapabilities(args: {\n selector?: string;\n hfId?: string;\n tagName?: string;\n inlineStyles: Record<string, string>;\n computedStyles: Record<string, string>;\n isCompositionHost: boolean;\n isCompositionRoot?: boolean;\n isInsideLockedComposition: boolean;\n isMasterView: boolean;\n existsInSource?: boolean;\n}): DomEditCapabilities {\n return resolveEditingAffordances(\n capabilityFacts({\n hasStableTarget: Boolean(args.selector || args.hfId),\n tag: (args.tagName ?? \"div\").toLowerCase(),\n inlineStyles: args.inlineStyles,\n computedStyles: args.computedStyles,\n isCompositionHost: args.isCompositionHost,\n isCompositionRoot: args.isCompositionRoot ?? false,\n isInsideLockedComposition: args.isInsideLockedComposition ?? false,\n isMasterView: args.isMasterView,\n existsInSource: args.existsInSource ?? true,\n }),\n ).capabilities;\n}\n\n// fallow-ignore-next-line complexity\nexport async function resolveDomEditSelection(\n startEl: HTMLElement | null,\n options: DomEditContextOptions & {\n projectId?: string | null;\n skipSourceProbe?: boolean;\n exactTarget?: boolean;\n previous?: DomEditSelection | null;\n },\n): Promise<DomEditSelection | null> {\n if (!startEl) return null;\n const doc = startEl.ownerDocument;\n\n let capture = options.exactTarget\n ? ({ kind: \"unit\", element: startEl } as const)\n : resolveGroupCapture(startEl, options.activeGroupElement ?? null);\n if (capture.kind === \"out-of-scope\") {\n // Drill-in is non-sticky: clicking/hovering OUTSIDE the drilled-into group\n // exits it and resolves the target normally, rather than selecting nothing\n // (which felt like \"can't select anything\" once you'd drilled in).\n capture = resolveGroupCapture(startEl, null);\n }\n let current: HTMLElement | null =\n capture.kind === \"unit\" ? capture.element : getSelectionCandidate(startEl, options);\n while (current && current !== doc.body && current !== doc.documentElement) {\n const selector = buildStableSelector(current);\n const hfId = readHfId(current);\n if (!selector && !hfId) {\n current = current.parentElement;\n continue;\n }\n\n const { sourceFile, compositionPath } = getSourceFileForElement(\n current,\n options.activeCompositionPath,\n );\n const selectorIndex = selector\n ? getSelectorIndex(doc, current, selector, sourceFile, options.activeCompositionPath)\n : undefined;\n const compositionSrc =\n current.getAttribute(\"data-composition-src\") ??\n current.getAttribute(\"data-composition-file\") ??\n undefined;\n const inlineStyles = getInlineStyles(current);\n const computedStyles = getCuratedComputedStyles(current);\n const isCompositionRoot =\n (current.hasAttribute(\"data-composition-id\") && !compositionSrc) ||\n isCompositionRootLayer(current, doc, computedStyles);\n const textFields = collectDomEditTextFields(current);\n const isInsideLocked = Boolean(findClosestByAttribute(current, [\"data-timeline-locked\"]));\n const probeTarget: ProbeTarget = {};\n if (current.id) probeTarget.id = current.id;\n if (hfId) probeTarget.hfId = hfId;\n if (selector) probeTarget.selector = selector;\n if (selectorIndex != null) probeTarget.selectorIndex = selectorIndex;\n let existsInSource = knownSourceAnswer(options.previous, current, sourceFile, probeTarget);\n const probe = existsInSource === undefined && !options.skipSourceProbe;\n if (probe && options.projectId && (current.id || selector || hfId)) {\n existsInSource = await probeSourceElement(options.projectId, sourceFile, probeTarget);\n }\n const capabilities = resolveEditingAffordances(\n capabilityFacts({\n hasStableTarget: Boolean(selector || hfId),\n tag: current.tagName.toLowerCase(),\n inlineStyles,\n computedStyles,\n isCompositionHost: Boolean(compositionSrc),\n isCompositionRoot,\n isInsideLockedComposition: isInsideLocked,\n isMasterView: options.isMasterView,\n existsInSource: existsInSource ?? true,\n }),\n ).capabilities;\n const rect = current.getBoundingClientRect();\n\n return {\n element: current,\n id: current.id || undefined,\n hfId,\n selector,\n selectorIndex,\n sourceFile,\n compositionPath,\n compositionSrc,\n isCompositionHost: Boolean(compositionSrc),\n isInsideLockedComposition: isInsideLocked,\n label: buildElementLabel(current),\n tagName: current.tagName.toLowerCase(),\n boundingBox: {\n x: rect.left,\n y: rect.top,\n width: rect.width,\n height: rect.height,\n },\n textContent: current.textContent?.trim() || null,\n dataAttributes: getDataAttributes(current),\n inlineStyles,\n computedStyles,\n textFields,\n capabilities,\n existsInSource,\n };\n }\n\n return null;\n}\n\nexport async function refreshDomEditSelection(\n selection: DomEditSelection,\n activeCompositionPath: string | null,\n): Promise<DomEditSelection | null> {\n const doc = selection.element.ownerDocument;\n const nextElement = findElementForSelection(doc, selection, activeCompositionPath);\n return nextElement\n ? resolveDomEditSelection(nextElement, {\n activeCompositionPath,\n isMasterView: !activeCompositionPath || activeCompositionPath === \"index.html\",\n })\n : null;\n}\n\n// ─── Layer items ─────────────────────────────────────────────────────────────\n\nexport function getDomEditLayerKey(\n target: Pick<DomEditSelection, \"id\" | \"selector\" | \"selectorIndex\" | \"sourceFile\">,\n): string {\n const selectorIndex = target.selectorIndex ?? 0;\n return `${target.sourceFile}:${target.id ?? target.selector ?? \"layer\"}:${selectorIndex}`;\n}\n\nexport function countDomEditChildLayers(\n root: HTMLElement | null | undefined,\n options: DomEditContextOptions,\n maxCount = 99,\n): number {\n if (!root) return 0;\n\n let count = 0;\n const visit = (el: HTMLElement) => {\n for (const child of Array.from(el.children)) {\n if (!isHtmlElement(child)) continue;\n if (isDomLayerElement(child)) {\n count += 1;\n if (count >= maxCount) return;\n }\n visit(child);\n if (count >= maxCount) return;\n }\n };\n\n visit(root);\n return count;\n}\n\n// Every editable element under `root`, in document order. `maxItems` is a\n// caller's rendering budget, not a property of the document: hit-testing\n// callers (marquee, off-canvas indicators) must see all of it, and sharing a\n// truncated list left everything past the cut unselectable however far you drag.\nexport function collectDomEditLayerItems(\n root: HTMLElement | null | undefined,\n options: DomEditContextOptions,\n maxItems = Number.POSITIVE_INFINITY,\n cache?: DomEditLayerWalkCache,\n): DomEditLayerItem[] {\n if (!root) return [];\n cache?.beginWalk(options.activeCompositionPath);\n\n const items: DomEditLayerItem[] = [];\n // fallow-ignore-next-line complexity\n const visit = (el: HTMLElement, depth: number) => {\n if (items.length >= maxItems) return;\n\n const entry = readDomEditLayerWalkEntry(el, options.activeCompositionPath, cache);\n if (entry) {\n const { target } = entry;\n items.push({\n key: getDomEditLayerKey(target),\n element: el,\n label: entry.label,\n tagName: el.tagName.toLowerCase(),\n depth,\n childCount: entry.childCount,\n id: target.id ?? undefined,\n hfId: target.hfId ?? undefined,\n selector: target.selector ?? undefined,\n selectorIndex: target.selectorIndex,\n sourceFile: target.sourceFile,\n });\n }\n\n const nextDepth = entry ? depth + 1 : depth;\n for (const child of Array.from(el.children)) {\n if (!isHtmlElement(child)) continue;\n visit(child, nextDepth);\n if (items.length >= maxItems) return;\n }\n };\n\n // Every item resolves its selector's occurrence index, and unshared that is a\n // whole-document query per element — quadratic once a composition repeats a\n // card or tile class. The walk is one synchronous read of a document it does\n // not mutate, so one index per selector serves the whole of it. The pass lives\n // here rather than in each caller because this function owns the loop.\n withSelectorIndexPass(root.ownerDocument, () => {\n // Drilled into a group → show only its members; otherwise the whole tree.\n for (const el of groupScopedLayerRoots(root, options.activeGroupElement ?? null)) visit(el, 0);\n });\n return items;\n}\n\nexport function liveLayerElement(\n layer: DomEditLayerItem,\n doc: Document | null | undefined,\n activeCompositionPath: string | null,\n): HTMLElement {\n if (layer.element.isConnected || !doc) return layer.element;\n return findElementForSelection(doc, layer, activeCompositionPath) ?? layer.element;\n}\n\n// ─── Patch operations ────────────────────────────────────────────────────────\n\nexport function buildDomEditStylePatchOperation(\n property: string,\n value: string | null,\n childLocator?: DomEditChildLocator,\n): PatchOperation {\n return {\n type: \"inline-style\",\n property,\n value,\n ...childLocator,\n };\n}\n\nexport function buildDomEditTextPatchOperation(\n value: string,\n childLocator?: DomEditChildLocator,\n): PatchOperation {\n return { type: \"text-content\", property: \"text\", value, ...childLocator };\n}\n\n/** Replace an element's contents with markup, for a change no per-child operation\n * can express (a text layer added, removed or reordered). Sanitized at both ends. */\nexport function buildDomEditRichTextPatchOperation(value: string): PatchOperation {\n return { type: \"rich-text\", property: \"\", value };\n}\n\n// ─── Non-editable reason ─────────────────────────────────────────────────────\n\nfunction hasSupportedDirectEdit(capabilities: DomEditCapabilities): boolean {\n return (\n capabilities.canEditStyles ||\n capabilities.canMove ||\n capabilities.canResize ||\n capabilities.canApplyManualOffset ||\n capabilities.canApplyManualSize ||\n capabilities.canApplyManualRotation\n );\n}\n\nexport function getDomEditNonEditableReason(\n element: HTMLElement,\n selection: DomEditSelection | null,\n): string | null {\n if (!selection) {\n return \"No stable source target\";\n }\n\n if (selection.element !== element) {\n return selection.isCompositionHost\n ? \"Nested composition boundary\"\n : `Selection resolves to ${selection.label}`;\n }\n\n if (!hasSupportedDirectEdit(selection.capabilities)) {\n return selection.capabilities.reasonIfDisabled ?? \"No supported direct edits\";\n }\n\n return null;\n}\n\nexport function getDomEditTargetKey(\n selection: Pick<DomEditSelection, \"id\" | \"hfId\" | \"selector\" | \"selectorIndex\" | \"sourceFile\">,\n): string {\n return [\n selection.sourceFile || \"index.html\",\n selection.hfId ?? \"\",\n selection.id ?? \"\",\n selection.selector ?? \"\",\n selection.selectorIndex ?? \"\",\n ].join(\"|\");\n}\n\nexport function isTextEditableSelection(selection: DomEditSelection): boolean {\n return resolveEditingSections(domEditSelectionToFacts(selection)).text;\n}\n\n// buildElementAgentPrompt is in domEditingAgentPrompt.ts\n\nexport function readHfId(element: Element): string | undefined {\n return element.getAttribute(\"data-hf-id\")?.trim() || undefined;\n}\n\nexport function buildDomEditPatchTarget(\n selection: Pick<DomEditSelection, \"id\" | \"hfId\" | \"selector\" | \"selectorIndex\">,\n): { id?: string | null; hfId?: string; selector?: string; selectorIndex?: number } {\n return {\n id: selection.id,\n hfId: selection.hfId,\n selector: selection.selector,\n selectorIndex: selection.selectorIndex,\n };\n}\n","import { isHtmlElement } from \"./domEditingDom\";\n\n// `data-hf-group` selection semantics: a group wrapper is selected as one unit\n// until the user drills into it; once drilled in, clicks resolve to its children\n// (or to the next nested group inside it). One level of drill-in at a time keeps\n// nested groups navigable.\n\nexport type GroupCapture =\n | { kind: \"unit\"; element: HTMLElement } // select this group wrapper as one unit\n | { kind: \"child\" } // resolve the clicked element normally\n | { kind: \"out-of-scope\" }; // clicked outside the drilled-into group → select nothing\n\n// Layer-tree roots: the drilled-into group's element children, else the doc root.\nexport function groupScopedLayerRoots(\n root: HTMLElement,\n activeGroupElement: HTMLElement | null,\n): HTMLElement[] {\n const els = activeGroupElement?.isConnected ? Array.from(activeGroupElement.children) : [root];\n return els.filter(isHtmlElement);\n}\n\nexport function resolveGroupCapture(\n startEl: HTMLElement,\n activeGroupElement: HTMLElement | null,\n): GroupCapture {\n const groups: HTMLElement[] = [];\n for (let n: HTMLElement | null = startEl; n; n = n.parentElement) {\n if (n.hasAttribute(\"data-hf-group\")) groups.push(n);\n }\n const result = ((): GroupCapture => {\n if (!activeGroupElement) {\n const outermost = groups[groups.length - 1];\n return outermost ? { kind: \"unit\", element: outermost } : { kind: \"child\" };\n }\n const idx = groups.indexOf(activeGroupElement);\n if (idx === -1) return { kind: \"out-of-scope\" };\n const nestedInside = groups[idx - 1];\n return nestedInside ? { kind: \"unit\", element: nestedInside } : { kind: \"child\" };\n })();\n return result;\n}\n","/**\n * Element visibility, visual scoring, layer patch targets, element finders,\n * and the `findElementForSelection` / `findElementForTimelineElement` lookups.\n */\nimport type {\n DomEditContextOptions,\n DomEditSelection,\n DomEditViewport,\n TimelineElementDomTarget,\n TimelineElementDomTargetOptions,\n} from \"./domEditingTypes\";\nimport {\n buildStableSelector,\n escapeCssString,\n getSelectorIndex,\n getSourceFileForElement,\n isHtmlElement,\n isElementVisibleThroughAncestors,\n normalizeTimelineCompositionSource,\n querySelectorAllSafely,\n} from \"./domEditingDom\";\n\n// ─── Visibility ──────────────────────────────────────────────────────────────\n\nexport function isElementComputedVisible(\n el: HTMLElement,\n memo?: Map<HTMLElement, boolean>,\n): boolean {\n return isElementVisibleThroughAncestors(el, memo);\n}\n\nconst VISUAL_LEAF_TAGS = new Set([\"img\", \"video\", \"canvas\", \"svg\", \"audio\"]);\n\n// fallow-ignore-next-line complexity\nfunction hasVisualPresence(el: HTMLElement): boolean {\n const win = el.ownerDocument.defaultView;\n if (!win) return false;\n const cs = win.getComputedStyle(el);\n if (cs.backgroundImage !== \"none\") return true;\n if (\n cs.backgroundColor &&\n cs.backgroundColor !== \"transparent\" &&\n cs.backgroundColor !== \"rgba(0, 0, 0, 0)\"\n )\n return true;\n if (cs.borderWidth && parseFloat(cs.borderWidth) > 0 && cs.borderStyle !== \"none\") return true;\n if (cs.boxShadow && cs.boxShadow !== \"none\") return true;\n return false;\n}\n\nfunction isEmptyVisualContainer(el: HTMLElement): boolean {\n const tag = el.tagName.toLowerCase();\n if (VISUAL_LEAF_TAGS.has(tag)) return false;\n if (hasVisualPresence(el)) return false;\n\n const { children } = el;\n if (children.length === 0) {\n return (el.textContent ?? \"\").trim().length === 0;\n }\n\n for (let i = 0; i < children.length; i += 1) {\n const child = children[i];\n if (!isHtmlElement(child)) continue;\n if (VISUAL_LEAF_TAGS.has(child.tagName.toLowerCase())) return false;\n if (isElementComputedVisible(child)) return false;\n }\n\n return true;\n}\n\nfunction hasRenderedBox(el: HTMLElement): boolean {\n const rect = el.getBoundingClientRect();\n if (rect.width <= 1 || rect.height <= 1) return false;\n if (!isElementComputedVisible(el)) return false;\n if (isEmptyVisualContainer(el)) return false;\n return true;\n}\n\n// ─── Visual scoring ──────────────────────────────────────────────────────────\n\n// ─── Layer patch target ──────────────────────────────────────────────────────\n\nconst DOM_LAYER_IGNORED_TAGS = new Set([\n \"base\",\n \"br\",\n \"canvas\",\n \"link\",\n \"meta\",\n \"script\",\n \"source\",\n \"style\",\n \"template\",\n \"track\",\n \"wbr\",\n]);\n\n/**\n * Is the element rendered at all? The half of `getDomLayerPatchTarget` that a\n * plain style write can flip, and the only half that reads computed style.\n * Exported so a caller memoizing a layer walk can give it its own (short)\n * cache lifetime — see `domEditLayerWalkCache`.\n */\nexport function isInspectableLayerElement(el: HTMLElement): boolean {\n const tagName = el.tagName.toLowerCase();\n if (DOM_LAYER_IGNORED_TAGS.has(tagName)) return false;\n\n const computed = el.ownerDocument.defaultView?.getComputedStyle(el);\n if (computed?.display === \"none\" || computed?.visibility === \"hidden\") return false;\n\n return true;\n}\n\n/**\n * How the element is ADDRESSED — its selector, that selector's occurrence index\n * within the source file, and the file itself. Independent of whether the\n * element currently renders, so it survives every style write and moves only\n * when an identity attribute changes or the document's population of elements\n * sharing the selector does.\n */\n/**\n * The selector an element is addressed by, or undefined when it cannot be a\n * layer at all. Sole owner of that rule: `isDomLayerElement` answers the same\n * question without paying for the occurrence index, and a second copy of the\n * conditions would go stale the first time one of them changed.\n */\nfunction resolveLayerSelector(el: HTMLElement): string | undefined {\n if (el.hasAttribute(\"data-composition-id\")) return undefined;\n return buildStableSelector(el);\n}\n\nexport function resolveDomLayerIdentity(\n el: HTMLElement,\n activeCompositionPath: string | null,\n): Pick<DomEditSelection, \"id\" | \"hfId\" | \"selector\" | \"selectorIndex\" | \"sourceFile\"> | null {\n const selector = resolveLayerSelector(el);\n if (!selector) return null;\n\n const { sourceFile } = getSourceFileForElement(el, activeCompositionPath);\n return {\n id: el.id || undefined,\n hfId: el.getAttribute(\"data-hf-id\") || undefined,\n selector,\n selectorIndex: getSelectorIndex(\n el.ownerDocument,\n el,\n selector,\n sourceFile,\n activeCompositionPath,\n ),\n sourceFile,\n };\n}\n\nexport function getDomLayerPatchTarget(\n el: HTMLElement,\n activeCompositionPath: string | null,\n): Pick<DomEditSelection, \"id\" | \"hfId\" | \"selector\" | \"selectorIndex\" | \"sourceFile\"> | null {\n return isInspectableLayerElement(el) ? resolveDomLayerIdentity(el, activeCompositionPath) : null;\n}\n\n/**\n * Is `el` a layer at all? Exactly the condition under which\n * `getDomLayerPatchTarget` returns non-null, for callers that want the yes/no\n * and throw the target away.\n *\n * Worth its own function because the target carries the selector's OCCURRENCE\n * INDEX, and resolving that is a whole-document query — which the yes/no does\n * not depend on. Counting an element's layer children asked for one per child.\n */\nexport function isDomLayerElement(el: HTMLElement): boolean {\n return isInspectableLayerElement(el) && resolveLayerSelector(el) !== undefined;\n}\n\n// ─── Clip ancestor / selection candidate ─────────────────────────────────────\n\nfunction getPreferredClipAncestor(startEl: HTMLElement): HTMLElement | null {\n let current: HTMLElement | null = startEl;\n while (current) {\n if (current.classList.contains(\"clip\")) {\n const isCompositionHost =\n current.hasAttribute(\"data-composition-src\") ||\n current.hasAttribute(\"data-composition-file\");\n if (!isCompositionHost || current === startEl) return current;\n }\n current = current.parentElement;\n }\n return null;\n}\n\nexport function getSelectionCandidate(\n startEl: HTMLElement,\n options: DomEditContextOptions,\n): HTMLElement {\n if (options.preferClipAncestor) {\n const clipAncestor = getPreferredClipAncestor(startEl);\n if (clipAncestor) {\n return clipAncestor;\n }\n }\n\n return startEl;\n}\n\n// ─── Visual target resolution ─────────────────────────────────────────────────\n\nexport function resolveVisualDomEditSelectionTarget(\n elementsFromPoint: Iterable<Element | null | undefined>,\n options: Pick<DomEditContextOptions, \"activeCompositionPath\">,\n): HTMLElement | null {\n const candidates = resolveAllVisualDomEditTargets(elementsFromPoint, options);\n return candidates[0] ?? null;\n}\n\n/**\n * Returns all independently-selectable elements at the given point, in paint\n * order (topmost first). Used for click-cycling through stacked layers.\n *\n * Each entry in the returned array is an independent \"layer\" — an element\n * that is not an ancestor of an earlier entry. This gives one result per\n * z-stacked element rather than one per DOM node.\n */\nexport function resolveAllVisualDomEditTargets(\n elementsFromPoint: Iterable<Element | null | undefined>,\n options: Pick<DomEditContextOptions, \"activeCompositionPath\">,\n): HTMLElement[] {\n const raw: HTMLElement[] = [];\n\n for (const entry of elementsFromPoint) {\n if (!isHtmlElement(entry)) continue;\n if (hasRenderedBox(entry) && getDomLayerPatchTarget(entry, options.activeCompositionPath)) {\n raw.push(entry);\n }\n }\n\n if (raw.length === 0) return [];\n\n // First pass: for each contiguous ancestor-descendant run, keep only the\n // deepest (most specific) element, matching the original single-pick logic.\n const layers: HTMLElement[] = [];\n let best = raw[0];\n for (let i = 1; i < raw.length; i++) {\n const el = raw[i];\n if (best.contains(el)) {\n best = el; // go deeper in this subtree\n } else {\n layers.push(best);\n best = el;\n }\n }\n layers.push(best);\n\n return layers;\n}\n\n// ─── Raster detection ────────────────────────────────────────────────────────\n\nfunction hasRasterBackground(selection: Pick<DomEditSelection, \"computedStyles\">): boolean {\n const backgroundImage = selection.computedStyles[\"background-image\"]?.trim();\n return Boolean(backgroundImage && backgroundImage !== \"none\");\n}\n\nexport function isLargeRasterDomEditSelection(\n selection: Pick<DomEditSelection, \"boundingBox\" | \"computedStyles\" | \"tagName\">,\n viewport?: DomEditViewport | null,\n): boolean {\n const tagName = selection.tagName.toLowerCase();\n const isRasterLike = tagName === \"img\" || hasRasterBackground(selection);\n if (!isRasterLike) return false;\n\n const { width, height } = selection.boundingBox;\n if (width <= 1 || height <= 1) return false;\n if (!viewport || viewport.width <= 1 || viewport.height <= 1) {\n return width >= 960 && height >= 540;\n }\n\n const areaRatio = (width * height) / (viewport.width * viewport.height);\n const widthRatio = width / viewport.width;\n const heightRatio = height / viewport.height;\n return areaRatio >= 0.4 || (widthRatio >= 0.7 && heightRatio >= 0.5);\n}\n\n// ─── Element finders ──────────────────────────────────────────────────────────\n\ntype FindElementSelection = Pick<DomEditSelection, \"id\" | \"hfId\" | \"selector\" | \"selectorIndex\"> & {\n sourceFile?: string;\n};\n\nexport function findElementForSelection(\n doc: Document,\n selection: FindElementSelection,\n activeCompositionPath: string | null = null,\n): HTMLElement | null {\n const sourceMatches = (candidate: Element): candidate is HTMLElement =>\n isHtmlElement(candidate) &&\n (!selection.sourceFile ||\n getSourceFileForElement(candidate, activeCompositionPath).sourceFile ===\n selection.sourceFile);\n const findAll = (selector: string): HTMLElement[] =>\n querySelectorAllSafely(doc, selector).filter(sourceMatches);\n\n if (selection.hfId) {\n const byHfId = findAll(`[data-hf-id=\"${escapeCssString(selection.hfId)}\"]`)[0];\n if (byHfId) return byHfId;\n }\n\n if (selection.id) {\n // Flattened sub-compositions can repeat authored ids. getElementById returns\n // only the first document match, so filter every id match by source first.\n const byId = findAll(`[id=\"${escapeCssString(selection.id)}\"]`)[0];\n if (byId) return byId;\n }\n\n if (!selection.selector) return null;\n return findAll(selection.selector)[selection.selectorIndex ?? 0] ?? null;\n}\n\n// The selected node while mounted, else its copy in the selection's own file (ids repeat across files), else any copy.\nexport function findPreviewNode(\n doc: Document | null | undefined,\n el: DomEditSelection,\n): Element | null {\n if (!doc) return null;\n if (el.element?.isConnected && el.element.ownerDocument === doc) return el.element;\n return (\n findElementForSelection(doc, el) ??\n findElementForSelection(doc, { ...el, sourceFile: undefined })\n );\n}\n\n// fallow-ignore-next-line complexity\nexport function findElementForTimelineElement(\n doc: Document,\n element: TimelineElementDomTarget,\n options: TimelineElementDomTargetOptions,\n): HTMLElement | null {\n const elementId = typeof element.id === \"string\" ? element.id : \"\";\n const compositionSource =\n normalizeTimelineCompositionSource(element.compositionSrc) ??\n options.compIdToSrc?.get(elementId);\n const sourceFile =\n compositionSource ??\n normalizeTimelineCompositionSource(element.sourceFile) ??\n options.activeCompositionPath ??\n \"index.html\";\n const escapedElementId = escapeCssString(elementId);\n const escapedCompositionSource = compositionSource ? escapeCssString(compositionSource) : null;\n const selector =\n element.selector ??\n (compositionSource\n ? `[data-composition-src=\"${escapedCompositionSource}\"],[data-composition-file=\"${escapedCompositionSource}\"],[data-composition-id=\"${escapedElementId}\"]`\n : escapedElementId\n ? `[data-composition-id=\"${escapedElementId}\"]`\n : undefined);\n\n if (selector || element.domId) {\n const targetElement = findElementForSelection(\n doc,\n {\n id: element.domId ?? undefined,\n selector,\n selectorIndex: element.selectorIndex,\n sourceFile,\n },\n options.activeCompositionPath,\n );\n if (targetElement) return targetElement;\n }\n\n const hasExplicitDomTarget = Boolean(element.domId || element.selector || compositionSource);\n if (options.isMasterView || hasExplicitDomTarget || !options.activeCompositionPath) {\n return null;\n }\n\n const root = doc.querySelector(\"[data-composition-id]\");\n if (!isHtmlElement(root)) return null;\n return getSourceFileForElement(root, options.activeCompositionPath).sourceFile === sourceFile\n ? root\n : null;\n}\n\n// ─── Layer children ───────────────────────────────────────────────────────────\n\n/** `el`'s direct children that are layers. No longer takes the context options:\n * layer-ness does not depend on the active composition path. */\nexport function getDirectLayerChildren(el: HTMLElement): HTMLElement[] {\n return Array.from(el.children).filter(\n (child): child is HTMLElement => isHtmlElement(child) && isDomLayerElement(child),\n );\n}\n","import { parsePx } from \"./domEditingDom\";\n\nconst COMPOSITION_ROOT_LAYER_EPSILON_PX = 1;\n\nfunction readPositiveDimension(value: string | null): number | null {\n if (!value) return null;\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction approximatelyEqual(a: number, b: number) {\n return Math.abs(a - b) <= COMPOSITION_ROOT_LAYER_EPSILON_PX;\n}\n\nfunction getCompositionRootBounds(doc: Document) {\n const root =\n doc.querySelector<HTMLElement>(\"[data-composition-id]\") ?? doc.documentElement ?? null;\n const rootWidth = readPositiveDimension(root?.getAttribute(\"data-width\") ?? null);\n const rootHeight = readPositiveDimension(root?.getAttribute(\"data-height\") ?? null);\n if (!root || !rootWidth || !rootHeight) return null;\n return { rect: root.getBoundingClientRect(), width: rootWidth, height: rootHeight };\n}\n\nfunction getRenderedLayerSize(element: HTMLElement, computedStyles: Record<string, string>) {\n const rect = element.getBoundingClientRect();\n const width = rect.width || parsePx(computedStyles.width);\n const height = rect.height || parsePx(computedStyles.height);\n return width && height ? { width, height } : null;\n}\n\nfunction matchesCompositionRootBounds(\n elementRect: DOMRect,\n elementSize: { width: number; height: number },\n rootBounds: { rect: DOMRect; width: number; height: number },\n) {\n return (\n approximatelyEqual(elementRect.left, rootBounds.rect.left) &&\n approximatelyEqual(elementRect.top, rootBounds.rect.top) &&\n approximatelyEqual(elementSize.width, rootBounds.width) &&\n approximatelyEqual(elementSize.height, rootBounds.height)\n );\n}\n\nfunction isExplicitFullBleedLayer(computedStyles: Record<string, string>) {\n return computedStyles.position === \"absolute\" || computedStyles.position === \"fixed\";\n}\n\nexport function isCompositionRootLayer(\n element: HTMLElement,\n doc: Document,\n computedStyles: Record<string, string>,\n) {\n if (element.parentElement !== doc.body) return false;\n if (element.hasAttribute(\"data-hf-allow-root-edit\")) return false;\n if (isExplicitFullBleedLayer(computedStyles)) return false;\n\n const rootBounds = getCompositionRootBounds(doc);\n const elementSize = getRenderedLayerSize(element, computedStyles);\n return Boolean(\n rootBounds &&\n elementSize &&\n matchesCompositionRootBounds(element.getBoundingClientRect(), elementSize, rootBounds),\n );\n}\n","/**\n * Incremental memory for `collectDomEditLayerItems`.\n *\n * The layer walk is re-run from scratch every time a MutationObserver says the\n * preview changed, and the observer's loudest source is inline `style` — which\n * is exactly what animation writes. So a paused-looking editor re-derived every\n * element's patch target, label and child count several times a second, and each\n * derivation costs two `getComputedStyle` reads (its own plus one per direct\n * child), two ancestor walks for the source file, and a `textContent` read whose\n * cost is the element's whole subtree.\n *\n * None of that depends on the traversal — only on the element. So the traversal\n * stays live (it is pointer-chasing, and `depth` genuinely is positional) and the\n * per-element half is memoized, with the mutation records deciding what to drop.\n *\n * WHAT MAKES A CACHED ENTRY WRONG, and how each is caught:\n *\n * - the element's own attributes (`style` -> computed display, `class`/`id`/\n * `data-hf-group` -> selector and label) -> attribute record on it\n * - an ancestor's `visibility`, the ONLY inherited input to the\n * display/visibility gate (`display:none` on an ancestor does not change a\n * descendant's own computed `display`) -> attribute record on the\n * ancestor, whose subtree is\n * dropped only when the\n * style declares visibility\n * - a direct child appearing or disappearing from the layer list, which moves\n * the parent's `childCount` -> the parent is dropped\n * alongside every element\n * - descendant text, which moves an ancestor's label -> characterData record,\n * ancestors dropped\n * - selector occurrence indices, which shift for EVERY element sharing a\n * selector when one element's identity changes -> whole cache dropped\n * - nodes added or removed, which shift indices, order, labels and counts at\n * once and cannot be attributed to one element -> whole cache dropped\n * - a different active composition path, or a new composition-id -> source-file\n * map, both of which re-scope every source file -> checked per walk\n *\n * The bias is deliberate and matches the duration cache in the runtime: a\n * redundant recomputation is a missed optimisation, a missed one is a wrong\n * layer tree.\n */\n\nimport { buildElementLabel, getCompositionSourceMapRevision, isHtmlElement } from \"./domEditingDom\";\nimport {\n getDirectLayerChildren,\n isInspectableLayerElement,\n resolveDomLayerIdentity,\n} from \"./domEditingElement\";\nimport type { DomEditSelection } from \"./domEditingTypes\";\n\n/** How an element is addressed. Survives style writes; see `readIdentity`. */\nexport type DomEditLayerIdentity = Pick<\n DomEditSelection,\n \"id\" | \"hfId\" | \"selector\" | \"selectorIndex\" | \"sourceFile\"\n>;\n\n/** Whether the element renders, and how many of its direct children are layers.\n * Both are computed style reads, and both a style write can flip. Filled\n * lazily: `childCount` is only asked for once an element is known to be one. */\ninterface PresenceMemo {\n inspectable?: boolean;\n childCount?: number;\n}\n\ninterface IdentityMemo {\n identity?: DomEditLayerIdentity | null;\n label?: string;\n}\n\n/**\n * Attributes that decide an element's SELECTOR, and therefore the occurrence\n * index of every other element sharing that selector. One of these changing\n * renumbers elements the record does not mention, so the only sound response is\n * to drop everything. `class` is here because `buildStableSelector` falls back\n * to the preferred class.\n */\nconst SELECTOR_IDENTITY_ATTRIBUTES = new Set([\n \"id\",\n \"class\",\n \"data-hf-group\",\n \"data-composition-id\",\n \"data-composition-file\",\n \"data-composition-src\",\n \"data-hf-original-composition-id\",\n]);\n\n/**\n * The observer configuration the cache's invalidation is written against.\n * Exported so the refresh loop and the tests cannot drift from it.\n *\n * No `attributeFilter`: an unlisted attribute is one the cache would never learn\n * about, and serving a stale entry is worse than the extra records.\n */\nexport const DOM_EDIT_LAYER_OBSERVER_INIT: MutationObserverInit = {\n attributes: true,\n characterData: true,\n childList: true,\n subtree: true,\n};\n\n/**\n * The inline `visibility` each element last presented. Deliberately NOT cleared\n * by `invalidateAll`: it records what the DOM said, not a value derived from it.\n */\nconst lastInlineVisibility = new WeakMap<HTMLElement, string>();\n\n/**\n * Did this style write move the element's inline `visibility`?\n *\n * `visibility` is inherited, so changing it changes the layer-list membership of\n * the element's whole subtree, and only then is the subtree worth dropping.\n *\n * The comparison is on the PARSED value, remembered per element. Testing the\n * attribute TEXT for \"visibility\" looks equivalent and is not: the standard\n * GSAP fade (`autoAlpha`) writes `visibility: visible` once and leaves it in the\n * attribute for the rest of the clip, so a text test stays true for every\n * transform tick afterwards. That is a whole-subtree walk per animation frame,\n * in the observer callback rather than behind the rebuild throttle, on exactly\n * the elements a composition animates most.\n *\n * An element seen for the first time reports changed, which costs one drop and\n * is the safe answer: its entries were derived before this write.\n */\nfunction inlineVisibilityChanged(el: HTMLElement): boolean {\n const next = el.style.visibility;\n if (lastInlineVisibility.get(el) === next) return false;\n lastInlineVisibility.set(el, next);\n return true;\n}\n\nexport interface DomEditLayerWalkCache {\n /**\n * Start a walk. Drops everything when the scoping inputs the entries were\n * built under no longer hold. Call once per `collectDomEditLayerItems`.\n */\n beginWalk(activeCompositionPath: string | null): void;\n /**\n * Does `el` render? Cheap to invalidate and invalidated often: any attribute\n * write on the element, on its parent, or a `visibility` write on an ancestor\n * drops it, because all three can flip the answer.\n */\n readInspectable(el: HTMLElement, compute: () => boolean): boolean;\n /** How many of `el`'s direct children are layers. Same lifetime as\n * `readInspectable`: it is a sum over their answers. */\n readChildCount(el: HTMLElement, compute: () => number): number;\n /**\n * `el`'s selector, occurrence index and source file. A SEPARATE, much longer\n * lifetime than presence: a style write cannot renumber a selector, so this\n * survives one, and it is the only part of the walk that queries the\n * document. That split is what makes an ordinary animation frame cost no\n * document queries at all.\n */\n readIdentity(\n el: HTMLElement,\n compute: () => DomEditLayerIdentity | null,\n ): DomEditLayerIdentity | null;\n /** `el`'s display label. Shares the identity lifetime, plus descendant text. */\n readLabel(el: HTMLElement, compute: () => string): string;\n /** Apply mutation records. Safe to call with an empty array. */\n ingest(records: MutationRecord[]): void;\n /** Forget every entry — the fallback for anything not attributable. */\n invalidateAll(): void;\n}\n\nexport function createDomEditLayerWalkCache(): DomEditLayerWalkCache {\n let presence = new WeakMap<HTMLElement, PresenceMemo>();\n let identities = new WeakMap<HTMLElement, IdentityMemo>();\n let scope: string | null = null;\n\n const invalidateAll = () => {\n presence = new WeakMap();\n identities = new WeakMap();\n };\n\n const drop = (el: HTMLElement | null) => {\n if (el) presence.delete(el);\n };\n\n const dropSubtree = (el: HTMLElement) => {\n for (const descendant of el.querySelectorAll(\"*\")) {\n if (isHtmlElement(descendant)) presence.delete(descendant);\n }\n };\n\n const ingestOne = (record: MutationRecord): boolean => {\n // Structural change: order, occurrence indices, labels and child counts all\n // move at once, and the record names the parent rather than everything\n // affected. This is the documented full-rebuild fallback.\n if (record.type === \"childList\") return false;\n\n if (record.type === \"characterData\") {\n // `buildElementLabel` falls back to `textContent`, so edited text changes\n // the label of every ancestor that contains it.\n for (\n let ancestor = record.target.parentElement;\n ancestor;\n ancestor = ancestor.parentElement\n ) {\n identities.delete(ancestor);\n }\n return true;\n }\n\n const target = record.target;\n if (!isHtmlElement(target)) return true;\n if (record.attributeName && SELECTOR_IDENTITY_ATTRIBUTES.has(record.attributeName))\n return false;\n\n drop(target);\n // The parent counts its layer children, and this element may have just\n // joined or left that count.\n drop(target.parentElement);\n if (record.attributeName === \"style\" && inlineVisibilityChanged(target)) dropSubtree(target);\n return true;\n };\n\n return {\n beginWalk(activeCompositionPath) {\n const nextScope = `${activeCompositionPath ?? \"\"}|${getCompositionSourceMapRevision()}`;\n if (nextScope === scope) return;\n scope = nextScope;\n invalidateAll();\n },\n readInspectable(el, compute) {\n const memo = presence.get(el) ?? {};\n if (memo.inspectable === undefined) {\n memo.inspectable = compute();\n presence.set(el, memo);\n }\n return memo.inspectable;\n },\n readChildCount(el, compute) {\n const memo = presence.get(el) ?? {};\n if (memo.childCount === undefined) {\n memo.childCount = compute();\n presence.set(el, memo);\n }\n return memo.childCount;\n },\n readIdentity(el, compute) {\n const memo = identities.get(el) ?? {};\n if (memo.identity === undefined) {\n memo.identity = compute();\n identities.set(el, memo);\n }\n return memo.identity;\n },\n readLabel(el, compute) {\n const memo = identities.get(el) ?? {};\n if (memo.label === undefined) {\n memo.label = compute();\n identities.set(el, memo);\n }\n return memo.label;\n },\n ingest(records) {\n for (const record of records) {\n if (!ingestOne(record)) {\n invalidateAll();\n return;\n }\n }\n },\n invalidateAll,\n };\n}\n\n/** One element's contribution to a layer walk. `depth` is absent on purpose: it\n * belongs to the traversal, not to the element. */\nexport interface DomEditLayerWalkEntry {\n target: DomEditLayerIdentity;\n label: string;\n childCount: number;\n}\n\n/**\n * Everything `collectDomEditLayerItems` needs about ONE element, served from\n * `cache` where it is still valid. Null when the element is not a layer.\n *\n * The four reads go through the cache separately rather than as one record\n * because they do not go stale together: a style write flips whether an element\n * renders without touching how it is addressed. Without a cache this is exactly\n * the original per-element derivation, which is what every other caller of the\n * walk still gets.\n *\n * Lives here rather than in the walk so the two halves of the memoization —\n * what is stored and what is read — sit in one file.\n */\nexport function readDomEditLayerWalkEntry(\n el: HTMLElement,\n activeCompositionPath: string | null,\n cache?: DomEditLayerWalkCache,\n): DomEditLayerWalkEntry | null {\n const inspectable = cache\n ? cache.readInspectable(el, () => isInspectableLayerElement(el))\n : isInspectableLayerElement(el);\n if (!inspectable) return null;\n\n const identity = () => resolveDomLayerIdentity(el, activeCompositionPath);\n const target = cache ? cache.readIdentity(el, identity) : identity();\n if (!target) return null;\n\n const label = () => buildElementLabel(el);\n const childCount = () => getDirectLayerChildren(el).length;\n return {\n target,\n label: cache ? cache.readLabel(el, label) : label(),\n childCount: cache ? cache.readChildCount(el, childCount) : childCount(),\n };\n}\n\n/**\n * Apply the records the observer has taken in but not yet delivered.\n *\n * Records arrive in a microtask, so an edit made earlier in THIS task would\n * otherwise be read back against entries that predate it. Taking them suppresses\n * the observer's own callback for them, which is equivalent here: that callback\n * only ingests and marks a rebuild owed, and a caller draining is rebuilding\n * regardless. A caller with no observer yet has nothing pending.\n */\nexport function drainPendingLayerMutations(\n observer: MutationObserver | null,\n cache: DomEditLayerWalkCache,\n): void {\n if (!observer) return;\n cache.ingest(observer.takeRecords());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,gCAAgC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA4CO,SAAS,0BACdA,MACA,eACuC;AACvC,MAAI,CAAC,cAAe,QAAO,oBAAI,IAAI;AACnC,QAAM,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