{"version":3,"file":"index.mjs","names":["judge","lockedAncestorOf","lockedAncestorIn","placementOf","registryBlockSource","lockedAncestorOf","siblingsOf","applyOp","registryBlockSource","permittedLabel","permittedLabelWith","permittedLabel","placementRefusal","BASE_BREAKPOINT","placementOf","bound","bound","bound","textOf"],"sources":["../src/canvas/dom-kind.ts","../src/canvas/geometry-dom.ts","../src/canvas/drop-targets.ts","../src/styles/style-values.ts","../src/styles/breakpoints.ts","../src/canvas/canvas-width.ts","../src/panels/add/inserter-types.ts","../src/panels/add/inserter-catalog.ts","../src/editor-words.ts","../src/panels/add/inserter.ts","../src/canvas/target-switch.ts","../src/conditions/condition-gate.ts","../src/inspector/custom-css.ts","../src/placement-props.ts","../src/panels/layers/layers.ts","../src/locking.ts","../src/canvas/canvas-addressing.ts","../src/lock-refusal.ts","../src/canvas/drag-refusal.ts","../src/move-refusal.ts","../src/inspector/inspector-sections.ts","../src/inspector/inspector.ts","../src/conditions/applied-conditions.ts","../src/canvas/selection.ts","../src/canvas/reduced-motion.ts","../src/canvas/reveal-node.ts","../src/shell/key-hint.ts","../src/canvas/component-holds.ts","../src/inspector/instance-inspector.ts","../src/canvas/duplicate-block.ts","../src/canvas/delete-block.ts","../src/canvas/keyboard-move.ts","../src/canvas/selection-ops.ts","../src/canvas/turn-into-verb.ts","../src/shell/builder-commands.ts","../src/canvas/permitted-prose.ts","../src/canvas/composition-refusal.ts","../src/canvas/canvas-escape.ts","../src/styles/class-library.ts","../src/panels/design/colour-groups.ts","../src/styles/style-colour.ts","../src/styles/shared-style-library.ts","../src/styles/shared-style-target.ts","../src/canvas/entry-content-rules.ts","../src/canvas/selection-wrap.ts","../src/canvas/toolbar-actions.ts","../src/styles/style-baseline.ts","../src/styles/style-controls.ts","../src/styles/style-provenance.ts","../src/styles/style-scrub.ts","../src/styles/style-control-behaviour.ts","../src/inspector/style-inspector/style-inspector.ts","../src/styles/batch-style.ts","../src/page-checks/page-checks.ts","../src/page-checks/rich-text-parts.ts","../src/page-checks/contrast-check.ts","../src/inspector/content/image-group.ts","../src/page-checks/stored-values.ts","../src/page-checks/empty-blocks-check.ts","../src/shell/read-budget.ts","../src/shell/unread-places.ts","../src/page-checks/fact-checks.ts","../src/inspector/content/form-picked.ts","../src/page-checks/form-nowhere-check.ts","../src/page-checks/heading-check.ts","../src/page-checks/image-alt-check.ts","../src/page-checks/labels-check.ts","../src/page-checks/link-text-check.ts","../src/page-checks/core-checks.ts","../src/index.ts"],"sourcesContent":["/**\n * What kind of DOM node a value is, answered the same way in every realm.\n *\n * `x instanceof HTMLElement` compares `x` against the constructor of the realm\n * doing the asking. A node built by another document's window — the canvas\n * mounted into a same-origin iframe, an event fired inside it — carries that\n * window's constructors, so the check answers `false` for a perfectly ordinary\n * element. Code reading it that way returns early and does nothing, silently,\n * on exactly the canvas it was written for.\n *\n * So every question here is asked of the node's own STRUCTURE: its `nodeType`,\n * its namespace and its local name, which are the same values whichever window\n * built it. They are also what the DOM itself means by the interfaces: every\n * element in the HTML namespace implements `HTMLElement`, and a `<textarea>`\n * there is an `HTMLTextAreaElement`.\n *\n * One module, because a realm-safe spelling written correctly once is copied\n * wrongly afterwards. `dom-kind-ban.test.ts` refuses an `instanceof` against a\n * DOM constructor anywhere else in this package's shipped source.\n *\n * @module dom-kind\n */\n\n/** `Node.ELEMENT_NODE`, spelled as the number so no realm's `Node` is read. */\nconst ELEMENT_NODE = 1;\n\n/** The namespace every element of an HTML document is created in. */\nconst HTML_NAMESPACE = \"http://www.w3.org/1999/xhtml\";\n\n/**\n * Whether a value is an element, from any realm.\n *\n * Takes `unknown` because the callers hold an `EventTarget` — an event's\n * target can be the window or the document as well as an element — and asking\n * for `nodeType` on anything else answers no rather than throwing.\n */\nexport function isElement(value: unknown): value is Element {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"nodeType\" in value &&\n    value.nodeType === ELEMENT_NODE\n  );\n}\n\n/**\n * Whether a value is an HTML element, from any realm.\n *\n * By namespace, because that is what decides the interface: an element in the\n * HTML namespace is an `HTMLElement`, and an `<svg>` or MathML element is not,\n * however it is spelled. `focus`, `offsetWidth` and `isContentEditable` are on\n * this interface, so it is the question to ask before reaching for them.\n */\nexport function isHTMLElement(value: unknown): value is HTMLElement {\n  return isElement(value) && value.namespaceURI === HTML_NAMESPACE;\n}\n\n/** Whether a value is a `<textarea>`, from any realm. */\nexport function isTextArea(value: unknown): value is HTMLTextAreaElement {\n  return isHTMLElement(value) && value.localName === \"textarea\";\n}\n\n/** Whether a value is an `<input>`, from any realm. */\nexport function isInput(value: unknown): value is HTMLInputElement {\n  return isHTMLElement(value) && value.localName === \"input\";\n}\n\n/**\n * Whether a value is a form field whose value lives outside the DOM: an\n * `<input>`, a `<textarea>` or a `<select>`, from any realm.\n */\nexport function isFormField(\n  value: unknown\n): value is HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement {\n  return (\n    isHTMLElement(value) &&\n    (value.localName === \"input\" ||\n      value.localName === \"textarea\" ||\n      value.localName === \"select\")\n  );\n}\n\n/** Whether a value is an `<iframe>`, from any realm. */\nexport function isIFrame(value: unknown): value is HTMLIFrameElement {\n  return isHTMLElement(value) && value.localName === \"iframe\";\n}\n\n/**\n * The element that has focus, looking inside a focused same-origin iframe.\n *\n * `document.activeElement` read from the host reports the IFRAME while focus\n * is on something inside it, so a question about what the author is typing in\n * — a field, a contenteditable passage — has to be asked of the frame's own\n * document. This follows focus down through each focused frame whose document\n * the host can read; a cross-origin frame has no readable document and is\n * where the walk stops.\n *\n * A frame whose document has nothing focused — its `activeElement` is its body\n * or nothing — answers with the iframe element itself. That is what holds focus\n * from the host's side, and it is the element focus can be put back on: a\n * frame's body takes no focus of its own.\n *\n * Not the answer to \"is focus inside this container\" for a container in the\n * host. The innermost element belongs to the frame's document, which no host\n * element contains, while the iframe the host reports is contained by the\n * region that renders it — so those checks read `activeElement` directly.\n */\nexport function deepActiveElement(doc: Document): Element | null {\n  let active = doc.activeElement;\n  while (isIFrame(active)) {\n    const inner = active.contentDocument;\n    if (inner === null) break;\n    const focused = inner.activeElement;\n    if (\n      focused === null ||\n      focused === inner.body ||\n      focused === inner.documentElement\n    ) {\n      break;\n    }\n    active = focused;\n  }\n  return active;\n}\n","/**\n * The one place a frame's inset is READ from the DOM.\n *\n * `geometry.ts` deliberately takes plain numbers so the mapping can be\n * exercised without a browser. That leaves one question it cannot answer, and\n * it is the question every caller gets wrong: which measurements add up to the\n * offset between a frame's border box and its content viewport.\n *\n * Answering it in prose did not work. The contract was documented as\n * `clientLeft`/`clientTop`, three call sites followed that recipe, and all\n * three were wrong by the padding — because an iframe's nested viewport begins\n * at the CONTENT box, so padding displaces it exactly as a border does. A\n * recipe a caller applies is a recipe a caller can misapply; a function they\n * call is not.\n *\n * Kept in its own module rather than folded into `geometry.ts` so that the\n * arithmetic stays testable without a DOM. This is the edge; that is the pure\n * part.\n *\n * Every rectangle read stays in this file. What is worked out from those reads\n * without reading again sits beside it: the arithmetic of an element's own\n * transform in `geometry-transform.ts`, and the comparisons that decide whether\n * a clipping ancestor cuts a block in `geometry-clip.ts`.\n *\n * @module geometry-dom\n */\n\nimport {\n  frameContentOrigin,\n  pointToCanvas,\n  pointToHost,\n  rectToHost,\n  type FrameGeometry,\n  type FrameInset,\n  type Point,\n  type Rect,\n  type Scale,\n} from \"../geometry\";\n\nimport type { CornerRadii } from \"./border-radii\";\nimport { SQUARE_CORNERS, usedCornerRadii } from \"./border-radii\";\nimport { isHTMLElement, isIFrame } from \"./dom-kind\";\nimport {\n  anyAncestorCuts,\n  type AncestorClipContext,\n  clipEdges,\n  cornerCut,\n  narrowTo,\n  overflowApplies,\n  rectCut,\n} from \"./geometry-clip\";\nimport {\n  AXIS_ALIGNED_TOLERANCE,\n  edgesMovedBy,\n  NO_EDGE_MOVED,\n  type RenderedScale,\n  transformOriginOf,\n} from \"./geometry-transform\";\n\n// The transform arithmetic and the clip comparisons live in modules of their\n// own; their public names are still exported from here.\nexport { overflowApplies } from \"./geometry-clip\";\nexport type { RenderedScale } from \"./geometry-transform\";\n// Kept so the module's exported names stay the same, though nothing imports it.\n// fallow-ignore-next-line unused-type\nexport type { MovedEdges } from \"./geometry-transform\";\n\n/**\n * How far a frame's content viewport sits inside its border box.\n *\n * Border plus padding, in the frame's own untransformed CSS pixels — which is\n * what {@link FrameInset} means and what `frameContentOrigin` scales.\n *\n * `clientLeft`/`clientTop` report the border alone. Padding comes from the\n * computed style because there is no element property that carries it, and a\n * non-pixel value (a percentage, `auto`) resolves to pixels there too.\n */\nexport function frameInsetOf(frame: HTMLIFrameElement): FrameInset {\n  const style = frame.ownerDocument.defaultView?.getComputedStyle(frame);\n  // A frame detached from its document has no view and therefore no computed\n  // padding. Its border is still readable, so report what is knowable rather\n  // than guessing a padding that would silently displace every mapped point.\n  const paddingLeft = style === undefined ? 0 : parseFloat(style.paddingLeft);\n  const paddingTop = style === undefined ? 0 : parseFloat(style.paddingTop);\n  return {\n    left: frame.clientLeft + (Number.isFinite(paddingLeft) ? paddingLeft : 0),\n    top: frame.clientTop + (Number.isFinite(paddingTop) ? paddingTop : 0),\n  };\n}\n\n/**\n * How much smaller the canvas is PAINTED than it is laid out, per axis.\n *\n * The editor scales the canvas so a tier wider than the region can still be\n * edited, and a transform is paint-time: the root stays its requested width to\n * layout — which is what keeps the container queries resolving at the tier the\n * author asked for — while `getBoundingClientRect` answers in painted pixels.\n * A distance taken from client rectangles is therefore in a different unit from\n * the content coordinates the chrome is placed in, and the two agree only at\n * 100%. That is the shape this module's own header warns about: an error of\n * `(1 - scale)` times the distance, exactly zero while nothing is scaled and\n * growing as the canvas zooms out, so every test at default scale passes.\n *\n * Measured from the ROOT rather than read from its `transform`, because the\n * scale may be applied by an ancestor the canvas does not own and a declaration\n * read off one element cannot see that. The ratio is true wherever it came\n * from.\n *\n * `1` when nothing has been laid out — jsdom, or a root not yet in the\n * document — which is the identity the callers below already assume, so an\n * unmeasurable canvas behaves exactly as it did before there was a scale.\n */\nfunction paintedScale(root: HTMLElement, painted: DOMRect): Scale {\n  const width = root.offsetWidth;\n  const height = root.offsetHeight;\n  return {\n    x: width > 0 && painted.width > 0 ? painted.width / width : 1,\n    y: height > 0 && painted.height > 0 ? painted.height / height : 1,\n  };\n}\n\n/**\n * A point in the host page's client coordinates, in the frame's own.\n *\n * A pointer moving over the editor's panels is reported in the HOST's client\n * coordinates, while every rectangle of the canvas is read inside the frame,\n * relative to the frame's viewport. A drag begun on a palette row hears both,\n * and the host's points have to be carried into the frame before they are\n * compared with anything there.\n *\n * Composed from the one mapping rather than restated: the frame's border box\n * and its painted scale are read here, where reads are allowed, and the\n * arithmetic is {@link frameContentOrigin} and {@link pointToCanvas}. The scale\n * is measured from the frame for the reason {@link paintedScale} gives — it may\n * be applied by an ancestor no declaration on the frame records.\n */\nexport function hostPointInFrame(\n  frame: HTMLIFrameElement,\n  point: Point\n): Point {\n  return pointToCanvas(point, frameGeometryOf(frame));\n}\n\n/**\n * Where a frame's content viewport sits in the host and how it is scaled, read\n * once for the two directions of the mapping.\n */\nfunction frameGeometryOf(frame: HTMLIFrameElement): FrameGeometry {\n  const box = frame.getBoundingClientRect();\n  const scale = framePaintedScale(frame);\n  const origin = frameContentOrigin(\n    { x: box.left, y: box.top },\n    frameInsetOf(frame),\n    scale\n  );\n  return { origin, scale };\n}\n\n/**\n * A point in a frame's client coordinates, in the host page's.\n *\n * The inverse of {@link hostPointInFrame}, built from the same reads and the\n * same mapping run forwards: a context menu opened by a press inside the frame\n * is reported in the frame's coordinates and drawn by the host.\n */\nexport function framePointInHost(\n  frame: HTMLIFrameElement,\n  point: Point\n): Point {\n  return pointToHost(point, frameGeometryOf(frame));\n}\n\n/**\n * The part of a frame's page on screen, in the frame's own CSS pixels.\n *\n * The root element's client box, which is the viewport WITHOUT its scrollbars:\n * a frame whose page is taller than it shows a scrollbar inside, and chrome\n * clipped to the frame's whole width would be drawn over that scrollbar.\n * `null` while the frame holds no readable document.\n */\nexport function frameViewportOf(\n  frame: HTMLIFrameElement\n): { readonly width: number; readonly height: number } | null {\n  const element = frame.contentDocument?.documentElement;\n  if (element === undefined) return null;\n  return { width: element.clientWidth, height: element.clientHeight };\n}\n\n/**\n * Where a canvas root's top-left corner is, in its frame's VIEWPORT.\n *\n * Read from the root's own client rectangle inside the frame, which already\n * moves with the frame's scroll: a page scrolled 200px down puts its root at\n * `y: -200`. Chrome drawn over the frame is offset by this, once, rather than\n * adding the frame's scroll a second time.\n */\nexport function rootInFrameViewport(root: HTMLElement): Point {\n  const box = root.getBoundingClientRect();\n  return { x: box.left, y: box.top };\n}\n\n/**\n * Where an element of a frame's page is, in that frame's VIEWPORT: its client\n * rectangle inside the frame, which moves with the frame's scroll, as the\n * canvas root's corner does above. Chrome drawn over the frame scales it by\n * the frame's painted scale.\n */\nexport function boxInFrameViewport(element: Element): Rect {\n  const box = element.getBoundingClientRect();\n  return { x: box.left, y: box.top, width: box.width, height: box.height };\n}\n\n/**\n * Where editor chrome is drawn, and how it maps the canvas's coordinates.\n *\n * Chrome is drawn in one of two places. Over a canvas sharing the editor's\n * document it sits INSIDE the canvas root, and the root's own content\n * coordinates are its coordinates. Over a canvas in a frame it sits in the\n * editor's document, in the layer `CanvasFrame` draws over the frame, whose\n * content box is laid over the root and moved with the frame's scroll — so a\n * rectangle in the root's coordinates only has to be scaled by the frame's\n * painted scale to land on what it describes, and the chrome itself is drawn\n * at its own size rather than scaled with the page.\n */\nexport interface OverlaySpace {\n  /** The canvas root the chrome describes. */\n  readonly root: HTMLElement;\n  /** The frame the root is in, or `null` when it shares the chrome's document. */\n  readonly frame: HTMLIFrameElement | null;\n  /** How much larger the chrome's coordinates are than the root's. */\n  readonly scale: number;\n  /** A rectangle in the root's content coordinates, in the chrome's. */\n  readonly place: (rect: Rect) => Rect;\n  /** A chrome element's own size, in the chrome's coordinates. */\n  readonly sizeOf: (element: HTMLElement) => {\n    readonly width: number;\n    readonly height: number;\n  };\n  /**\n   * A client point of an event delivered to the CHROME's document, in the\n   * canvas document's client coordinates, where its rectangles are read.\n   */\n  readonly pointInCanvas: (point: Point) => Point;\n}\n\n/**\n * The attribute marking the layer `CanvasFrame` draws chrome in.\n *\n * Here rather than beside the component because this module is what looks for\n * it, and the component imports it from here.\n */\nexport const CANVAS_LAYER_ATTRIBUTE = \"data-nx-canvas-layer\";\n\n/**\n * How far past the frame's viewport the layer draws, on every side, in the\n * chrome's pixels: as far as a selection ring stands outside its block, so the\n * ring of a block flush with the page's edge is drawn rather than cut off.\n */\nexport const CHROME_BLEED = 4;\n\n/** The attribute marking the box holding a canvas frame and its layer. */\nexport const CANVAS_FRAME_BOX_ATTRIBUTE = \"data-nx-canvas-frame-box\";\n\n/**\n * The coordinate space a piece of chrome is drawn in, found from the chrome's\n * own element, or `null` when it is over no canvas.\n *\n * Found from the element rather than handed in, as the canvas root always was:\n * the chrome does not exist until after its first render, and a space passed\n * from elsewhere could describe a canvas the chrome is not drawn over.\n */\nexport function overlaySpaceOf(\n  element: Element,\n  rootClass: string\n): OverlaySpace | null {\n  const own = canvasRootFrom(element, rootClass);\n  if (own !== null) {\n    return {\n      root: own,\n      frame: null,\n      scale: 1,\n      place: rect => rect,\n      sizeOf: chrome => {\n        const box = canvasContentRect(chrome, own);\n        return { width: box.width, height: box.height };\n      },\n      pointInCanvas: point => point,\n    };\n  }\n  const frame = layerFrameOf(element);\n  const root = frame?.contentDocument?.querySelector(`.${rootClass}`);\n  if (frame === null || !isHTMLElement(root)) return null;\n  if (root.ownerDocument.defaultView === null) return null;\n  // Measured when first read, then kept for this space. Reading the frame's\n  // box lays the editor out, and many callers want only the root: a check run\n  // on every render that the layer is still over the same canvas laid the page\n  // out each time, between React's commit and the paint.\n  let measured: number | undefined;\n  const scaleNow = (): number => (measured ??= framePaintedScale(frame));\n  return {\n    root,\n    frame,\n    get scale(): number {\n      return scaleNow();\n    },\n    // The layer's content box is laid over the root, so the root's origin is\n    // the chrome's: only the scale is left to apply.\n    place: rect =>\n      rectToHost(rect, { origin: { x: 0, y: 0 }, scale: scaleNow() }),\n    // The chrome is not scaled, so its layout size is its size on screen.\n    sizeOf: chrome => ({\n      width: chrome.offsetWidth,\n      height: chrome.offsetHeight,\n    }),\n    pointInCanvas: point => hostPointInFrame(frame, point),\n  };\n}\n\n/**\n * The frame whose layer an element is drawn in, or `null` when it is in none.\n *\n * The layer and the frame are children of one box, so the box names both and\n * neither has to carry a reference to the other.\n */\nfunction layerFrameOf(element: Element): HTMLIFrameElement | null {\n  const layer = element.closest(`[${CANVAS_LAYER_ATTRIBUTE}]`);\n  const box = layer?.closest(`[${CANVAS_FRAME_BOX_ATTRIBUTE}]`);\n  if (box === null || box === undefined) return null;\n  for (const child of Array.from(box.children)) {\n    if (isIFrame(child)) return child;\n  }\n  return null;\n}\n\n/**\n * How many of the host's painted pixels one of a frame's pixels covers.\n *\n * `0.25` for a frame Fit has painted at a quarter of its layout size. A\n * distance read inside the frame is multiplied by it to become a distance the\n * author's hand moved, which is what every drag threshold is about.\n */\nexport function framePaintedScale(frame: HTMLIFrameElement): number {\n  return paintedScale(frame, frame.getBoundingClientRect()).x;\n}\n\n/**\n * A rectangle in the canvas's own CONTENT coordinates.\n *\n * The space the editor's chrome is drawn in: the origin is the canvas root's\n * top-left, and scrolling the root does not move it. `getBoundingClientRect`\n * answers in VIEWPORT coordinates, which move with every scroll and with the\n * page's own layout — so a rectangle stored raw is only correct until something\n * scrolls, and the symptom is an overlay that drifts rather than one that is\n * plainly wrong.\n *\n * Adding the root's scroll is what makes the result stable, and it is also what\n * makes it the same space an absolutely positioned child of the root resolves\n * against: such a child is placed relative to the padding box with scroll\n * included. So a rectangle measured here can be handed straight to `style.top`\n * and lands on what was measured.\n */\nexport function canvasContentRect(element: Element, root: HTMLElement): Rect {\n  return clientRectInCanvas(element.getBoundingClientRect(), root);\n}\n\n/**\n * The words a selection covers inside `element`, in the canvas's content\n * coordinates: the selection's own box when it is in the element and covers\n * anything, and the element's box otherwise. What a bar drawn over selected\n * words is placed against.\n */\nexport function selectedWordsRect(element: Element, root: HTMLElement): Rect {\n  const selection = element.ownerDocument.getSelection();\n  if (selection !== null && selection.rangeCount > 0) {\n    const range = selection.getRangeAt(0);\n    if (element.contains(range.commonAncestorContainer)) {\n      const box = range.getBoundingClientRect();\n      if (box.width > 0 || box.height > 0) return clientRectInCanvas(box, root);\n    }\n  }\n  return canvasContentRect(element, root);\n}\n\n/**\n * A rectangle in CLIENT coordinates, in the canvas's content coordinates.\n *\n * The conversion {@link canvasContentRect} applies to an element's own box,\n * for a rectangle that is not one element's: the visible part of a viewport,\n * or the words a selection covers ({@link selectedWordsRect}).\n */\nfunction clientRectInCanvas(box: Rect, root: HTMLElement): Rect {\n  const rootBox = root.getBoundingClientRect();\n  const scale = paintedScale(root, rootBox);\n  return {\n    // The SCROLL is added after the division, not inside it. A scroll offset is\n    // already in content pixels — it counts the element's own laid-out content,\n    // which a transform never touches — so dividing it would shrink a real\n    // offset by the zoom and drift the whole overlay as the page is scrolled.\n    x: (box.x - rootBox.x) / scale.x + root.scrollLeft,\n    y: (box.y - rootBox.y) / scale.y + root.scrollTop,\n    width: box.width / scale.x,\n    height: box.height / scale.y,\n  };\n}\n\n/**\n * One pointer position, in the two canvas spaces a drag reads it in.\n *\n * Both are taken from a SINGLE measurement of the root, and that is the whole\n * reason they arrive together. They are the same offset expressed twice — the\n * painted one IS the numerator the content one divides — so a caller that\n * measured the root once for each would be free to answer the same move from\n * two rectangles, and a drag would compare its pointer against rectangles the\n * hysteresis had already stopped agreeing with.\n */\nexport interface CanvasPointerPoints {\n  /**\n   * The point in the canvas's own content coordinates.\n   *\n   * The exact counterpart of {@link canvasContentRect} rather than a second\n   * mapping written to match: a pointer event arrives in viewport coordinates\n   * and has to be compared against rectangles measured there, and the two\n   * disagreeing by a scroll offset is the fault this pairing exists to prevent.\n   */\n  readonly content: Point;\n  /**\n   * The point relative to the canvas's PAINTED top-left corner.\n   *\n   * A third space, and it exists because the other two each lose one of the two\n   * things a drag's hysteresis has to see.\n   *\n   * CLIENT coordinates are hand-scale — 8px of them is 8px of real movement,\n   * whatever the canvas is painted at — but they do not move when the page\n   * scrolls under a stationary pointer, which is exactly what autoscroll does.\n   * Measured there, a rival target's distance from its anchor stays zero\n   * however far the page travels, so the committed target never advances and\n   * the indicator stays on a position that has scrolled off screen.\n   *\n   * CANVAS CONTENT coordinates move with the scroll but are divided by the\n   * canvas scale, so the same threshold asks for less hand movement the further\n   * the canvas is zoomed out.\n   *\n   * This one moves with the scroll — the root's own painted rectangle travels —\n   * and is not divided, so a threshold in it stays a threshold about the hand.\n   * It is NOT interchangeable with {@link canvasContentRect}: nothing may be\n   * drawn from it, because it does not survive a scroll.\n   */\n  readonly painted: Point;\n}\n\n/**\n * Map a viewport point into the canvas, in both spaces, from one rect read.\n *\n * `getBoundingClientRect` is the expensive part — it forces the layout the\n * browser was hoping to defer — so a pointer handler that wants both spaces\n * asks once here rather than calling two mappings that each measure.\n *\n * The pair describes the root as it was AT THE MOMENT OF THE READ, and it stops\n * being true the next time anything moves the canvas. Callers that scroll,\n * resize or restyle between using the two halves must measure again.\n */\nexport function canvasPointerPoints(\n  clientX: number,\n  clientY: number,\n  root: HTMLElement,\n  handScale = 1\n): CanvasPointerPoints {\n  const rootBox = root.getBoundingClientRect();\n  const scale = paintedScale(root, rootBox);\n  const offset = { x: clientX - rootBox.x, y: clientY - rootBox.y };\n  // `handScale` carries the offset into the host's painted pixels when the\n  // canvas is in a frame the host paints scaled: the root's own rectangle is\n  // read inside the frame, where that scale does not show.\n  const painted = { x: offset.x * handScale, y: offset.y * handScale };\n  return {\n    painted,\n    // DERIVED from the painted offset rather than subtracting the root a second\n    // time: the two spaces differ only by the canvas scale and the root's\n    // scroll, so written apart they would be two subtractions to keep in step.\n    //\n    // The SCROLL is added after the division, exactly as in canvasContentRect.\n    // A scroll offset is already in content pixels — it counts the root's own\n    // laid-out content, which a transform never touches — so dividing it would\n    // shrink a real offset by the zoom.\n    content: {\n      x: offset.x / scale.x + root.scrollLeft,\n      y: offset.y / scale.y + root.scrollTop,\n    },\n  };\n}\n\n/**\n * A viewport point in the canvas's own content coordinates.\n *\n * For the callers that need only that space, and a projection of\n * {@link canvasPointerPoints} rather than a mapping of its own — a second\n * subtraction here would be free to disagree with the one a drag reads.\n * The discarded half costs nothing: the root is measured once either way.\n */\nexport function canvasContentPoint(\n  clientX: number,\n  clientY: number,\n  root: HTMLElement\n): Point {\n  return canvasPointerPoints(clientX, clientY, root).content;\n}\n\n/**\n * Whether an element is positioned against the VIEWPORT rather than against the\n * page {@link canvasContentRect} measures in.\n *\n * `position` is a catalog keyword — `blocks-engine`'s style catalog offers\n * `static`, `relative`, `absolute`, `fixed` and `sticky` — so taking a block\n * out of the canvas's content coordinates is something an author can store.\n * `fixed` and `sticky` are the two values that do it: both hold the element\n * still against a viewport or a scrollport while the content around it travels,\n * so a rectangle read here describes where the element was at the instant of\n * the read and stops describing it on the very next scroll.\n *\n * Nothing corrects that drift, which is what makes it a refusal rather than a\n * staleness to re-measure away. The canvas root does not scroll — the shell\n * scrolls a section ABOVE it — and a scroll event does not bubble, so the\n * capture-phase listener `canvas-geometry-watch.ts` installs on the root\n * reaches a scroller nested INSIDE the canvas and nothing outside it.\n *\n * Asked of the ELEMENT rather than of a computed string handed in, so every\n * overlay drawn in this space asks one question and gets one answer. A caller\n * given the string would decide for itself which property carries it and in\n * which realm to read it, which is two more chances to answer differently about\n * the same element.\n *\n * The element's own view rather than the ambient `window`, for the reason\n * {@link canvasRootFrom} gives: a canvas portalled into a same-origin iframe is\n * styled by that document, and reading through this one would answer about\n * rules that do not apply to it. An element with no view at all is reported as\n * NOT viewport-positioned — nothing has positioned it, because nothing has laid\n * it out, and the callers that reach this already decline an element with no\n * box for their own reasons.\n *\n * The two values are NAMED rather than reached by excluding the ones that stay\n * in this space, and that direction is load-bearing. An element no rule\n * positions computes to `static` in a browser and to the EMPTY STRING under\n * jsdom, so an allow-list of the values that are in the space would refuse both\n * — every ordinary block, in the runtime the tests run in. Anything this does\n * not recognise is therefore accepted, `static`, `relative` and `absolute`\n * included.\n */\n/**\n * How one element's border box responds to a temporary style, in viewport\n * coordinates.\n *\n * Here rather than beside its caller because this module is the ONE door a\n * rectangle enters this package through, and `geometry-ownership.test.ts`\n * enforces it: a second reader is correct about its own question and disagrees\n * with this one about the shared one. The caller supplies the change and its\n * exact undo; this reads either side of it and hands back both boxes.\n *\n * SYNCHRONOUS throughout, which is what makes it safe against a rendered node.\n * The write, both reads and the undo happen in one task, so no frame is painted\n * with the change applied and no `ResizeObserver` is delivered a size that\n * differs from the one it last reported.\n *\n * @param element - the element to measure\n * @param apply - makes the temporary change\n * @param undo - puts the element back exactly as it was\n * @returns its border box before and after the change\n */\nexport function boxAcross(\n  element: Element,\n  apply: () => void,\n  undo: () => void\n): { readonly before: DOMRect; readonly after: DOMRect } {\n  const before = element.getBoundingClientRect();\n  apply();\n  const after = element.getBoundingClientRect();\n  undo();\n  return { before, after };\n}\n\n/**\n * How much smaller than its own layout the canvas root is PAINTED.\n *\n * The factor that sits between the two units this package mixes: a computed\n * length is unscaled CSS pixels, and anything from `getBoundingClientRect` has\n * already been through the canvas's transform. `renderedScale` deliberately\n * stops BELOW the root — the overlay is a child of the root and is drawn\n * through that transform already — so any comparison whose two readings sit on\n * opposite sides of it has to compose this back in.\n *\n * Asked by node kind, as {@link canvasRootFrom} does. A canvas portalled into\n * a same-origin iframe has a root built by that document's constructor, so the\n * ambient `HTMLElement` is a different function object and a plain\n * `instanceof` is false for an ordinary div — which would substitute an\n * identity scale on a canvas that really is scaled, the very case this exists\n * for.\n *\n * Identity for a root this cannot measure. `offsetWidth` is an HTML property,\n * so a genuinely foreign root — an SVG element, or one with no window at all —\n * cannot be asked how much smaller it is painted, and answering 1 leaves the\n * arithmetic as it was before there was a canvas scale.\n */\nexport function canvasPaintedScale(root: Element): Scale {\n  // A root with no window has never been laid out, and has no scale to read.\n  return root.ownerDocument.defaultView !== null && isHTMLElement(root)\n    ? paintedScale(root, root.getBoundingClientRect())\n    : { x: 1, y: 1 };\n}\n\nexport function viewportPositioned(element: Element): boolean {\n  const view = element.ownerDocument.defaultView;\n  if (view === null) return false;\n  const position = view.getComputedStyle(element).position;\n  return position === \"fixed\" || position === \"sticky\";\n}\n\n/**\n * The nearest ancestor that actually scrolls, or `null` when nothing does.\n *\n * The canvas root is NOT it. That element carries the drag handlers and sizes\n * itself to its content — `overflow: visible` — so assigning `scrollTop` on it\n * is silently ignored, and an autoscroll written against it does nothing on a\n * page long enough to need one. The scrolling is done by an ancestor the shell\n * owns, which is where the visible window's edges live too.\n *\n * Matched on the COMPUTED overflow rather than on whether the element currently\n * overflows. A container is the scroller because of how it is styled, not\n * because of how much happens to be in it right now — testing the current\n * amount would answer \"no\" for an empty canvas and change its mind once a block\n * was added, which is a different element for the same drag.\n *\n * Starts at the root's parent: the root is excluded by definition, since it is\n * the thing being scrolled WITHIN.\n */\nfunction scrollableAncestor(root: HTMLElement): HTMLElement | null {\n  let element = root.parentElement;\n  while (element !== null) {\n    const overflowY = getComputedStyle(element).overflowY;\n    if (overflowY === \"auto\" || overflowY === \"scroll\") return element;\n    element = element.parentElement;\n  }\n  return null;\n}\n\n/**\n * The container's top and bottom edges, in CLIENT coordinates.\n *\n * Client rather than content, because the only caller compares them against a\n * pointer's client position to decide whether it is resting near an edge. That\n * question is about where the container sits on SCREEN, and converting either\n * side into content space would answer a different one — a container scrolled\n * halfway down its content has the same edges on screen as one scrolled to the\n * top.\n *\n * Here rather than at the caller because this module is the one place allowed to\n * read layout from the DOM, and a guard enforces it. The rule is worth the\n * indirection: every reflow-forcing read being in one file is what makes the\n * cost of one findable.\n */\nexport function containerEdges(root: Element): {\n  top: number;\n  bottom: number;\n  left: number;\n  right: number;\n} {\n  const visible = visibleClientRect(root);\n  // The sides as well, for a caller placing something just outside the\n  // container on screen, such as a note drawn beside a panel rather than on it.\n  return {\n    top: visible.y,\n    bottom: visible.y + visible.height,\n    left: visible.x,\n    right: visible.x + visible.width,\n  };\n}\n\n/**\n * The part of a scroller on screen, in CLIENT coordinates.\n *\n * A document's scrolling element is scrolled by the VIEWPORT, so what is on\n * screen is the viewport: from `0` to the window's inner size. Its own\n * rectangle is the whole document, which starts above the viewport once it\n * has scrolled and ends far below it, so an edge band or a clamp measured\n * against that never holds the pointer or the message at all.\n */\nfunction visibleClientRect(scroller: Element): Rect {\n  /*\n   * The CLIENT box where the scroller has one: a classic scrollbar takes its\n   * width out of what the scroller shows, and chrome kept to the border box\n   * would sit under it. `clientWidth` is 0 for a scroller with no layout box,\n   * where there is no scrollbar to leave out either, so the outer size stands.\n   */\n  const inner = (outer: number, client: number): number =>\n    client > 0 ? Math.min(outer, client) : outer;\n  const view = scroller.ownerDocument.defaultView;\n  if (view !== null && scroller === scroller.ownerDocument.scrollingElement) {\n    return {\n      x: 0,\n      y: 0,\n      width: inner(view.innerWidth, scroller.clientWidth),\n      height: inner(view.innerHeight, scroller.clientHeight),\n    };\n  }\n  const box = scroller.getBoundingClientRect();\n  /*\n   * The client box is in layout pixels and the border box is painted, so a\n   * scroller drawn under a transform has the two in different units: the\n   * client box is scaled by the scroller's painted scale before the two are\n   * compared. `clientLeft` and `clientTop` are the border, and a scrollbar on\n   * the left in a right-to-left scroller.\n   */\n  const scaleX =\n    isHTMLElement(scroller) && scroller.offsetWidth > 0\n      ? box.width / scroller.offsetWidth\n      : 1;\n  const scaleY =\n    isHTMLElement(scroller) && scroller.offsetHeight > 0\n      ? (box.bottom - box.top) / scroller.offsetHeight\n      : 1;\n  const laidOut = scroller.clientWidth > 0;\n  return {\n    x: box.left + (laidOut ? scroller.clientLeft * scaleX : 0),\n    y: box.top + (scroller.clientHeight > 0 ? scroller.clientTop * scaleY : 0),\n    width: inner(box.width, scroller.clientWidth * scaleX),\n    height: inner(box.bottom - box.top, scroller.clientHeight * scaleY),\n  };\n}\n\n/**\n * The part of a scroller on screen, in the canvas's content coordinates.\n *\n * What chrome drawn in the canvas has to stay inside to be seen. Read through\n * the same {@link visibleClientRect} the drag's edges are, so a scroller that\n * is a frame's viewport is clamped to the viewport here as well.\n */\nexport function visibleBandOf(scroller: Element, root: HTMLElement): Rect {\n  return clientRectInCanvas(visibleClientRect(scroller), root);\n}\n\n/**\n * The element that scrolls the canvas, or `null` when nothing does.\n *\n * In the editor's own document that is an ancestor the shell styles to\n * scroll, which {@link scrollableAncestor} finds. In a frame of its own the\n * canvas is scrolled by the frame's viewport instead, whose element is the\n * frame document's `scrollingElement`: nothing above the root inside the frame\n * is styled to scroll, so the walk would find nothing and a drag held at the\n * frame's edge would never scroll it.\n *\n * `framed` comes from whoever knows the canvas is in the editor's frame, rather\n * than from asking whether the root's window is one: an editor that is itself\n * embedded in another page's frame is in a frame too, and its canvas is still\n * scrolled by the shell.\n */\nexport function canvasScroller(\n  root: HTMLElement,\n  framed: boolean\n): Element | null {\n  // `?? null` because a document with no scrolling element reports\n  // `undefined` in some runtimes, which is the same \"nothing scrolls\".\n  return framed\n    ? (root.ownerDocument.scrollingElement ?? null)\n    : scrollableAncestor(root);\n}\n\n/**\n * What of a canvas is on screen, in the chrome's coordinates: the part of the\n * page its scroller shows, where the canvas cuts off anything drawn past it;\n * the whole page where nothing scrolls it. The marks and the block toolbar\n * keep to it, so a tag or a bar is never drawn where the canvas cuts it off.\n */\nexport function onScreenOf(space: OverlaySpace): Rect {\n  return space.place(onScreenBandOf(space.root, space.frame));\n}\n\n/**\n * What of a canvas is on screen, in the canvas's own content coordinates:\n * {@link onScreenOf} before it is placed in the chrome's, for chrome drawn\n * inside the canvas, such as a Layout region's lock, which is positioned in\n * the page's own pixels.\n */\nexport function onScreenBandOf(\n  root: HTMLElement,\n  frame: HTMLIFrameElement | null\n): Rect {\n  const scroller = canvasScroller(root, frame !== null);\n  const band =\n    scroller === null\n      ? canvasContentRect(root, root)\n      : visibleBandOf(scroller, root);\n  // A frame zoomed past the region around it is clipped and scrolled by the\n  // host's scroller as well, so what is on screen is the part both show.\n  const host = frame === null ? null : hostScrollerBandOf(frame, root);\n  return host === null ? band : intersectionOf(band, host);\n}\n\n/** The part two rectangles share; empty, at the first's corner, if none. */\nfunction intersectionOf(a: Rect, b: Rect): Rect {\n  const x = Math.max(a.x, b.x);\n  const y = Math.max(a.y, b.y);\n  const right = Math.min(a.x + a.width, b.x + b.width);\n  const bottom = Math.min(a.y + a.height, b.y + b.height);\n  return right < x || bottom < y\n    ? { x: a.x, y: a.y, width: 0, height: 0 }\n    : { x, y, width: right - x, height: bottom - y };\n}\n\n/**\n * The part of a frame the host's scroller shows, in the canvas's content\n * coordinates, or `null` when no host scroller holds the frame.\n *\n * The shell scrolls a frame zoomed past the region it sits in, from the\n * host's document, where nothing in the frame hears it: its visible box is\n * read in the host, carried into the frame through the one mapping\n * (`hostPointInFrame`), and into the canvas's coordinates from there.\n */\nexport function hostScrollerBandOf(\n  frame: HTMLIFrameElement,\n  root: HTMLElement\n): Rect | null {\n  const host = scrollableAncestor(frame);\n  if (host === null) return null;\n  const visible = visibleClientRect(host);\n  const start = hostPointInFrame(frame, { x: visible.x, y: visible.y });\n  const end = hostPointInFrame(frame, {\n    x: visible.x + visible.width,\n    y: visible.y + visible.height,\n  });\n  return clientRectInCanvas(\n    { x: start.x, y: start.y, width: end.x - start.x, height: end.y - start.y },\n    root\n  );\n}\n\n/**\n * Every scroller whose scroll or size moves what of the canvas is on screen:\n * the canvas's own, and the host's around a frame. The same two\n * {@link onScreenOf} reads, so the band chrome keeps to and what it listens to\n * are one set.\n */\nexport function screenScrollers(\n  root: HTMLElement,\n  frame: HTMLIFrameElement | null\n): Element[] {\n  const scrollers: Element[] = [];\n  const own = canvasScroller(root, frame !== null);\n  if (own !== null) scrollers.push(own);\n  const host = frame === null ? null : scrollableAncestor(frame);\n  if (host !== null) scrollers.push(host);\n  return scrollers;\n}\n\n/**\n * Where a scroller's `scroll` events are dispatched.\n *\n * At the element for an ordinary scroller, and at its DOCUMENT for a\n * document's scrolling element: a viewport's scroll is reported on the\n * document, never on `<html>`, so a listener on the element would hear\n * nothing however far the page scrolled.\n */\nexport function scrollEventTarget(scroller: Element): EventTarget {\n  return scroller === scroller.ownerDocument.scrollingElement\n    ? scroller.ownerDocument\n    : scroller;\n}\n\n/**\n * How many layout boxes an element generates.\n *\n * `display: none` and `display: contents` are both catalog values, and an\n * element carrying either can still be SELECTED — the Layers panel addresses\n * nodes by id and does not require them to be visible. Neither generates a box,\n * so every rectangle read from one is the zero rectangle, while its computed\n * margin and padding stay whatever the author set. Chrome positioned from that\n * pair lands at the canvas origin describing spacing that is nowhere on screen.\n *\n * ZERO means the element generates no box: `display: none` and\n * `display: contents` both reach it. `getClientRects` is the direct question\n * rather than a proxy, because a zero-SIZED rectangle is also what a genuinely\n * empty block reports and `core/spacer` legitimately has one — an element that\n * generates no box returns no rectangles at all.\n *\n * MORE THAN ONE means an inline box fragmented across lines. Its padding and\n * margins belong to the individual fragments while `getBoundingClientRect`\n * reports their union, so a band drawn from that union runs through the\n * whitespace between lines and puts the start and end padding on the union's\n * edges rather than on the first and last fragment.\n *\n * Here because this module is the one place allowed to read a rectangle from the\n * DOM, and a sibling guard enforces it by name.\n */\nexport function layoutFragments(element: Element): number {\n  return element.getClientRects().length;\n}\n\n/**\n * The elements that draw an element's boxes: itself when it generates one, its\n * children's drawing when it is `display: contents` (which generates no box of\n * its own and leaves its children on the page), nothing when it is hidden or\n * skipped. What a rectangle for the element is read from.\n *\n * `display: contents` is asked FIRST. A browser's `checkVisibility()` answers\n * false for an element with no box, and `contents` generates none, so asking\n * {@link renderSkips} first would drop a section whose children are all on the\n * page. A child under a skipped ancestor still answers for itself.\n */\nexport function drawnBoxes(element: Element): Element[] {\n  const view = element.ownerDocument.defaultView;\n  if (view?.getComputedStyle(element).display === \"contents\") {\n    return Array.from(element.children).flatMap(drawnBoxes);\n  }\n  if (renderSkips(element)) return [];\n  return layoutFragments(element) > 0 ? [element] : [];\n}\n\n/**\n * Whether the render SKIPS this element, so a rectangle read from it describes\n * nothing that is on the page.\n *\n * `getBoundingClientRect` and `getClientRects` answer for a skipped element as\n * readily as for a drawn one, and what they answer is not always the zero\n * rectangle {@link layoutFragments} refuses on. A closed `<details>` is the\n * case that makes the difference visible: an engine that removes the contents\n * from the rendering reports NO fragments for a descendant, while one that\n * gives the contents `content-visibility: hidden` — which is what the HTML\n * rendering section now describes — reports ONE, sized and positioned as though\n * the disclosure were open. That rectangle overlaps whatever the page actually\n * draws at those coordinates, so chrome anchored to it is chrome placed on\n * somebody else's content.\n *\n * The element cannot answer this about itself. The skip is a property of a box\n * ABOVE it — for a disclosure, the `::details-content` box the engine generates\n * for the parent — so the element's own computed `content-visibility` reads\n * `visible` throughout, and no property read from the element separates the two\n * renderings.\n *\n * `checkVisibility()` is the standard question and it is asked with NO options,\n * which is a narrowing rather than a default. Un-optioned it refuses exactly\n * two things: an element with no box at all, and an element under an ancestor\n * with `content-visibility: hidden`. Each option would widen it to \"is this\n * PAINTED\", which is a different question and the wrong one here:\n *\n * - `contentVisibilityAuto` refuses a subtree the engine is skipping only\n *   because it is off-screen. The box is real, reserved in flow and correctly\n *   placed; the skip ends when it is scrolled to. Nothing between the canvas\n *   root and the window reports that scroll, so a refusal taken on it would not\n *   be re-decided when it stopped being true.\n * - `opacityProperty` (and its historical alias `checkOpacity`) refuses a\n *   transparent element. A transparent element still lays out where it says it\n *   does and still takes pointer events, so chrome anchored to it is anchored\n *   correctly.\n * - `visibilityProperty` (`checkVisibilityCSS`) refuses `visibility: hidden`,\n *   which likewise reserves its box in flow at the position it reports.\n *\n * An ancestor walk for a closed disclosure — `closest(\"details:not([open])\")` —\n * needs no new API and is rejected on two counts. It identifies the case by one\n * element's spelling rather than by the property that makes it wrong, so it\n * says nothing about `content-visibility: hidden` arriving any other way; and\n * it over-refuses, because a `<summary>` and its descendants are rendered while\n * the disclosure is closed and are inside that same `<details>`.\n *\n * An engine with no `checkVisibility` reports NOT SKIPPED, so it behaves as it\n * did before this question existed. That is a deliberate posture rather than a\n * fallback: the method predates the author-visible `::details-content` in every\n * engine that ships it, and an engine old enough to lack the method removes a\n * closed disclosure's contents from the rendering instead, where the fragment\n * count already answers. Refusing on absence would instead delete an affordance\n * from every container on such an engine, on no evidence at all.\n */\nexport function renderSkips(element: Element): boolean {\n  if (typeof element.checkVisibility !== \"function\") return false;\n  return !element.checkVisibility();\n}\n\nconst IDENTITY_SCALE: RenderedScale = {\n  x: 1,\n  y: 1,\n  ancestor: { x: 1, y: 1 },\n  describable: true,\n  selfMoved: NO_EDGE_MOVED,\n};\n\nexport function renderedScale(element: Element, root: Element): RenderedScale {\n  const view = element.ownerDocument.defaultView;\n  // Absent in jsdom, which lays nothing out and so has no transform to compose.\n  // Identity is the honest answer there: nothing is scaled because nothing is\n  // laid out, and every caller still measures.\n  if (view === null || typeof view.DOMMatrix === \"undefined\") {\n    return IDENTITY_SCALE;\n  }\n\n  let matrix = new view.DOMMatrix();\n  /*\n   * Stops BELOW the root, which is not an off-by-one.\n   *\n   * The overlay is a child of the root, so it is inside whatever transform the\n   * root carries and is drawn through it already. Composing the root's own\n   * transform here would apply it a second time — the bands would be scaled by\n   * its square while the page was scaled by it once.\n   */\n  let own: DOMMatrix | null = null;\n  /*\n   * The composition ABOVE the element, accumulated in the same walk.\n   *\n   * Margins need it and padding does not, because they live in different\n   * spaces: padding is inside the element's own transform and renders scaled\n   * with it, while a margin is laid out in the PARENT's coordinates and the\n   * element's own transform never touches it.\n   */\n  let ancestors = new view.DOMMatrix();\n  for (\n    let node: Element | null = element;\n    node !== null && node !== root;\n    node = node.parentElement\n  ) {\n    const declared = view.getComputedStyle(node).transform;\n    if (declared === \"\" || declared === \"none\") continue;\n    const step = new view.DOMMatrix(declared);\n    // Kept from the walk that is already happening rather than read again, so\n    // the composed answer and the element's own cannot disagree about which\n    // declaration was seen.\n    if (node === element) own = step;\n    else ancestors = step.multiply(ancestors);\n    matrix = step.multiply(matrix);\n  }\n\n  /*\n   * `b` and `c` are the off-diagonal terms: zero for any composition of\n   * translations and axis-aligned scales, non-zero the moment a rotation or a\n   * skew enters.\n   *\n   * Compared against a TOLERANCE rather than to zero exactly. A transform that is\n   * geometrically the identity can be written as one that is not —\n   * `rotate(360deg)`, `rotate(1turn)` — and an engine is free to serialize the\n   * sine residue rather than normalize it away. Measured in Chromium, both of\n   * those come back exactly zero, so this guards an engine that behaves\n   * differently rather than a failure anyone has seen here.\n   *\n   * The bound rejects nothing real: the off-diagonal term of a thousandth of a\n   * degree of rotation is about 1.7e-5, four orders of magnitude above it.\n   *\n   * `is2D` is a separate question and a 2D check does not imply it. A\n   * `perspective(500px) rotateY(30deg)` projects the box as a trapezoid whose\n   * scale varies across it, and the flattened matrix can still show zero\n   * off-diagonal terms with positive `a` and `d` — describable by those tests\n   * and describable by nothing that draws rectangles.\n   */\n  const axisAligned =\n    matrix.is2D &&\n    Math.abs(matrix.b) < AXIS_ALIGNED_TOLERANCE &&\n    Math.abs(matrix.c) < AXIS_ALIGNED_TOLERANCE;\n  const describable = axisAligned && matrix.a > 0 && matrix.d > 0;\n  const scale = { x: matrix.a, y: matrix.d };\n  const ancestor = { x: ancestors.a, y: ancestors.d };\n  return {\n    ...scale,\n    ancestor,\n    describable,\n    /*\n     * Only asked where the composed scale is usable, because deriving the\n     * untransformed box divides by it: a collapsed or mirrored composition has\n     * no box to measure against, and the caller refuses such an element\n     * outright, so every edge is reported moved rather than divided for.\n     */\n    selfMoved: describable\n      ? edgesMovedBy(\n          own,\n          transformOriginOf(view.getComputedStyle(element)),\n          untransformedBox(element, scale),\n          ancestor\n        )\n      : { top: true, right: true, bottom: true, left: true },\n  };\n}\n\n/**\n * The element's own border box before its own transform, in local pixels.\n *\n * Derived from the rendered rectangle and the COMPOSED scale rather than read\n * from `offsetWidth`, which is integer-rounded: half a pixel of rounding is\n * multiplied by `1 - factor` in the arithmetic above, and under a large scale\n * that is enough to report a stationary edge as displaced.\n *\n * The composed scale is used because the rendered rectangle has been through\n * every transform between the element and the root, not only its own.\n */\nfunction untransformedBox(\n  element: Element,\n  scale: { x: number; y: number }\n): { width: number; height: number } {\n  const rect = element.getBoundingClientRect();\n  return { width: rect.width / scale.x, height: rect.height / scale.y };\n}\n\n/**\n * Whether a classic scrollbar reserves space inside the element's border box.\n *\n * `overflow: auto` and `overflow: scroll` are catalog values, and on a platform\n * without overlay scrollbars the scrollbar takes its width from BETWEEN the\n * padding box and the border — so a padding box derived by removing only the\n * borders is too wide by the gutter, and the right or bottom padding band is\n * drawn over the scrollbar instead of over the padding. Which side it takes is\n * a function of the writing direction, so a right-hand assumption is wrong in\n * RTL.\n *\n * `clientWidth` excludes both the border and the gutter while `offsetWidth`\n * excludes neither, so their difference beyond the borders IS the gutter.\n *\n * THE THRESHOLD IS A ROUNDING BOUND, not a guess. Both readings are integer\n * rounded INDEPENDENTLY while the border subtracted from them is exact and may\n * be fractional, so the residue on a container with no scrollbar at all can\n * reach a whole pixel — half from each — and a fractional border on a high-DPI\n * display is enough to produce it. Two pixels clears that bound with room, and\n * clears nothing real: the narrowest scrollbar a platform draws is `thin`, which\n * is eight pixels at its slimmest, and a classic one is around fifteen.\n *\n * Reported rather than corrected. The caller declines a block whose padding\n * geometry cannot be represented, which is one rule it already applies to\n * several other shapes.\n */\n/**\n * The most two independently rounded readings can differ by, plus a margin.\n *\n * Half a pixel each, so a whole pixel of residue is reachable with no scrollbar\n * present; two leaves room without reaching any real scrollbar width.\n */\nconst ROUNDING_BOUND_PX = 2;\n\nexport function hasScrollbarGutter(\n  element: Element,\n  borders: { x: number; y: number }\n): boolean {\n  const view = element.ownerDocument.defaultView;\n  if (view === null) return false;\n  /*\n   * By node kind, not by any realm's constructor — see `canvasRootFrom` for\n   * why the ambient `HTMLElement` is the wrong one to compare against.\n   *\n   * Getting it wrong here fails SILENTLY and in the unsafe direction. A canvas\n   * mounted into a same-origin iframe answers `false` before measuring\n   * anything, so the refusal below never fires and every scrolling block in\n   * that canvas draws its padding bands across the reserved scrollbar.\n   */\n  if (!isHTMLElement(element)) return false;\n\n  /*\n   * Only a scroll container can reserve one, and asking anything else is not\n   * merely wasted — it is WRONG. `clientWidth` and `clientHeight` are defined as\n   * zero for an element with no CSS layout box in the usual sense, which\n   * includes every inline box, so the subtraction below reports the element's\n   * whole width as a gutter and an ordinary inline block is refused for a\n   * scrollbar it could not have.\n   */\n  const style = view.getComputedStyle(element);\n  const scrolls = (overflow: string): boolean =>\n    overflow === \"auto\" || overflow === \"scroll\";\n  if (!scrolls(style.overflowX) && !scrolls(style.overflowY)) return false;\n\n  const gutterX = element.offsetWidth - element.clientWidth - borders.x;\n  const gutterY = element.offsetHeight - element.clientHeight - borders.y;\n  return gutterX > ROUNDING_BOUND_PX || gutterY > ROUNDING_BOUND_PX;\n}\n\n/**\n * Whether an ancestor between this element and the canvas root clips it.\n *\n * `overflow` is a catalog keyword taking `hidden`, `clip`, `scroll` or `auto` —\n * and taking TWO of them, so the axes can clip differently — so an author can\n * put a block inside a container that cuts part of it off. The\n * element's own bounding rectangle is reported UNCLIPPED, and the overlay draws\n * as a sibling of the page rather than inside that container — so bands derived\n * from the full rectangle escape the ancestor's clip and paint over ground where\n * the block is not rendered.\n *\n * Only a clip that ACTUALLY cuts is reported. A block sitting wholly inside an\n * `overflow: hidden` card is not clipped by it, and that is the ordinary case —\n * refusing on the presence of a clipping ancestor rather than on the fact of\n * being clipped would blank the overlay for most well-built pages.\n *\n * The walk stops BELOW the root. The shell scrolls the canvas from above, and\n * that clipping applies to the bands and the page alike, so it produces no\n * mismatch; only a clip between the block and the root does.\n */\nexport function clippedByAncestor(\n  element: Element,\n  root: Element,\n  radii: CornerRadii\n): boolean {\n  const view = element.ownerDocument.defaultView;\n  if (view === null) return false;\n  const box = element.getBoundingClientRect();\n  return anyAncestorCuts(element, root, node =>\n    cutByAncestor(node, box, radii, view, root)\n  );\n}\n\n/**\n * The part of `element`'s box its clipping ancestors leave visible, in the\n * canvas's content coordinates: the box cut to every ancestor's clip, on each\n * axis that ancestor clips. `\"hidden\"` when nothing of it is left, and\n * `null` when a clip cannot be described (an ancestor not aligned with the\n * axes), which leaves the caller its own fallback. Two answers, because \"the\n * page shows none of it\" and \"it cannot be said what the page shows\" call for\n * different marks.\n *\n * Read from the same per-ancestor answer {@link clippedByAncestor} reads, so\n * the box that is said to be cut and the part said to be visible come from\n * one reading of each ancestor.\n */\nexport function visiblePartOf(\n  element: Element,\n  root: HTMLElement\n): Rect | \"hidden\" | null {\n  const view = element.ownerDocument.defaultView;\n  if (view === null) return null;\n  const box = element.getBoundingClientRect();\n  const edges = {\n    left: box.left,\n    top: box.top,\n    right: box.right,\n    bottom: box.bottom,\n  };\n  const described = !anyAncestorCuts(element, root, node => {\n    const context = ancestorClipContext(node, view, root);\n    if (context.kind === \"cut\") return true;\n    if (context.kind === \"clips\") narrowTo(edges, context);\n    return false;\n  });\n  if (!described) return null;\n  if (edges.right <= edges.left || edges.bottom <= edges.top) return \"hidden\";\n  return clientRectInCanvas(\n    {\n      x: edges.left,\n      y: edges.top,\n      width: edges.right - edges.left,\n      height: edges.bottom - edges.top,\n    },\n    root\n  );\n}\n\n/**\n * Whether an ancestor cuts the block's own RECTANGLE — the straight-edge\n * question alone, with no opinion about a rounded corner.\n *\n * {@link clippedByAncestor} additionally refuses a block whose SQUARE corner\n * pokes past a more tightly rounded ancestor's arc — correct for a bounding\n * box a caller draws chrome flush against, like a spacing band that runs the\n * full length of an edge. A caller drawing something anchored to the block's\n * CENTRE and never reaching its corners has no use for that refinement: it\n * would refuse a container for a clip that exists only within a few pixels of\n * a corner nothing is drawn near, and it is refused for exactly the\n * containers most likely to have one — an ordinary full-width child sitting\n * flush inside a rounded, clipping parent is genuinely cut by a few pixels at\n * each corner where the two curves disagree, which is real and irrelevant to\n * anything drawn away from the corners.\n *\n * Shares {@link ancestorClipContext} and {@link rectCut} with\n * {@link clippedByAncestor} rather than reading `overflow`, composing scale,\n * resolving the clip rectangle or judging the edges a second time: the two\n * answer different questions about the same ancestor, and the parts they share\n * have to stay exactly the same reading. What is left after that sharing is\n * the whole of the difference — this function is `rectCut` alone, and the\n * corner-aware one is `rectCut` plus {@link cornerCut}.\n */\nexport function clippedByAncestorRect(\n  element: Element,\n  root: Element\n): boolean {\n  const view = element.ownerDocument.defaultView;\n  if (view === null) return false;\n  const box = element.getBoundingClientRect();\n  return anyAncestorCuts(element, root, node =>\n    rectCut(ancestorClipContext(node, view, root), box)\n  );\n}\n\n/**\n * Whether ONE ancestor cuts the block.\n *\n * Separated from the walk above so that each answers a single question: which\n * elements to ask, and what the answer is for one of them. The decision needs\n * four readings of that element and three independent reasons to refuse, and\n * inlining it into the loop puts all of that inside a `for` whose own job is\n * one line long.\n */\nfunction cutByAncestor(\n  node: Element,\n  box: DOMRect,\n  radii: CornerRadii,\n  view: Window,\n  root: Element\n): boolean {\n  const context = ancestorClipContext(node, view, root);\n  return rectCut(context, box) || cornerCut(context, box, radii);\n}\n\nfunction ancestorClipContext(\n  node: Element,\n  view: Window,\n  root: Element\n): AncestorClipContext {\n  const style = view.getComputedStyle(node);\n  /*\n   * PER AXIS, because the two can differ and the catalog ships the shorthand\n   * that makes them differ: `overflow` takes two values, so `clip visible` is\n   * a declaration an author can store. Measured in Chromium it is also the\n   * ONLY mixed pair that survives computation — pairing `visible` with\n   * `hidden`, `auto` or `scroll` resolves the `visible` side to `auto`, while\n   * `clip visible` stays exactly as written.\n   *\n   * Asking whether EITHER axis clips and then comparing all four edges\n   * refuses a block that overflows only the axis still rendering it, and a\n   * refusal costs every band on the block.\n   */\n  const clipsX = style.overflowX !== \"visible\";\n  const clipsY = style.overflowY !== \"visible\";\n  if (!clipsX && !clipsY) return { kind: \"no-clip\" };\n  /*\n   * A computed `overflow` is not the same as an overflow that CLIPS. The\n   * property does not apply to every generated box, and the computed value says\n   * nothing about that — so an author who writes `overflow: hidden` on an inline\n   * span gets the declaration in the computed style and no clip on the page.\n   * Reading the first as the second cuts a descendant nothing removes.\n   */\n  if (!overflowApplies(style.display)) return { kind: \"no-clip\" };\n  /*\n   * Overflow clips at the PADDING edge, and `getBoundingClientRect` reports the\n   * BORDER box. On a container with a border the two differ by its width, so a\n   * child pulled into the border by a negative margin or a transform is\n   * visibly cut while a border-box comparison reports it contained — measured,\n   * a 20px border puts the border box at 217 and the clip edge at 237.\n   */\n  const outer = node.getBoundingClientRect();\n  /*\n   * Scaled, because the two readings are in different units: `outer` is\n   * post-transform and a computed border width is unscaled CSS pixels. Under\n   * `scale(2)` a 20px border renders 40px thick, so insetting by 20 puts the\n   * clip edge half way through the border and accepts a child the container\n   * visibly cuts — measured, the real padding edge sat at 40 while this\n   * arithmetic answered 20 and a child at exactly 20 was let through.\n   */\n  /*\n   * Composed with the ROOT's own painted scale, which `renderedScale` stops\n   * below on purpose.\n   *\n   * That exclusion is right for the overlay, which is a child of the root and\n   * is drawn through the root's scale already. It is wrong here, because the\n   * two readings this compares live on opposite sides of it: `outer` comes from\n   * `getBoundingClientRect` and is post-zoom, while a computed border width is\n   * unscaled CSS pixels. Left uncomposed, the canvas's own scale is applied to\n   * one and not the other.\n   *\n   * Measured at a canvas painted to half size: a 20px border renders 10px, the\n   * inset is computed as 20, and a child sitting flush against the real padding\n   * edge is classified as clipped — which suppresses every spacing band on it,\n   * so the symptom is an overlay that silently stops drawing rather than one\n   * that draws wrongly.\n   */\n  const painted = canvasPaintedScale(root);\n  const own = renderedScale(node, root);\n  const scale: RenderedScale = {\n    ...own,\n    x: own.x * painted.x,\n    y: own.y * painted.y,\n    ancestor: {\n      x: own.ancestor.x * painted.x,\n      y: own.ancestor.y * painted.y,\n    },\n  };\n  /*\n   * A clipping ancestor that is not axis-aligned is DECLINED rather than\n   * measured, because neither reading survives its transform: `a` and `d` are\n   * not scale factors once a rotation is present, and `getBoundingClientRect`\n   * answers with an axis-aligned BOUNDING box whose edges are not the clip\n   * edges at all. The real clip is a slanted rectangle sitting inside that\n   * box, so a child cut by it still reads as contained.\n   *\n   * It cannot be left to the caller's own describability check, which is what\n   * an earlier version of this assumed: a descendant carrying the INVERSE\n   * transform composes back to an axis-aligned matrix, so the block passes\n   * that check while this ancestor fails it. Measured — a block under\n   * `rotate(-30deg)` inside an ancestor under `rotate(30deg)` composes to\n   * `a=0.999999, b=0, c=0, d=0.999999` and is called describable, while its\n   * ancestor's own matrix carries `b=0.5, c=-0.5`; the block sat inside the\n   * ancestor's bounding box with a quarter of it beyond the clip.\n   *\n   * Refusing is deliberately broader than the defect: a block WHOLLY INSIDE a\n   * rotated clipping ancestor is not cut and loses its bands anyway. Deciding\n   * that needs the clip as an oriented rectangle, and drawing nothing is the\n   * same answer this module already gives for every other shape it cannot\n   * describe.\n   */\n  if (!scale.describable) return { kind: \"cut\" };\n  const clip = clipEdges(outer, style, scale);\n  return { kind: \"clips\", clipsX, clipsY, style, clip, scale, painted };\n}\n\n/**\n * The canvas root an element sits inside, as an `HTMLElement` of any realm.\n *\n * `instanceof HTMLElement` compares against the constructor of the realm doing\n * the asking. A host that mounts the canvas into a same-origin iframe through a\n * portal gets a root built by that iframe's realm, and the check fails for a\n * perfectly good element — so chrome would return early and draw nothing,\n * silently, on exactly the iframe canvas `geometry.ts` documents. The root is\n * classified by node kind instead, through `dom-kind`.\n *\n * Here rather than at each caller because two of them ask the same question, and\n * the realm-safe spelling is the kind of detail that gets written correctly once\n * and copied wrongly afterwards.\n */\nexport function canvasRootFrom(\n  element: Element,\n  rootClass: string\n): HTMLElement | null {\n  const root = element.closest(`.${rootClass}`);\n  if (root === null) return null;\n  // A root with no window is not on screen, so there is nothing to draw over.\n  if (root.ownerDocument.defaultView === null) return null;\n  return isHTMLElement(root) ? root : null;\n}\n\n/**\n * An element's USED border-box corner radii, in LAYOUT pixels, from its\n * computed style and its rectangle as measured here.\n *\n * Here rather than in one overlay because every overlay drawn on a block's\n * shape asks it, and a second reading of the radii would drift from the first.\n *\n * A percentage radius resolves against the border box's own size, and the size\n * that governs is the one the element was LAID OUT at rather than the one it is\n * drawn at — `border-radius: 50%` on a block under `scale(2)` is half its layout\n * width, which then renders doubled like everything else inside the transform.\n *\n * That layout size is the measured rectangle divided back out by the scale it\n * was measured at, rather than a second reading from the element. `offsetWidth`\n * would answer the same question in whole pixels only, and `getComputedStyle`\n * reports whichever box `box-sizing` selects — so both are a second answer to a\n * question `renderedScale` has already answered exactly.\n *\n * A scale that is zero on either axis leaves nothing to resolve against and no\n * band to draw; `describable` refuses that block anyway, and answering square\n * here keeps this from dividing by it on the way to that refusal.\n *\n * UNDEFINED when a corner cannot be resolved at all — a percentage inside a\n * `calc()` stays unresolved in the computed value — which the caller treats as a\n * shape it cannot describe rather than as a square one.\n */\nexport function usedRadiiOf(\n  style: CSSStyleDeclaration,\n  border: Rect,\n  scale: Scale\n): CornerRadii | undefined {\n  if (!(scale.x > 0) || !(scale.y > 0)) return SQUARE_CORNERS;\n  return usedCornerRadii(\n    {\n      topLeft: style.borderTopLeftRadius,\n      topRight: style.borderTopRightRadius,\n      bottomRight: style.borderBottomRightRadius,\n      bottomLeft: style.borderBottomLeftRadius,\n    },\n    { width: border.width / scale.x, height: border.height / scale.y }\n  );\n}\n","/**\n * Where a dragged block can land, and which of those places the pointer means.\n *\n * The canvas has to answer one question on every pointer move: of all the\n * positions a block could be dropped into, which one is the author aiming at?\n * This module answers it, and the shape of the answer is the whole design.\n *\n * ## Regions first, then lines — and that order is the point\n *\n * Three earlier designs for this failed, and they failed for one reason. Each\n * tried to SCORE every candidate position against the pointer and take the best\n * score. Scoring is comparative, so the moment two positions in different\n * containers can tie, their scores have to mean the same thing — and no measure\n * of a single position can encode \"the pointer is inside THIS container and not\n * that one\", because containment is a statement about the candidates you are\n * being compared against.\n *\n * The way out is to stop comparing across containers at all:\n *\n * 1. **Resolve the region.** The deepest container whose rectangle holds the\n *    pointer owns the drop. This is decided, not scored.\n * 2. **Rank inside it.** Only then, and only among that region's own insertion\n *    points, measure a distance.\n *\n * Every number in a comparison is then the same kind of number by construction,\n * and \"which container\" is never something a distance has to smuggle.\n *\n * ## An insertion point is a LINE, not a rectangle\n *\n * The natural thing to measure against is the middle of a drop zone. It is also\n * wrong, and wrong in a way that only shows up when adjacent blocks have\n * different heights: a short block's midpoint sits close to its neighbour's, so\n * the target flips while the pointer is still well inside the block the author\n * is pointing at, and the block lands at the wrong index.\n *\n * An insertion point is a place children are separated, so it is a LINE. Ranking\n * by distance to that line puts the switch boundary exactly at each child's\n * centre, whatever the children's sizes are — which is the behaviour an author\n * expects and describes as \"it goes where I point\".\n *\n * ## Nothing here reads a block's height as a threshold\n *\n * A rule of the form \"a block must be at least N pixels tall to compete\" cannot\n * work on this canvas. `core/spacer` takes its height from an author-set prop\n * with no lower bound, and `core/divider` renders as a one-pixel rule — so any\n * N excludes some block an author can legitimately place, and excluding it\n * means they can never drop beside it. There is no floor to measure, so this\n * module measures distances and never a size.\n *\n * Steadiness near a boundary is not this module's job either. It reports the\n * target the pointer is over right now; {@link nextTargetSwitchState} decides\n * when a new one is allowed to replace the committed one, on pointer travel\n * rather than on geometry. Keeping the two apart is what lets a region boundary\n * be an ordinary candidate change rather than a special case: hysteresis is\n * applied to the resolved answer, so it does not matter which region produced\n * it.\n *\n * Pure, and it takes measured rectangles rather than elements — so every rule\n * above is assertable without a browser, which matters because jsdom reports\n * every element as zero-sized and could not exercise one of them.\n *\n * @module drop-targets\n */\n\nimport type {\n  BlockDocument,\n  BlockNode,\n  ComponentLookup,\n  NestingSource,\n  PlacedNode,\n  PlacementRefusal,\n  PlacementRefused,\n  PlacementSources,\n  PlacementVerdict,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  canPlaceIn,\n  findNode,\n  placementVerdict,\n  registryBlockSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { Point, Rect } from \"../geometry\";\nimport type { OpPosition } from \"../op-vocabulary\";\nimport type { PlacementTarget, SlotSource } from \"../panels/add/inserter\";\n\n/**\n * The direction a region lays its children out.\n *\n * `\"y\"` is an ordinary vertical stack; `\"x\"` is a row or a grid track running\n * across. It decides which coordinate separates two children and therefore\n * which way an insertion line is drawn.\n */\nexport type DropAxis = \"x\" | \"y\";\n\n/** The region id standing for the document's top level. */\nexport const ROOT_REGION = \"root\";\n\n/**\n * Rectangles, measured from wherever they actually are.\n *\n * An interface rather than a DOM read so this module stays pure. The canvas\n * supplies one backed by `getBoundingClientRect`; a test supplies a literal.\n *\n * All rectangles must be in ONE coordinate space — the canvas's. Mixing spaces\n * produces an indicator drawn a constant distance from the gap it names, which\n * looks like a styling mistake rather than a measurement one.\n */\nexport interface RectSource {\n  /** Where a node's element sits, or `undefined` when it rendered nothing. */\n  rectOf(nodeId: string): Rect | undefined;\n  /** The canvas's own extent, which is the root region's. */\n  rootRect(): Rect;\n}\n\n/**\n * One container's child list, as somewhere a block can be dropped.\n *\n * A region is addressed by a parent and a slot, never by position: the document\n * makes ids the only thing anything stores, and a positional region would name\n * a different container the moment a sibling is inserted above it.\n */\nexport interface DropRegion {\n  /** Stable identity: {@link ROOT_REGION}, or `\"<parentId>::<slot>\"`. */\n  readonly id: string;\n  /**\n   * What this region is, as the nesting rule needs to see it.\n   *\n   * Named as {@link DropTarget.target} is, because it is the same thing: the\n   * placement a block would be nested into. `at` is reserved for a POSITION\n   * throughout this module, and a reader holding a region and a target should\n   * not have to remember which of two meanings the one word carries.\n   */\n  readonly target: PlacementTarget;\n  /** The container node, absent for the root region. */\n  readonly parentId?: string;\n  /** The slot within that container, absent for the root region. */\n  readonly slot?: string;\n  /** How far inside the document this region sits; the root is 0. */\n  readonly depth: number;\n  /** The container's measured extent, which decides what it contains. */\n  readonly rect: Rect;\n  /** Which way its children run. */\n  readonly axis: DropAxis;\n  /** Its children's ids, in document order. */\n  readonly childIds: readonly string[];\n}\n\n/**\n * One place a block can land, and the line that says so.\n *\n * `at` is what the op needs and `line` is what the author sees, produced\n * together for the same reason the inserter produces a position and its target\n * together: computed apart, the indicator and the drop can be derived from\n * different readings and the block lands somewhere other than where the line\n * was drawn.\n */\nexport interface DropTarget {\n  /**\n   * Stable identity across pointer moves.\n   *\n   * Required by the switch rule, which compares the committed target with a\n   * rival — an identity derived from the rectangle would differ every time the\n   * page reflowed, and every reflow would read as a crossing.\n   */\n  readonly id: string;\n  /** The region this target belongs to. */\n  readonly regionId: string;\n  /** Where the block goes. */\n  readonly at: OpPosition;\n  /** What that position is, for the nesting rule. */\n  readonly target: PlacementTarget;\n  /** The axis children are separated along. */\n  readonly axis: DropAxis;\n  /**\n   * Where the line sits along {@link axis} — a `y` for a horizontal line, an\n   * `x` for a vertical one.\n   */\n  readonly line: number;\n  /** Where the line starts, across the axis. */\n  readonly from: number;\n  /** Where the line ends, across the axis. */\n  readonly to: number;\n}\n\n/**\n * Why a drop the author aimed at cannot happen.\n *\n * The engine's refusal CODE, not a sentence. Wording is a presentation\n * decision — it belongs where the words are drawn and where they can be\n * translated — and a code is what a caller can branch on. `permitted` travels\n * with it because naming what the region DOES take is the difference between\n * \"no\" and an instruction.\n */\nexport interface DropRefusal {\n  readonly regionId: string;\n  /**\n   * The container node the refusing region belongs to, absent at the root.\n   *\n   * Where an ancestor on the page refused for its content model, that ancestor\n   * instead: a Button aimed at a Box inside a linked Card names the Card, which\n   * is the block the refusal's words name and the one its notice sits over.\n   * {@link DropRefusal.regionId} still names the region the pointer is in.\n   *\n   * Carried for the same reason `permitted` is: a surface explaining the\n   * refusal needs it, and this is the only place it is still known. A region is\n   * identified by `\"<parentId>::<slot>\"`, so recovering the node from\n   * {@link DropRefusal.regionId} means splitting a composite string — reading a\n   * value back out of a spelling this module chose, which stops being correct\n   * the moment the spelling does.\n   *\n   * Absent rather than a sentinel at the root, because \"there is no container\"\n   * is the fact that separates a refusal an author can fix by aiming elsewhere\n   * from one that needs a container to exist first.\n   */\n  readonly parentId?: string;\n  /**\n   * Why the region refuses. Beside the name rules' reasons (`\"wrong-parent\"`,\n   * `\"restricted-at-root\"`, `\"not-allowed-in-slot\"`) this carries the\n   * placement rule's: `\"undeclared-slot\"`, `\"holds-no-blocks\"`,\n   * `\"phrasing-only\"` and `\"content-model\"`. A `switch` over it needs a\n   * `default`, or a case for each of those; {@link DropRefusal.verdict}\n   * carries the facts each of them is explained by.\n   */\n  readonly reason: PlacementRefusal;\n  readonly permitted: readonly string[];\n  /**\n   * The one placement rule's whole answer, when the drop was judged by it, so\n   * its words can name a slot the container lacks or the linked block that\n   * refuses what is being dropped.\n   */\n  readonly verdict?: PlacementRefused;\n}\n\n/**\n * What the one placement rule needs to judge a drop: the document, the blocks\n * being placed with everything inside them, and where it reads its answers.\n */\nexport interface DropPlacement {\n  readonly nodes: readonly unknown[];\n  /**\n   * The blocks being placed, read only when a region is judged: an insert has\n   * no node until its palette builds one, and asking for it is what builds\n   * it. An empty answer leaves the drop to the name rules.\n   */\n  readonly placing: () => readonly PlacedNode[];\n  readonly sources: PlacementSources;\n  /**\n   * The answers already reached, kept for one gesture. The document, the\n   * blocks being placed and the regions are fixed while a drag lasts, so a\n   * region's answer is too, and every pointer move and autoscroll frame would\n   * otherwise walk the same subtree again.\n   */\n  readonly verdicts?: RegionVerdicts;\n}\n\n/**\n * Region answers keyed by the region's container, then its slot, with the\n * root region under `undefined` for both.\n *\n * Two keys rather than {@link DropRegion.id}: that id joins the two with `::`,\n * and a node id or a slot name may itself contain `::`, so container `a` with\n * slot `b::c` and container `a::b` with slot `c` spell the same id while\n * being different regions with different answers.\n */\nexport type RegionVerdicts = Map<\n  string | undefined,\n  Map<string | undefined, RegionVerdict>\n>;\n\n/**\n * A region's answer: the rule's verdict, and for a refusal the container it is\n * drawn over, worked out with the verdict so a cached answer carries both.\n */\nexport interface RegionVerdict {\n  readonly verdict: PlacementVerdict;\n  readonly parentId: string | undefined;\n}\n\n/**\n * What the pointer currently means.\n *\n * A refusal is a distinct answer rather than an absent target, and the\n * distinction is what the canvas needs to say why. An author who drags a\n * heading over an accordion has aimed at something; showing no indicator tells\n * them the editor did not notice, while showing a refusal tells them the region\n * does not take that block.\n */\nexport type DropResolution =\n  | { readonly kind: \"target\"; readonly target: DropTarget }\n  | { readonly kind: \"refused\"; readonly refusal: DropRefusal }\n  | { readonly kind: \"none\" };\n\n/** The coordinate that separates children on an axis. */\nfunction along(point: Point, axis: DropAxis): number {\n  return axis === \"y\" ? point.y : point.x;\n}\n\n/** A rectangle's leading edge on an axis. */\nfunction leadingEdge(rect: Rect, axis: DropAxis): number {\n  return axis === \"y\" ? rect.y : rect.x;\n}\n\n/** A rectangle's trailing edge on an axis. */\nfunction trailingEdge(rect: Rect, axis: DropAxis): number {\n  return axis === \"y\" ? rect.y + rect.height : rect.x + rect.width;\n}\n\n/** Whether a rectangle holds a point, edges included. */\nfunction contains(rect: Rect, point: Point): boolean {\n  return (\n    point.x >= rect.x &&\n    point.x <= rect.x + rect.width &&\n    point.y >= rect.y &&\n    point.y <= rect.y + rect.height\n  );\n}\n\n/**\n * Which way a region's children run, read from where they actually landed.\n *\n * Measured rather than declared. A container's CSS is only half the story — a\n * `flex-direction: row` whose children wrapped runs down the page, and a block\n * that declares nothing still lays out somehow — so the rectangles are the\n * evidence and the declaration is a claim about them. Reading the result also\n * means grid, flex, inline and ordinary flow need no separate handling.\n *\n * The axis with the greater spread of leading edges wins. Children stacked\n * vertically share an `x` and differ in `y`, and a row is the reverse.\n *\n * **Vertical when there is no evidence** — fewer than two children, or children\n * that spread equally. A single child cannot indicate a direction, and page\n * content runs down the page far more often than across.\n *\n * **Known limit: a region that WRAPS is served on one axis only.** A grid of\n * three columns by two rows genuinely separates its children both ways, and a\n * single line cannot express \"after the end of row one\". Such a region gets its\n * dominant axis, which orders row-major grids correctly and leaves column-major\n * ones approximate.\n */\nexport function axisOfRects(rects: readonly Rect[]): DropAxis {\n  if (rects.length < 2) return \"y\";\n  const xs = rects.map(rect => rect.x);\n  const ys = rects.map(rect => rect.y);\n  const spreadX = Math.max(...xs) - Math.min(...xs);\n  const spreadY = Math.max(...ys) - Math.min(...ys);\n  return spreadX > spreadY ? \"x\" : \"y\";\n}\n\n/**\n * Every region in the document, deepest last.\n *\n * A container contributes a region for each slot its DEFINITION declares, not\n * for each slot its node happens to hold. An empty container carries no `slots`\n * key at all — `makeNode` writes one only when children are supplied — so\n * asking the node would produce no region for exactly the containers that most\n * need one, and an author could never fill anything they had just inserted.\n *\n * A container that rendered nothing measurable is skipped rather than given a\n * zero rectangle. A zero rectangle contains no point, so it would never be\n * resolved, but it WOULD sit in the list claiming to be droppable — an absence\n * that reads as a presence is the harder of the two to notice.\n */\nexport function collectRegions(\n  document: BlockDocument,\n  slots: SlotSource,\n  rects: RectSource,\n  /**\n   * The slots a NODE declares, where its type alone cannot say: a component\n   * placement declares the slots its component exposes. Absent, or answering\n   * undefined, the type's slots are read.\n   */\n  slotsOfNode?: (node: BlockNode) => readonly string[] | undefined\n): DropRegion[] {\n  const regions: DropRegion[] = [];\n\n  const walk = (nodes: readonly BlockNode[], depth: number): void => {\n    for (const node of nodes) {\n      const declared = slotsOfNode?.(node) ?? slots.slotsOf(node.type) ?? [];\n      for (const slot of declared) {\n        const region = slotRegion(node, slot, depth, rects);\n        if (region === undefined) continue;\n        regions.push(region);\n        walk(node.slots?.[slot] ?? [], depth + 1);\n      }\n    }\n  };\n\n  regions.push(rootRegion(document, rects));\n  walk(document.nodes, 1);\n  return regions;\n}\n\n/** The axis the measured blocks among `ids` are laid out along. */\nfunction axisOfChildren(ids: readonly string[], rects: RectSource): DropAxis {\n  return axisOfRects(\n    ids\n      .map(id => rects.rectOf(id))\n      .filter((rect): rect is Rect => rect !== undefined)\n  );\n}\n\n/**\n * The page's top level as a region. One construction for every caller: a\n * drag's regions and the Add panel's insertion line read the same one.\n */\nexport function rootRegion(\n  document: BlockDocument,\n  rects: RectSource\n): DropRegion {\n  const childIds = document.nodes.map(node => node.id);\n  return {\n    id: ROOT_REGION,\n    target: { kind: \"root\" },\n    depth: 0,\n    rect: rects.rootRect(),\n    axis: axisOfChildren(childIds, rects),\n    childIds,\n  };\n}\n\n/**\n * One slot of a container as a region, or `undefined` when the container\n * rendered nothing measurable (see {@link collectRegions}). One construction\n * for every caller, as {@link rootRegion} is.\n */\nexport function slotRegion(\n  node: BlockNode,\n  slot: string,\n  depth: number,\n  rects: RectSource\n): DropRegion | undefined {\n  const rect = rects.rectOf(node.id);\n  if (rect === undefined) return undefined;\n  const childIds = (node.slots?.[slot] ?? []).map(child => child.id);\n  return {\n    id: `${node.id}::${slot}`,\n    target: { kind: \"slot\", parentType: node.type, slot },\n    parentId: node.id,\n    slot,\n    depth,\n    rect,\n    axis: axisOfChildren(childIds, rects),\n    childIds,\n  };\n}\n\n/**\n * The insertion lines inside one region, in index order.\n *\n * A region with `n` children has `n + 1` of them. The first sits on the first\n * child's leading edge and the last on the final child's trailing edge; the\n * ones between sit in the middle of the gap separating two children, which is\n * where an author sees the boundary and where a margin puts it.\n *\n * Ranking by distance to these lines is what makes each child's CENTRE the\n * place the target changes: a pointer in a child's leading half is nearer the\n * line before it, and in its trailing half nearer the line after. That holds\n * for children of any size, which is precisely what a rule measuring to a zone's\n * middle gets wrong.\n *\n * **An empty region still has one**, drawn across its middle. It is the only\n * way to fill a container that has just been inserted, and a container that\n * cannot be filled is decorative.\n *\n * A child that rendered nothing measurable is skipped, but its INDEX is not:\n * the op addresses a position in the stored children, and quietly renumbering\n * around an unrendered node would drop the block at a different index from the\n * one the line was drawn for.\n */\nexport function targetsInRegion(\n  region: DropRegion,\n  rects: RectSource\n): DropTarget[] {\n  const axis = region.axis;\n  const across: Pick<DropTarget, \"from\" | \"to\"> =\n    axis === \"y\"\n      ? { from: region.rect.x, to: region.rect.x + region.rect.width }\n      : { from: region.rect.y, to: region.rect.y + region.rect.height };\n\n  const positionAt = (index: number): OpPosition =>\n    region.parentId === undefined || region.slot === undefined\n      ? { index }\n      : { parentId: region.parentId, slot: region.slot, index };\n\n  const make = (index: number, line: number): DropTarget => ({\n    id: `${region.id}#${String(index)}`,\n    regionId: region.id,\n    at: positionAt(index),\n    target: region.target,\n    axis,\n    line,\n    ...across,\n  });\n\n  const measured = region.childIds.map(id => rects.rectOf(id));\n  const rendered = measured.filter((rect): rect is Rect => rect !== undefined);\n  if (rendered.length === 0) {\n    // Across the middle: with nothing rendered there is no gap to sit in, and\n    // an edge would read as \"beside this container\" rather than \"inside it\".\n    const middle =\n      axis === \"y\"\n        ? region.rect.y + region.rect.height / 2\n        : region.rect.x + region.rect.width / 2;\n    return [make(0, middle)];\n  }\n\n  const targets: DropTarget[] = [];\n  let previous: Rect | undefined;\n  measured.forEach((rect, index) => {\n    if (rect === undefined) return;\n    targets.push(\n      make(\n        index,\n        previous === undefined\n          ? leadingEdge(rect, axis)\n          : // The middle of the gap. Reading either edge alone puts the line\n            // against one of the two blocks, so a margin makes it look like it\n            // belongs to that one rather than to the space between them.\n            (trailingEdge(previous, axis) + leadingEdge(rect, axis)) / 2\n      )\n    );\n    previous = rect;\n  });\n  if (previous !== undefined) {\n    targets.push(make(region.childIds.length, trailingEdge(previous, axis)));\n  }\n  return targets;\n}\n\n/**\n * A target's line as a rectangle in the canvas's content coordinates: across\n * the region at `line` for a vertical flow, down it for a row, with no\n * thickness. One conversion for everything drawn from a target: the drag's\n * line, and the Add panel's preview of a place, its label and edge label.\n */\nexport function targetLineRect(target: DropTarget): Rect {\n  const span = target.to - target.from;\n  return target.axis === \"y\"\n    ? { x: target.from, y: target.line, width: span, height: 0 }\n    : { x: target.line, y: target.from, width: 0, height: span };\n}\n\n/** Ids of a node and everything under it. */\nfunction subtreeIds(node: BlockNode, into: Set<string>): void {\n  into.add(node.id);\n  for (const children of Object.values(node.slots ?? {})) {\n    for (const child of children) subtreeIds(child, into);\n  }\n}\n\n/**\n * The node with this id, and everything inside it.\n *\n * A block cannot be dropped into itself or into anything it contains: the move\n * would detach a subtree and re-attach it beneath itself, which is not a page.\n * Collected as a set so the check below is a lookup rather than a walk per\n * candidate region.\n */\nexport function movingSubtree(\n  document: BlockDocument,\n  movingId: string | undefined\n): Set<string> {\n  const ids = new Set<string>();\n  if (movingId === undefined) return ids;\n  const find = (nodes: readonly BlockNode[]): BlockNode | undefined => {\n    for (const node of nodes) {\n      if (node.id === movingId) return node;\n      for (const children of Object.values(node.slots ?? {})) {\n        const found = find(children);\n        if (found !== undefined) return found;\n      }\n    }\n    return undefined;\n  };\n  const node = find(document.nodes);\n  if (node !== undefined) subtreeIds(node, ids);\n  return ids;\n}\n\n/**\n * Where the one placement rule reads its answers in the editor: the host's\n * nesting rules, the registered blocks, and the component definitions the\n * canvas draws instances from, when it has them.\n *\n * One builder for every surface that asks the rule — the canvas drag, the\n * Layers drag and the keyboard move — so a placement cannot be judged against\n * one set of sources on one surface and another set beside it.\n */\nexport function placementSources(current: {\n  nesting: NestingSource;\n  definitions?: ComponentLookup;\n}): PlacementSources {\n  return {\n    nesting: current.nesting,\n    definitions: registryBlockSource(),\n    ...(current.definitions === undefined\n      ? {}\n      : { components: current.definitions }),\n  };\n}\n\n/** What {@link resolveDrop} needs to answer a pointer. */\nexport interface DropQuery {\n  /**\n   * The block types the placement is judged by.\n   *\n   * One for a block, its registered type name. Several for a component\n   * instance: the ROOTS of the definition it draws, resolved as its tile was\n   * (`placementTypesOf`), because the instance node's own type is not a\n   * registered block and the nesting source answers \"no restriction\" for it.\n   * Every type must be admitted, as every root of a pattern must be.\n   */\n  readonly blockNames: readonly string[];\n  /**\n   * Nodes the drop may not land inside: the dragged block and its descendants.\n   *\n   * Empty for a drag from the palette, where nothing is being detached. Passed\n   * in already computed rather than derived here, because it cannot change\n   * during a drag while this runs on every pointer move — and a walk of the\n   * document per move is work whose answer is known before the drag starts.\n   *\n   * Build it with {@link movingSubtree}.\n   */\n  readonly forbiddenParents: ReadonlySet<string>;\n  readonly regions: readonly DropRegion[];\n  readonly nesting: NestingSource;\n  readonly rects: RectSource;\n  /**\n   * The blocks being placed, judged by the one placement rule. Absent, the\n   * drop is judged by the name rules alone, as before the rule existed.\n   */\n  readonly placement?: DropPlacement;\n}\n\n/**\n * Which region owns the pointer.\n *\n * The DEEPEST containing one, so a container nested inside another claims the\n * pointer over its own area rather than losing it to the ancestor it sits in.\n * Ties on depth go to the one declared later, which is document order — a\n * region overlapping a sibling is already a layout the author can see, and\n * taking the later one matches which of the two paints on top.\n *\n * `undefined` when the pointer is outside everything, INCLUDING outside the\n * root. Falling back to the root would let a drop resolve from a pointer that\n * had left the canvas, which is how a block lands on the page after a drag the\n * author abandoned by dragging away.\n */\nexport function regionAt(\n  regions: readonly DropRegion[],\n  pointer: Point,\n  forbiddenParents: ReadonlySet<string> = new Set()\n): DropRegion | undefined {\n  let owner: DropRegion | undefined;\n  for (const region of regions) {\n    // A region inside the block being dragged is SKIPPED rather than refused,\n    // so the pointer falls through to the container around it. That is what an\n    // author dragging a box over its own interior means: put it beside itself.\n    // Refusing here would show \"you cannot drop that there\" for a gesture with\n    // an obvious correct reading.\n    if (\n      region.parentId !== undefined &&\n      forbiddenParents.has(region.parentId)\n    ) {\n      continue;\n    }\n    if (!contains(region.rect, pointer)) continue;\n    if (owner === undefined || region.depth >= owner.depth) owner = region;\n  }\n  return owner;\n}\n\n/**\n * The target the pointer means right now.\n *\n * Region first, then the nearest line inside it — never a distance across the\n * two, for the reason in the module docblock.\n *\n * A region the block cannot go in produces a REFUSAL rather than deferring to\n * the container around it. Resolving to the ancestor would silently drop the\n * block somewhere the author was not aiming, which the nesting rule exists to\n * prevent; saying no is the honest answer and it carries the reason.\n */\nexport function resolveDrop(query: DropQuery, pointer: Point): DropResolution {\n  const region = regionAt(query.regions, pointer, query.forbiddenParents);\n  if (region === undefined) return { kind: \"none\" };\n\n  const { verdict, parentId } = judgeRegion(query, region);\n  if (!verdict.allowed) {\n    return {\n      kind: \"refused\",\n      refusal: {\n        regionId: region.id,\n        // SPREAD rather than assigned, so the root case has no `parentId` key\n        // at all, as the type documents it.\n        ...(parentId === undefined ? {} : { parentId }),\n        reason: verdict.reason,\n        permitted: \"permitted\" in verdict ? verdict.permitted : [],\n        ...(query.placement === undefined ? {} : { verdict }),\n      },\n    };\n  }\n\n  let best: DropTarget | undefined;\n  let bestDistance = Number.POSITIVE_INFINITY;\n  for (const candidate of targetsInRegion(region, query.rects)) {\n    const distance = Math.abs(along(pointer, candidate.axis) - candidate.line);\n    // Strictly nearer, so an exact tie keeps the EARLIER index. Two lines\n    // coincide when a child measures zero on the axis, and preferring the later\n    // one there would make a drop land after a block the author aimed before.\n    if (distance < bestDistance) {\n      best = candidate;\n      bestDistance = distance;\n    }\n  }\n  // Undefined for a region with no lines at all, and for one whose coordinates\n  // are not comparable. Starting from an infinite distance rather than from the\n  // first element is what makes those the same answer: seeding with `targets[0]`\n  // would commit to a line before measuring it, so a region producing only\n  // unusable coordinates would resolve to one of them.\n  if (best === undefined) return { kind: \"none\" };\n  return { kind: \"target\", target: best };\n}\n\n/**\n * Whether the dragged blocks may go into a region: the one placement rule at\n * the region's position when the query carries the placement, the name rules\n * otherwise.\n */\nfunction judgeRegion(query: DropQuery, region: DropRegion): RegionVerdict {\n  const { placement } = query;\n  const held = placement?.verdicts?.get(region.parentId)?.get(region.slot);\n  if (held !== undefined) return held;\n  const placing = placement?.placing() ?? [];\n  const verdict =\n    placement === undefined || placing.length === 0\n      ? nameVerdict(query, region)\n      : canPlaceIn(\n          placement.nodes,\n          placing,\n          region.parentId === undefined\n            ? { kind: \"root\" }\n            : {\n                kind: \"slot\",\n                parentId: region.parentId,\n                slot: region.slot ?? \"\",\n              },\n          placement.sources\n        );\n  const judged: RegionVerdict = {\n    verdict,\n    parentId: verdict.allowed\n      ? region.parentId\n      : refusingParent(query, region, verdict),\n  };\n  const verdicts = placement?.verdicts;\n  if (verdicts !== undefined) {\n    const bySlot = verdicts.get(region.parentId) ?? new Map();\n    bySlot.set(region.slot, judged);\n    verdicts.set(region.parentId, bySlot);\n  }\n  return judged;\n}\n\n/**\n * The container a refusal is drawn over, as the `parentId` it carries.\n *\n * The region's own container, except where the rule refused because of an\n * ancestor's content model: a Button aimed at a Box inside a linked Card is\n * refused by the Card, so the Card is the block the notice names and the one\n * it sits over. Only an ancestor ON THE PAGE that holds the region counts; a\n * refuser inside the dragged blocks themselves is not where the author aimed,\n * and an insert's is not on the page at all.\n */\nfunction refusingParent(\n  query: DropQuery,\n  region: DropRegion,\n  verdict: PlacementRefused\n): string | undefined {\n  const own = region.parentId;\n  if (verdict.reason !== \"content-model\" || own === undefined) return own;\n  const refuserId = verdict.refusedBy.id;\n  const nodes = query.placement?.nodes;\n  if (refuserId === undefined || nodes === undefined) return own;\n  // Asserted only to the mutable array `findNode` is typed to take; it reads\n  // the forest and writes nothing.\n  const refuser = findNode(nodes as BlockNode[], refuserId);\n  return refuser !== undefined && findNode([refuser], own) !== undefined\n    ? refuserId\n    : own;\n}\n\n/** The name rules' answer for a region, in the one placement rule's shape. */\nfunction nameVerdict(query: DropQuery, region: DropRegion): PlacementVerdict {\n  const verdict = placementVerdict(\n    query.blockNames,\n    region.target,\n    query.nesting\n  );\n  return verdict.allowed\n    ? { allowed: true }\n    : {\n        allowed: false,\n        reason: verdict.reason,\n        blockType: query.blockNames[0] ?? \"\",\n        permitted: verdict.permitted,\n      };\n}\n","/**\n * Reading and writing one control's value inside a node's style envelope.\n *\n * The envelope is `state × breakpoint × property`, both outer levels sparse, and\n * a control addresses one position in it. Every control goes through here rather\n * than reaching into `node.styles` itself, so the addressing exists once: a\n * control that spelled the path itself would be a second answer to \"where does\n * this value live\", and the two disagree the first time the envelope moves.\n *\n * **Validation is DELEGATED, never repeated.** `validateStyleValues` is the\n * catalog's own grammar check, and this calls it on the values that would\n * result. A control that re-checked units or ranges would be a second\n * implementation of the same question — and the one that drifted would be this\n * one, because the catalog is where new properties arrive.\n *\n * **A write is ONE op.** `editorState.apply` pushes exactly one undo entry per\n * call, so a control that commits through a single `update` op is a single step\n * of undo by construction rather than by remembering to batch.\n *\n * @module style-values\n */\n\nimport {\n  breakpointContexts,\n  isPlainRecord,\n  isTokenRef,\n  validateStyleValues,\n  type BreakpointId,\n  type BreakpointSet,\n  type NodeStyles,\n  type StyleState,\n  type StyleValue,\n  type StyleValues,\n  type ValidationIssue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { sameStyleValue, type BuilderOp } from \"../op-vocabulary\";\n\nimport type { StyleControlOptions } from \"./style-controls\";\n\n/**\n * The site policy a value is judged against.\n *\n * Carried rather than defaulted, because the engine ships no host list of its\n * own: which hosts a site will fetch from is the operator's decision. Omitting\n * it from a validation run does not mean \"allow\" — it means the question was\n * never asked — so a control that never forwarded it would accept a URL the\n * published compiler refuses, show it in the preview, fetch it from the editor,\n * and let the author save a value that then vanishes from the page.\n *\n * DERIVED rather than restated. This and `StyleControlOptions` are the same\n * contract read at two moments — choosing which arm to draw, and judging the\n * write — and they must never disagree about a field. Both trace to the\n * engine's own option type, so a field added there reaches all three at once.\n */\nexport type StylePolicy = StyleControlOptions;\n\n/** Where a control reads and writes. */\nexport interface StyleAddress {\n  readonly state: StyleState;\n  readonly breakpoint: BreakpointId;\n  /** The catalog key, as stored in a `StyleValues` record. */\n  readonly property: string;\n  /**\n   * The position inside the property's value, from `StyleControl.path`.\n   *\n   * Empty addresses the property itself. A control never builds this by hand:\n   * it carries the path the descriptor gave it, which is what keeps the two\n   * from disagreeing about where a side or a corner lives.\n   */\n  readonly path: readonly string[];\n}\n\n/**\n * The outcome of asking for a write.\n *\n * A discriminated union rather than a thrown error, because a refused value is\n * an ordinary thing for a control to encounter — a half-typed length is invalid\n * for as long as it takes to type the unit — and an exception on every keystroke\n * is not a control flow anyone wants to write against.\n */\nexport type StyleWrite =\n  | {\n      readonly ok: true;\n      /**\n       * The op to apply, or `null` when the document already holds this value.\n       *\n       * `applyOp` REFUSES an update that changes nothing — \"a history entry for\n       * it would undo to no visible effect\" — so an SDK that always handed back\n       * an op would advertise one that throws on the ordinary cases: resetting\n       * a control that was already unset, or retyping the value a node already\n       * holds. Null says the ask was valid and there is nothing to do.\n       */\n      readonly op: BuilderOp | null;\n      /**\n       * Findings the catalog reported that do not refuse the write.\n       *\n       * Carried rather than dropped: a warning is the validator explaining\n       * something about a value it accepted, and a control that discarded them\n       * would present an accepted-with-reservations value as an unremarkable\n       * one.\n       */\n      readonly warnings: readonly ValidationIssue[];\n    }\n  | { readonly ok: false; readonly issues: readonly ValidationIssue[] };\n\n/** A stored value holding named sub-values. */\ntype CompositeValue = { readonly [key: string]: StyleValue };\n\n/**\n * Whether a value addresses sub-values.\n *\n * A token reference is an object and is nonetheless a scalar, so `typeof` alone\n * would descend into `{ $token }` looking for a side that is not there.\n */\nfunction isComposite(value: StyleValue | undefined): value is CompositeValue {\n  return typeof value === \"object\" && value !== null && !isTokenRef(value);\n}\n\n/**\n * A value's OWN entry at a name, ignoring anything reached through a prototype.\n *\n * The engine reads style maps this way — `validateStyleValues` and the shape\n * walk beside it both guard with `Object.hasOwn` — so a document carrying\n * prototype-bearing maps, or running under a polluted `Object.prototype`, is\n * validated and compiled from own keys alone. Reading any wider here would show\n * an author a value the page will not carry, and spread it into the op that\n * stores it; an inherited accessor would also RUN during the read.\n */\n/**\n * The value an own DATA property holds, or `undefined` when there is none to\n * read.\n *\n * The single descriptor read this module addresses anything through. A bracket\n * read runs an own accessor, and every tier of a style address is walked while\n * `sharedValueAt` inspects a selection for a panel — so a getter with a side\n * effect fires from rendering and a throwing one aborts the read.\n *\n * Every tier, because the address has four and they were not all covered by\n * fixing the innermost one: the state, the breakpoint, the property, and each\n * path segment inside the value. A guard on some of them is a guard on none, as\n * the first getter met decides the outcome.\n *\n * The descriptor subsumes the ownership check — an inherited property has none\n * here — so this replaces `Object.hasOwn` rather than joining it.\n */\nfunction ownData(holder: object, key: string): unknown {\n  const part = Object.getOwnPropertyDescriptor(holder, key);\n  return part !== undefined && \"value\" in part ? part.value : undefined;\n}\n\nfunction ownValue(value: CompositeValue, name: string): StyleValue | undefined {\n  // An accessor reads as ABSENT rather than as a value, and the residue is\n  // worth naming: two nodes that both hold one at the same address then look\n  // equally unset, so a control shows nothing and typing sets them both. That\n  // is benign — nothing real is overwritten, because such a value cannot be\n  // stored at all. `applyOp` refuses it: \"styles\" holds a value JSON cannot\n  // carry unchanged. So it is only ever met on nodes a caller built in memory.\n  return ownData(value, name) as StyleValue | undefined;\n}\n\n/** The value at a path inside one property's stored value. */\nfunction readAtPath(\n  value: StyleValue | undefined,\n  path: readonly string[]\n): StyleValue | undefined {\n  let at = value;\n  for (const step of path) {\n    if (!isComposite(at)) return undefined;\n    at = ownValue(at, step);\n  }\n  return at;\n}\n\n/**\n * One property's value with `next` written at `path`.\n *\n * Rebuilt rather than mutated at every level, because the document the editor\n * holds is the one React renders from: writing through a nested reference\n * changes a value the previous render is still displaying, and the two states\n * differ with nothing having re-rendered.\n */\nfunction writeAtPath(\n  value: StyleValue | undefined,\n  path: readonly string[],\n  next: StyleValue\n): StyleValue {\n  if (path.length === 0) return next;\n  const [step, ...rest] = path;\n  // A scalar standing where a composite is addressed is REPLACED rather than\n  // descended into. It happens when a union moves between its arms — a radius\n  // stored as one measurement, then edited per corner — and preserving the\n  // scalar would leave a value that is neither arm.\n  const parent: CompositeValue = isComposite(value) ? value : {};\n  return { ...parent, [step]: writeAtPath(ownValue(parent, step), rest, next) };\n}\n\n/**\n * One property's value with `path` removed, or `undefined` when nothing is left.\n *\n * Pruning upward matters because an emptied container is not the same as an\n * absent one to anything that reads the envelope: an empty record still counts\n * as a value set at this breakpoint, so a reset that left one behind would show\n * a control as authored-here with nothing in it.\n */\nfunction clearAtPath(\n  value: StyleValue | undefined,\n  path: readonly string[]\n): StyleValue | undefined {\n  if (path.length === 0) return undefined;\n  if (!isComposite(value)) return value;\n  const [step, ...rest] = path;\n  // `in` walks the prototype chain, so an inherited name would be \"cleared\"\n  // from an own map that never held it — materialising the inherited value as\n  // an own key on the way.\n  if (!Object.hasOwn(value, step)) return value;\n  const next = clearAtPath(ownValue(value, step), rest);\n  const remaining: Record<string, StyleValue> = { ...value };\n  if (next === undefined) delete remaining[step];\n  else remaining[step] = next;\n  return Object.keys(remaining).length === 0 ? undefined : remaining;\n}\n\n/**\n * A value wrapped in the containers its path names.\n *\n * A control holds a scalar and an address; both the validator and the compiler\n * take the property's WHOLE value. Building the containers in one place is what\n * lets the commit judge exactly the shape the preview compiled — two copies\n * would agree until either moved.\n */\nexport function styleValueAtPath(\n  path: readonly string[],\n  value: StyleValue\n): StyleValue {\n  let wrapped = value;\n  for (let index = path.length - 1; index >= 0; index -= 1) {\n    wrapped = { [path[index]]: wrapped };\n  }\n  return wrapped;\n}\n\n/** The value a control is currently showing, or `undefined` when nothing set it. */\nexport function readStyleValue(\n  styles: NodeStyles | undefined,\n  address: StyleAddress\n): StyleValue | undefined {\n  const values = valuesAt(styles, address.state, address.breakpoint);\n  if (values === undefined) return undefined;\n  return readAtPath(ownValue(values, address.property), address.path);\n}\n\n/**\n * The stored values at one state × breakpoint, by own keys at every level.\n *\n * Every level is guarded for two reasons at once, and the second is the one\n * that bites. The envelope is a plain object, so a state or breakpoint name\n * reached through a PROTOTYPE is one the compiler will not read — that is what\n * `Object.hasOwn` is for.\n *\n * And every level is tested for being a record before it is read at all,\n * because the envelope arrives from storage rather than from this editor. A\n * migration, a DTCG import or a hand-edited row can leave `{ base: null }`\n * here, and the field's own guard admits it: it checks that `nodes` is an\n * array and no more, deliberately, so a malformed document does not throw\n * inside the render. `Object.hasOwn(null, …)` throws, which is precisely the\n * failure that guard exists to prevent — and it throws during render, so it\n * takes the whole Style tab down and leaves the author no way to repair the\n * value that broke it.\n *\n * This is the CHOKEPOINT for that: reading a value, writing one and clearing\n * one all come through here, so guarding it covers every path into a tier\n * rather than the one path someone remembered.\n *\n * The guard is deliberately NOT the engine's `isPlainRecord`, which answers a\n * different question. That one asks whether a value is JSON-shaped, and refuses\n * anything carrying a prototype — which would refuse the very shapes the own-key\n * rule above exists to handle correctly, reading nothing from a map whose own\n * keys are perfectly good. What is needed here is only whether own keys can be\n * read from the value AT ALL, which is the question `Object.hasOwn` throws on.\n */\n/**\n * Whether own keys can be read from this at all.\n *\n * The narrowest question that prevents the throw, and narrower on purpose than\n * \"is this a record\". `Object.hasOwn` rejects a prototype-reached key by\n * itself, so a map carrying a prototype is handled correctly by the checks that\n * follow and must not be refused here — refusing it would drop values the\n * document really does own. What it cannot survive is `null` or a primitive,\n * which is the whole of what this excludes.\n */\nfunction hasOwnKeys(value: unknown): value is Record<string, never> {\n  return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Whether a record carries at least one own key.\n *\n * The LOOP stops at the first own key; the ENUMERATION does not, and the\n * difference is worth stating because it is easy to read this as bounded and it\n * is not. `for...in` asks the engine for the record's key list before the body\n * runs, so this is O(n) in the record's width however early it returns —\n * measured here at 0.08ms for a thousand keys, 10.75ms for a hundred thousand\n * and 103ms for a million. `Object.keys(...).length > 0` costs the same and\n * allocates as well, which is the only reason to prefer this form.\n *\n * No bounded alternative exists at this layer: JavaScript has no O(1) emptiness\n * test for a plain object, and this package publishes no list of style property\n * names to probe instead. The width is therefore a property of the DOCUMENT,\n * and the place to bound it is where a document is admitted.\n *\n * What makes that acceptable rather than merely unavoidable: the compiler\n * enumerates the same record the same way — `validateStyleValues` iterates it\n * with a bare `for...in` — so a values record wide enough to cost this marker\n * anything has already cost the compile that produced the page. The bound the\n * engine DOES apply, `MAX_SCANNED_KEYS` in `boundedKeys`, is over the\n * breakpoint DEFINITIONS record, which this no longer walks at all.\n */\nfunction hasAnyOwnKey(record: object): boolean {\n  for (const key in record) {\n    if (Object.hasOwn(record, key)) return true;\n  }\n  return false;\n}\n\nfunction valuesAt(\n  styles: NodeStyles | undefined,\n  state: StyleState,\n  breakpoint: BreakpointId\n): StyleValues | undefined {\n  if (!hasOwnKeys(styles)) return undefined;\n  const breakpoints = ownData(styles, state);\n  if (!hasOwnKeys(breakpoints)) return undefined;\n  const values = ownData(breakpoints, breakpoint);\n  return hasOwnKeys(values) ? values : undefined;\n}\n\n/**\n * Whether a state holds any declaration of its own, at any breakpoint.\n *\n * Here rather than beside the control that draws the answer, because this file\n * is the chokepoint for reading this envelope and the reading is the whole\n * difficulty. The value arrives from storage, so a migration, a DTCG import or\n * a hand-edited row can leave `hover: null` or `{ base: null }` behind, and the\n * field's own guard admits both — it checks that `nodes` is an array and no\n * more, deliberately, so a malformed document stays repairable instead of\n * throwing. `Object.values(null)` throws during RENDER, which takes the Style\n * tab down and removes the only surface that could repair the value that broke\n * it.\n *\n * Own keys at every level, for the reason `valuesAt` gives: a state or\n * breakpoint reached through a PROTOTYPE is one the compiler will not read, so\n * reporting it as styled would mark a state whose values never reach the page.\n *\n * A PLAIN RECORD at every level, and the engine's own predicate rather than a\n * looser one, for the same reason stated positively: this must agree with what\n * the COMPILER will read. An array is a non-null object, so a guard asking only\n * that would accept `hover: []` and count its numeric indexes as declarations —\n * while `isPlainRecord` makes the compiler emit nothing for it. A state marked\n * as styled that cannot affect the page is worse than an unmarked one, because\n * it sends an author looking for a value that was never going to apply.\n *\n * A TIER THE SHEET HAS. A value stored under a breakpoint the site has since\n * deleted is not reachable by any visitor — the compiler iterates the\n * breakpoint contexts it was given and never looks at the rest — so counting it\n * would mark a state whose appearance nobody can see.\n *\n * EMPTY IS NOT SET. Both levels are sparse and either can survive empty — a\n * state whose last declaration was cleared leaves the keys behind — so a\n * presence test reports a state as styled when it carries nothing, which is\n * precisely the false reassurance the marker exists to remove.\n *\n * REFUSED IS NOT UNSET, and this is the one boundary here that is a judgement\n * rather than a fact about the shape. A declaration the current policy rejects\n * emits no CSS, so validating here would make the marker agree with the sheet\n * in that case too. It is deliberately not done: a policy is a HOST SETTING\n * that changes without the document changing, so a value refused today is\n * still the author's, still deliberate, and restored by a policy change. A\n * marker that vanished for it would report their work as ABSENT rather than as\n * refused — and refusal already has a better channel, the control that shows\n * the value and says why it did not apply.\n *\n * So this answers \"you have set something here that this site can express\",\n * and the tiers and shapes above are the part of that question decided by the\n * document rather than by configuration.\n */\nexport function stateHasOwnValues(\n  styles: NodeStyles | undefined,\n  state: StyleState,\n  breakpoints: BreakpointSet | undefined\n): boolean {\n  if (!isPlainRecord(styles)) return false;\n  const tiers = ownData(styles, state);\n  if (!isPlainRecord(tiers)) return false;\n\n  const holdsValues = (tier: string): boolean => {\n    const values = ownData(tiers, tier);\n    return isPlainRecord(values) && hasAnyOwnKey(values);\n  };\n\n  /*\n   * Driven by the tiers the SHEET has, asked of the compiler's own reader.\n   * `breakpointContexts` is what decides which breakpoints a site actually has\n   * — it drops a definition whose bound it cannot use and claims each id once —\n   * so a value stored under a tier that has since been deleted emits nothing at\n   * all. Measured: the same node compiles to 73 bytes under a known tier and to\n   * an empty sheet under an unknown one.\n   *\n   * Iterating the KNOWN ids rather than the stored ones is also what bounds\n   * this. A stored record arrives from storage and can be arbitrarily wide, so\n   * asking it for its keys reads all of them before any filter can narrow the\n   * set — on every render, once per non-base state. Asking the sheet instead\n   * costs one lookup per tier the site actually has, which is a handful.\n   */\n  if (breakpoints !== undefined) {\n    return breakpointContexts(breakpoints).some(context =>\n      holdsValues(context.id)\n    );\n  }\n\n  /*\n   * With no breakpoints known there is NO ANSWER, and this returns false rather\n   * than guessing one.\n   *\n   * The marker means \"you have set something here that this site can express\",\n   * and without the site's tiers that question cannot be asked at all — a value\n   * under a tier the sheet lacks reaches nobody, and which tiers the sheet has\n   * is exactly what is missing. Reporting from the stored keys instead would\n   * answer a different question and read as the same dot.\n   *\n   * It is also what makes this bounded BY CONSTRUCTION rather than by a cap.\n   * The stored record arrives from storage and can be arbitrarily wide, and\n   * every way of walking it — `Object.keys`, `for...in` with an early break —\n   * asks the engine for the whole key list first, so an early exit bounds the\n   * BODY and not the enumeration. Measured by review: a plain-object probe\n   * breaking after 256 entries still grew from ~32ms at 100,000 keys to ~573ms\n   * at 1,000,000. A cap cannot fix that; not enumerating can.\n   *\n   * The product always supplies them — `BlocksField` passes the same\n   * breakpoints it compiles the canvas against — so this is the path for a host\n   * that has not adopted the marker rather than a case an author reaches.\n   */\n  return false;\n}\n\n/** The whole envelope with one state × breakpoint replaced, pruning what empties. */\nfunction withValues(\n  styles: NodeStyles | undefined,\n  state: StyleState,\n  breakpoint: BreakpointId,\n  values: StyleValues | undefined\n): NodeStyles {\n  const states: NodeStyles = { ...styles };\n  // Read through the descriptor like every other tier: a spread of\n  // `states[state]` invokes an own accessor exactly as a bare bracket read\n  // does, and this runs on the way to writing rather than only on the way to\n  // reading.\n  const breakpoints: Partial<Record<BreakpointId, StyleValues>> = {\n    ...(ownData(states, state) as Partial<Record<BreakpointId, StyleValues>>),\n  };\n  if (values === undefined || Object.keys(values).length === 0) {\n    delete breakpoints[breakpoint];\n  } else {\n    // DEFINED rather than assigned. A breakpoint id is site-supplied free text\n    // — nothing in `validateBreakpoints` restricts its characters — and the id\n    // `__proto__` reaches JavaScript's legacy prototype setter through an\n    // ordinary assignment: the key never becomes an own property, the map reads\n    // as empty, the state is pruned, and the write reports success with nothing\n    // to do. Every control at that breakpoint would be unable to author its\n    // first value, silently. The spread above is safe on its own, because\n    // spreading DEFINES own properties rather than setting them.\n    Object.defineProperty(breakpoints, breakpoint, {\n      value: values,\n      enumerable: true,\n      writable: true,\n      configurable: true,\n    });\n  }\n  if (Object.keys(breakpoints).length === 0) delete states[state];\n  else states[state] = breakpoints;\n  return states;\n}\n\n/** The op that writes an envelope, removing the field outright when it empties. */\nfunction patchOp(nodeId: string, styles: NodeStyles): BuilderOp {\n  if (Object.keys(styles).length > 0) {\n    return { kind: \"update\", id: nodeId, patch: { styles } };\n  }\n  // Named for removal rather than set to `undefined`. An op is persisted, and\n  // `JSON.stringify` drops an undefined value — so the inverse of an edit that\n  // ADDED the first style would arrive back from storage as an empty patch and\n  // undo nothing.\n  return { kind: \"update\", id: nodeId, patch: {}, unset: [\"styles\"] };\n}\n\n/**\n * The issues that refuse a write, as distinct from those that annotate it.\n *\n * Severity is read off each issue rather than assumed from the list being\n * non-empty: a value the catalog accepts while remarking on it would otherwise\n * be refused, and the control would show an error for a value that is fine.\n */\nfunction errorsIn(\n  issues: readonly ValidationIssue[]\n): readonly ValidationIssue[] {\n  return issues.filter(issue => issue.severity === \"error\");\n}\n\n/**\n * What the validator says about the ONE leaf an edit writes.\n *\n * Only that leaf. A sibling that is already invalid is not this edit's fault,\n * and judging anything wider lets one bad value block the controls around it\n * with no way to fix them: a breakpoint-wide check blocks every control on the\n * breakpoint, and a property-wide one blocks every side of a margin whose top\n * is malformed. It is also what keeps the commit judging exactly what the\n * preview compiled, so a clean drag cannot snap back on release. The document\n * validator still reads the whole map where completeness is the question.\n *\n * `strict` because the author is writing this value right now: a property this\n * build does not know is a mistake to report at the keystroke, not a document\n * from a newer engine to be forgiving about.\n */\nfunction judge(\n  subject: StyleValues,\n  policy: StylePolicy | undefined\n): readonly ValidationIssue[] {\n  return validateStyleValues(\n    subject,\n    \"\",\n    \"strict\",\n    undefined,\n    false,\n    policy?.tokens,\n    { mayFetchUrl: policy?.mayFetchUrl }\n  );\n}\n\n/**\n * The op that moves a node from one envelope to another, or `null`.\n *\n * Asked with the op layer's OWN comparison rather than a second one, so the\n * answer here and the answer `applyOp` would give cannot differ. An empty\n * envelope stands in for an absent one: a node with no styles and a node whose\n * styles cleared to nothing are the same document.\n *\n * The STYLE predicate, not the general stored one: the compiler sorts a\n * composite's keys, so a reorder renders identically and an op for it would\n * rewrite the document and cost an undo entry for nothing.\n */\nfunction opFor(\n  nodeId: string,\n  before: NodeStyles | undefined,\n  after: NodeStyles\n): BuilderOp | null {\n  return sameStyleValue(before ?? {}, after) ? null : patchOp(nodeId, after);\n}\n\n/** The issues that accompany an accepted write. */\nfunction acceptedWarnings(\n  issues: readonly ValidationIssue[]\n): readonly ValidationIssue[] {\n  return issues.filter(issue => issue.severity !== \"error\");\n}\n\n/**\n * Validate the values that would result, and answer with the op or the reasons.\n */\nfunction writeResult(\n  nodeId: string,\n  before: NodeStyles | undefined,\n  after: NodeStyles,\n  subject: StyleValues,\n  policy: StylePolicy | undefined\n): StyleWrite {\n  const issues = judge(subject, policy);\n  const errors = errorsIn(issues);\n  if (errors.length > 0) return { ok: false, issues: errors };\n  return {\n    ok: true,\n    op: opFor(nodeId, before, after),\n    warnings: acceptedWarnings(issues),\n  };\n}\n\n/** The envelope one write produces, and the leaf it has to be judged on. */\nfunction nextStyles(\n  styles: NodeStyles | undefined,\n  address: StyleAddress,\n  value: StyleValue\n): { readonly after: NodeStyles; readonly subject: StyleValues } {\n  const current = valuesAt(styles, address.state, address.breakpoint);\n  const values: StyleValues = {\n    ...current,\n    [address.property]: writeAtPath(\n      current === undefined ? undefined : ownValue(current, address.property),\n      address.path,\n      value\n    ),\n  };\n  return {\n    after: withValues(styles, address.state, address.breakpoint, values),\n    subject: { [address.property]: styleValueAtPath(address.path, value) },\n  };\n}\n\n/** The op that sets one control's value, or the reasons the value was refused. */\nexport function styleWriteOp(\n  nodeId: string,\n  styles: NodeStyles | undefined,\n  address: StyleAddress,\n  value: StyleValue,\n  policy?: StylePolicy\n): StyleWrite {\n  const next = nextStyles(styles, address, value);\n  return writeResult(nodeId, styles, next.after, next.subject, policy);\n}\n\n/** One address and the value to put there. */\nexport interface StyleWriteRequest {\n  readonly address: StyleAddress;\n  readonly value: StyleValue;\n}\n\n/**\n * ONE op that sets several addresses on ONE node.\n *\n * ## Why this is not a list of `styleWriteOp` results\n *\n * A style op patches the WHOLE `styles` envelope. Four calls to `styleWriteOp`\n * built from the same node therefore produce four complete envelopes that each\n * know about one side, and whichever is applied last wins — the other three\n * sides are silently dropped. `batchStyleWriteOps` documents the same mechanism\n * from the other direction, where an op built from the primary carried the\n * primary's unrelated declarations to every block in the selection.\n *\n * Folding is what fixes it: each write is computed against the envelope the\n * previous one produced, so the last envelope carries all of them and is the\n * only op anyone needs. That it is ONE op rather than a group is also what\n * makes \"one gesture, one undo entry\" a property of the value layer instead of\n * something every caller has to remember to ask `applyAll` for.\n *\n * ## Judged per write, not on the merged result\n *\n * Every write is validated on its own leaf, exactly as the singular does.\n * Judging the folded envelope instead would look at the LAST value written to a\n * property and miss the other three — so a drag that set three legal sides and\n * one impossible one would commit all four.\n *\n * Atomic: the first refusal ends it and no op is returned. A gesture that\n * writes some of the sides it promised is not a smaller version of the edit the\n * author asked for.\n *\n * An empty list is not an error and produces `op: null` — the same answer as a\n * write that changes nothing, which is what it is.\n *\n * @param nodeId - the node being edited\n * @param styles - that node's own styles before the edit\n * @param writes - the addresses to set, applied in order\n * @param policy - the site policy every value is judged under\n * @returns one op for all of them, or the reasons the first refusal gives\n */\nexport function styleWriteOps(\n  nodeId: string,\n  styles: NodeStyles | undefined,\n  writes: readonly StyleWriteRequest[],\n  policy?: StylePolicy\n): StyleWrite {\n  let after: NodeStyles | undefined = styles;\n  const warnings: ValidationIssue[] = [];\n  for (const write of writes) {\n    const next = nextStyles(after, write.address, write.value);\n    const issues = judge(next.subject, policy);\n    const errors = errorsIn(issues);\n    if (errors.length > 0) return { ok: false, issues: errors };\n    warnings.push(...acceptedWarnings(issues));\n    after = next.after;\n  }\n  return {\n    ok: true,\n    // Against the ORIGINAL envelope, so a gesture that ends where it started\n    // costs no undo entry however many addresses it passed through.\n    op: opFor(nodeId, styles, after ?? {}),\n    warnings,\n  };\n}\n\n/**\n * The op that clears one control's value at this state × breakpoint.\n *\n * Clearing is not writing an empty string: a property with no entry falls back\n * through the cascade to whatever a class, a block default or a wider\n * breakpoint set, which is what an author asking to reset a control means. A\n * stored empty value would instead pin the property to nothing here and win\n * over the tier the author wanted back.\n */\nexport function styleClearOp(\n  nodeId: string,\n  styles: NodeStyles | undefined,\n  address: StyleAddress,\n  policy?: StylePolicy\n): StyleWrite {\n  const current = valuesAt(styles, address.state, address.breakpoint);\n  const values: StyleValues = { ...current };\n  const remaining = clearAtPath(\n    Object.hasOwn(values, address.property)\n      ? values[address.property]\n      : undefined,\n    address.path\n  );\n  if (remaining === undefined) delete values[address.property];\n  else values[address.property] = remaining;\n  // Nothing is being written, so there is nothing to judge: removing a value\n  // cannot make a document invalid, and validating what REMAINS would refuse a\n  // reset because of a sibling the author is not touching.\n  return writeResult(\n    nodeId,\n    styles,\n    withValues(styles, address.state, address.breakpoint, values),\n    {},\n    policy\n  );\n}\n","/**\n * Breakpoint definitions, and the rules an editor must hold them to.\n *\n * The style compiler reads a site's breakpoints from stored settings and treats\n * them as untrusted: a definition it cannot use is DROPPED rather than raising,\n * because throwing would take down every page over one bad settings record. The\n * consequence for an editor is that almost every way of getting a breakpoint\n * wrong is silent — the definition simply stops existing, and the styles saved\n * against it are reported stale later, far from the screen that caused it.\n *\n * So this is not defensive validation of arbitrary input. Each rule below names\n * a definition the compiler would discard, checked here so the editor can say so\n * while the author is still looking at the field.\n *\n * The types and the cap are IMPORTED from the engine, not restated. This module\n * lived in `@nextlyhq/ui` until 2026-08-12, where it could not import the engine\n * — that package is the block-agnostic layer — so it mirrored the engine's\n * shapes structurally and kept its own copy of the cap. Two implementations of\n * one rule agree the day they are written and drift silently after, which is\n * what the `derived-checks` skill is about, and it is why this belongs\n * here: `packages/builder` already depends on the engine and can ASK.\n *\n * What is still restated, stated plainly rather than left to be discovered: the\n * per-rule DROP decisions below mirror `compile-page.ts` rather than calling it.\n * The compiler makes those decisions inline while emitting, so there is no\n * predicate to call yet. Exporting one from the engine — so the compiler and\n * this editor ask the same function — is the remaining half of this fix, and it\n * is an engine change, not a builder one.\n *\n * @module breakpoints\n */\nimport {\n  authoredBreakpoints,\n  BASE_BREAKPOINT,\n  BREAKPOINT_AXES,\n  MAX_BREAKPOINT_ID_LENGTH,\n  MAX_BREAKPOINTS_PER_AXIS,\n  type BreakpointAxis,\n  type BreakpointDef,\n  breakpointContexts,\n  type BreakpointContextOptions,\n  type BreakpointId,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * Re-exported from the engine, not restated.\n *\n * Every one of these is a value the COMPILER decides and this editor only\n * reports on, so a local copy is a second opinion that drifts silently:\n *\n * - `BASE_BREAKPOINT` — the reserved id for the unconditional context. The\n *   compiler claims it before reading settings, so a stored definition reusing\n *   it contributes nothing. A local `\"base\"` literal would keep rejecting the\n *   old id and start accepting a renamed one, admitting definitions compilation\n *   drops.\n * - `BREAKPOINT_AXES` — not merely a list. The engine reads it as cascade\n *   PRECEDENCE and uses the order to decide which cross-axis duplicate wins, so\n *   a second array that reorders marks the opposite definition as the duplicate.\n * - `MAX_BREAKPOINTS_PER_AXIS` — the cap the compiler enforces while emitting.\n *\n * @experimental\n */\nexport {\n  authoredBreakpoints,\n  BASE_BREAKPOINT,\n  BREAKPOINT_AXES,\n  MAX_BREAKPOINTS_PER_AXIS,\n};\nexport type { BreakpointAxis, BreakpointDef, BreakpointSet };\n\n/**\n * Why a definition would not survive compilation.\n *\n * @experimental\n */\nexport type BreakpointIssueCode =\n  | \"id-too-long\"\n  | \"id-required\"\n  | \"id-reserved\"\n  | \"id-duplicate\"\n  | \"label-required\"\n  | \"label-duplicate\"\n  | \"width-required\"\n  | \"width-not-positive\"\n  | \"width-duplicate\"\n  | \"second-unbounded-container\"\n  | \"over-axis-limit\";\n\n/**\n * One reason one definition is unusable, addressed to the field that caused it.\n *\n * @experimental\n */\nexport interface BreakpointIssue {\n  axis: BreakpointAxis;\n  /** Index within its axis, so an editor can mark the row. */\n  index: number;\n  field: \"id\" | \"label\" | \"maxWidth\";\n  code: BreakpointIssueCode;\n  message: string;\n}\n\n/**\n * The base tier's name wherever the editor names a device. The device\n * switcher calls it Desktop whatever the site's settings label it, so the\n * inspector, saying where a value came from or what a reset reveals, uses the\n * same word rather than a second name for the tier on the same screen.\n */\nexport const BASE_DEVICE_LABEL = \"Desktop\";\n\n/**\n * How many definitions an axis may hold in STORED settings.\n *\n * The viewport axis is one lower than the declared limit because its\n * unconditional context is inserted by the compiler rather than stored, and it\n * counts against the same cap. The container axis stores its own unbounded\n * definition, so the whole cap is available to it.\n *\n * @experimental\n */\nexport function storedLimitFor(axis: BreakpointAxis): number {\n  return axis === \"viewport\"\n    ? MAX_BREAKPOINTS_PER_AXIS - 1\n    : MAX_BREAKPOINTS_PER_AXIS;\n}\n\n/**\n * Whether two sets describe the same breakpoints.\n *\n * By CONTENT, never by object identity. The prop contract does not promise a\n * stable reference — a host that rebuilds an equal object on any parent render\n * is within its rights — so identity answers \"has the read changed\" wrongly in\n * both directions, and a surface that asks it gets a different wrong answer\n * depending on which way the host happens to render.\n *\n * Compares the AUTHORED sets, so a stored base row on one side and none on the\n * other is not a difference: the compiler prepends that context either way, and\n * treating it as a change would report a set that renders identically as new.\n *\n * @experimental\n */\nexport function sameBreakpoints(\n  a: BreakpointSet | undefined,\n  b: BreakpointSet | undefined\n): boolean {\n  const shape = (set: BreakpointSet | undefined) => {\n    const authored = authoredBreakpoints(set);\n    const axis = (defs: readonly BreakpointDef[]) =>\n      defs.map(def => `${def.id}\\u0000${def.label}\\u0000${def.maxWidth ?? \"\"}`);\n    return [axis(authored.viewport), axis(authored.container)];\n  };\n  return JSON.stringify(shape(a)) === JSON.stringify(shape(b));\n}\n\n/**\n * Whether a bound is one the compiler will keep.\n *\n * @experimental\n */\nexport function isUsableWidth(width: number | undefined): width is number {\n  return typeof width === \"number\" && Number.isFinite(width) && width > 0;\n}\n\n/**\n * What is wrong with one row's name, if anything, claiming it on its axis.\n *\n * Names are what the device menu shows, and new ids are made from them, so two\n * rows on one axis with the same name are two buttons nobody can tell apart.\n * Compared the way a reader would: case and edge spaces aside.\n */\nfunction claimLabel(\n  label: string,\n  seen: Set<string>\n): { code: BreakpointIssueCode; message: string } | undefined {\n  const key = label.trim().toLowerCase();\n  if (key.length === 0) {\n    return { code: \"label-required\", message: \"Give this breakpoint a label.\" };\n  }\n  if (seen.has(key)) {\n    return {\n      code: \"label-duplicate\",\n      message: `Another breakpoint is already called \"${label.trim()}\".`,\n    };\n  }\n  seen.add(key);\n  return undefined;\n}\n\n/**\n * Every reason the given set would lose a definition on compilation.\n *\n * Ordered by axis and then by row so an editor can present them beside the\n * fields. Ids are checked across BOTH axes together, because that is the scope\n * the compiler claims them in: an id repeated on the other axis is dropped just\n * as one repeated within an axis is.\n *\n * @experimental\n */\nexport function validateBreakpoints(set: BreakpointSet): BreakpointIssue[] {\n  const issues: BreakpointIssue[] = [];\n  // Seeded with the reserved id, which the compiler claims before it reads any\n  // stored definition — so a definition naming it is a duplicate of something\n  // the author cannot see in the list.\n  const claimedIds = new Set<string>([BASE_BREAKPOINT]);\n\n  for (const axis of BREAKPOINT_AXES) {\n    const defs = set[axis] ?? [];\n    const widthsSeen = new Set<number>();\n    const labelsSeen = new Set<string>();\n    let unboundedSeen = false;\n    const limit = storedLimitFor(axis);\n    // WHICH rows the cap drops, decided the way the compiler decides it: it\n    // sorts widest-first and keeps the front of that list, so the casualties\n    // are the narrowest definitions, not the last ones stored. Marking by\n    // stored position instead would send an author to delete a breakpoint the\n    // compiler was going to keep — and would say nothing about the one it drops.\n    const overLimit = new Set(\n      defs\n        .map((def, index) => ({ def, index }))\n        .sort(\n          (a, b) => (b.def.maxWidth ?? Infinity) - (a.def.maxWidth ?? Infinity)\n        )\n        .slice(limit)\n        .map(entry => entry.index)\n    );\n\n    defs.forEach((def, index) => {\n      const at = (\n        field: BreakpointIssue[\"field\"],\n        code: BreakpointIssueCode,\n        message: string\n      ): void => {\n        issues.push({ axis, index, field, code, message });\n      };\n\n      // Compared VERBATIM, never normalised. The compiler keys styles by the\n      // stored string, so `\" tablet \"` and `\"tablet\"` are two different\n      // breakpoints to it; trimming here would report one legal set as\n      // duplicates and another as using the reserved id, and since a saved id\n      // is not editable the author would have no way to answer either.\n      const id = def.id;\n      if (id.length === 0) {\n        at(\"id\", \"id-required\", \"Give this breakpoint an id.\");\n      } else if (id.length > MAX_BREAKPOINT_ID_LENGTH) {\n        /*\n         * The COMPILER's limit, not one chosen here. `namedDefinition` drops a\n         * definition whose id exceeds it, so an id this screen accepted would\n         * save, report success, and then exist nowhere — with every style filed\n         * under it silently unapplied. Two gates disagreeing about what is\n         * storable is worse than either being strict.\n         */\n        at(\n          \"id\",\n          \"id-too-long\",\n          `An id can be at most ${MAX_BREAKPOINT_ID_LENGTH} characters.`\n        );\n      } else if (id === BASE_BREAKPOINT) {\n        at(\n          \"id\",\n          \"id-reserved\",\n          `\"${BASE_BREAKPOINT}\" is the built-in unconditional breakpoint. Choose another id.`\n        );\n      } else if (claimedIds.has(id)) {\n        at(\n          \"id\",\n          \"id-duplicate\",\n          `Another breakpoint already uses the id \"${id}\". Ids must be unique across both axes.`\n        );\n      } else {\n        claimedIds.add(id);\n      }\n\n      const labelIssue = claimLabel(def.label, labelsSeen);\n      if (labelIssue) at(\"label\", labelIssue.code, labelIssue.message);\n\n      if (def.maxWidth === undefined) {\n        // An unbounded definition means different things per axis, and only the\n        // container axis has a use for one.\n        if (axis === \"viewport\") {\n          at(\n            \"maxWidth\",\n            \"width-required\",\n            \"A viewport breakpoint needs a maximum width. Without one it would apply at every width and override the base.\"\n          );\n        } else if (unboundedSeen) {\n          at(\n            \"maxWidth\",\n            \"second-unbounded-container\",\n            \"Another container breakpoint is already unbounded. Two cover the same range and one would silently win.\"\n          );\n        } else {\n          unboundedSeen = true;\n        }\n      } else if (!isUsableWidth(def.maxWidth)) {\n        at(\n          \"maxWidth\",\n          \"width-not-positive\",\n          \"Maximum width must be a positive number of pixels.\"\n        );\n      } else if (widthsSeen.has(def.maxWidth)) {\n        at(\n          \"maxWidth\",\n          \"width-duplicate\",\n          `Another ${axis} breakpoint already ends at ${def.maxWidth}px. Both would produce the same query and one would silently win.`\n        );\n      } else {\n        widthsSeen.add(def.maxWidth);\n      }\n\n      if (overLimit.has(index)) {\n        at(\n          \"id\",\n          \"over-axis-limit\",\n          `An axis holds at most ${limit} breakpoints, widest kept. This one would be dropped.`\n        );\n      }\n    });\n  }\n\n  return issues;\n}\n\n/**\n * Every breakpoint whose rules are live while the editor is showing one.\n *\n * `styleProvenance` needs this and cannot derive it: which declarations are in\n * PLAY is a fact about the width being viewed, while the breakpoint being edited\n * only decides whether the winner among them belongs to this control. An editor\n * simulating a narrow viewport inside a wide window is the ordinary case.\n *\n * ## Read from what is EMITTED, never from the stored set\n *\n * The stored axes and the emitted ones disagree, and this is the one question\n * where that matters. `breakpointContexts` drops a definition whose bound is\n * missing, non-finite or at or below zero; keeps only the FIRST of a duplicated\n * id; allows one unbounded definition on the container axis and none on the\n * viewport; and slices each axis to the per-axis cap. A set read raw therefore\n * names breakpoints no stylesheet ever mentions, and reports a value keyed to a\n * dropped id as live.\n *\n * That failure is SILENT in both directions: a badge naming a real-looking id\n * looks identical whether or not a rule was written under it, and a value whose\n * breakpoint was dropped is a value the author cannot see the source of. Asking\n * the compiler's own normaliser is what keeps the panel and the page saying the\n * same thing.\n *\n * ## Outward, never inward\n *\n * The model is DESKTOP-FIRST — every bounded definition compiles to\n * `@media (max-width: N)` — so a narrow width satisfies its own query and every\n * WIDER one as well. Showing a 768px breakpoint means the 768 rules apply, the\n * 1024 rules apply, and the base rules underneath them all. The set therefore\n * runs outward from the edited definition, never inward.\n *\n * ## An unknown container context is EXCLUDED, not assumed live\n *\n * The viewport's unbounded context matches at every width and is always in play.\n * The container axis is not its counterpart: even at its widest a container\n * context emits `@container (min-width: 0)`, which matches only an element that\n * HAS a query-container ancestor. Whether the selected block has one is a fact\n * about the rendered tree that this arithmetic cannot see, so treating it as\n * universally live lets a container declaration win for a root block the browser\n * is applying nothing to — a false indicator, in the direction that states\n * something wrong rather than saying nothing.\n *\n * So the container axis contributes only when the author is EDITING that axis,\n * which is the one case where they have said which context they mean. Otherwise\n * it is left out entirely.\n *\n * The cost is the reverse — a value genuinely arriving from a container\n * breakpoint is attributed to whatever the viewport axis says while a viewport\n * breakpoint is being edited — and that is the safer of the two, because a\n * control that under-reports its origin is quiet where one that over-reports is\n * wrong.\n *\n * An id belonging to no emitted context yields the viewport's unbounded context\n * alone, which is what an unknown breakpoint actually leaves matching.\n *\n * @experimental\n */\nexport function liveBreakpointsFor(\n  set: BreakpointSet | undefined,\n  edited: BreakpointId\n): BreakpointId[] {\n  const contexts = breakpointContexts(set);\n  const chosen = contexts.find(context => context.id === edited);\n  /*\n   * The viewport's unbounded context alone. A container one is only included\n   * when the author is editing the container axis — see the note above: at its\n   * widest it still emits a query that matches only an element inside a query\n   * container, which this cannot know.\n   */\n  const unbounded = contexts\n    .filter(\n      context =>\n        !isUsableWidth(context.maxWidth) &&\n        (context.axis !== \"container\" || chosen?.axis === \"container\")\n    )\n    .map(context => context.id);\n  // An unknown id, or an unbounded context itself: neither adds anything to the\n  // contexts already matching.\n  if (chosen === undefined || !isUsableWidth(chosen.maxWidth)) return unbounded;\n  const width = chosen.maxWidth;\n  const wider = contexts\n    .filter(\n      context =>\n        context.axis === chosen.axis &&\n        isUsableWidth(context.maxWidth) &&\n        context.maxWidth >= width\n    )\n    .map(context => context.id);\n  return [...unbounded, ...wider];\n}\n\n/**\n * The breakpoints that apply where a write at `edited` lands, as the canvas\n * shows it: the edited axis's own band ({@link liveBreakpointsFor}), and on\n * the other axis the contexts the canvas is already applying (`live`).\n *\n * Both axes apply at once in the browser, so a value at the canvas's tablet\n * width still shows beneath a small-container value being edited.\n */\nexport function editedTierLive(\n  set: BreakpointSet | undefined,\n  edited: BreakpointId,\n  live: readonly BreakpointId[]\n): BreakpointId[] {\n  const axisOf = new Map(\n    breakpointContexts(set).map(context => [context.id, context.axis])\n  );\n  const axis = axisOf.get(edited);\n  const band = liveBreakpointsFor(set, edited);\n  const other = live.filter(\n    id => axisOf.has(id) && axisOf.get(id) !== axis && !band.includes(id)\n  );\n  return [...band, ...other];\n}\n\n/**\n * The breakpoints whose rules the BROWSER is currently applying.\n *\n * Asked of the browser rather than derived from the breakpoint being edited,\n * because those are different facts and only one of them decides what is on\n * screen. The edited breakpoint says where a write LANDS; which declarations are\n * in play is a property of the width the page is being viewed at, and the editor\n * renders its canvas inline rather than in a frame — so an ordinary window\n * narrow enough to satisfy `@media (max-width: 1024px)` has those rules active\n * while the panel is still editing the base breakpoint.\n *\n * Evaluated by `matchMedia` against each emitted context's OWN at-rule text, so\n * there is no second reading of what a breakpoint means: the compiler wrote the\n * query, and the browser answers it. Width arithmetic here would be a second\n * implementation of the same condition and would drift the moment the emitted\n * form changed.\n *\n * **Container contexts are excluded and cannot be answered this way.** A\n * `@container` query resolves against an element's query container, not the\n * viewport, so `matchMedia` has nothing to say about it — see\n * {@link liveBreakpointsFor}, which excludes them for the same reason.\n *\n * A runtime without `matchMedia` gets the unconditional contexts alone, which is\n * what is certainly live anywhere.\n *\n * @experimental\n */\nexport function matchedBreakpoints(\n  set: BreakpointSet | undefined,\n  matches: (query: string) => boolean,\n  options?: BreakpointContextOptions\n): BreakpointId[] {\n  const live: BreakpointId[] = [];\n  /*\n   * The queries the sheet was actually EMITTED under, preview option included.\n   *\n   * Asked without it, this compares the window against `@media` rules a preview\n   * compile never wrote — and the answer is not merely stale, it is confidently\n   * wrong in a direction that looks plausible: a narrow admin window reports\n   * tablet and mobile live while a wide canvas box is showing desktop.\n   *\n   * Passing the option makes the viewport contexts container queries, which the\n   * `@media` test below then declines to answer, so the result is the base\n   * context alone. That is silence rather than a wrong claim, and it is what a\n   * `matchMedia` caller can honestly say: a container query is a question about\n   * an element, and this function is only given a way to ask the window.\n   */\n  for (const context of breakpointContexts(set, options)) {\n    if (context.atRule === undefined) {\n      // The unconditional VIEWPORT context: no query to ask, and always\n      // applying. A container's widest context is not this case — it still\n      // carries `@container (min-width: 0)` and is filtered below.\n      live.push(context.id);\n      continue;\n    }\n    /*\n     * Only a MEDIA query is answerable here, and the at-rule's own prefix is\n     * what decides. An explicit axis check beside this would be a second\n     * decision about one question: a container context's at-rule is\n     * `@container (...)`, so it fails this test already, and the two could only\n     * ever disagree by drifting apart.\n     */\n    const condition = context.atRule.replace(/^@media\\s*/, \"\");\n    if (condition === context.atRule) continue;\n    if (matches(condition)) live.push(context.id);\n  }\n  return live;\n}\n\n/**\n * Every media condition the site's viewport breakpoints emit, for subscribing to.\n *\n * Beside {@link matchedBreakpoints} because they must agree on which contexts\n * carry a query and how its text is reduced to a condition — a subscriber\n * listening to a different set than the reader evaluates is a panel that stops\n * updating at exactly the widths it was added for.\n *\n * @experimental\n */\nexport function breakpointQueries(\n  set: BreakpointSet | undefined,\n  options?: BreakpointContextOptions\n): string[] {\n  const queries: string[] = [];\n  for (const context of breakpointContexts(set, options)) {\n    if (context.atRule === undefined) continue;\n    const condition = context.atRule.replace(/^@media\\s*/, \"\");\n    // The same single test {@link matchedBreakpoints} applies, deliberately.\n    if (condition !== context.atRule) queries.push(condition);\n  }\n  return queries;\n}\n","/**\n * Widths for the canvas: the width each breakpoint is previewed at, which\n * tiers a box of a given width shows, and how the frame is fitted and sized.\n *\n * ## The chosen breakpoint comes first, and the width follows from it\n *\n * The breakpoint the author is styling is a stored choice, `editingBreakpoint`\n * in `shell-state.ts`: the device the author picked (`breakpoint-switcher.tsx`),\n * or one the host asks the shell to show. It is never read off the width the\n * canvas measured: opening a panel or narrowing the window changes the room\n * the canvas has, and a breakpoint derived from that room moved every edit to\n * a breakpoint the author never picked.\n *\n * So the order is choice, then width. {@link editingBreakpointOf} turns the\n * stored choice into the breakpoint an edit goes to, and {@link previewWidth}\n * gives the width the canvas lays that breakpoint out at. Opening and closing\n * panels changes only the zoom that fits that width into the region\n * ({@link frameFitScale}), so the author always sees the layout of the\n * breakpoint they are editing.\n *\n * {@link breakpointsAtWidth} still answers \"which tiers does a box this wide\n * show\": the style inspector reads it to say which values are live at the\n * canvas's width.\n *\n * ## Why this reads `maxWidth` and not the emitted query text\n *\n * {@link matchedBreakpoints} evaluates each context's OWN at-rule through a\n * `matches` callback, and its docblock is emphatic that width arithmetic beside\n * it would be a second implementation of the same condition. That warning is\n * about parsing the emitted STRING, which is a second reading of what the\n * compiler wrote.\n *\n * This module does something different: it reads `maxWidth` off the context the\n * compiler produced, which is the same structured field `liveBreakpointsFor`\n * already decides with. The compiler derives its query text from that number,\n * so both are downstream of one value rather than two readings of one string.\n * `agreesWithTheEmittedQuery` in the tests pins them together, so a compiler\n * that changed to `min-width`, to a different unit, or to a half-open bound\n * fails here rather than silently disagreeing.\n *\n * ## The container axis is excluded\n *\n * For the reason {@link liveBreakpointsFor} gives: even at its widest a\n * container context emits `@container (min-width: 0)`, which matches only an\n * element that HAS a query container above it. Whether the selected block does\n * is a fact about the rendered tree that width arithmetic cannot see, so\n * including it would let a container declaration be reported live for a block\n * the browser is applying nothing to — wrong rather than quiet.\n *\n * @module canvas-width\n */\n\nimport {\n  BASE_BREAKPOINT,\n  breakpointContexts,\n  type BreakpointId,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { isUsableWidth } from \"../styles/breakpoints\";\n\nimport { usableScale, type CanvasZoom } from \"./canvas-zoom\";\n\n/**\n * The viewport tiers a canvas of this width is applying, widest first.\n *\n * The same question {@link matchedBreakpoints} answers for the browser window,\n * asked of a box whose width the editor owns instead. Under a preview compile\n * the window cannot answer at all — the tiers are container queries and\n * `matchMedia` has nothing to say about an element — which is why the canvas\n * has to answer for itself, and why the panel withholds its provenance\n * indicator until something does.\n *\n * Note the set is read WITHOUT the preview option. That is deliberate and it is\n * the whole point: the preview option decides how the sheet is EMITTED, and\n * this decides what a box of a given width shows. A canvas at 800px shows what\n * a real viewport at 800px would show, and the preview compile exists so that\n * remains true inside a box.\n *\n * @experimental\n */\nexport function breakpointsAtWidth(\n  set: BreakpointSet | undefined,\n  width: number | undefined\n): BreakpointId[] {\n  const contexts = breakpointContexts(set).filter(\n    context => context.axis !== \"container\"\n  );\n  return contexts\n    .filter(context => {\n      // The unconditional context applies at every width, which is what makes\n      // it the base: it is the only tier that is never a query.\n      if (!isUsableWidth(context.maxWidth)) return true;\n      /*\n       * An unmeasured canvas reports the unconditional context alone rather\n       * than guessing.\n       *\n       * Nothing has been observed yet on the first render, before layout has\n       * run — and reporting the widest PRESET there would be a claim about a\n       * box nobody has measured. The tier this yields is the honest one, and it\n       * is also what the server render produces, so the two agree and React\n       * does not discard the subtree.\n       */\n      if (width === undefined) return false;\n      // Desktop-first: the compiler emits `(max-width: Npx)`, which applies at\n      // N and below. Inclusive, matching the query rather than approximating it.\n      return width <= context.maxWidth;\n    })\n    .map(context => context.id);\n}\n\n/**\n * The tier an edit lands in at this width: the NARROWEST one applying.\n *\n * Narrowest rather than widest, because that is the one whose declaration wins.\n * At 800px on a site defining tablet (991) and mobile (575), both the base and\n * tablet contexts apply and tablet is what the browser paints — so an edit made\n * while looking at 800px must land in tablet, or the author changes a value they\n * cannot see change.\n *\n * Falls back to {@link BASE_BREAKPOINT} rather than to whatever came first: a\n * site that has defined no breakpoints, or a width above every bound, is\n * editing the unconditional tier, and that is a real answer rather than a\n * default standing in for a missing one.\n *\n * @experimental\n */\nexport function editedBreakpointAtWidth(\n  set: BreakpointSet | undefined,\n  width: number | undefined\n): BreakpointId {\n  const contexts = breakpointContexts(set).filter(\n    context => context.axis !== \"container\"\n  );\n  const live = new Set(breakpointsAtWidth(set, width));\n  let narrowest: { id: BreakpointId; maxWidth: number } | undefined;\n  for (const context of contexts) {\n    if (!live.has(context.id)) continue;\n    if (!isUsableWidth(context.maxWidth)) continue;\n    /*\n     * `<=`, so among tiers sharing a bound the LAST one wins.\n     *\n     * Two viewport ids can carry the same `maxWidth` — a stored set written\n     * through the API can say so — and the compiler emits both, in order, into\n     * one at-rule. Measured: `alpha` then `beta` at 991 produce two\n     * declarations in a single `@media (max-width: 991px)` block, so `beta` is\n     * what the browser paints. Taking the first would write the author's edit\n     * into a tier whose value is then overridden by the one below it, and the\n     * control would look correct while nothing changed on screen.\n     */\n    if (narrowest === undefined || context.maxWidth <= narrowest.maxWidth) {\n      narrowest = { id: context.id, maxWidth: context.maxWidth };\n    }\n  }\n  if (narrowest !== undefined) return narrowest.id;\n  /*\n   * The unconditional context's own id, not the constant, when the set has one.\n   *\n   * `breakpointContexts` names that context, and a site whose stored set spells\n   * the unconditional tier differently would otherwise be told it is editing an\n   * id its own document does not use — a write addressed to a tier that is not\n   * there.\n   */\n  const unconditional = contexts.find(\n    context => !isUsableWidth(context.maxWidth)\n  );\n  return unconditional?.id ?? BASE_BREAKPOINT;\n}\n\n/**\n * The tiers a canvas width can actually select, widest first.\n *\n * ONE per distinct bound. Selecting a tier sets a WIDTH and everything else is\n * derived from it, so two tiers sharing a bound are not two choices: both\n * radios would emit the same number, the match would resolve to one of them,\n * and clicking the other would silently select the first.\n *\n * Among tiers sharing a bound the LAST is kept, because that is the one the\n * browser paints — the compiler emits both into a single at-rule in order, so\n * the later declaration wins. Keeping the first would name a tier whose value\n * is overridden by the one below it, and {@link editedBreakpointAtWidth} would\n * disagree with this list about which tier an edit lands in.\n *\n * Taken from the compiler's contexts rather than the stored definitions, so a\n * definition it declines to emit a bounded context for is not offered: sizing\n * the canvas to a number nothing responds to reads as the feature being broken\n * rather than as the definition being unusable.\n *\n * @experimental\n */\nexport function offeredTiers(\n  set: BreakpointSet | undefined\n): Array<{ id: BreakpointId; maxWidth: number }> {\n  const byWidth = new Map<number, BreakpointId>();\n  for (const context of breakpointContexts(set)) {\n    if (context.axis === \"container\") continue;\n    if (!isUsableWidth(context.maxWidth)) continue;\n    // Later assignment wins, which is the collapse rule stated above.\n    byWidth.set(context.maxWidth, context.id);\n  }\n  return [...byWidth.entries()]\n    .map(([maxWidth, id]) => ({ id, maxWidth }))\n    .sort((a, b) => b.maxWidth - a.maxWidth);\n}\n\n/**\n * The canvas width that puts a tier on screen, or `undefined` for the widest.\n *\n * The switcher's whole job in one function: choosing a tier SETS a width, and\n * everything else follows from the width. `undefined` means \"as wide as the\n * region allows\" — the unconditional tier has no upper bound, so pinning it to\n * a number would invent one and make the widest preset narrower than the space\n * available.\n *\n * The tier's own `maxWidth` rather than one pixel below it. The query is\n * `(max-width: Npx)` and therefore inclusive, so N is inside the tier — and it\n * is the width at which the author sees the tier at its roomiest, which is\n * where a layout decision is actually made.\n *\n * @experimental\n */\n/**\n * The narrowest canvas width at which the UNCONDITIONAL tier applies.\n *\n * One past the widest bound, because a bounded tier applies at `width <= bound`\n * — so the first width no bounded tier claims is `bound + 1`, and that is where\n * the base rules are what an author is editing.\n *\n * Derived rather than chosen. A conventional desktop number would be a width\n * the site never declared, and the canvas would then simulate a viewport\n * nothing in the document mentions; one past the widest bound is the only width\n * the site's own tiers imply. It is also the SMALLEST such width, which matters\n * because the canvas is scaled to fit: every pixel past it costs the author\n * legibility for nothing.\n *\n * `undefined` when the site bounds no viewport tier at all. Base already\n * applies at every width there, so there is no width to go to — and offering\n * one would size the canvas to a bound the site never declared, which is what\n * the switcher's own tier list refuses to do.\n */\nexport function baseWidth(set: BreakpointSet | undefined): number | undefined {\n  const widest = offeredTiers(set)[0];\n  return widest === undefined ? undefined : widest.maxWidth + 1;\n}\n\n/**\n * Every tier the breakpoint control can put the canvas at, widest first.\n *\n * The bounded tiers AND the unconditional one, which is offered at the width it\n * applies from. Published as one list because two places need the same answer\n * and they are not the same code: the control builds its options from it, and\n * the host clears a requested width that is not on it — a canvas pinned to a\n * bound the stylesheet no longer has, after an author deletes the tier they\n * selected, has no control on screen to release it.\n *\n * Measured: those two DID disagree. The host compared against the bounded tiers\n * alone while the control had begun offering the unconditional one, so choosing\n * base set a width the host cleared on the very next render — the canvas\n * returned to filling the region, and base stayed uneditable exactly where it\n * had been. Nothing failed; the option simply did nothing.\n */\nexport function selectableTiers(\n  set: BreakpointSet | undefined\n): Array<{ id: BreakpointId; maxWidth: number; unconditional?: boolean }> {\n  const base = baseWidth(set);\n  return [\n    ...(base === undefined\n      ? []\n      : [{ id: BASE_BREAKPOINT, maxWidth: base, unconditional: true }]),\n    ...offeredTiers(set),\n  ];\n}\n\nexport function widthForBreakpoint(\n  set: BreakpointSet | undefined,\n  id: BreakpointId\n): number | undefined {\n  /*\n   * Read from {@link selectableTiers}, not from the contexts directly.\n   *\n   * The SELECTABLE list rather than the bounded one, because a jump and a\n   * choice are the same act reached two ways: the switcher offers the\n   * unconditional tier at the width it applies from, and a control whose value\n   * came from that tier has to send the canvas to the same place. Answering\n   * from the bounded tiers alone returned `undefined` for base and released the\n   * canvas to the region — which, wherever the region is narrower than the\n   * widest bound, lands on the tier the author was jumping AWAY from.\n   *\n   * Two ids can carry the same bound, and only one of them is what a canvas at\n   * that width is showing: the compiler emits both into one at-rule and the\n   * later declaration wins. Answering from the contexts would hand back the\n   * bound for the LOSING id too — so a caller sets that width believing it\n   * selected `alpha`, and every edit made there is written to `beta`, which is\n   * the disagreement between the control and the write that collapsing the\n   * choice exists to remove.\n   *\n   * `undefined` for an id that is not selectable is still the honest answer:\n   * there is no width that puts that tier on screen, because another tier owns\n   * the bound — or, for a site that bounds nothing, because base already\n   * applies at every width and the region is where it belongs.\n   */\n  return selectableTiers(set).find(tier => tier.id === id)?.maxWidth;\n}\n\n/**\n * The narrowest the base breakpoint, Desktop, is previewed at.\n *\n * A fixed width rather than the region's: the region changes as panels open\n * and close, and a preview that followed it would show a different layout for\n * the same device. 1280 is the narrowest window the editor supports.\n */\nexport const DESKTOP_PREVIEW_WIDTH = 1280;\n\n/**\n * The width the canvas lays a device out at, which the zoom then fits into\n * the room the panels leave.\n *\n * A bounded breakpoint is shown at its own bound, the widest width at which\n * it applies, rather than at some device's width: that is the width whose\n * layout the author is styling. The base is shown at 1280, or one pixel past\n * the widest bound on a site whose widest bound reaches 1280, so the base\n * preview never sits inside a narrower breakpoint.\n *\n * `undefined` for an id the site does not define as a viewport breakpoint,\n * and on a site with no viewport breakpoints at all, where there is nothing\n * to simulate and the canvas fills its region.\n */\nexport function previewWidth(\n  set: BreakpointSet | undefined,\n  id: BreakpointId\n): number | undefined {\n  const tiers = offeredTiers(set);\n  if (tiers.length === 0) return undefined;\n  if (id === BASE_BREAKPOINT) {\n    return Math.max(DESKTOP_PREVIEW_WIDTH, (tiers[0]?.maxWidth ?? 0) + 1);\n  }\n  return tiers.find(tier => tier.id === id)?.maxWidth;\n}\n\n/** The narrowest width the canvas previews a page at: a small phone. */\nexport const NARROWEST_PREVIEW_WIDTH = 320;\n\n/** The widths a preview width can take, both ends included. */\nexport interface PreviewWidthRange {\n  readonly min: number;\n  readonly max: number;\n}\n\n/**\n * The widths the author can preview the page at by dragging the frame's\n * edges: from a small phone to the Desktop preview width, which is 1280 or\n * one pixel past the widest bound where a site's widest breakpoint reaches\n * 1280. A site with no viewport breakpoints previews up to 1280 too, the\n * width its canvas is drawn at.\n *\n * @experimental\n */\nexport function previewWidthRange(\n  set: BreakpointSet | undefined\n): PreviewWidthRange {\n  return {\n    min: NARROWEST_PREVIEW_WIDTH,\n    max: previewWidth(set, BASE_BREAKPOINT) ?? DESKTOP_PREVIEW_WIDTH,\n  };\n}\n\n/** A width brought into the range, in whole pixels. @experimental */\nexport function clampPreviewWidth(\n  width: number,\n  range: PreviewWidthRange\n): number {\n  return Math.min(range.max, Math.max(range.min, Math.round(width)));\n}\n\n/**\n * The breakpoint an edit goes to, from the device the author chose.\n *\n * The choice is stored as the author left it, so it can name a breakpoint the\n * site has since removed, or a container breakpoint, which is not a device.\n * Either way the edit goes to the base breakpoint: a value written under an\n * id the site does not define as a device would never be drawn.\n */\nexport function editingBreakpointOf(\n  set: BreakpointSet | undefined,\n  chosen: string | null\n): BreakpointId {\n  if (chosen === null || chosen === BASE_BREAKPOINT) return BASE_BREAKPOINT;\n  return offeredTiers(set).some(tier => tier.id === chosen)\n    ? chosen\n    : BASE_BREAKPOINT;\n}\n\n/**\n * The device to edit at once the site's breakpoints change from `before` to\n * `after`, given the device the author had chosen.\n *\n * The chosen breakpoint while the site still offers it. Once it is removed,\n * the narrowest device that remains at least as wide as it was, so the author\n * stays as close as the site allows to the layout they were styling, without\n * moving to a narrower one whose styles reach fewer widths. A breakpoint left\n * at exactly the removed one's width is the same layout, and is kept: a set\n * may define two at one bound, where only the later one is offered until the\n * other is removed. The base when nothing as wide remains, which covers every\n * width above the remaining bounds.\n *\n * The removed breakpoint's width is read from `before`, since `after` no\n * longer has it. A chosen id `before` never offered as a device has no width\n * to compare, so it goes to the base, as {@link editingBreakpointOf} sends it.\n *\n * @experimental\n */\nexport function fallbackBreakpoint(\n  before: BreakpointSet | undefined,\n  after: BreakpointSet | undefined,\n  chosen: string | null\n): BreakpointId {\n  const kept = editingBreakpointOf(after, chosen);\n  if (kept === chosen || chosen === null) return kept;\n  const former = offeredTiers(before).find(tier => tier.id === chosen);\n  if (former === undefined) return BASE_BREAKPOINT;\n  // Widest first, so the last one at least as wide is the narrowest of them.\n  const wider = offeredTiers(after).filter(\n    tier => tier.maxWidth >= former.maxWidth\n  );\n  return wider.at(-1)?.id ?? BASE_BREAKPOINT;\n}\n\n/** A frame's preview height below 600px wide: a phone held upright. */\nconst PHONE_PREVIEW_HEIGHT = 844;\n\n/** A frame's preview height from 600px up to below 1024px: a tablet. */\nconst TABLET_PREVIEW_HEIGHT = 1024;\n\n/** A frame's preview height from 1024px up: a laptop screen. */\nconst DESKTOP_PREVIEW_HEIGHT = 800;\n\n/**\n * The height of the device a width previews, in three bands: a phone, a\n * tablet, a laptop.\n *\n * The canvas's frame fills its region instead (see {@link frameFillingRegion})\n * and takes this only until the region is measured; a host that wants a\n * frame laid out at the device's own height states this as the frame's.\n *\n * Bands rather than one height per breakpoint, because a site can add its own\n * breakpoints at any width and each still needs a height. The same three\n * bands answer for those: a site-added 700px breakpoint is previewed at a\n * tablet's height, like any other width in that band.\n *\n * @experimental\n */\nexport function previewHeight(width: number): number {\n  if (width < 600) return PHONE_PREVIEW_HEIGHT;\n  if (width < 1024) return TABLET_PREVIEW_HEIGHT;\n  return DESKTOP_PREVIEW_HEIGHT;\n}\n\n/** A width and a height, in CSS pixels. */\nexport interface FrameSize {\n  readonly width: number;\n  readonly height: number;\n}\n\n/**\n * The scale that fits a whole frame into the region around it.\n *\n * BOTH dimensions, because the frame has a height of its own: fitting only the\n * width leaves a desktop frame taller than a short region, and the bottom of\n * the previewed viewport is then off screen with nothing to say so. The\n * smaller of the two ratios is the one at which the frame fits both ways.\n *\n * Never above 1, for the reason the width-only fit gives: a frame shown larger\n * than life makes every measurement an author takes from the screen wrong in\n * the flattering direction. `1` for a region not yet measured, or one of zero,\n * because a ratio taken from either is infinite or `NaN` and would paint the\n * frame nowhere.\n *\n * @experimental\n */\nexport function frameFitScale(\n  frame: FrameSize,\n  region: { readonly width?: number; readonly height?: number }\n): number {\n  const { width, height } = region;\n  if (width === undefined || height === undefined) return 1;\n  if (!(width > 0) || !(height > 0)) return 1;\n  if (!(frame.width > 0) || !(frame.height > 0)) return 1;\n  return Math.min(1, width / frame.width, height / frame.height);\n}\n\n/**\n * The frame that fills its region: the scale it is painted at, and the height\n * the page is laid out at so that, painted, the frame is exactly as tall as\n * the region.\n *\n * The canvas is the author's window onto the page, as a browser window is a\n * visitor's: it fills the room the editor gives it at any zoom, and a page\n * taller than that scrolls inside it. So only the WIDTH is fitted, the\n * device's; the height follows the room. `vh` on the page then answers for\n * the window the author is looking through, as it does for a visitor.\n *\n * Never above 1 to fit, for the reason {@link frameFitScale} gives. Until the\n * region is measured, the device's own height at actual size: a frame sized\n * from nothing would be drawn nowhere.\n *\n * @experimental\n */\nexport function frameFillingRegion(\n  width: number,\n  region: { readonly width?: number; readonly height?: number } | undefined,\n  zoom: CanvasZoom\n): { readonly scale: number; readonly height: number } {\n  const chosen = zoom.kind === \"fixed\" ? usableScale(zoom.scale) : null;\n  const room = region?.height;\n  if (room === undefined || !(room > 0)) {\n    const height = previewHeight(width);\n    return {\n      scale: chosen ?? frameFitScale({ width, height }, region ?? {}),\n      height,\n    };\n  }\n  // Fitted by the one rule every fit uses, asked with the region's own height\n  // on both sides, so only the width decides.\n  const scale =\n    chosen ??\n    frameFitScale(\n      { width, height: room },\n      { width: region?.width, height: room }\n    );\n  return { scale, height: room / scale };\n}\n","/**\n * What the inserter offers and is handed: the categories every entry falls\n * under, the block, pattern and component entries, the saved patterns and\n * components they are made from, the slots a block declares, and which of\n * those show an empty state. `inserter.ts` still exports each of these names.\n *\n * @module inserter-types\n */\n\nimport type {\n  BlockDocument,\n  BlockNode,\n  ComponentDocument,\n  PlacementTarget,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * The category an entry falls under when its block declares none.\n *\n * A literal rather than an empty string, because the panel groups by this value\n * and a heading has to be nameable. Blocks arrive from plugins that need not\n * categorise themselves, so this is the common case for third-party blocks\n * rather than an error state.\n */\nexport const UNCATEGORISED = \"other\";\n\n/**\n * The one category every component entry falls under, whatever its row says.\n *\n * A component is the site's own, placed as a link back to its definition, and\n * an author looks for it apart from the library's blocks: filing it under the\n * row's category would scatter the site's components among blocks they look\n * nothing like. Namespaced so no plugin's free-string category can collide\n * with it.\n */\nexport const COMPONENT_CATEGORY = \"nextly:components\";\n\n/**\n * One offerable BLOCK: a block, or a block under one of its named variations.\n *\n * Two tiers in one list rather than a nested structure, because the panel\n * filters and keyboard-navigates across both and a nested shape would make\n * every consumer flatten it first. The third tier — patterns — is\n * {@link PatternInsertEntry}, a separate member of {@link InsertEntry} rather\n * than a block wearing extra fields: a pattern has no block name, no version\n * and no props, so folding it in here would make four fields optional on the\n * common case and leave every reader handling an absence blocks never produce.\n */\nexport interface BlockInsertEntry {\n  /**\n   * Which tier this is.\n   *\n   * Carried on the entry rather than inferred from which fields are present.\n   * A shape test — \"does it have a `blockName`\" — is a second statement of the\n   * same fact, and it answers wrongly the first time a tier gains a field the\n   * test happens to name.\n   */\n  readonly kind: \"block\";\n  /**\n   * Stable identity, for React keys and for naming a selection across a\n   * re-filter.\n   *\n   * Derived from the block and variation names rather than an index, because a\n   * search narrows the list and an index-keyed selection would silently follow\n   * the position instead of the entry — the highlighted row changing meaning\n   * under the author as they type.\n   */\n  readonly id: string;\n  readonly blockName: string;\n  /** Absent on a block's own entry; present on each of its variations. */\n  readonly variationName?: string;\n  readonly label: string;\n  readonly description: string;\n  readonly category: string;\n  readonly keywords: readonly string[];\n  readonly icon?: string;\n  /**\n   * The version to stamp, taken from the definition that produced this entry.\n   *\n   * Carried rather than looked up again at insert time. The registry is\n   * mutable — a plugin can register while a panel is open — so a second lookup\n   * can answer with a different definition than the one the author was shown,\n   * and stamp a version the props do not match.\n   */\n  readonly version: number;\n  /**\n   * The props this entry inserts with: the block's defaults, overlaid by the\n   * variation's.\n   *\n   * A variation may narrow its block's props and never introduce one the\n   * renderer does not accept, which is what makes the overlay safe to compute\n   * here rather than at the call site.\n   */\n  readonly props: Readonly<Record<string, unknown>>;\n}\n\n/**\n * A stored pattern, as the palette needs to read it.\n *\n * The fields a pattern is STORED with that no palette reads — its slug, its\n * status, its granularity — are deliberately absent. A granularity decides\n * whether a pattern is offered as something to insert or as a way to start a\n * page, and that vocabulary belongs to the collection that declares it; a copy\n * of the four words here would be a second enumeration nothing keeps in step,\n * so the caller splits its own list and hands this the rows it means to offer.\n *\n * `keywords` arrives as ONE string because that is how it is stored — matched,\n * never enumerated — and {@link patternEntriesFrom} is where it becomes the\n * word list the palette searches.\n */\nexport interface SavedPattern {\n  /** The stored row's id, which the insert plans against. */\n  readonly id: string;\n  readonly title: string;\n  readonly description?: string;\n  readonly category?: string;\n  /**\n   * The author's own search terms, however they separated them.\n   *\n   * `null` as well as absent, because that is what a stored row holds: the\n   * field is not required, and Nextly writes an unset non-required field as SQL\n   * `NULL` and reads it back with the KEY PRESENT. A pattern saved without\n   * keywords — the ordinary case — arrives here as `null`, so an\n   * undefined-only check would reach `null.split` and take catalog\n   * construction down with it.\n   */\n  readonly keywords?: string | null;\n  /**\n   * The pattern's document, carried whole — or absent, as a stored row's is.\n   *\n   * The collection does not mark its blocks field required and the field layer\n   * persists an omitted document as SQL `NULL`, so a published row with a\n   * title, a slug and a granularity but no content is a legal row. There is\n   * nothing to offer for one, so it is skipped exactly as an empty pattern is;\n   * reading `kind` off it took catalogue construction down.\n   *\n   * Held BY REFERENCE, and treated as immutable, which is how a stored row is\n   * treated everywhere else it travels. Cloning each one instead would copy\n   * every pattern's whole forest on each build of the catalogue, and the\n   * catalogue is rebuilt whenever the palette opens — against a library the\n   * design sizes at three thousand entries.\n   *\n   * What that costs is bounded, because the planner judges the forest AGAIN\n   * before it plans: a row mutated between being offered and being clicked can\n   * make the insert refuse, and cannot make it place something the nesting\n   * rules forbid. And the value it would then place is the row as it stands\n   * now, which for a live library is the better of the two answers.\n   */\n  readonly document?: BlockDocument | null;\n}\n\n/**\n * One offerable PATTERN: a saved document inserted as a copy that keeps no\n * link back.\n *\n * **The document travels with the entry.** The palette judges what it offers\n * from these roots and the insert plans from the same value, so the two cannot\n * read different versions of one pattern — which is the palette-and-drop\n * disagreement {@link entryAllowedAt} already exists to prevent, one tier up.\n *\n * The root types are NOT carried beside it. They are a narrower view of the\n * document, derived where they are needed; storing both would be two statements\n * of one fact, and the stored one goes stale the first time an entry is built\n * from a document that has moved on.\n */\nexport interface PatternInsertEntry {\n  readonly kind: \"pattern\";\n  /**\n   * Stable identity across the whole catalog, which is why it is not the\n   * pattern's own id.\n   *\n   * Blocks are keyed by their namespaced name, and nothing stops a stored\n   * pattern being saved under `core/heading`. Two entries sharing a key make\n   * React reuse one row's state for the other and make a selection ambiguous,\n   * so the tier is part of the key.\n   */\n  readonly id: string;\n  /** The stored row's id, as {@link SavedPattern.id}. */\n  readonly patternId: string;\n  readonly label: string;\n  readonly description: string;\n  readonly category: string;\n  readonly keywords: readonly string[];\n  readonly icon?: string;\n  readonly document: BlockDocument;\n}\n\n/**\n * Anything the palette can offer.\n *\n * A discriminated union rather than one widened shape: the two tiers share\n * what the panel DRAWS — a label, a description, a category, search words —\n * and share nothing about what inserting them does. One block becomes one node\n * from a name and a version; one pattern becomes a whole forest, re-identified,\n * planned against the destination document. A single shape would have to make\n * both halves optional and every consumer would branch on which half was\n * filled in — the branch this union makes the compiler check.\n */\nexport type InsertEntry =\n  | BlockInsertEntry\n  | PatternInsertEntry\n  | ComponentInsertEntry;\n\n/**\n * A stored component definition, as the library hands it to the palette.\n *\n * The same shape and the same caveats as {@link SavedPattern}, because it is\n * the same kind of row from a sibling collection: `keywords` is one stored\n * string, and `document` may be `null` for a published row saved without\n * content. Carried separately rather than widened onto `SavedPattern` because\n * what the two are FOR differs — a pattern is copied in and forgets its source,\n * a component is placed as one node that keeps pointing back — and a reader\n * should be able to tell from the type which it holds.\n */\nexport interface SavedComponent {\n  /** The stored row's id, which an instance node points at. */\n  readonly id: string;\n  readonly title: string;\n  readonly description?: string;\n  readonly category?: string;\n  readonly keywords?: string | null;\n  readonly document?: ComponentDocument | null;\n  /**\n   * How many pages currently place it, when the library can say.\n   *\n   * Optional because the count is a separate read the library may not have\n   * made, and a tile that showed \"used on 0 pages\" for a count nobody took\n   * would be stating a fact it does not hold.\n   */\n  readonly usedOn?: number;\n}\n\n/**\n * One offerable COMPONENT: a definition placed as a single instance node that\n * keeps pointing back at it.\n *\n * The document travels with the entry for the reason a pattern's does — the\n * palette judges placement from its roots — but what inserting it does is the\n * opposite of a pattern: nothing from the document is copied into the page.\n * One node is written, carrying the definition's id, and the renderer inlines\n * the definition at read time. That is what makes an edit to the definition\n * reach every page that placed it.\n */\nexport interface ComponentInsertEntry {\n  readonly kind: \"component\";\n  /** Prefixed, for the reason {@link PatternInsertEntry.id} is. */\n  readonly id: string;\n  /** The definition's stored id, which the instance node will point at. */\n  readonly componentId: string;\n  readonly label: string;\n  readonly description: string;\n  readonly category: string;\n  readonly keywords: readonly string[];\n  readonly icon?: string;\n  /**\n   * The definition the canvas resolves the placed instance against — the\n   * lookup's, by identity — which is what a preview of the tile draws.\n   */\n  readonly document: ComponentDocument;\n  /**\n   * The block types at the roots of the definition AS THE CANVAS WILL DRAW\n   * IT: a root that is itself an instance is followed into the definition it\n   * names, through the same lookup the canvas resolves against.\n   *\n   * A definition may hold instances of other components, at its root included,\n   * and an instance node's type is not a registered block — the nesting rule\n   * answers \"no restriction\" for a type it cannot resolve. Judging placement\n   * from the STORED roots would therefore offer a component whose real root is\n   * confined to one parent at any destination, and the canvas would then draw\n   * that root where it does not belong. The roots here are the block types\n   * that actually land — each type once, in the order first met, which is all\n   * a placement verdict reads. Read without composing the definition, because\n   * a library of small wrappers around one large definition would otherwise\n   * be cloned whole, once per wrapper, every time the panel opened.\n   */\n  readonly roots: readonly string[];\n  readonly usedOn?: number;\n}\n\n/**\n * How a caller answers for a block's declared child regions.\n *\n * Deliberately NOT a registry, matching `NestingSource`: resolving a type to\n * its definition differs per caller, and a one-method source lets each supply\n * its own resolution while sharing the rule applied to the result.\n *\n * The NODE cannot answer this. A container inserted from the palette carries no\n * `slots` key at all — `makeNode` writes one only when children are supplied —\n * so asking the node whether it is a container answers \"no\" for every empty\n * one, which is exactly the case that needs filling.\n */\nexport interface SlotSource {\n  /** The names of the child regions this block type declares, in order. */\n  slotsOf(type: string): readonly string[] | undefined;\n  /**\n   * The region the canvas draws for this block in place of its first, when\n   * it draws another: a collection list whose empty state is shown. Adding\n   * inside such a block adds to the region the author sees.\n   */\n  shownSlotOf?(node: BlockNode): string | undefined;\n}\n\n/** The slot a list's empty state is drawn from. */\nconst EMPTY_STATE_SLOT = \"empty\";\n\n/**\n * `slots`, naming the empty-state slot as the one drawn for each list the\n * canvas shows empty (see `EditorState.listsShowingEmpty`), so a block added\n * inside it, from the canvas or the Add panel, lands where it is seen.\n */\nexport function slotsShowingEmpty(\n  slots: SlotSource,\n  showingEmpty: ReadonlySet<string> | undefined\n): SlotSource {\n  if (showingEmpty === undefined || showingEmpty.size === 0) return slots;\n  return {\n    slotsOf: type => slots.slotsOf(type),\n    shownSlotOf: node =>\n      showingEmpty.has(node.id) &&\n      slots.slotsOf(node.type)?.includes(EMPTY_STATE_SLOT) === true\n        ? EMPTY_STATE_SLOT\n        : slots.shownSlotOf?.(node),\n  };\n}\n\n/**\n * Where an insert would land, as the nesting rule needs to see it.\n *\n * The engine's type, re-exported rather than restated. It is the input to\n * `placementVerdict`, which is the one implementation of the placement rule, so\n * a second declaration here would be a second vocabulary for the rule's own\n * argument — and every caller would reach the rule through a translation whose\n * two sides could drift.\n */\nexport type { PlacementTarget } from \"@nextlyhq/blocks-engine\";\n\n/**\n * @deprecated Renamed to `PlacementTarget`, which is the engine's name for it\n * and now the only one. Kept as an alias for one release because this type is\n * published from the package entry; import `PlacementTarget` instead.\n *\n * Note the discriminant moved with the name: the member is `kind`, not `at`.\n * A value written as `{ at: \"slot\", ... }` no longer satisfies this type, and\n * that is deliberate — a silently accepted `at` would fall through every\n * `kind === \"slot\"` narrowing and be judged as a root placement.\n */\nexport type InsertTarget = PlacementTarget;\n","/**\n * Building the inserter's catalog: a block's entries and their variations,\n * the entries for saved patterns and components, why a component cannot be\n * offered, the words each entry is found by, and an entry's label.\n *\n * @module inserter-catalog\n */\n\nimport {\n  blockLabelFrom,\n  patternRefusal,\n  getBlock,\n  makeNode,\n  composedRootTypes,\n  readableDefinition,\n  resolveComponentInstances,\n  COMPONENT_INSTANCE_TYPE,\n  type AnyBlockDefinition,\n  type BlockDocument,\n  type BlockNode,\n  type ComponentLookup,\n  type ComponentUnresolvedReason,\n  type DocumentLimits,\n  type NestingSource,\n  type ResolvedComposition,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  type BlockInsertEntry,\n  COMPONENT_CATEGORY,\n  type ComponentInsertEntry,\n  type InsertEntry,\n  type PatternInsertEntry,\n  type SavedComponent,\n  type SavedPattern,\n  UNCATEGORISED,\n} from \"./inserter-types\";\n\n/**\n * The props a block is placed with: its defaults, overlaid by its example.\n *\n * The one answer for \"what a block starts as\", for the inserter that places\n * it and for anything that must tell an author's own values from a block's\n * starting ones (Getting started's \"Write something\"). Spread, so the caller\n * owns its copy and cannot reach back into the definition.\n */\nfunction insertionProps(\n  definition: Pick<AnyBlockDefinition, \"defaultProps\" | \"example\">\n): Record<string, unknown> {\n  return {\n    ...(definition.defaultProps ?? {}),\n    ...(definition.example?.props ?? {}),\n  };\n}\n\n/**\n * A block's insert presets: its variations that are neither a look (one with\n * styles, picked for a block already on the page) nor the block's own named\n * look (`isDefault`). The one reading both the Add panel and the props a block\n * could have been placed with take, so the two can't disagree.\n */\nfunction insertVariations(\n  editor: AnyBlockDefinition[\"editor\"]\n): NonNullable<NonNullable<AnyBlockDefinition[\"editor\"]>[\"variations\"]> {\n  return (editor?.variations ?? []).filter(\n    variation => variation.styles === undefined && variation.isDefault !== true\n  );\n}\n\n/** The props a block is placed with under one of its variations. */\nfunction variationProps(\n  base: Record<string, unknown>,\n  variation: { readonly props?: object }\n): Record<string, unknown> {\n  return { ...base, ...(variation.props ?? {}) };\n}\n\n/**\n * Every set of props a block can be placed with: its own, then each\n * variation's. The candidates the inserter offers, for anything that must\n * tell an author's values from ones a block was placed with.\n */\nexport function insertionPropSets(\n  definition: Pick<AnyBlockDefinition, \"defaultProps\" | \"example\" | \"editor\">\n): Record<string, unknown>[] {\n  const base = insertionProps(definition);\n  return [\n    base,\n    ...insertVariations(definition.editor).map(variation =>\n      variationProps(base, variation)\n    ),\n  ];\n}\n\n/**\n * Build the offerable list from block definitions.\n *\n * Takes definitions rather than reading the registry, matching how the engine\n * hands out `NestingSource`: the caller supplies `allBlocks()`, and a test\n * supplies a fixture without a global registry to clear between cases.\n *\n * A block emits its own entry followed immediately by its variations, and\n * blocks are ordered by the label the author actually reads. Registration\n * order is an implementation detail of whichever plugin loaded first, so\n * ordering by it would rearrange the palette when an unrelated plugin is\n * installed.\n */\nexport function catalogFrom(\n  definitions: readonly AnyBlockDefinition[]\n): BlockInsertEntry[] {\n  const byLabel = [...definitions].sort((a, b) =>\n    labelOf(a).localeCompare(labelOf(b))\n  );\n\n  const entries: BlockInsertEntry[] = [];\n  for (const definition of byLabel) {\n    const editor = definition.editor;\n    const category = editor?.category ?? UNCATEGORISED;\n    // A plugin block that names no keywords is still found by its own name,\n    // which is the one word an author searching for it will type.\n    const keywords =\n      editor?.keywords === undefined || editor.keywords.length === 0\n        ? [labelOf(definition)]\n        : editor.keywords;\n    // The block's DEFAULTS, overlaid by its EXAMPLE: see `insertionProps`.\n    //\n    // Defaults alone are what an author was getting, and they are deliberately\n    // empty: `core/heading` defaults to `text: \"\"`, `core/text` to `text: \"\"`,\n    // `core/button` to `label: \"\"`. Inserting those renders an empty `<h2>` —\n    // an element with no height and nothing to read — so the block was added\n    // and the page looked unchanged. An author cannot edit what they cannot\n    // find, and cannot tell it from the insert having failed.\n    //\n    // `example` is the right source and needs no new contract: the engine\n    // REQUIRES it on every definition, describing it as a worked instance, so\n    // every block already carries one and a third-party block gets this for\n    // free. Defaults stay underneath it, because an example states what is\n    // worth showing rather than every prop — `core/image` illustrates a `src`\n    // while its `loading: \"lazy\"` default still applies.\n    //\n    // Spread rather than referenced, so the entry owns its copy and the clone\n    // taken at insert time cannot reach back into the definition.\n    const defaults = insertionProps(definition);\n\n    entries.push({\n      kind: \"block\",\n      id: definition.name,\n      blockName: definition.name,\n      label: labelOf(definition),\n      // The engine refuses an empty description at registration; a blank one\n      // still says nothing, so the block's name stands in rather than a gap.\n      description:\n        definition.description.trim() === \"\"\n          ? labelOf(definition)\n          : definition.description,\n      category,\n      keywords,\n      icon: editor?.icon,\n      version: definition.version,\n      props: defaults,\n    });\n\n    for (const variation of insertVariations(editor)) {\n      entries.push({\n        kind: \"block\",\n        id: `${definition.name}#${variation.name}`,\n        blockName: definition.name,\n        variationName: variation.name,\n        // A variation without a label is still offerable; naming it by its own\n        // `name` beats falling back to the block's label, which would show two\n        // identical rows and give the author no way to tell them apart.\n        label: variationLabel(variation),\n        // Variations carry no description of their own. The block's is the\n        // honest answer: it describes what will be inserted, which is a\n        // configured instance of that block.\n        description: definition.description,\n        category,\n        keywords,\n        // No `icon` on a variation by design — the engine's `BlockVariation` has\n        // no icon field, so every variation shares its block's. Inventing one\n        // here would put a second, richer contract in the panel than the one\n        // plugin authors can actually write against.\n        icon: editor?.icon,\n        version: definition.version,\n        props: variationProps(defaults, variation),\n      });\n    }\n  }\n  return entries;\n}\n\n/**\n * Build the offerable pattern list from stored rows.\n *\n * **A pattern with no roots produces no entry.** Inserting it would add\n * nothing, so offering it is a row that reads as an action and is not one —\n * and it is the shape a pattern saved from a cleared selection actually takes,\n * rather than a hypothetical. Skipped rather than refused: an empty pattern is\n * a row someone can still finish, not an error to report from a palette.\n *\n * Order is the caller's. Blocks are sorted here because their order comes from\n * whichever plugin registered first, which is an implementation detail; stored\n * rows arrive from a query that already said what order it wanted, and sorting\n * them again would overrule it.\n */\nexport function patternEntriesFrom(\n  patterns: readonly SavedPattern[],\n  nesting: NestingSource,\n  definitions?: ComponentLookup\n): PatternInsertEntry[] {\n  const entries: PatternInsertEntry[] = [];\n  for (const pattern of patterns) {\n    const document = pattern.document;\n    if (document === undefined || document === null) continue;\n    // The planner refuses a document that is not a pattern outright, as\n    // `not-a-pattern`, and the type admits one: `SavedPattern.document` is a\n    // `BlockDocument`, so a page or a component row handed to this by mistake\n    // is a legal value. Offering it produces a tile that accepts a click and\n    // cannot succeed, which is the disagreement between the palette and the\n    // insert that this module exists to prevent.\n    // The planner's own preflight, asked whole rather than reproduced in part.\n    // The ways a stored row can be unusable are not a short list: the wrong\n    // kind, no nodes, an envelope the apply cannot read, a node whose shape it\n    // cannot apply, two nodes rendering one DOM id, an internal placement the\n    // rules no longer allow. `planInsertPattern` refuses every one of them\n    // wherever the pattern is put, so a tile for one accepts a click that\n    // cannot succeed — and a palette keeping its own subset of that list drifts\n    // the first time the planner learns a new way to say no.\n    //\n    // Asked ONCE per row rather than inside `entryAllowedAt`, because none of\n    // it depends on the destination: per target it would re-walk every\n    // pattern's forest on each keystroke of a filter, against a library the\n    // design sizes at three thousand entries.\n    if (patternRefusal(document, nesting, definitions) !== undefined) continue;\n    entries.push({\n      kind: \"pattern\",\n      id: `${PATTERN_ENTRY_PREFIX}${pattern.id}`,\n      patternId: pattern.id,\n      label: pattern.title,\n      // Empty rather than absent, matching a block's, so the panel draws one\n      // description slot for both tiers instead of two.\n      description: pattern.description ?? \"\",\n      category: pattern.category ?? UNCATEGORISED,\n      keywords: keywordsOf(pattern.keywords),\n      document,\n    });\n  }\n  return entries;\n}\n\n/**\n * The prefix that keeps a pattern's catalog id out of the block namespace.\n *\n * Blocks are keyed by their namespaced name and a stored pattern can be saved\n * under any string, `core/heading` included, so the tier has to be part of the\n * key. A colon rather than a separator a block name can contain: `#` already\n * separates a block from its variation, and reusing it would make\n * `core/heading#hero` and a pattern named `hero` compete for one id.\n */\nexport const PATTERN_ENTRY_PREFIX = \"pattern:\";\n\n/** The same rule for a component's catalog id, in its own namespace. */\nexport const COMPONENT_ENTRY_PREFIX = \"component:\";\n\n/**\n * The component entries a library of stored definitions yields.\n *\n * Skipped, never refused: a row the palette has nothing to offer for — see\n * {@link offerableDefinition} for which, and a row whose definition the\n * canvas's lookup does not hold — produces no entry, because a tile that\n * accepts a click and then fails is worse than no tile. The row supplies the\n * label, category and usage; the definition judged and drawn is the lookup's. Where a\n * definition's roots may sit on THIS page is asked per placement, by\n * {@link entryAllowedAt}, exactly as a pattern's are.\n */\nexport function componentEntriesFrom(\n  components: readonly SavedComponent[],\n  definitions: ComponentLookup\n): ComponentInsertEntry[] {\n  const entries: ComponentInsertEntry[] = [];\n  for (const component of components) {\n    // The LOOKUP's definition, not the row's copy: it is what the canvas will\n    // resolve the placed instance against, so a row the lookup does not hold\n    // would place an instance drawn as missing, and a row whose copy differs\n    // would be judged by roots the canvas does not draw.\n    const offered = offerableDefinition(\n      definitions.get(component.id),\n      definitions\n    );\n    if (offered === undefined) continue;\n    entries.push(componentEntryOf(component, offered));\n  }\n  return entries;\n}\n\n/**\n * The rows {@link componentEntriesFrom} offered no entry for, each as an entry\n * with nothing in it to place: no roots, and an empty definition.\n *\n * For a surface that lists the library to manage it as well as to place from\n * it. A component saved without content, or with none the canvas could draw,\n * is still one an author can open and fill, so it is listed, refused, rather\n * than left out. Never handed to the offers: there is nothing in it to judge\n * or to place, and the surface says so.\n *\n * Given the entries already built rather than the lookup, because building\n * them walks every definition's roots, and a second walk to learn which rows\n * were offered would repeat it.\n */\nexport function unplaceableComponentEntries(\n  components: readonly SavedComponent[],\n  entries: readonly InsertEntry[]\n): ComponentInsertEntry[] {\n  const offered = new Set(\n    entries.flatMap(entry =>\n      entry.kind === \"component\" ? [entry.componentId] : []\n    )\n  );\n  return components\n    .filter(component => !offered.has(component.id))\n    .map(component =>\n      componentEntryOf(component, {\n        document: { formatVersion: 1, kind: \"component\", nodes: [] },\n        roots: [],\n      })\n    );\n}\n\n/** One stored row as an entry, with the definition and roots it offers. */\nfunction componentEntryOf(\n  component: SavedComponent,\n  offered: Pick<ComponentInsertEntry, \"document\" | \"roots\">\n): ComponentInsertEntry {\n  return {\n    kind: \"component\",\n    id: `${COMPONENT_ENTRY_PREFIX}${component.id}`,\n    componentId: component.id,\n    label: component.title,\n    description: component.description ?? \"\",\n    // Every component under the one components group and with the one\n    // component mark, whatever its row declares: see COMPONENT_CATEGORY.\n    category: COMPONENT_CATEGORY,\n    icon: \"component\",\n    keywords: keywordsOf(component.keywords),\n    ...offered,\n    ...(component.usedOn === undefined ? {} : { usedOn: component.usedOn }),\n  };\n}\n\n/**\n * What a stored row offers — the definition and the roots it draws — or\n * nothing, when the palette has nothing to offer for the row.\n *\n * Nothing for a row with no document, one whose document the resolver would\n * not read — not a component definition, another format, nodes that are not a\n * list — or one with no roots: each is a legal stored row and none can be\n * placed. A definition's INTERNAL nesting is not re-judged here — it was judged\n * when the definition was saved, and it is the definition's own concern rather\n * than the page's.\n *\n * The roots are read through `definitions` — the lookup the canvas resolves\n * against, handed in rather than rebuilt from the list so the tile and the\n * canvas cannot read two different maps — by the engine's own roots query,\n * which follows a root instance into the definition it names without\n * composing anything, and answers nothing where the resolver would leave a\n * root STANDING. That is a root the canvas would draw as a placeholder and\n * the nesting rule cannot judge: the component it points at is missing from\n * the lookup, is this definition itself, or nests past the composition cap.\n * A row whose roots compose to nothing is withheld too: a tile for it would\n * be placed vacuously — no root type to refuse — and render nothing. An\n * unresolvable instance BELOW the root is the definition's own concern,\n * exactly as its internal nesting is, and does not withhold the tile.\n *\n * Room is NOT asked here. Whether a definition fits the page's caps is a\n * property of the page that moves with every edit, and the click asks the\n * resolver about it with the page in hand ({@link compositionRefusal}); a\n * definition too large for the site's cap under any page is a tile whose\n * every click says so.\n *\n * Read ONCE per row here rather than per placement inside\n * {@link entryAllowedAt}, for the reason a pattern's preflight is: per target\n * it would re-walk every definition on each keystroke of a filter.\n */\nfunction offerableDefinition(\n  stored: BlockDocument | null | undefined,\n  definitions: ComponentLookup\n): Pick<ComponentInsertEntry, \"document\" | \"roots\"> | undefined {\n  // The resolver's OWN rule for a supplied definition, not the kind alone: a\n  // definition in a format this build does not read is left standing on the\n  // canvas, and a tile for it would place a placeholder.\n  const document = readableDefinition(stored ?? undefined);\n  if (document === undefined || document.nodes.length === 0) return undefined;\n  const roots = composedRootTypes(document, definitions);\n  if (roots === undefined || roots.length === 0) return undefined;\n  return { document, roots };\n}\n\n/**\n * Why the edit that turned `before` into `after` would leave an instance\n * standing on THIS page, or nothing when it would not.\n *\n * A definition is judged offerable on its own — its roots — but whether the\n * page has ROOM for it is a property of the page: the resolver spends one\n * node budget across every instance it inlines, in document order, and nests\n * to a depth counted from the page root, so a page near its cap can hold the\n * one stored instance node and then leave it unresolved when it renders. The\n * op layer cannot see that (it counts stored nodes, and an instance is one),\n * so the edit asks the RESOLVER ITSELF: the edited document is composed the\n * way the canvas will compose it, and the reason the resolver gives is the\n * reason the author is told.\n *\n * Asked of the two DOCUMENTS rather than of a placed node, because every\n * edit asks the same question: a move carries an instance ahead of another\n * and takes the budget that one had, or into another's slot content one\n * composition deeper; a duplicate or a paste places a copy; a pattern brings\n * instances of its own. What refuses is every instance the edit LEAVES\n * STANDING that stood before it — a placed one, an instance nested inside its\n * definition, which the resolver reports under an id it minted rather than\n * the node's, and an instance already on the page that the edit takes the\n * budget from. Each is a placeholder the edit would put on the page. An\n * instance the page could not hold BEFORE the edit is not the edit's doing,\n * so the two compositions are compared rather than the second read alone;\n * the resolver mints an instance's ids from what it derives them from, so the\n * same instance answers to the same id in both.\n *\n * Asked by the editor's own apply, once per accepted group, rather than by\n * each surface before it applies: room is a property of the page that moves\n * with every edit, every surface reaches the page through that apply, and a\n * surface that asked for itself would be one more that could forget to. Two\n * compositions per edit are cheap where one per tile per keystroke is not.\n *\n * `undefined` for \"it composes\", and for a reason that is not about room —\n * a missing definition is the tile's concern and was judged when it was\n * offered — so this refuses only what the page cannot hold. Judged under the\n * same `limits` the edit was applied under, since the editor and the canvas\n * both run under the site's.\n */\nexport function compositionRefusal(\n  before: BlockDocument,\n  after: BlockDocument,\n  definitions: ComponentLookup,\n  limits?: DocumentLimits,\n  /**\n   * How a document is composed, for a caller that already holds compositions:\n   * the editor's store shares one per document between this check and its\n   * lock check. Defaults to composing each document here.\n   */\n  compose: (document: BlockDocument) => ResolvedComposition = document =>\n    resolveComponentInstances(\n      document,\n      definitions,\n      limits === undefined ? {} : { limits }\n    )\n): CompositionRefusal | undefined {\n  const standing = new Set(\n    compose(before).unresolved.map(entry => entry.instanceId)\n  );\n  const introduced = compose(after).unresolved.find(\n    entry => !standing.has(entry.instanceId) && entry.reason in ROOM_REFUSALS\n  );\n  if (introduced === undefined) return undefined;\n  const sentence = ROOM_REFUSALS[introduced.reason];\n  return sentence === undefined\n    ? undefined\n    : { reason: introduced.reason, sentence };\n}\n\n/** A refusal about room: the resolver's reason, and the words an author reads. */\nexport interface CompositionRefusal {\n  readonly reason: ComponentUnresolvedReason;\n  readonly sentence: string;\n}\n\n/**\n * The resolver's reasons that are about the PAGE having no room, each as the\n * sentence the author reads. Every other reason — a missing definition, a\n * cycle, a malformed row — is about the definition, and was the tile's\n * concern when it was offered.\n */\nconst ROOM_REFUSALS: Readonly<\n  Partial<Record<ComponentUnresolvedReason, string>>\n> = {\n  budget:\n    \"This page has no room left for that component: placing it would take the page past its block limit.\",\n  \"node-depth\":\n    \"That component's content would be nested too deeply here. Place it nearer the top of the page.\",\n  \"composed-depth\":\n    \"That component would be nested inside too many components here. Place it nearer the top of the page.\",\n};\n\n/**\n * The single node placing a component writes.\n *\n * ONE node, carrying the definition's id and nothing of its content. The\n * renderer inlines the definition at read time, which is the whole point of\n * placing a component rather than copying a pattern: an edit to the definition\n * reaches this page without this page being touched. No variant and no\n * overrides yet — an instance freshly placed inherits everything.\n */\nexport function nodeForComponentEntry(entry: ComponentInsertEntry): BlockNode {\n  return makeNode(COMPONENT_INSTANCE_TYPE, 1, {\n    componentId: entry.componentId,\n  });\n}\n\n/**\n * The author's stored search terms, as the list the palette matches.\n *\n * Stored as ONE string because the field is matched and never enumerated, and\n * the collection's own note says authors separate them however they like — so\n * commas, semicolons and whitespace all split, and empty runs between two\n * separators produce nothing rather than an empty term that matches every\n * query.\n */\nfunction keywordsOf(stored: string | null | undefined): readonly string[] {\n  // Both absences, and they arrive by different roads: `undefined` from a\n  // caller that omitted the field, `null` from a stored row whose author never\n  // filled it in.\n  if (stored === undefined || stored === null) return [];\n  return stored\n    .split(/[\\s,;]+/u)\n    .map(word => word.trim())\n    .filter(word => word !== \"\");\n}\n\n/**\n * The name an author reads.\n *\n * A declared `editor.label` wins. Without one, the namespaced identity is\n * humanised rather than shown raw: \"core/collection-loop\" reads as \"Collection\n * loop\". Showing the identity verbatim is honest and hostile — a palette is\n * read by whoever writes the page, not by whoever registered the block, and\n * every block that has simply not been labelled yet would present as an\n * internal name.\n *\n * Derived rather than stored, because a definition gaining a real label must\n * override this immediately, and a copy written into the entry at build time\n * would keep the guess alongside it.\n *\n * `lookup` is where the definition comes from, the process registry unless a\n * caller says otherwise. A surface outside the editor — the entry screen, which\n * deliberately registers nothing — resolves blocks through its own resolver,\n * and asking the empty registry there would humanise a block whose declared\n * label the editor shows, so the two screens would name one block twice.\n */\nexport function blockLabel(\n  type: string,\n  lookup: (type: string) => AnyBlockDefinition | undefined = getBlock\n): string {\n  // An unregistered type still has to read as something: its name made\n  // readable, the same fallback a registered-but-unlabelled block gets, so a\n  // block that disappears from the registry does not change what it is called\n  // in the middle of an editing session. The engine words it, so a refusal\n  // from a save names a block the way the editor does.\n  return blockLabelFrom(type, lookup(type));\n}\n\n/** A registered definition's label, as {@link blockLabel} reads it. */\nfunction labelOf(definition: AnyBlockDefinition): string {\n  return blockLabelFrom(definition.name, definition);\n}\n\n/**\n * A variation's name as the surfaces show it: its label, or its own `name`\n * when it has none, so two unlabeled variations of one block stay apart.\n */\nexport function variationLabel(variation: {\n  readonly name: string;\n  readonly label?: string;\n}): string {\n  return variation.label ?? variation.name;\n}\n","/**\n * The editor's words: what an author calls each place in it, spelled once.\n *\n * Every surface that names one of these places reads it from here — the rail,\n * the inspector's tabs, the Add panel, the Design panel — so a rename is one\n * edit and two surfaces cannot call one place by two names. The words are\n * the author's, not the code's: \"Shared styles\" rather than classes,\n * \"Variables\" rather than tokens, \"Saved sections\" rather than patterns.\n *\n * The words for what a variable gives the places using it are here too, by\n * kind, for the same reason: \"colour\" rather than color, \"size\" rather than\n * dimension, said one way wherever a variable's loss is.\n *\n * @module editor-words\n */\nimport type { TokenKind } from \"@nextlyhq/blocks-engine\";\n\nexport const EDITOR_WORDS = {\n  add: \"Add\",\n  layers: \"Layers\",\n  pages: \"Pages\",\n  components: \"Components\",\n  design: \"Design\",\n  // The Design panel's tabs, by kind.\n  colours: \"Colours\",\n  type: \"Type\",\n  spacing: \"Spacing\",\n  styles: \"Styles\",\n  variables: \"Variables\",\n  sharedStyles: \"Shared styles\",\n  blockStyles: \"Block styles\",\n  fonts: \"Fonts\",\n  // The Type tab's section setting every page's text.\n  siteText: \"Site text\",\n  // The Type tab's named looks of text, which any block can wear.\n  textStyles: \"Text styles\",\n  sections: \"Saved sections\",\n  content: \"Content\",\n  style: \"Style\",\n  advanced: \"Advanced\",\n  settings: \"Settings\",\n  help: \"Help\",\n  blocks: \"Blocks\",\n  page: \"Page\",\n} as const;\n\n/** One place the editor names, by its key in {@link EDITOR_WORDS}. */\nexport type EditorWord = keyof typeof EDITOR_WORDS;\n\n/**\n * The verb for each conversion between a selection, a saved section and a\n * component, spelled once. The bar, its ⋯ menu, the right-click menu and the\n * command palette all name these three with these words, so an author meets\n * one verb for one act wherever they look for it.\n */\nexport const CONVERSION_WORDS = {\n  saveAsSection: \"Save as section…\",\n  turnIntoComponent: \"Turn into component…\",\n  detachFromComponent: \"Detach from component\",\n} as const;\n\n/**\n * The top bar's light and dark preview: its name for assistive technology,\n * which stays the same pressed or not, and its tooltip, which says that\n * nothing a visitor sees changes with it.\n */\nexport const DARK_PREVIEW_WORDS = {\n  name: \"Preview in dark mode\",\n  tooltip: \"Preview only. Visitors see what their own device is set to.\",\n} as const;\n\n/**\n * The Type tab's two site-wide fonts: their names, what each says while it\n * writes nothing, and the line under Headings when its font has no bold.\n */\nexport const FONT_ROLE_WORDS = {\n  body: \"Body font\",\n  heading: \"Headings font\",\n  ownFont: \"Your site's own font\",\n  sameAsBody: \"Same as body\",\n  addBold: \"Add Bold\",\n} as const;\n\n/** The line under Headings when its font has no bold of its own. */\nexport function noBoldWords(family: string): string {\n  return `${family} has no Bold, so browsers draw a fake bold`;\n}\n\n/**\n * What a place using a variable would lose with it, by the variable's kind:\n * \"they would lose this colour\". The author's words for each kind, not the\n * engine's, so a dimension is a size and anything without a plainer word is\n * a value.\n */\nexport const VARIABLE_LOSS_WORDS: Readonly<\n  Record<TokenKind | \"lineHeight\", string>\n> = {\n  color: \"colour\",\n  dimension: \"size\",\n  fontFamily: \"font\",\n  fontWeight: \"font weight\",\n  number: \"value\",\n  shadow: \"shadow\",\n  duration: \"value\",\n  custom: \"value\",\n  // A type size's line height, removed on its own beside a size the site's\n  // code supplies: a dimension, but what the places lose is its line height.\n  lineHeight: \"line height\",\n};\n\n/**\n * The Design panel's ⋯ menu of site-wide actions, and the words of what an\n * export reports. Each item says what it makes; \"DTCG\" is only ever the hint\n * beside the one that writes that format.\n */\nexport const DESIGN_ACTION_WORDS = {\n  more: \"More design actions\",\n  importTokens: \"Import design tokens…\",\n  exportTokens: \"Export design tokens (.json)\",\n  exportTokensHint: \"DTCG 2025.10\",\n  exportFigma: \"Export for Figma\",\n  copyCss: \"Copy CSS variables\",\n  notExported: \"What wasn't exported\",\n  kept: \"Kept for Nextly only\",\n  leftOut: \"Left out\",\n  withoutData: \"Exported without its extra data\",\n  textStyles: \"Text styles\",\n  alsoInFile: \"Also in the file\",\n  missingFonts: \"Fonts this site doesn't have\",\n  addFromGoogle: \"Add from Google Fonts\",\n  fontAdded: \"Added\",\n  uploadFont: \"Upload its font file in Fonts to use it.\",\n  /** Why a shadow or a text style is not in the Figma files. */\n  figmaStyles:\n    \"Figma keeps these as effect styles and text styles; the variables they use are in the file\",\n} as const;\n","/**\n * What the inserter may offer, and where a chosen entry would land.\n *\n * Pure, and separate from the panel that draws it, for the reason\n * `shell-state` gives: this is set membership and derivation, none of it needs\n * React, and a component test in jsdom cannot assert it — jsdom reports every\n * element as zero-sized and renders a filtered list identically to an unfiltered\n * one that happens to be short. The decisions are made here, where they can be\n * asserted; the panel only draws what this returns.\n *\n * **The palette and the insert must agree, and that is why the target travels\n * with the position.** A panel that decides what to OFFER from one reading and\n * inserts against another will show a block, accept the click, and have the op\n * layer refuse it — a refusal the author cannot act on, because the thing they\n * were offered is the thing that was rejected. {@link insertionCandidates}\n * therefore hands out each place as a position AND the target it implies, and\n * everything downstream takes the target from it rather than recomputing one.\n *\n * **The nesting rule is CALLED, never restated.** `canBeRoot` and `canNest`\n * come from the engine, which documents itself as the one implementation\n * precisely because a canvas judging a drop and a validator judging a stored\n * document are the same question at different moments.\n *\n * This module answers where an entry may be inserted and the node it inserts,\n * and is the entry for the rest: the entries' shapes are in\n * `inserter-types.ts`, building the catalog in `inserter-catalog.ts`, the\n * palette's search and groups in `inserter-palette.ts`, and the places an\n * insert could land in `insertion-candidates.ts`.\n *\n * @module inserter\n */\n\nimport {\n  expandSlotDefaults,\n  makeNode,\n  placementTypesOf,\n  canPlace,\n  placementVerdict,\n  registryBlockSource,\n  COMPONENT_INSTANCE_TYPE,\n  type AnyBlockDefinition,\n  type BlockDocument,\n  type BlockNode,\n  type ComponentLookup,\n  type NestingSource,\n  type NestingVerdict,\n  type PlacedNode,\n  type PlacementSite,\n  type PlacementSources,\n  type PlacementTarget,\n  type PlacementVerdict,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type {\n  BlockInsertEntry,\n  InsertEntry,\n  SlotSource,\n} from \"./inserter-types\";\nimport { definitionsByName } from \"./insertion-candidates\";\n\n// The entries' shapes, building the catalog, grouping and searching the\n// palette, and where an insert may land live in modules of their own beside\n// this one; every name this module exported still is.\nexport {\n  blockLabel,\n  catalogFrom,\n  COMPONENT_ENTRY_PREFIX,\n  componentEntriesFrom,\n  type CompositionRefusal,\n  compositionRefusal,\n  insertionPropSets,\n  nodeForComponentEntry,\n  PATTERN_ENTRY_PREFIX,\n  patternEntriesFrom,\n  unplaceableComponentEntries,\n  variationLabel,\n} from \"./inserter-catalog\";\nexport {\n  categoryHeading,\n  filterEntries,\n  groupByCategory,\n  type InsertGroup,\n  paletteGroups,\n} from \"./inserter-palette\";\nexport {\n  type BlockInsertEntry,\n  COMPONENT_CATEGORY,\n  type ComponentInsertEntry,\n  type InsertEntry,\n  type InsertTarget,\n  type PatternInsertEntry,\n  type SavedComponent,\n  type SavedPattern,\n  type SlotSource,\n  slotsShowingEmpty,\n  UNCATEGORISED,\n  type PlacementTarget,\n} from \"./inserter-types\";\nexport {\n  type InsertionCandidate,\n  insertionCandidates,\n  insertionFor,\n} from \"./insertion-candidates\";\n\n/**\n * Whether this entry may be placed at this target, and why not when it may not.\n *\n * The verdict travels rather than a boolean, because a caller explaining a\n * refusal is the only place the reason is still known — and recovering it means\n * classifying the placement a second time.\n *\n * BOTH halves are asked, and the child's first. `block.ts` is explicit that\n * neither implies the other: a slot naming a type does not confine that type to\n * it, and a child restricting its parents says nothing about which of that\n * parent's slots may hold it. Asking only the allow-list would offer a column\n * at the page root; asking only `parent` would let anything into a slot that\n * names what it holds.\n *\n * The child's half runs first so its reason survives when both would refuse.\n * \"This block belongs inside a Columns\" tells an author where to go; \"this\n * region does not take that block\" leaves them looking for a region, which is\n * the less actionable of the two sentences.\n */\nexport function entryAllowedAt(\n  entry: InsertEntry,\n  target: PlacementTarget,\n  source: NestingSource,\n  definitions?: ComponentLookup\n): NestingVerdict {\n  // A pattern and a component are both judged by their ROOTS. The instance\n  // node's own type is not a registered block, and the nesting source answers\n  // \"no restriction\" for a type it cannot resolve — so judging the instance by\n  // its type would let a component whose root is a section be placed inside a\n  // paragraph. The definition's roots are what will actually render there,\n  // and a component's were read through the canvas's lookup when it was\n  // offered.\n  if (entry.kind === \"pattern\") {\n    return rootsAllowedAt(entry.document, target, source, definitions);\n  }\n  if (entry.kind === \"component\") {\n    return placementVerdict(entry.roots, target, source);\n  }\n  return blockAllowedAt(entry.blockName, target, source);\n}\n\n/**\n * Whether every root of a pattern may sit at a target.\n *\n * A pattern arrives as a FOREST and is inserted as one atomic group, so it goes\n * where all of its roots go: offering one whose second root the destination\n * refuses would accept the click and then have the planner reject the whole\n * insert, which is the palette-and-drop disagreement this module exists to\n * prevent. `planInsertPattern` asks exactly this before it plans, root by root,\n * against the same rule.\n *\n * The FIRST refusal is returned rather than a collected list, and the reason is\n * the point: a verdict names one restriction and the set that produced it, so\n * an author is told where the thing they picked can go. A refusal summarising\n * three roots would name none of them.\n *\n * Only the roots. A pattern's INTERNAL nesting is a property of the pattern\n * rather than of the destination — it is the same wherever it is offered — so\n * it belongs to whatever judges the pattern itself, not to a question about\n * this target.\n *\n * Each root is resolved as a placed node is ({@link placementTypesOf}): a\n * pattern is COPIED into the page as it stands, and one of its roots may be a\n * component instance — saving a placed component as a pattern stores exactly\n * that node. Judged by its own type, which is not a registered block and which\n * the nesting source therefore restricts nowhere, such a pattern was offered\n * where the component's own tile is refused.\n */\nfunction rootsAllowedAt(\n  document: BlockDocument,\n  target: PlacementTarget,\n  source: NestingSource,\n  definitions?: ComponentLookup\n): NestingVerdict {\n  return placementVerdict(\n    document.nodes.flatMap(root => placementTypesOf(root, definitions)),\n    target,\n    source\n  );\n}\n\n/**\n * The block types a node ALREADY ON THE PAGE is judged by when it moves.\n *\n * The engine's rule, re-exported here because this is where the builder's\n * placement questions are answered and every one of them asks it: the drag,\n * the keyboard move, a pattern's roots, and — in the engine itself — the\n * planners the click runs. One implementation, so an offer cannot resolve\n * against a forest the mutation judges raw.\n */\nexport { placementTypesOf };\n\n/**\n * Whether a block type may be placed at a target, by NAME.\n *\n * The same rule as {@link entryAllowedAt} and the same code, reached without a\n * palette entry. A drag moves a node that already exists, so the only thing it\n * has is a type name — and asking the question a second way is how the palette\n * and the canvas come to disagree about where a block may go, with the palette\n * offering what the drop refuses.\n *\n * Both halves are asked, because a placement needs both to agree and neither is\n * derivable from the other: `parent` is the child saying where it makes sense,\n * a slot's `allow` is the container saying what it holds.\n *\n * The child's half runs first so its reason survives when both would refuse.\n * \"This block belongs inside a Columns\" tells an author where to go; \"this\n * region does not take that block\" leaves them looking for a region, which is\n * the less actionable of the two sentences.\n */\nexport function blockAllowedAt(\n  blockName: string,\n  target: PlacementTarget,\n  source: NestingSource\n): NestingVerdict {\n  return placementVerdict([blockName], target, source);\n}\n\n/**\n * The entries a target will actually accept: {@link entryVerdictAt}'s allowed\n * ones, for a caller that needs the set rather than each reason.\n */\nexport function allowedEntries<TEntry extends InsertEntry>(\n  entries: readonly TEntry[],\n  target: PlacementTarget,\n  source: NestingSource,\n  definitions?: ComponentLookup,\n  placement?: EntryPlacement\n): TEntry[] {\n  // Derived from the verdict rather than asked beside it, so the set and the\n  // reasons the panel shows for what is left out come from one question.\n  return entries.filter(\n    entry =>\n      entryVerdictAt(entry, target, source, definitions, placement).allowed\n  );\n}\n\n/**\n * Whether one entry may be placed at a target, with the rule's reason when it\n * may not.\n *\n * The verdict rather than a boolean, because the Add panel keeps a refused\n * entry in view and says why: an author who cannot see a block has no way to\n * learn where it would go.\n */\nexport function entryVerdictAt(\n  entry: InsertEntry,\n  target: PlacementTarget,\n  source: NestingSource,\n  definitions?: ComponentLookup,\n  /**\n   * The place as the one placement rule sees it: the site, with what its\n   * ancestors refuse, and what an insert expands a block's starting children\n   * from. Absent, the entry is judged by the name rules alone.\n   */\n  placement?: EntryPlacement\n): NestingVerdict | PlacementVerdict {\n  // Present, the placement rule is the whole answer: it asks the name rules\n  // itself, of the same parent and slot, for a component's roots read through\n  // `placement.sources.components`, which is why that has to be the lookup\n  // the catalog was built with. Asking `entryAllowedAt` beside it would ask\n  // each name rule twice.\n  return placement === undefined\n    ? entryAllowedAt(entry, target, source, definitions)\n    : canPlace(\n        insertedBy(entry, placement.expansion),\n        placement.site,\n        placement.sources\n      );\n}\n\n/** What {@link allowedEntries} needs to judge entries by the one placement rule. */\nexport interface EntryPlacement {\n  readonly site: PlacementSite;\n  /**\n   * Where the rule reads its answers. `components` is the lookup the catalog's\n   * component and pattern entries were read through: the rule judges a\n   * placement by the roots it reads there, and without it a placement's roots\n   * are unknown and restrict nothing.\n   */\n  readonly sources: PlacementSources;\n  /**\n   * The pair a click insert hands {@link nodeForEntry}, so a block is judged\n   * with exactly the children its insert seeds.\n   */\n  readonly expansion: {\n    readonly definitions: SlotDefaultSource;\n    readonly nesting: NestingSource | undefined;\n  };\n}\n\n/**\n * What an entry would insert, as the placement rule reads it: a block as\n * {@link nodeForEntry} builds it, starting children included, a pattern's\n * blocks, or a component placement.\n *\n * A block is built by the insert's own function rather than described as its\n * type and props: a block whose slot starts with a clickable child is refused\n * under a linked card for that child, and judging the empty shell would offer\n * a row whose click the store then refuses.\n */\nfunction insertedBy(\n  entry: InsertEntry,\n  expansion: EntryPlacement[\"expansion\"]\n): readonly PlacedNode[] {\n  switch (entry.kind) {\n    case \"block\":\n      return [nodeForEntry(entry, expansion.definitions, expansion.nesting)];\n    case \"pattern\":\n      return entry.document.nodes;\n    case \"component\":\n      return [\n        {\n          type: COMPONENT_INSTANCE_TYPE,\n          props: { componentId: entry.componentId },\n        },\n      ];\n  }\n}\n\n/**\n * The node a BLOCK entry inserts, carrying whatever children its block declares\n * it starts with.\n *\n * Blocks only, and the parameter says so rather than the body branching. One\n * pattern is a forest, re-identified against the ids the destination already\n * holds and planned as one atomic group — `planInsertPattern` in the engine —\n * so there is no single node to hand back, and a function returning one for a\n * pattern would have to invent an answer or throw.\n *\n * Props are deep-copied. The entry outlives every insert made from it, so\n * handing out its own object would let an edit to one inserted block reach the\n * catalog — and through it every block inserted from that entry afterwards.\n * A shallow copy is not enough, because a default value may be an array or a\n * nested object and those would still be shared.\n *\n * The children come from `expandSlotDefaults` rather than from anything written\n * here, so \"what does this slot start with\" is answered in one place: the block\n * declares it, the engine expands it with ids minted per instance, and a\n * container that declares nothing still arrives with no `slots` key at all.\n * Building the children here instead would put a second answer beside the\n * declaration, and the two would agree only until one of them changed.\n */\nexport function nodeForEntry(\n  entry: BlockInsertEntry,\n  definitions: SlotDefaultSource,\n  nesting?: NestingSource\n): BlockNode {\n  return makeNode(\n    entry.blockName,\n    entry.version,\n    structuredClone(entry.props),\n    // The nesting source travels with the definitions rather than being\n    // rederived inside the engine. A caller that supplies its own rules uses\n    // them to decide what may be OFFERED, and a seeded child that skipped them\n    // would be a placement the caller's own rules forbid, arriving by being\n    // declared rather than chosen.\n    expandSlotDefaults(entry.blockName, definitions, nesting)\n  );\n}\n\n/**\n * The registry as a block-definition source, re-exported from the engine.\n *\n * Defined there rather than here because the save validator reads the same\n * source to check a locked slot's children, and two readings of one registry\n * agree only until one of them changes.\n */\nexport { registryBlockSource };\n\n/**\n * The definitions an insert expands declared starting children from, given the\n * palette's own catalog.\n *\n * Supplied definitions are consulted FIRST and the registry second, which is\n * what keeps the offer and the insert reading one declaration. A caller may\n * hand the palette a definition the registry does not hold — a host block, a\n * fixture — and the catalog then offers it; resolving only against the registry\n * would find no declaration for that block and insert it stripped of the\n * children it declares, silently, because an absent declaration and a declared\n * emptiness are the same answer.\n *\n * The fallback is the other half and not a leftover: an entry names child TYPES\n * the supplied list has no reason to contain, so those still resolve against\n * everything registered. Consulting the supplied list first changes which\n * declaration wins for a name in both, and that is the intended order — the\n * palette offered THAT definition, so the insert must build THAT block.\n */\nexport function blockSourceFor(\n  definitions: readonly AnyBlockDefinition[] | undefined\n): SlotDefaultSource {\n  // Both readings are taken ONCE, here, rather than on each lookup. A source\n  // that consulted the live registry per call would answer from a different\n  // set of definitions than the catalog its caller built alongside it, so a\n  // row offered from one reading could be inserted with children from another.\n  const byName = definitionsByName(definitions);\n  return { get: type => byName.get(type) };\n}\n\n/**\n * The registry as a slot source.\n *\n * DERIVED from `registryBlockSource` rather than reading the registry again:\n * the names of a block's slots are a narrower view of its declaration, and two\n * readings of one registry would agree until one of them learned to filter.\n *\n * Here rather than beside either caller. The palette asks it where an insert\n * would land and the canvas asks it which regions a drag can aim at, and those\n * two have to agree: a container the palette will fill but the drag cannot see\n * is a block that behaves differently depending on how an author reached it.\n */\nexport function registrySlotSource(): SlotSource {\n  const definitions = registryBlockSource();\n  return {\n    slotsOf: type => {\n      const declared = definitions.get(type)?.slots;\n      return declared === undefined ? undefined : Object.keys(declared);\n    },\n  };\n}\n","/**\n * When a drag is allowed to change its drop target.\n *\n * A pointer resting near the boundary between two drop targets jitters by a pixel\n * or two, and the target underneath it alternates with the jitter. Committed\n * directly, that alternation is visible as a flickering insertion indicator and as\n * a block landing somewhere the author did not aim — the two failures this rule\n * exists to remove.\n *\n * The rule: **a candidate target must hold while the pointer travels a set\n * distance before it replaces the committed one.**\n *\n * @remarks\n * **Why distance rather than a dwell timer.** A timer makes the editor's\n * behaviour depend on how long the author hesitates, so a slow deliberate drag\n * and a jitter become indistinguishable, and the delay is felt on every genuine\n * boundary crossing. Distance is a property of the gesture rather than of the\n * clock: a 2px jitter never accumulates it, and a deliberate move always does.\n *\n * **Why nothing here reads a BLOCK's size.** The obvious alternative is to\n * require a target to be some minimum height before it can be claimed, which is\n * what a survey of the field suggests. It cannot work in this editor. A\n * `core/spacer`'s height is an author-set prop with no lower bound and a divider\n * is a single pixel, so any absolute floor makes some authored block impossible\n * to drop beside. Keying on the GAP between blocks moves the same hazard rather\n * than removing it, because two blocks with no margin have a gap of zero. This\n * rule reads two points and a number, so a 1px divider, a 0px spacer, a 900px\n * hero, a vertical stack and a grid all behave identically.\n *\n * The functions are pure and take plain points, so the behaviour is exercised\n * without a browser and the pointer reads stay at the edge.\n *\n * @module target-switch\n */\nimport type { Point } from \"../geometry\";\n\n/**\n * A drop target's identity, or `null` for \"the pointer is over none\".\n *\n * `null` is an ordinary value here rather than an absence: losing a target at a\n * boundary flickers exactly as gaining the wrong one does, so dropping the\n * committed target is held to the same threshold as replacing it.\n */\nexport type TargetId = string | null;\n\n/**\n * A candidate that has appeared but not yet earned the switch.\n *\n * `anchor` is where the pointer was when this candidate FIRST differed from the\n * committed target, which is the subtlety the whole rule turns on. See\n * {@link nextTargetSwitchState}.\n */\nexport interface PendingTarget {\n  readonly target: TargetId;\n  readonly anchor: Point;\n}\n\n/** What the rule remembers between pointer moves. */\nexport interface TargetSwitchState {\n  /** The target actually in effect — what the indicator draws and a drop uses. */\n  readonly committed: TargetId;\n  /** A rival waiting to earn the switch, or `null` when none is waiting. */\n  readonly pending: PendingTarget | null;\n}\n\n/** A drag that has not yet resolved a target. */\nexport const NO_TARGET: TargetSwitchState = {\n  committed: null,\n  pending: null,\n};\n\n/** Straight-line distance between two points. */\nfunction distance(a: Point, b: Point): number {\n  return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\n/**\n * Advances the rule by one pointer move.\n *\n * @param state - what the previous move left behind; {@link NO_TARGET} to begin\n * @param candidate - the target the collision engine resolves at `pointer` now\n * @param pointer - the pointer, in any one coordinate space used consistently\n * @param thresholdPx - how far the pointer must travel for a rival to win\n * @returns the next state; `committed` is what the editor should act on\n *\n * @throws RangeError if `thresholdPx` is negative or not finite. A threshold is\n * a contract rather than a hint, and a `NaN` arriving from an unparsed\n * configuration value would make every comparison false and silently disable the\n * rule — a flickering canvas with nothing to point at.\n *\n * @remarks\n * **The anchor is where the candidate CHANGED, not where the last switch\n * happened, and the difference is the whole mechanism.**\n *\n * Measuring from the last switch reads plausibly and gives no hysteresis at all\n * in the commonest case. An author dragging from the block library crosses most\n * of the page before reaching the seam between two blocks: by the time they\n * arrive, the distance since the last switch is already far past any threshold,\n * so the first pixel over the boundary switches immediately and the jitter that\n * follows switches back just as fast. The rule would be satisfied and absent\n * exactly where it is needed.\n *\n * Anchoring at the moment the candidate first differs makes the threshold\n * measure the crossing itself, so it costs the same and applies wherever the\n * crossing happens.\n *\n * **Displacement, not path length.** A pointer jittering back and forth across a\n * seam accumulates unbounded path length while never getting anywhere, so a path\n * measure would eventually grant the switch it exists to withhold. Distance from\n * the anchor cannot be accumulated by going nowhere.\n *\n * **The first target commits immediately.** There is nothing to flicker between\n * before a target exists, and withholding it would leave a drag with no\n * indicator until the pointer had travelled the threshold, which reads as the\n * canvas failing to respond.\n */\nexport function nextTargetSwitchState(\n  state: TargetSwitchState,\n  candidate: TargetId,\n  pointer: Point,\n  thresholdPx: number\n): TargetSwitchState {\n  if (!Number.isFinite(thresholdPx) || thresholdPx < 0) {\n    throw new RangeError(\n      `target switch threshold must be a finite, non-negative number of pixels, received ${String(thresholdPx)}`\n    );\n  }\n\n  // Agreement clears any rival: a candidate that has gone back to matching what\n  // is committed is no longer waiting for anything, and leaving it pending would\n  // let a later return to that same value inherit a stale anchor and switch on a\n  // crossing it never made.\n  if (candidate === state.committed) {\n    return state.pending === null ? state : { ...state, pending: null };\n  }\n\n  // Nothing is committed yet, so there is no incumbent to protect.\n  if (state.committed === null) {\n    return { committed: candidate, pending: null };\n  }\n\n  // A different rival from the one that was waiting restarts the measurement,\n  // because the distance travelled while some OTHER target was pending says\n  // nothing about how far the pointer has moved since this one appeared.\n  //\n  // Established and then MEASURED in the same move rather than returned early.\n  // A new rival is zero pixels from its own anchor, so the check below rejects\n  // it for any positive threshold exactly as an early return would — and a\n  // threshold of zero, which is a legitimate request for no hysteresis, switches\n  // at once instead of carrying a one-move delay nothing asked for.\n  const pending =\n    state.pending !== null && state.pending.target === candidate\n      ? state.pending\n      : { target: candidate, anchor: pointer };\n\n  if (distance(pointer, pending.anchor) < thresholdPx) {\n    return state.pending === pending ? state : { ...state, pending };\n  }\n\n  // Earned. The rival becomes the incumbent and the next crossing is measured\n  // from wherever it happens rather than from here.\n  return { committed: candidate, pending: null };\n}\n","/**\n * Whether a stored block's conditions decide who sees it, as the published\n * page judges it. Its own module, importing nothing of the editor's\n * controls, so Layers and the canvas can ask it without depending on them.\n *\n * @module condition-gate\n */\nimport {\n  DEFAULT_LIMITS,\n  isConditionGated,\n  storedVisibilityOf,\n  type BlockNode,\n  type ComponentLookup,\n  type DefinitionsById,\n  type DocumentLimits,\n} from \"@nextlyhq/blocks-engine\";\nimport { repairingLookup } from \"@nextlyhq/blocks-react\";\n\n/**\n * Whether a stored block's conditions decide who sees it, as the published\n * page judges it: through the engine's gate, with any placement gates a\n * stored document holds removed first, as the renderer removes them. The one\n * question the canvas badge, Layers and these checks all ask.\n */\nexport function gatedAsStored(node: BlockNode): boolean {\n  return isConditionGated({ visibility: storedVisibilityOf(node.visibility) });\n}\n\n/**\n * Whether a block of a composed tree is drawn only for some visitors: its own\n * conditions, or the gates of the placements it was expanded from, which only\n * the tree a renderer composes holds and the page judges with the rest.\n */\nexport function gatedAsDrawn(node: BlockNode): boolean {\n  return isConditionGated(node);\n}\n\n/**\n * The definitions as the renderer reads them, so the canvas's marks and the\n * conditions it can't check compose exactly the tree the canvas draws. It is\n * the renderer's own repairing lookup, not a copy of it: a placement gate\n * stored in a definition, as hand-edited or older data may hold, is removed;\n * an entry that is not a block is dropped before it counts against the page's\n * node budget; a tree past the limits is read no further than the renderer\n * reads it; and a definition it can't read at all is reported unreadable by\n * the resolver rather than throwing here. Each one is read on demand, so a\n * large component library costs nothing until a page places it.\n */\nexport function asStoredDefinitions(\n  definitions: DefinitionsById,\n  limits?: DocumentLimits\n): ComponentLookup {\n  return repairingLookup(definitions, limits ?? DEFAULT_LIMITS);\n}\n","/**\n * A block's own custom CSS, as the panel reads and writes it: whether a block\n * holds some, the words that name it, and the one op that stores it.\n *\n * The CSS is kept on the node as the author wrote it, with `selector` where\n * the block goes; the engine scopes it when the page is compiled. The panel\n * checks it before storing as a courtesy, and the server judges every write\n * again, so nothing here is the gate.\n *\n * @module custom-css\n */\nimport type { BlockNode } from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\n\n/**\n * What the panel needs to offer a block's custom CSS: given only to someone\n * who may change the site's settings, the permission site code is held to.\n * Without it the panel draws no Custom CSS section and never shows the CSS.\n *\n * @experimental Settles with custom CSS.\n */\nexport interface BlockCustomCssAccess {\n  /**\n   * Checks a block's CSS as the server will: every line that can't be used,\n   * each worded for the author with its line (\"Line 3: …\"), in line\n   * order; none when it may be stored.\n   */\n  readonly check: (css: string) => readonly string[];\n}\n\n/** The section's name in Advanced, which its fold is remembered by. */\nexport const CUSTOM_CSS_SECTION = \"Custom CSS\";\n\n/** The section's key in the Advanced tab's accordion. */\nexport const CUSTOM_CSS_KEY = \"custom-css\";\n\n/** The setting's id, as the settings index and an ask for it name it. */\nexport const CUSTOM_CSS_SETTING = \"customCss\";\n\n/** The Layers mark's words: its tooltip and its accessible name. */\nexport const HAS_CUSTOM_CSS = \"Has custom CSS\";\n\n/**\n * Whether a block holds custom CSS: a stored value with more than white\n * space in it. One answer for the Layers mark, the Style tab's line, the\n * section's value dot and \"Only changed\".\n */\nexport function holdsCustomCss(\n  node: Pick<BlockNode, \"customCss\"> | undefined\n): boolean {\n  return typeof node?.customCss === \"string\" && node.customCss.trim() !== \"\";\n}\n\n/**\n * The op that stores a block's CSS, or removes it once the box is emptied, so\n * a block whose CSS was cleared keeps no empty value behind. One update, so it\n * is one undoable step.\n */\nexport function customCssOp(nodeId: string, css: string): BuilderOp {\n  return css.trim() === \"\"\n    ? { kind: \"update\", id: nodeId, patch: {}, unset: [\"customCss\"] }\n    : { kind: \"update\", id: nodeId, patch: { customCss: css } };\n}\n","/**\n * What a component placement stores, read defensively.\n *\n * A placement is one node of the engine's instance type whose props name the\n * component it draws. Two readers need that id — the instance inspector, which\n * edits the placement, and the layers tree, which names it — and they must\n * read it the same way. Kept apart from both because each imports a module\n * that imports the other's.\n *\n * @module placement-props\n */\n\nimport type { BlockNode } from \"@nextlyhq/blocks-engine\";\n\n/**\n * The component id the node stores, or an empty string for a node that names\n * none.\n *\n * Read defensively: a stored document can hold anything the database\n * returned, and a `componentId` that is not a string must not reach a lookup\n * typed for one. An empty id resolves to no definition, which the panel then\n * says.\n */\nexport function storedComponentId(node: BlockNode): string {\n  const id = instanceProps(node).componentId;\n  return typeof id === \"string\" ? id : \"\";\n}\n\n/**\n * The instance's props as a record, or an empty one.\n *\n * A stored document can hold an instance whose `props` is missing or is not a\n * record — an import, a hook, a hand edit — and the canvas draws it as a\n * malformed placeholder rather than failing. Selecting that placeholder must\n * not throw either, so every read of an instance's props goes through this\n * one guard, which is how the resolver reads them too.\n */\nexport function instanceProps(node: BlockNode): Record<string, unknown> {\n  const props: unknown = node.props;\n  return typeof props === \"object\" && props !== null && !Array.isArray(props)\n    ? (props as Record<string, unknown>)\n    : {};\n}\n","/**\n * The document as a structure an author can see: the layers tree, the path to\n * the selected block, and what a search leaves standing.\n *\n * The canvas shows a page. It does not show that the heading is inside a box\n * which is inside a section, and it cannot show a block that renders nothing —\n * an empty container is a couple of pixels, and a block hidden at the current\n * breakpoint is not there at all. Those are exactly the blocks an author loses.\n * This module is the other view of the same document.\n *\n * **One tree, two consumers.** The layers panel draws it and the breadcrumb\n * walks it, so both take their labels, their nesting and their badges from\n * here. Computed separately they would agree until the first time either\n * changed what it matched, and the disagreement would be silent: a breadcrumb\n * naming one ancestor while the panel highlights another.\n *\n * ## Children are flattened across slots, and that is measured rather than\n * assumed\n *\n * A block may declare several named child regions. Every container in the core\n * library declares exactly ONE, always called `children` — measured across the\n * catalogue, 9 containers with one slot and none with more. So a flat tree\n * describes the document faithfully today, and slot rows would add a level of\n * nesting to every tree in order to name a distinction no block currently\n * makes.\n *\n * **One block has two regions an author tells apart:** a collection list's\n * template, repeated for each entry, and its empty state, drawn when none\n * match. Its row names both ({@link LayerNode.slotRows}) and each child says\n * which it sits in ({@link LayerNode.slot}), so the panel draws \"Each entry\"\n * and \"When empty\" between the list and its blocks. The children stay one\n * flat list here, so the breadcrumb, the search and every caller walking the\n * tree read it as before. Any other block declaring two slots still renders\n * its children in one flat run; this is the module that grows its rows too.\n *\n * Pure, and it takes a document rather than a registry lookup per row, so the\n * tree can be asserted without React and without a DOM.\n *\n * @module layers\n */\n\nimport {\n  allBlocks,\n  COLLECTION_LIST_TYPE,\n  hiddenOnDevice,\n  isComponentInstance,\n  type AnyBlockDefinition,\n  type BlockDocument,\n  type BlockNode,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { gatedAsStored } from \"../../conditions/condition-gate\";\nimport { holdsCustomCss } from \"../../inspector/custom-css\";\nimport { storedComponentId } from \"../../placement-props\";\nimport { blockLabel, type SavedComponent } from \"../add/inserter\";\n\n/**\n * A component's title, by the id a placement stores.\n *\n * A placement is one node of the engine's instance type, so its type says only\n * that it IS a placement; the document holds no title. The library is the one\n * holder of a component's title, and the host that read it hands this in.\n */\nexport type ComponentTitleOf = (componentId: string) => string | undefined;\n\n/** What a placement reads as when nothing names its component. */\nexport const UNNAMED_COMPONENT = \"Component\";\n\n/**\n * The title lookup for a library's rows, built once per list.\n *\n * A map rather than a search per row, since the tree asks once for every\n * placement on the page, on every render.\n */\nexport function componentTitles(\n  components: readonly Pick<SavedComponent, \"id\" | \"title\">[]\n): ComponentTitleOf {\n  const titles = new Map(\n    components.map(component => [component.id, component.title] as const)\n  );\n  return componentId => titles.get(componentId);\n}\n\n/**\n * One block, as a row in the tree.\n *\n * Badges are FACTS about the node rather than switches. `locked` is a boolean\n * the engine defines; the two visibility flags are not, and conflating them\n * into one \"hidden\" is the mistake this shape exists to prevent — see\n * {@link LayerNode.conditional}.\n */\nexport interface LayerNode {\n  readonly id: string;\n  readonly type: string;\n  /** The instance name if the author gave one, otherwise the block's name. */\n  readonly label: string;\n  /**\n   * The name the author gave, when they gave one: what a rename starts from.\n   * The label falls back to the type or the component's title, which is not\n   * a name the author wrote and must not be stored as one by a rename.\n   */\n  readonly name?: string;\n  /**\n   * The block is a component placement, so its row is marked as one: its label\n   * may be the component's title, which would otherwise read as a block's own\n   * name.\n   */\n  readonly component: boolean;\n  /** The author has locked this block in Layers. */\n  readonly locked: boolean;\n  /**\n   * The name of the block locked in Layers that this one sits inside, when it\n   * is not locked itself: a lock covers everything inside the block, so the\n   * row says it is held and by which block, where the lock is lifted.\n   */\n  readonly lockedBy?: string;\n  /**\n   * The block declares conditions, so whether it appears depends on the entry.\n   *\n   * NOT \"hidden\". Conditions are predicates over an entry's fields evaluated at\n   * render time, so the editor cannot know the answer — showing an eye here\n   * would state one. What is knowable, and worth showing, is that this block's\n   * presence is conditional at all.\n   */\n  readonly conditional: boolean;\n  /**\n   * The block is marked never to be quoted in search snippets, so its row\n   * says so in words a screen reader reads.\n   */\n  readonly notQuoted?: boolean;\n  /**\n   * The block holds custom CSS of its own, so its row is marked for everyone.\n   * Only that it does: the CSS itself is never part of the tree.\n   */\n  readonly customCss?: true;\n  /**\n   * The block is hidden at one or more breakpoints.\n   *\n   * Also not \"hidden\", for a different reason: visibility is per breakpoint, so\n   * a block hidden on mobile is fully present on desktop. A single eye would\n   * have to pick one of those to be true about.\n   */\n  readonly breakpointHidden: boolean;\n  /**\n   * The block is hidden on the device being edited, which is the device the\n   * canvas shows: the row is drawn dimmed with a \"Hidden\" badge. Only known\n   * when the tree was asked for a device.\n   */\n  readonly hiddenHere?: boolean;\n  /**\n   * The name of the block hidden on the device being edited that this one\n   * sits inside, when it is not hidden itself: a visitor on that device sees\n   * none of what the block holds, so the row says it is hidden with it, and\n   * where it is shown again.\n   */\n  readonly hiddenWith?: string;\n  /** The region of its parent this block sits in. */\n  readonly slot?: string;\n  /**\n   * The regions an author tells apart in this block, in order, each with\n   * what it is called: a collection list's \"Each entry\" and \"When empty\".\n   * Absent for a block whose children read as one run.\n   */\n  readonly slotRows?: readonly SlotRow[];\n  readonly children: readonly LayerNode[];\n}\n\n/**\n * One region of a block, as Layers draws it between the block and its\n * children. `rowId` is the row's own identity in the tree, chosen so that no\n * block of the document has it: a stored id may be any non-empty string, so\n * no spelling alone could be kept apart from them.\n */\nexport interface SlotRow {\n  readonly slot: string;\n  readonly label: string;\n  readonly rowId: string;\n}\n\n/** A collection list's regions, as Layers names them. */\nconst LIST_SLOT_ROWS = [\n  { slot: \"children\", label: \"Each entry\" },\n  { slot: \"empty\", label: \"When empty\" },\n] as const;\n\n/** Every block id in a document, so a region row can take an id none has. */\nfunction documentIds(nodes: readonly BlockNode[]): Set<string> {\n  const ids = new Set<string>();\n  const stack = [...nodes];\n  for (let node = stack.pop(); node !== undefined; node = stack.pop()) {\n    ids.add(node.id);\n    for (const children of Object.values(node.slots ?? {})) {\n      if (Array.isArray(children)) stack.push(...children);\n    }\n  }\n  return ids;\n}\n\n/**\n * A list's region rows, each with an id no block and no other row has: the\n * readable spelling, counted on until it is free. `taken` holds the\n * document's ids and grows with each row's.\n */\nfunction listSlotRows(parentId: string, taken: Set<string>): SlotRow[] {\n  return LIST_SLOT_ROWS.map(row => {\n    const spelled = `nx-slot:${row.slot}:${parentId}`;\n    let rowId = spelled;\n    for (let count = 1; taken.has(rowId); count += 1) {\n      rowId = `${spelled}~${String(count)}`;\n    }\n    taken.add(rowId);\n    return { ...row, rowId };\n  });\n}\n\n/**\n * The device the tree is read for: the site's breakpoints and the one being\n * edited, which decides each row's {@link LayerNode.hiddenHere}.\n */\nexport interface LayersDevice {\n  readonly breakpoints: BreakpointSet | undefined;\n  readonly id: string;\n}\n\n/** Whether any breakpoint switches this node off. */\nfunction hiddenAtSomeBreakpoint(node: BlockNode): boolean {\n  const devices = node.visibility?.devices;\n  if (devices === undefined) return false;\n  return Object.values(devices).some(visible => visible === false);\n}\n\n/**\n * Whether the node's conditions decide who sees it, asked of the engine's\n * own gate, so Layers marks exactly the blocks the page judges: conditions it\n * can't read included, a group with no conditions (which lets everyone\n * through) not.\n */\nfunction hasConditions(node: BlockNode): boolean {\n  return gatedAsStored(node);\n}\n\n/**\n * The author's own name for a node, when they gave it a non-blank one.\n *\n * Trimmed and an empty result treated as absent: a name of spaces would read\n * as though the author had named the block while giving nothing that\n * distinguishes it from its neighbours.\n *\n * Exported so a second caller needing \"does this node carry an authored\n * name\" asks this rather than restating the trim-and-blank check — precisely\n * the two-implementations risk this module's own header warns about for the\n * tree it builds from the same field.\n */\nexport function authoredName(node: BlockNode): string | undefined {\n  const named = node.name?.trim();\n  return named !== undefined && named !== \"\" ? named : undefined;\n}\n\n/**\n * The name an author reads for one block.\n *\n * An instance name wins, because it is the only part an author wrote. A\n * component placement is then named by its component's title: its type's\n * label, \"Component instance\", names the engine's mechanism rather than what\n * the author placed. With no title to read (none handed in, a component the\n * library no longer holds, a blank title) it is a \"Component\".\n */\nexport function layerLabel(\n  node: BlockNode,\n  lookup?: Parameters<typeof blockLabel>[1],\n  componentTitle?: ComponentTitleOf\n): string {\n  const named = authoredName(node);\n  if (named !== undefined) return named;\n  if (isComponentInstance(node)) {\n    const id = storedComponentId(node);\n    const title = id === \"\" ? undefined : componentTitle?.(id)?.trim();\n    return title === undefined || title === \"\" ? UNNAMED_COMPONENT : title;\n  }\n  // Forwarded as given, so an absent lookup keeps `blockLabel`'s own default\n  // rather than a second statement of it here.\n  return blockLabel(node.type, lookup);\n}\n\n/**\n * Every block's name in a document, by address, as Layers reads them, kept\n * per tree {@link layersOf} hands out: the canvas asks for a placement's name\n * each time it draws its frame, and a selection can hold many placements, so\n * the tree is read once rather than once per name. A tree built afresh (an\n * edit, another title lookup, a block registered) is read afresh.\n */\nconst BLOCK_NAMES = new WeakMap<readonly LayerNode[], Map<string, string>>();\n\n/**\n * The name of the block at an address anywhere in the document, as its Layers\n * row reads (see {@link layerLabel}), or `undefined` where the document holds\n * no such block. The canvas tags a selected placement with it, so the page and\n * the tree call one block by one name.\n */\nexport function blockNameOf(\n  document: BlockDocument,\n  id: string,\n  componentTitle?: ComponentTitleOf\n): string | undefined {\n  const tree = layersOf(document, componentTitle);\n  let names = BLOCK_NAMES.get(tree);\n  if (names === undefined) {\n    const found = new Map<string, string>();\n    const walk = (rows: readonly LayerNode[]): void => {\n      for (const row of rows) {\n        found.set(row.id, row.label);\n        walk(row.children);\n      }\n    };\n    walk(tree);\n    names = found;\n    BLOCK_NAMES.set(tree, names);\n  }\n  return names.get(id);\n}\n\n/** Which region of `node` each of its children sits in, by the child. */\nfunction slotsOfChildren(\n  node: BlockNode\n): (child: BlockNode) => string | undefined {\n  const by = new Map<BlockNode, string>();\n  for (const [slot, children] of Object.entries(node.slots ?? {})) {\n    if (!Array.isArray(children)) continue;\n    for (const child of children) by.set(child, slot);\n  }\n  return child => by.get(child);\n}\n\n/**\n * The region rows a tree holds, by their row id: the block each stands for\n * and its region. Read from the rows themselves, so a block whose id is\n * spelled like a row's is never taken for one.\n */\nexport function slotRowsIn(\n  tree: readonly LayerNode[]\n): ReadonlyMap<string, { readonly parentId: string; readonly slot: string }> {\n  const rows = new Map<string, { parentId: string; slot: string }>();\n  const stack = [...tree];\n  for (let node = stack.pop(); node !== undefined; node = stack.pop()) {\n    for (const row of node.slotRows ?? []) {\n      rows.set(row.rowId, { parentId: node.id, slot: row.slot });\n    }\n    stack.push(...node.children);\n  }\n  return rows;\n}\n\n/**\n * The regions on the way to a node: each list above it, the region the path\n * goes through, and that region's row. What the panel opens with the\n * node's ancestors, and what a list shows on the canvas so the node is drawn.\n */\nexport function regionsTo(\n  document: BlockDocument,\n  id: string | null\n): {\n  readonly parentId: string;\n  readonly slot: string;\n  readonly rowId: string;\n}[] {\n  const path = pathTo(document, id);\n  const regions: { parentId: string; slot: string; rowId: string }[] = [];\n  for (let index = 1; index < path.length; index += 1) {\n    const parent = path[index - 1];\n    const slot = path[index]?.slot;\n    const row = parent?.slotRows?.find(candidate => candidate.slot === slot);\n    if (parent !== undefined && row !== undefined) {\n      regions.push({ parentId: parent.id, slot: row.slot, rowId: row.rowId });\n    }\n  }\n  return regions;\n}\n\n/**\n * A document's tree with no device, as last built for a title lookup and the\n * registry's definitions, which name its rows. Kept for the untitled tree and\n * for the last titled one, so a lookup made again on every render keeps one.\n */\ninterface KeptTree {\n  readonly titles: ComponentTitleOf | undefined;\n  readonly blocks: readonly AnyBlockDefinition[];\n  readonly tree: LayerNode[];\n}\n\nconst KEPT_TREES = new WeakMap<\n  BlockDocument,\n  { untitled?: KeptTree; titled?: KeptTree }\n>();\n\n/** Whether two lists hold the same definitions, in the same order. */\nfunction sameDefinitions(\n  one: readonly AnyBlockDefinition[],\n  other: readonly AnyBlockDefinition[]\n): boolean {\n  return (\n    one.length === other.length &&\n    one.every((definition, index) => definition === other[index])\n  );\n}\n\n/**\n * The document as a tree of rows.\n *\n * `componentTitle` names component placements; see {@link layerLabel}.\n *\n * Without a device, the tree is built once per document, title lookup and set\n * of registered definitions and handed out again after that: the breadcrumb\n * and the selected block's toolbar and keyboard verbs each ask for the path to\n * the selection on every click, and each path was a whole tree. An edit makes\n * a new document, and a block registered or replaced changes the definitions,\n * so either is built afresh. What is handed out is shared, so no caller may\n * change it.\n */\nexport function layersOf(\n  document: BlockDocument,\n  componentTitle?: ComponentTitleOf,\n  device?: LayersDevice\n): LayerNode[] {\n  if (device !== undefined)\n    return buildLayers(document, componentTitle, device);\n  const blocks = allBlocks();\n  const kept = KEPT_TREES.get(document) ?? {};\n  const slot = componentTitle === undefined ? \"untitled\" : \"titled\";\n  const found = kept[slot];\n  if (\n    found !== undefined &&\n    found.titles === componentTitle &&\n    sameDefinitions(found.blocks, blocks)\n  ) {\n    return found.tree;\n  }\n  const tree = buildLayers(document, componentTitle, undefined);\n  KEPT_TREES.set(document, {\n    ...kept,\n    [slot]: { titles: componentTitle, blocks, tree },\n  });\n  return tree;\n}\n\n/** The tree {@link layersOf} answers with, built from the document. */\nfunction buildLayers(\n  document: BlockDocument,\n  componentTitle: ComponentTitleOf | undefined,\n  device: LayersDevice | undefined\n): LayerNode[] {\n  // `heldBy` is the nearest locked block above and `hiddenBy` the nearest\n  // block hidden on the device, carried down the walk so the tree is read once\n  // rather than climbed per row.\n  // The ids a region row may not take: every block's, then every row's.\n  const taken = documentIds(document.nodes);\n  const walk = (\n    nodes: readonly BlockNode[],\n    heldBy: string | undefined,\n    hiddenBy: string | undefined,\n    slotOf: (child: BlockNode) => string | undefined = () => undefined\n  ): LayerNode[] =>\n    nodes.map(node => {\n      const slot = slotOf(node);\n      const label = layerLabel(node, undefined, componentTitle);\n      const locked = node.locked === true;\n      const name = authoredName(node);\n      // Asked of the engine's per-device reading, the cascade the published\n      // stylesheet is compiled from, so a row says hidden exactly where a\n      // visitor on that device sees nothing.\n      const hiddenHere =\n        device !== undefined &&\n        hiddenOnDevice(node.visibility, device.breakpoints, device.id);\n      return {\n        id: node.id,\n        type: node.type,\n        label,\n        ...(name === undefined ? {} : { name }),\n        component: isComponentInstance(node),\n        locked,\n        ...(locked || heldBy === undefined ? {} : { lockedBy: heldBy }),\n        conditional: hasConditions(node),\n        ...(node.nosnippet === true ? { notQuoted: true } : {}),\n        // The one answer the inspector's Style line and dot read too.\n        ...(holdsCustomCss(node) ? { customCss: true as const } : {}),\n        breakpointHidden: hiddenAtSomeBreakpoint(node),\n        ...(device === undefined ? {} : { hiddenHere }),\n        // Kept on a row hidden itself as well: showing it here shows nothing\n        // while the block around it is hidden, so the row offers no eye.\n        ...(hiddenBy === undefined ? {} : { hiddenWith: hiddenBy }),\n        ...(slot === undefined ? {} : { slot }),\n        ...(node.type === COLLECTION_LIST_TYPE\n          ? { slotRows: listSlotRows(node.id, taken) }\n          : {}),\n        // Declaration order across every slot the node holds. `Object.values`\n        // preserves insertion order for string keys, which is the order the\n        // document was written in — so the tree matches the document rather\n        // than an alphabetical rearrangement of its regions. The nearest lock\n        // is this block's own when it has one.\n        children: walk(\n          Object.values(node.slots ?? {}).flat(),\n          locked ? label : heldBy,\n          hiddenHere ? label : hiddenBy,\n          slotsOfChildren(node)\n        ),\n      };\n    });\n\n  return walk(document.nodes, undefined, undefined);\n}\n\n/**\n * The ancestors of a node, outermost first, ending with the node itself.\n *\n * Empty when nothing is selected or the id is not in the document — which the\n * breadcrumb draws as nothing rather than as a broken trail, and which happens\n * routinely: an undo can remove the selected node while the selection stands.\n */\nexport function pathTo(\n  document: BlockDocument,\n  id: string | null,\n  componentTitle?: ComponentTitleOf\n): LayerNode[] {\n  if (id === null) return [];\n\n  const find = (nodes: readonly LayerNode[]): LayerNode[] => {\n    for (const node of nodes) {\n      if (node.id === id) return [node];\n      const below = find(node.children);\n      if (below.length > 0) return [node, ...below];\n    }\n    return [];\n  };\n\n  return find(layersOf(document, componentTitle));\n}\n\n/**\n * Every ancestor id on the way to a node, excluding the node itself.\n *\n * What the panel must expand for a selection made elsewhere to be visible. A\n * block selected on the canvas inside three collapsed containers is otherwise\n * highlighted in a tree that shows none of it, which reads as the panel\n * ignoring the click.\n */\nexport function ancestorIds(\n  document: BlockDocument,\n  id: string | null\n): string[] {\n  return pathTo(document, id)\n    .slice(0, -1)\n    .map(node => node.id);\n}\n\n/** What a search left standing, and what has to open for it to be visible. */\nexport interface LayerSearch {\n  readonly roots: readonly LayerNode[];\n  /** Ids to expand so every match is on screen. */\n  readonly expand: readonly string[];\n}\n\n/** Whether a row itself answers the query. */\nfunction matches(node: LayerNode, needle: string): boolean {\n  // The type as well as the label, because an author who knows a block as\n  // `core/heading` — from documentation, or from an agent's output — should not\n  // have to guess what it is called in the panel.\n  return (\n    node.label.toLowerCase().includes(needle) ||\n    node.type.toLowerCase().includes(needle)\n  );\n}\n\n/**\n * Narrow the tree to what matches, keeping the ancestors of every match.\n *\n * A match's ancestors are KEPT even when they do not match themselves, because\n * a tree that dropped them would present matches as top-level blocks and lose\n * the one thing this panel exists to show. A matching node keeps its whole\n * subtree, so searching for a container still shows what is inside it.\n *\n * An empty or whitespace-only query returns the tree unchanged rather than\n * nothing — the panel renders with no query, and treating that as \"match\n * nothing\" would show an empty panel on open.\n */\nexport function filterLayers(\n  roots: readonly LayerNode[],\n  query: string\n): LayerSearch {\n  const needle = query.trim().toLowerCase();\n  if (needle === \"\") return { roots, expand: [] };\n\n  const expand: string[] = [];\n\n  const prune = (nodes: readonly LayerNode[]): LayerNode[] =>\n    nodes.flatMap(node => {\n      if (matches(node, needle)) {\n        // Kept whole. Its descendants are the contents of a thing the author\n        // asked for, and hiding them would answer a narrower question than the\n        // one they typed.\n        return [node];\n      }\n      const children = prune(node.children);\n      if (children.length === 0) return [];\n      // Only a node kept BECAUSE of a descendant needs opening; a node that\n      // matched is visible where it stands. So does each region the kept\n      // children sit in, where the panel draws one.\n      expand.push(node.id);\n      for (const row of node.slotRows ?? []) {\n        if (children.some(child => child.slot === row.slot)) {\n          expand.push(row.rowId);\n        }\n      }\n      return [{ ...node, children }];\n    });\n\n  return { roots: prune(roots), expand };\n}\n","/**\n * Whether the editor may change, move or delete a block an author has locked.\n *\n * `BlockNode.locked` is the Layers lock: while it is set, nothing changes the\n * block or anything inside it, and the op layer refuses any op that would\n * (`layersLockBreak` in the engine). The editor asks the same question BEFORE\n * offering an action, so a control never offers what the apply then refuses,\n * and the answer comes from the engine's own rule rather than a second reading\n * of the flag here.\n *\n * **One predicate per question, because the command layer is several places.**\n * Delete, the keyboard moves, the toolbar, the canvas drag and the inspector\n * each have to ask, and copies of \"is this locked\" agree only until one of\n * them gains the subtree rule below.\n *\n * ## A lock covers its subtree\n *\n * A block inside a locked one is locked too, without a flag of its own: it can\n * be neither changed nor moved out, and nothing can be added beside it. And a\n * block HOLDING a locked one cannot be moved or deleted, because moving or\n * deleting it takes the locked block with it, through an action aimed at\n * something else.\n *\n * What stays free is the block around a locked one: a section holding a locked\n * caption can still be restyled, because its own props are not inside the\n * caption.\n *\n * @module locking\n */\n\nimport {\n  findNode,\n  lockedAncestorOf as lockedAncestorIn,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\n/** Whether this node itself carries the author's lock. */\nexport function isLocked(node: BlockNode): boolean {\n  return node.locked === true;\n}\n\n/**\n * The nearest locked block this one sits inside, or `undefined`. The node's\n * own flag is not read: a block inside a locked one is locked by it.\n *\n * The engine's answer, asked rather than restated.\n */\nexport function lockedAncestorOf(\n  document: BlockDocument,\n  id: string\n): BlockNode | undefined {\n  return lockedAncestorIn(document.nodes, id);\n}\n\n/**\n * The locked block that stops this one being CHANGED, or `undefined`: the\n * block itself, or a locked block it sits inside. A locked block further down\n * does not stop it, because a block's own props are not inside its children.\n */\nexport function lockBlockingEdit(\n  document: BlockDocument,\n  id: string\n): BlockNode | undefined {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return undefined;\n  return isLocked(node) ? node : lockedAncestorOf(document, id);\n}\n\n/**\n * The locked block that stops this one being MOVED, or `undefined`.\n *\n * The block itself or one inside it, outermost first, since the move would\n * carry it; else a locked block it sits inside, since the move would take it\n * out. The op layer refuses both, so offering either move would be offering a\n * refusal.\n */\nexport function lockBlockingMove(\n  document: BlockDocument,\n  id: string\n): BlockNode | undefined {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return undefined;\n  return firstLockedIn(node) ?? lockedAncestorOf(document, id);\n}\n\n/** The first locked node in a subtree, walking outermost first. */\nfunction firstLockedIn(node: BlockNode): BlockNode | undefined {\n  if (isLocked(node)) return node;\n  for (const children of Object.values(node.slots ?? {})) {\n    for (const child of children) {\n      const found = firstLockedIn(child);\n      if (found !== undefined) return found;\n    }\n  }\n  return undefined;\n}\n\n/**\n * The locked node that stops this one being DELETED, or `undefined`.\n *\n * The node or anything inside it, else a locked block it sits inside: deleting\n * a block out of a locked one changes what that lock protects. Returns the\n * OUTERMOST locked node inside rather than merely reporting that one exists,\n * because the refusal has to name something an author can act on — \"this\n * section holds a locked block\" is followed by going and finding it, and the\n * deepest match is the least likely to be the one they meant.\n *\n * The same answer as {@link lockBlockingMove}, asked under its own name\n * because the verb reaches the author: callers word a refusal to delete and a\n * refusal to move differently.\n */\nexport function lockBlockingDelete(\n  document: BlockDocument,\n  id: string\n): BlockNode | undefined {\n  return lockBlockingMove(document, id);\n}\n","/**\n * Which block an element on the canvas stands for, and back: the address a\n * press resolves to, whether an element is the outermost one for its\n * address, the elements a node was drawn as, and whether an element belongs\n * to the canvas asking rather than to a canvas drawn inside it.\n *\n * @module canvas-addressing\n */\n\nimport { INSTANCE_ATTRIBUTE, NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { isElement } from \"./dom-kind\";\nimport { nodeElements } from \"./rendered-nodes\";\n\n/**\n * How a pointer event on the canvas resolves to a node id, or to nothing.\n *\n * `closest` rather than reading the target directly: a click lands on whatever\n * leaf is under the pointer — a `<span>` inside a heading, an `<img>` inside a\n * card — and the node that owns it is an ancestor. Reading the target alone\n * selects nothing for every block that renders more than one element, which is\n * most of them.\n *\n * The attribute name comes from `@nextlyhq/blocks-react` rather than being\n * spelled here. The renderer writes it and this reads it, so two spellings\n * would be two declarations of one name, and the day it moves the hit-testing\n * would resolve nothing while every test that hard-coded it still passed.\n *\n * **Bounded at the canvas root, which is not a detail.** The renderer applies\n * the attribute by cloning the block's root element and returns the output\n * untouched when it is not a single host element — so a block rendering a\n * fragment or a component carries none. An unbounded `closest` then walks past\n * it to the nearest ANCESTOR that has one, and returns that node's id: a\n * confidently WRONG selection rather than a missing one.\n *\n * The two failures are not equally bad. A miss is visible immediately — the\n * author clicks and nothing happens. A wrong hit selects a container while the\n * author believes they selected the child inside it, and every edit afterwards\n * lands on the wrong node with nothing to indicate it.\n */\nexport function nodeIdFromEvent(target: EventTarget | null): string | null {\n  // Any realm's element, for the reason `contextMenuTargetOf` gives.\n  if (!isElement(target)) return null;\n  const owner = target.closest(`[${NODE_ID_ATTRIBUTE}]`);\n  if (owner === null) return null;\n  // Inside THIS canvas, not merely inside something carrying the attribute. A\n  // canvas rendered within another rendered page would otherwise resolve a\n  // click to the outer page's node.\n  if (owner.closest(`.${CANVAS_ROOT_CLASS}`) === null) return null;\n  return nodeAddressOf(owner);\n}\n\n/**\n * Which node an element stands for, once components are inlined.\n *\n * EXPORTED because it is the one rule, and every reader of the element-to-node\n * mapping has to use it. Slice one of this work updated the click path and the\n * geometry lookup and left three other readers on the raw attribute — the\n * context menu, the selection markers and the drag rectangles — which is how a\n * right-click came to act on the previously selected block.\n *\n * A component is inlined at render: the instance node is replaced by the tree\n * its definition describes, and every element of that tree carries a RE-MINTED\n * id the page's document does not contain. Returning that id hands the editor\n * an address it cannot select, edit or delete — so a definition-owned element\n * answers with the INSTANCE the author actually placed, which is a real node in\n * the page.\n *\n * ## Asked of the ELEMENT, never of its ancestors\n *\n * `owner.closest(\\`[${\"$\"}{INSTANCE_ATTRIBUTE}]\\`)` is the obvious implementation and\n * it is wrong. An instance's SLOT CONTENT belongs to the page and is\n * deliberately unmarked, but it renders NESTED INSIDE the definition's marked\n * box — so a walk upwards finds that box and answers with the component for a\n * node the author can and should select directly. That content is exactly what\n * a marketer opened the editor to change.\n *\n * The marker is per-node rather than a wrapper element precisely so this\n * question can be asked without walking, and `hasAttribute` is what asks it:\n * marked means definition-owned, unmarked means the page's own whatever\n * encloses it.\n */\nexport function nodeAddressOf(owner: Element): string | null {\n  const instance = owner.getAttribute(INSTANCE_ATTRIBUTE);\n  // Present AND non-empty. The renderer never emits an empty one — it treats\n  // that as no provenance — but an address of \"\" is not selectable, so reading\n  // it as page-owned is the answer that leaves the element addressable by its\n  // own id.\n  if (instance !== null && instance !== \"\") return instance;\n  return owner.getAttribute(NODE_ID_ATTRIBUTE);\n}\n\n/**\n * Whether this element is the OUTERMOST one standing for its address.\n *\n * Two different things put one address on several elements, and they need\n * opposite answers:\n *\n * - A node rendered more than once — a block that draws its child twice — puts\n *   the same node id on SIBLING elements. Every copy is a rendering of that\n *   node, and marking only one outlines a single row of ten while previewing a\n *   state on another. Neither copy encloses the other, so both are outermost.\n * - A component instance puts one address on every element its definition\n *   contributed, NESTED. Those are renderings of different definition nodes\n *   that share a host, so marking all of them outlines everything inside the\n *   component and measuring all of them keys the drag geometry to whichever was\n *   visited last.\n *\n * Enclosure is what separates them, so enclosure is what this asks. The host\n * marker is contiguous over a subtree, so the nearest enclosing one carrying\n * the same value is the whole test — no walk to the root is needed.\n */\nexport function isOutermostForAddress(\n  element: Element,\n  address: string,\n  container: HTMLElement\n): boolean {\n  const host = element.parentElement?.closest(`[${INSTANCE_ATTRIBUTE}]`);\n  if (host === null || host === undefined) return true;\n  // Bounded by the canvas that owns the element. A canvas can render inside a\n  // definition-owned element — component edit mode does — and ids are scoped\n  // per document, so the inner document may reuse the enclosing instance's\n  // address. An unbounded search then finds the OUTER document's marker,\n  // classifies the inner component as nested inside itself, and leaves it with\n  // no outline and no rectangle for a drag.\n  if (!ownedByCanvas(host, container)) return true;\n  return host.getAttribute(INSTANCE_ATTRIBUTE) !== address;\n}\n\n/**\n * Every element standing for each of `addresses` on this canvas: the\n * outermost per address, in document order. What a toolbar or a gap measures a\n * block by, so that a component placement whose definition draws several\n * top-level elements is measured as all of them rather than as its first.\n * Only this canvas's own: a canvas nested inside a block (component edit\n * mode) scopes ids to its own document, which may reuse an address from out\n * here.\n */\nexport function outermostElementsOf(\n  root: HTMLElement,\n  addresses: ReadonlySet<string>\n): Map<string, Element[]> {\n  const drawn = new Map<string, Element[]>();\n  for (const element of nodeElements(root)) {\n    if (!ownedByCanvas(element, root)) continue;\n    const address = nodeAddressOf(element);\n    if (address === null || !addresses.has(address)) continue;\n    if (!isOutermostForAddress(element, address, root)) continue;\n    const elements = drawn.get(address) ?? [];\n    elements.push(element);\n    drawn.set(address, elements);\n  }\n  return drawn;\n}\n\n/**\n * The element a node id was rendered as, or `null` when it is not on screen.\n *\n * The inverse of {@link nodeIdFromEvent}, and beside it because the two are one\n * mapping read in two directions — separated, they become two answers to what a\n * node id means in the DOM.\n *\n * Ids are COMPARED rather than interpolated into a selector. A node id reaches\n * here from stored data, so any character CSS treats specially makes\n * `querySelector` either throw or match something else entirely.\n *\n * Deliberately not the {@link SELECTED_ATTRIBUTE} marker. That marker is applied\n * in a passive effect, so on the render where the selection changes it is still\n * on the previously selected element, and any chrome measuring in a layout\n * effect would spend a frame measuring the wrong block.\n */\nexport function nodeElement(root: HTMLElement, id: string): Element | null {\n  let own: Element | null = null;\n  let hosted: Element | null = null;\n  // `forEach` rather than `for…of`: a `NodeList` is only iterable under a lib\n  // that declares its iterator, and this package compiles without one.\n  root.querySelectorAll(`[${NODE_ID_ATTRIBUTE}]`).forEach(element => {\n    if (own === null && element.getAttribute(NODE_ID_ATTRIBUTE) === id) {\n      own = element;\n    }\n    // An INSTANCE id addresses a node that renders no element of its own: it\n    // was replaced by the definition's tree. The first element that tree\n    // contributed is what a caller measuring the selection needs, and document\n    // order makes that the outermost one.\n    if (hosted === null && element.getAttribute(INSTANCE_ATTRIBUTE) === id) {\n      hosted = element;\n    }\n  });\n  // The node's OWN element wins where both exist. They cannot today — an\n  // instance is replaced rather than rendered — but the precedence states which\n  // answer is the node's rather than leaving it to iteration order.\n  return own ?? hosted;\n}\n\n/**\n * Whether this element belongs to the canvas doing the marking.\n *\n * A node id is unique within a DOCUMENT and not across documents, so a block\n * that renders a second canvas puts another document's ids inside the outer\n * walk's reach. An inner node sharing the dragged id would then be dimmed by a\n * drag it has no part in, and the refusal could anchor to it.\n */\nexport function ownedByCanvas(\n  element: Element,\n  container: HTMLElement\n): boolean {\n  if (element === container) return true;\n  return element.closest(`.${CANVAS_ROOT_CLASS}`) === container;\n}\n\n/**\n * The element drawing a node, restricted to the canvas that owns it.\n *\n * {@link nodeElement} answers with the first match anywhere beneath the root,\n * which is the wrong question once a block can render a canvas of its own: node\n * ids are unique within a DOCUMENT, so an inner document may legitimately carry\n * the same id and appear earlier in tree order.\n */\nexport function ownedNodeElement(\n  root: HTMLElement,\n  id: string\n): Element | null {\n  for (const candidate of nodeElements(root)) {\n    if (candidate.getAttribute(NODE_ID_ATTRIBUTE) !== id) continue;\n    if (ownedByCanvas(candidate, root)) return candidate;\n  }\n  return null;\n}\n","/**\n * The words for an action a lock refuses, from one place.\n *\n * Every surface that refuses inside a locked area (the drop indicator, the\n * inserter, a keyboard move, the toolbar and the context menu) and the\n * inspector's read-only settings word the reason through this function, so an\n * author meets one sentence for one rule wherever they meet it. The facts come\n * from the engine's `lockRefusal`, which judges an edit exactly as a save does.\n */\nimport {\n  addressesNoNode,\n  applyOp,\n  findNode,\n  layersLockBreak,\n  layersLockChanges,\n  OpError,\n  type BlockDocument,\n  type BlockNode,\n  type BuilderOp,\n  type LayersLockBreak,\n  type LocatedLockBreak,\n  type RepairStep,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { RefusalWording } from \"./canvas/drag-refusal\";\nimport { blockLabel } from \"./panels/add/inserter\";\nimport { layerLabel } from \"./panels/layers/layers\";\n\n/**\n * The facts a slot-lock refusal is worded from: the rule, and the block whose\n * slot it holds. A break on the page itself and one in the composed page,\n * inside a component a placement reaches, both answer with these.\n */\nexport type SlotLockRefusalFacts = Pick<\n  LocatedLockBreak,\n  \"code\" | \"holderType\" | \"lock\" | \"childType\"\n> & {\n  /** The placement a break inside a component is reached through. */\n  readonly instanceId?: string;\n};\n\n/** What an action does to a block, as a refusal of it says. */\nexport type LockedVerb = \"move\" | \"delete\" | \"change\" | \"add\";\n\n/**\n * Where a locked block sits relative to the block an action is aimed at:\n * - `self`: it is that block;\n * - `inside`: it is inside that block;\n * - `around`: that block is inside it;\n * - `destination`: the action would put a block into it;\n * - `component`: the block is a component's, which locks it; `label` is then\n *   the component's name, since the page cannot unlock it.\n */\nexport type LockedRelation =\n  | \"self\"\n  | \"inside\"\n  | \"around\"\n  | \"destination\"\n  | \"component\";\n\n/**\n * The facts a Layers-lock refusal is worded from: the locked block by the name\n * the author knows it by, where it sits, and what the action would do.\n *\n * `layers-locked-when-saved` is the lock the SAVED page still holds on a block\n * the author has unlocked since: a save refuses to delete it until the unlock\n * itself has been saved, so the editor refuses the delete before that.\n */\nexport interface LayersLockRefusalFacts {\n  readonly code: \"layers-locked\" | \"layers-locked-when-saved\";\n  readonly label: string;\n  readonly relation: LockedRelation;\n  readonly verb: LockedVerb;\n}\n\n/**\n * Why an edit is refused for a lock: a slot's lock a block declares, or a\n * block an author locked in Layers.\n */\nexport type LockRefusalFacts = SlotLockRefusalFacts | LayersLockRefusalFacts;\n\n/** Whether the facts are a Layers lock's rather than a slot's. */\nexport function isLayersLockFacts(\n  found: LockRefusalFacts\n): found is LayersLockRefusalFacts {\n  return (\n    found.code === \"layers-locked\" || found.code === \"layers-locked-when-saved\"\n  );\n}\n\n/**\n * Where `locked` sits relative to the block `subjectId`, which is either one\n * of its own or a block it is found beside: the block itself, around it when\n * the subject is found inside it, and inside it otherwise.\n */\nfunction relationOf(\n  locked: BlockNode,\n  subjectId: string\n): Exclude<LockedRelation, \"destination\"> {\n  if (locked.id === subjectId) return \"self\";\n  return findNode([locked], subjectId) === undefined ? \"inside\" : \"around\";\n}\n\n/**\n * The facts for a block locked in Layers that stops an action aimed at\n * `subjectId`, worded by {@link lockRefusalWording} like every other lock.\n */\nexport function layersLockFacts(\n  locked: BlockNode,\n  subjectId: string,\n  verb: LockedVerb\n): LayersLockRefusalFacts {\n  return {\n    code: \"layers-locked\",\n    label: layerLabel(locked),\n    relation: relationOf(locked, subjectId),\n    verb,\n  };\n}\n\n/** What an op does to the block it addresses, as a refusal of it says. */\nfunction verbOf(\n  op: Exclude<\n    BuilderOp,\n    { readonly kind: \"envelope\" | \"seo\" | \"code\" | \"customCss\" }\n  >\n): LockedVerb {\n  switch (op.kind) {\n    case \"remove\":\n      return \"delete\";\n    case \"move\":\n      return \"move\";\n    case \"update\":\n    case \"turnInto\":\n      // Turning a block into another type changes it in place.\n      return \"change\";\n    case \"insert\":\n      return \"add\";\n  }\n}\n\n/** A break the engine found, as the facts a refusal is worded from. */\nexport function factsOfBreak(\n  document: BlockDocument,\n  op: BuilderOp,\n  broken: LayersLockBreak\n): LayersLockRefusalFacts | undefined {\n  // An envelope or metadata edit changes no block, so no lock is broken by\n  // one.\n  if (addressesNoNode(op)) return undefined;\n  const locked = findNode(document.nodes, broken.lockedId);\n  if (locked === undefined) return undefined;\n  if (broken.where === \"destination\" || op.kind === \"insert\") {\n    return {\n      code: \"layers-locked\",\n      label: layerLabel(locked),\n      relation: \"destination\",\n      verb: \"add\",\n    };\n  }\n  return layersLockFacts(locked, op.id, verbOf(op));\n}\n\n/**\n * What the save would refuse of this edit's Layers locks, judged against the\n * SAVED page with the engine's own comparison (`layersLockChanges`), the one\n * the server uses, or undefined. Only what this edit adds is asked, not what an\n * earlier edit already did.\n *\n * - A block the edit deletes that the saved page still holds locked, even one\n *   unlocked since: the unlock has to be saved before the delete.\n * - A locked block a move of other blocks would read as moved: moving one\n *   sibling across it is the sibling's move, but moving several past it at\n *   once reads, at the save, as the locked block moving instead.\n *\n * A block unlocked since the save may otherwise be changed or moved in the\n * same save that carries its unlock.\n */\nexport function savedLockBrokenBy(\n  before: BlockDocument,\n  after: BlockDocument,\n  stored: BlockDocument,\n  ops: readonly BuilderOp[]\n): LayersLockRefusalFacts | undefined {\n  const asked = ops.find(op => op.kind === \"remove\" || op.kind === \"move\");\n  if (asked === undefined) return undefined;\n  const already = new Set(\n    layersLockChanges(before, stored).map(\n      change => `${change.kind}:${change.id}`\n    )\n  );\n  const added = layersLockChanges(after, stored).find(\n    change =>\n      (change.kind === \"removed\" || change.kind === \"moved\") &&\n      !already.has(`${change.kind}:${change.id}`)\n  );\n  if (added === undefined) return undefined;\n  if (added.kind === \"moved\") {\n    return {\n      code: \"layers-locked\",\n      label: added.label,\n      relation: \"self\",\n      verb: \"move\",\n    };\n  }\n  const removal = ops.find(op => op.kind === \"remove\");\n  return {\n    code: \"layers-locked-when-saved\",\n    label: added.label,\n    relation:\n      removal?.kind === \"remove\" && added.id === removal.id ? \"self\" : \"inside\",\n    verb: \"delete\",\n  };\n}\n\n/**\n * The Layers lock `ops` would break, as refusal facts, or undefined when they\n * keep every lock: a block locked now, asked op by op with the engine's own\n * rule (`layersLockBreak`) as the apply asks it, and with `stored`, a block\n * the saved page still holds locked that the ops would delete.\n *\n * Ops the document cannot take for another reason answer undefined: they are\n * the apply's to refuse, for that reason.\n */\nexport function layersLockRefusalFor(\n  document: BlockDocument,\n  ops: readonly BuilderOp[],\n  stored?: BlockDocument\n): LayersLockRefusalFacts | undefined {\n  let working = document;\n  for (const op of ops) {\n    const broken = layersLockBreak(working.nodes, op);\n    if (broken !== undefined) return factsOfBreak(working, op, broken);\n    try {\n      working = applyOp(working, op).document;\n    } catch (error) {\n      if (error instanceof OpError) return undefined;\n      throw error;\n    }\n  }\n  return stored === undefined\n    ? undefined\n    : savedLockBrokenBy(document, working, stored, ops);\n}\n\n/**\n * The one wording of a Layers lock, for every surface that refuses an action\n * for one: the toolbar, the menus, the keyboard, a drag and the inspector.\n */\nfunction layersLockWording(found: LayersLockRefusalFacts): RefusalWording {\n  if (found.code === \"layers-locked-when-saved\") {\n    return {\n      headline: `Save first: ${found.relation === \"self\" ? \"this block\" : found.label} is still locked on the saved page.`,\n      remedy: `Save, then ${found.verb} it.`,\n    };\n  }\n  switch (found.relation) {\n    case \"self\":\n      return {\n        headline: `${found.label} is locked.`,\n        remedy: `Unlock it to ${found.verb} it.`,\n      };\n    case \"inside\":\n      return {\n        headline: `${found.label} inside this block is locked.`,\n        remedy: `Unlock ${found.label} to ${found.verb} this block.`,\n      };\n    case \"around\":\n      return {\n        headline: `This block is inside ${found.label}, which is locked.`,\n        remedy: `Unlock ${found.label} to ${found.verb} this block.`,\n      };\n    case \"component\":\n      return {\n        // A host that names no component still says whose the block is.\n        headline:\n          found.label === \"\"\n            ? \"Set by its component.\"\n            : `Set by the component ${found.label}.`,\n        remedy: \"Change it where the component is edited.\",\n      };\n    case \"destination\":\n      return {\n        headline: `${found.label} is locked.`,\n        remedy: \"Unlock it to add blocks to it.\",\n      };\n  }\n}\n\n/** An edit the op store refused for a lock, as its host is told. */\nexport interface LockEditRefusal {\n  readonly reason: \"locked\";\n  /** The sentence the author reads, as every lock refusal words it. */\n  readonly sentence: string;\n  readonly lock: LockRefusalFacts;\n}\n\n/** A drop the locks refuse, as the canvas draws it over the refusing region. */\nexport interface LockDropRefusal {\n  readonly regionId: string;\n  /** The container the refusing region belongs to, absent at the top level. */\n  readonly parentId?: string;\n  readonly lock: LockRefusalFacts;\n}\n\n/**\n * Why a block locked in Layers, or one holding or held by it, will not move:\n * the locked block by the name the author knows it by, where it sits, and\n * the way forward.\n */\nexport function lockedBlockWording(\n  locked: BlockNode,\n  subjectId: string,\n  verb: LockedVerb = \"move\"\n): RefusalWording {\n  return layersLockWording(layersLockFacts(locked, subjectId, verb));\n}\n\n/**\n * The same refusal as one sentence, for a surface that says it in a single\n * line: a menu item's reason, an announcement.\n */\nexport function lockedBlockSentence(\n  locked: BlockNode,\n  subjectId: string,\n  verb: LockedVerb\n): string {\n  const wording = lockedBlockWording(locked, subjectId, verb);\n  return `${wording.headline} ${wording.remedy}`;\n}\n\n/**\n * The headline names the locked area by the block that holds it; the remedy\n * says what the lock still allows, which is the author's way forward. A\n * Layers lock is worded by the block the author locked.\n */\nexport function lockRefusalWording(found: LockRefusalFacts): RefusalWording {\n  if (isLayersLockFacts(found)) return layersLockWording(found);\n  const area = `This area of ${blockLabel(found.holderType)} is locked`;\n  if (found.code === \"locked-slot-content-only\") {\n    const child =\n      found.childType === undefined\n        ? \"This block\"\n        : blockLabel(found.childType);\n    return {\n      headline: `${area} to its content.`,\n      remedy: `${child}'s design and settings can't change here.`,\n    };\n  }\n  switch (found.lock) {\n    case \"insert\":\n      return {\n        headline: `${area}.`,\n        remedy: \"Its blocks can be reordered, but not added or removed.\",\n      };\n    case \"contentOnly\":\n      return {\n        headline: `${area}.`,\n        remedy:\n          \"Only its content can change. Its blocks can't be added, removed or moved.\",\n      };\n    case \"all\":\n      return {\n        headline: `${area}.`,\n        remedy: \"Its blocks can't be added, removed or moved.\",\n      };\n  }\n}\n\n/**\n * One step of a repair, as the preview lists it before the author confirms:\n * which block, whose locked area or which container, and what happens.\n *\n * Here beside the refusals so an area is named the same way in both: by the\n * block that holds it. A move says which rule moved the block, a lock or the\n * placement rule, since the author is told why it leaves.\n *\n * @param document - the document the plan was made from, where every block a\n *   step names is found\n */\nexport function repairStepSentence(\n  step: RepairStep,\n  document: BlockDocument\n): string {\n  const named = (id: string) => {\n    const node = findNode(document.nodes, id);\n    return node === undefined ? \"a block\" : blockLabel(node.type);\n  };\n  switch (step.kind) {\n    case \"move\":\n      return step.cause === \"lock\"\n        ? `Move ${blockLabel(step.type)} out of ${named(step.from.holderId)}'s locked area, to just after ${named(step.after)}.`\n        : `Move ${blockLabel(step.type)} out of ${named(step.from.holderId)}, where it isn't allowed, to just after ${named(step.after)}.`;\n    case \"add\":\n      return `Add the ${blockLabel(step.type)} that ${named(step.at.holderId)}'s locked area starts with.`;\n    case \"reorder\":\n      return `Put the blocks in ${named(step.holderId)}'s locked area back in their starting order.`;\n    case \"reset\":\n      return `Put ${blockLabel(step.type)}'s design back as it started: ${step.parts.join(\", \")}.`;\n  }\n}\n","/**\n * The words an author reads when a region will not take the block they hold.\n *\n * {@link drop-targets} produces a refusal CODE plus the list of what the region\n * accepts. The sentences themselves are the engine's\n * (`placementRefusalWording`), because the server words the same refusals on a\n * save and an author must read the same words from both; this module binds\n * them to the editor's block labels.\n *\n * ## Three reasons, three remedies\n *\n * The reasons are not three spellings of \"no\". `wrong-parent` means aim at a\n * different container; `restricted-at-root` means put the block inside\n * something, because at the root there is no container on screen that would\n * satisfy it; `not-allowed-in-slot` means this particular slot, not the block's\n * parent. {@link nesting} keeps them distinct for exactly this reason, and a\n * single sentence covering all three would answer the second with advice that\n * cannot be followed.\n *\n * ## Naming what the region DOES take\n *\n * `permitted` is what turns a refusal into an instruction. A message that only\n * says no leaves the author to discover the rule by trying containers one at a\n * time; one that names the accepted types answers the next question before it\n * is asked.\n *\n * ## Pure, and tested without a DOM\n *\n * Every sentence is a function of the refusal and two block types, so whether\n * the wording is RIGHT for a given reason is checkable without rendering\n * anything — which is the half most likely to be wrong.\n *\n * @module drag-refusal\n */\nimport {\n  placementRefusalWording,\n  type NestingRefusal,\n  type PlacementRefused,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { blockLabel } from \"../panels/add/inserter\";\n\nimport type { DropRefusal } from \"./drop-targets\";\n\n/**\n * The two facts a refusal's wording is built from.\n *\n * Narrower than {@link DropRefusal} on purpose. A drop carries a region id and\n * a parent id because the canvas needs them to draw the refusal in place; the\n * WORDS need only the reason and what the rule permits. Taking the pair rather\n * than the whole lets a caller that never had a region — a keyboard move, which\n * has a position and no pointer — reuse these sentences instead of inventing a\n * second vocabulary, without fabricating a region id to satisfy a type.\n */\nexport type RefusalFacts = Pick<\n  DropRefusal,\n  \"reason\" | \"permitted\" | \"verdict\"\n>;\n\n/** The two lines a refusal draws. */\nexport interface RefusalWording {\n  /** Why the drop will not happen, in one sentence. */\n  readonly headline: string;\n  /**\n   * What the author can do about it, or null when the engine named nothing.\n   *\n   * Named for the job rather than for one of its sentences, because\n   * `permitted` does NOT mean the same thing for every reason and the wording\n   * has to follow that. A slot refusal names what the SLOT admits; the other\n   * two name the containers the MOVING BLOCK is allowed to sit inside. Calling\n   * both \"This spot takes\" asserts something about the region that the second\n   * kind never said — it would read as the accordion accepting columns, which\n   * is not what was measured; those say where the block goes instead.\n   *\n   * Null rather than an empty string: a caller rendering it unconditionally\n   * would draw a sentence that was cut off rather than an absent fact.\n   */\n  readonly remedy: string | null;\n}\n\n/**\n * Why this drop will not happen, and what would.\n *\n * `regionType` is optional because one reason has no region to name —\n * `restricted-at-root` is a block sitting where there is no parent at all — and\n * because the caller resolves the region from the document by id, which can\n * legitimately come up empty while the refusal itself is sound. Both cases get\n * a sentence rather than a gap where a name should be.\n */\nexport function refusalWording(\n  refusal: RefusalFacts,\n  movingType: string,\n  regionType: string | undefined\n): RefusalWording {\n  // The rule's whole answer, when the drop was judged by it.\n  if (refusal.verdict !== undefined) {\n    return placementWording(refusal.verdict, movingType, regionType);\n  }\n  return placementRefusalWording(\n    {\n      allowed: false,\n      reason: refusal.reason as NestingRefusal,\n      blockType: movingType,\n      permitted: refusal.permitted,\n    },\n    {\n      labelOf: blockLabel,\n      ...(regionType === undefined ? {} : { regionType }),\n    }\n  );\n}\n\n/**\n * Why a placement the one rule refused will not happen, for any reason it\n * gives: a slot the container does not declare, a block that holds none, or\n * HTML's content model, as well as the name rules. Named for the block the\n * author moved; when the rule refused something inside it, both are named.\n */\nexport function placementWording(\n  verdict: PlacementRefused,\n  movingType: string,\n  regionType: string | undefined\n): RefusalWording {\n  return placementRefusalWording(verdict, {\n    labelOf: blockLabel,\n    movingType,\n    ...(regionType === undefined ? {} : { regionType }),\n  });\n}\n","/**\n * Whether the nesting rule refuses a move, and the words for saying so.\n *\n * ## This DECIDES, and it has to\n *\n * The op store does not ask the nesting rule — measured, zero references to it\n * in `ops.ts`, with a control showing the symbol resolves elsewhere in the\n * package. So a placement the rule forbids is not refused at apply time; it is\n * applied. The POINTER route is stopped because `drop-targets` asks\n * `placementVerdict` before a drop resolves; the keyboard route asks this,\n * before the move, for the same reason. Without it a keyboard author builds\n * documents a pointer author cannot.\n *\n * So this is the keyboard route's half of a decision the pointer route already\n * makes, asked of the same function, rather than a second implementation of it:\n * `placementVerdict` is the one answer and both surfaces ask it — of the same\n * types, too. A component instance is judged by the ROOTS of the definition it\n * draws (`placementTypesOf`), as a drop is, because the instance node's own\n * type is not a registered block and the nesting source restricts it nowhere.\n *\n * ## It does NOT move the question into `keyboard-move`\n *\n * That module answers where a block goes and says in its own docblock that it\n * \"answers WHERE, never WHETHER\". It still does. The wiring asks whether — as\n * the pointer wiring does — and the position function stays positional.\n *\n * ## Null is an honest answer, and it means ALLOWED\n *\n * Null is \"the nesting rule does not refuse this\", never \"something went\n * wrong\". A move can still fail after this returns null — a byte cap, a depth\n * limit, an op the forest rejects — and those are the store's to refuse and its\n * caller's to report, without a nesting cause being invented for them.\n *\n * @module move-refusal\n */\nimport type {\n  BlockDocument,\n  ComponentLookup,\n  NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport { canPlaceIn, findNode } from \"@nextlyhq/blocks-engine\";\n\nimport { placementWording, type RefusalWording } from \"./canvas/drag-refusal\";\nimport { placementSources } from \"./canvas/drop-targets\";\nimport type { OpPosition } from \"./op-vocabulary\";\nimport { layerLabel } from \"./panels/layers/layers\";\n\n/**\n * The nesting rule's refusal for a proposed move, or `null` if it permits it.\n *\n * Asked BEFORE the move is applied, which is what makes it a refusal rather\n * than a post-mortem.\n *\n * @param document - the document the move would change\n * @param movingId - the block being moved\n * @param to - the position it would move to\n * @param nesting - the rule source, the same one the pointer route asks\n * @param definitions - the component definitions the canvas draws, so an\n *   instance is judged by what it draws; without one, by its own type\n * @returns the refusal's headline and remedy, or `null` when it is permitted\n */\nexport function nestingRefusalForMove(\n  document: BlockDocument,\n  movingId: string,\n  to: OpPosition,\n  nesting: NestingSource,\n  definitions?: ComponentLookup\n): RefusalWording | null {\n  const moving = findNode(document.nodes, movingId);\n  if (moving === undefined) return null;\n  const parent =\n    to.parentId === undefined\n      ? undefined\n      : findNode(document.nodes, to.parentId);\n  if (to.parentId !== undefined && parent === undefined) return null;\n  // The one placement rule, over the moving block and everything it holds, at\n  // the destination with what its ancestors refuse. A position whose slot is\n  // unnamed is the root's.\n  const verdict = canPlaceIn(\n    document.nodes,\n    [moving],\n    parent === undefined\n      ? { kind: \"root\" }\n      : { kind: \"slot\", parentId: parent.id, slot: to.slot ?? \"\" },\n    placementSources({\n      nesting,\n      ...(definitions === undefined ? {} : { definitions }),\n    })\n  );\n  // ALLOWED is null: the rule permits this placement. Whether it survives the\n  // store's own limits is a later question with a different answer.\n  if (verdict.allowed) return null;\n  // Worded by the node being moved, as the pointer route words a refused drop:\n  // the author picked up the instance, not the root inside it that refused.\n  return placementWording(verdict, moving.type, parent?.type);\n}\n\n/**\n * One sentence for a refused move, ready to announce.\n *\n * Joined here rather than by the caller so the two halves cannot drift apart in\n * spacing or order between the surfaces that speak them. The remedy is omitted\n * rather than replaced when the engine named nothing — a trailing fragment\n * would read as a sentence that was cut off.\n *\n * @param wording - the refusal's two lines\n * @returns the announcement text\n */\nexport function refusalAnnouncement(wording: RefusalWording): string {\n  return wording.remedy === null\n    ? wording.headline\n    : `${wording.headline} ${wording.remedy}`;\n}\n\n/**\n * What is said when the store refused a move nothing judged beforehand would\n * refuse: a byte cap, a depth limit, an op the forest rejects. It names no\n * cause, because none was established, and it is still said, because a move\n * that was attempted and did not happen cannot otherwise be told apart from\n * one that did.\n *\n * @param document - the document the move was asked of\n * @param id - the block that did not move\n * @returns the announcement text\n */\nexport function unmovedAnnouncement(\n  document: BlockDocument,\n  id: string\n): string {\n  const block = findNode(document.nodes, id);\n  return `${block === undefined ? \"The block\" : layerLabel(block)} could not be moved.`;\n}\n","/**\n * Where each style property sits on the Style tab: which section, in what\n * order, and whether it shows at once or is one the author adds from \"Add CSS\n * property\".\n *\n * **The builder's own arrangement, over the engine's vocabulary.** The engine's\n * groups (`STYLE_GROUP_DEFS`) are also the `supports` keys block and plugin\n * authors declare, so they stay exactly as they are. What an author SEES is\n * arranged here: one order for every block, so a section is always in the\n * same place — Block style, Layout, Inside its parent, Spacing, Size,\n * Position, Text, Background, Border, Effects, Icon, CSS properties — with\n * the colour and list properties inside Text, shadow inside\n * Effects, and the container-query and box-sizing properties added from \"Add\n * CSS property\" with their sections named beside them. There is no \"Advanced\"\n * style section: that name belongs to Content alone, so an author never has to\n * guess which one is meant.\n *\n * **Every catalog property is placed exactly once**, and the test says so. A\n * property the engine adds later, before anyone places it, still appears: it\n * falls back to the section its engine group maps to, added from \"Add CSS\n * property\", so a new capability is reachable on the day it ships rather than\n * invisible until this table catches up.\n *\n * **Common first, the rest from \"Add CSS property\".** Each property's tier says\n * whether it is one an author reaches for first. A common property shows\n * without being asked for where it also has an effect on the block, which is\n * the engine's answer (`applies`), not this table's: the flex controls on a\n * flex container, the grid ones on a grid, a child's sizing inside a Row or a\n * Grid, an image's fit on a replaced element. Three tiers are the builder's\n * own, because they are about editing rather than CSS: the transition once a\n * state other than Normal is being edited, the outline while Focus is, and an\n * icon's position while an icon is drawn. A property holding a value always\n * shows, whatever its tier: a set value is never hidden.\n *\n * @module inspector-sections\n */\n\nimport type { StyleGroup, StyleState } from \"@nextlyhq/blocks-engine\";\n\n/** The Style tab's sections, by key. */\nexport type InspectorSectionKey =\n  | \"block-style\"\n  | \"layout\"\n  | \"inside-parent\"\n  | \"spacing\"\n  | \"size\"\n  | \"position\"\n  | \"typography\"\n  | \"background\"\n  | \"border\"\n  | \"effects\"\n  | \"icon\"\n  | \"css-properties\";\n\n/**\n * When a property shows without being asked for.\n *\n * - `common`: wherever it has an effect.\n * - `more`: only once the author adds it from \"Add CSS property\" (or from\n *   \"Find a setting\"), or once it holds a value; then it is drawn in \"CSS\n *   properties\", where it can be removed again.\n * - `common-on-media`: common where the block draws a replaced element (an\n *   image, a video, an embed), `more` on every other block. A choice about\n *   what an author reaches for first, not about whether the property works:\n *   an aspect ratio sizes any box, but it is what an image is set by.\n * - `icon-drawn`: while a disclosure draws an icon (any but none), which is\n *   what a position moves.\n * - `state`: while a state other than Normal is being edited.\n * - `focus-state`: while the Focus state is being edited, `more` in every\n *   other state. An outline is mostly a focus ring, so that is where an\n *   author looks for it.\n * - `content`: never in Style, and never added there. A style value chosen in\n *   the Content tab, because what it picks is what the block shows (an\n *   Accordion's icon): one place to set it, so two controls never disagree.\n */\nexport type PropertyTier =\n  | \"common\"\n  | \"more\"\n  | \"common-on-media\"\n  | \"icon-drawn\"\n  | \"state\"\n  | \"focus-state\"\n  | \"content\";\n\nexport interface InspectorSectionDef {\n  readonly key: InspectorSectionKey;\n  readonly label: string;\n  /** Catalog keys in the order the section lists them, each with its tier. */\n  readonly properties: readonly (readonly [\n    property: string,\n    tier: PropertyTier,\n  ])[];\n}\n\n/**\n * The sections, in order, and the properties each holds, in order.\n *\n * Inside a section the property that changes the most comes first and the\n * cosmetic ones last: display, then direction, then alignment; font, then\n * weight, then size.\n */\nexport const INSPECTOR_SECTIONS: readonly InspectorSectionDef[] = [\n  // Each block's style tiles. Their controls are drawn above the sections\n  // today, so the section holds no property yet; it is in the order so\n  // every block lists its sections the same way.\n  { key: \"block-style\", label: \"Block style\", properties: [] },\n  {\n    key: \"layout\",\n    label: \"Layout\",\n    properties: [\n      [\"display\", \"common\"],\n      [\"flexDirection\", \"common\"],\n      [\"justifyContent\", \"common\"],\n      [\"alignItems\", \"common\"],\n      [\"gap\", \"common\"],\n      [\"flexWrap\", \"common\"],\n      [\"gridTemplateColumns\", \"common\"],\n      [\"gridTemplateRows\", \"common\"],\n      [\"alignContent\", \"more\"],\n      [\"gridAutoFlow\", \"more\"],\n      [\"justifyItems\", \"more\"],\n      [\"rowGap\", \"more\"],\n      [\"columnGap\", \"more\"],\n      [\"containerType\", \"more\"],\n    ],\n  },\n  // How a block takes its place in its parent: Fill, Fit or Fixed drawn on\n  // top, and below it the CSS rows that apply in this parent. Those the\n  // choices draw leave while a choice reads them (plain-parent-controls).\n  {\n    key: \"inside-parent\",\n    label: \"Inside its parent\",\n    properties: [\n      [\"flexGrow\", \"common\"],\n      [\"flexShrink\", \"common\"],\n      [\"flexBasis\", \"common\"],\n      [\"alignSelf\", \"common\"],\n      [\"justifySelf\", \"common\"],\n      [\"order\", \"common\"],\n    ],\n  },\n  {\n    key: \"spacing\",\n    label: \"Spacing\",\n    properties: [\n      [\"padding\", \"common\"],\n      [\"margin\", \"common\"],\n    ],\n  },\n  {\n    key: \"size\",\n    label: \"Size\",\n    // An image's fit and focal point first: how it fills its box is what an\n    // author changes first on one. Both have an effect only on a replaced\n    // element, so a box never shows them. A child's share of a Row or a Grid\n    // is in \"Inside its parent\".\n    properties: [\n      [\"objectFit\", \"common\"],\n      [\"objectPosition\", \"common\"],\n      [\"width\", \"common\"],\n      [\"height\", \"common\"],\n      [\"minWidth\", \"common\"],\n      [\"maxWidth\", \"common\"],\n      [\"aspectRatio\", \"common-on-media\"],\n      [\"minHeight\", \"more\"],\n      [\"maxHeight\", \"more\"],\n      [\"overflow\", \"more\"],\n      [\"boxSizing\", \"more\"],\n    ],\n  },\n  {\n    key: \"position\",\n    label: \"Position\",\n    properties: [[\"position\", \"common\"]],\n  },\n  {\n    key: \"typography\",\n    label: \"Text\",\n    properties: [\n      [\"fontFamily\", \"common\"],\n      [\"fontWeight\", \"common\"],\n      [\"fontSize\", \"common\"],\n      [\"lineHeight\", \"common\"],\n      [\"color\", \"common\"],\n      [\"textAlign\", \"common\"],\n      // A list's own marker is chosen with \"List as\"; a custom one is a CSS\n      // detail, added from \"Add CSS property\" and drawn there once set.\n      [\"listStyleType\", \"more\"],\n      [\"letterSpacing\", \"more\"],\n      [\"textTransform\", \"more\"],\n      [\"fontStyle\", \"more\"],\n      [\"textDecoration\", \"more\"],\n      [\"linkColor\", \"more\"],\n      [\"linkColorHover\", \"more\"],\n      [\"textShadow\", \"more\"],\n      [\"wordSpacing\", \"more\"],\n    ],\n  },\n  {\n    key: \"background\",\n    label: \"Background\",\n    properties: [\n      [\"backgroundColor\", \"common\"],\n      [\"background\", \"common\"],\n      [\"backgroundGradient\", \"common\"],\n    ],\n  },\n  {\n    key: \"border\",\n    label: \"Border\",\n    properties: [\n      [\"border\", \"common\"],\n      [\"borderRadius\", \"common\"],\n      [\"outline\", \"focus-state\"],\n    ],\n  },\n  {\n    key: \"effects\",\n    label: \"Effects\",\n    properties: [\n      [\"boxShadow\", \"common\"],\n      [\"opacity\", \"common\"],\n      [\"appear\", \"common\"],\n      [\"transition\", \"state\"],\n      [\"transform\", \"more\"],\n      [\"filter\", \"more\"],\n      [\"mixBlendMode\", \"more\"],\n    ],\n  },\n  // Only a block offering it (an Accordion) shows the section.\n  {\n    key: \"icon\",\n    label: \"Icon\",\n    properties: [\n      // Chosen in the Content tab (`accordion-icon-field.tsx`).\n      [\"disclosureIcon\", \"content\"],\n      [\"disclosurePosition\", \"icon-drawn\"],\n    ],\n  },\n  // The properties the author added, each with its own Remove, and \"+ Add\n  // CSS property\". Last, and holding no property of its own: a property\n  // added here stays placed in the section above that it belongs to, which\n  // the picker names beside it.\n  { key: \"css-properties\", label: \"CSS properties\", properties: [] },\n];\n\n/**\n * Fields of an object property that \"Add CSS property\" offers as properties\n * of their own, with their plain names. A stacking order is reached for apart\n * from the positioning scheme, and has an effect in more places than the\n * offsets do (on a flex or grid item too), so its section draws the rest of\n * the property and it is added on its own.\n */\nexport const OWN_ROW_FIELDS: readonly {\n  readonly property: string;\n  readonly field: string;\n  readonly label: string;\n}[] = [{ property: \"position\", field: \"zIndex\", label: \"Layer order\" }];\n\n/**\n * Where a property the table does not place falls, by its engine group.\n *\n * A total record, so a group the engine adds fails to compile here rather\n * than leaving its properties nowhere.\n */\nconst SECTION_OF_GROUP: Readonly<Record<StyleGroup, InspectorSectionKey>> = {\n  spacing: \"spacing\",\n  layout: \"layout\",\n  dimensions: \"size\",\n  typography: \"typography\",\n  color: \"typography\",\n  background: \"background\",\n  border: \"border\",\n  shadow: \"effects\",\n  effects: \"effects\",\n  position: \"position\",\n  container: \"layout\",\n  list: \"typography\",\n  disclosure: \"icon\",\n};\n\n/** Where one property is placed. */\nexport interface PropertyPlacement {\n  readonly section: InspectorSectionKey;\n  readonly tier: PropertyTier;\n  /** Its position in the whole table, for ordering within a section. */\n  readonly order: number;\n}\n\nconst PLACEMENT: ReadonlyMap<string, PropertyPlacement> = new Map(\n  INSPECTOR_SECTIONS.flatMap((section, s) =>\n    section.properties.map(\n      ([property, tier], p) =>\n        [property, { section: section.key, tier, order: s * 100 + p }] as const\n    )\n  )\n);\n\n/**\n * Where a catalog property is placed: the table's answer, or added from \"Add\n * CSS property\" in its engine group's section when the table does not name it.\n */\nexport function placementOf(\n  property: string,\n  group: StyleGroup\n): PropertyPlacement {\n  const placed = PLACEMENT.get(property);\n  if (placed !== undefined) return placed;\n  const section = SECTION_OF_GROUP[group];\n  const index = INSPECTOR_SECTIONS.findIndex(entry => entry.key === section);\n  // After every placed property of its section.\n  return { section, tier: \"more\", order: index * 100 + 99 };\n}\n\n/**\n * What a tier needs to know about the editing, beyond what the block is: the\n * engine's `applies` judges that.\n */\nexport interface TierContext {\n  /**\n   * Whether the block draws a replaced element, `undefined` until the canvas\n   * has said what it draws.\n   */\n  readonly replaced?: boolean | undefined;\n  /** The disclosure icon the block draws here, if it is given one. */\n  readonly disclosureIcon?: string | undefined;\n  /** The state being edited. */\n  readonly state: StyleState;\n}\n\n/** The disclosure icon that draws nothing a position could move. */\nconst UNDRAWN_ICONS: ReadonlySet<string> = new Set([\"none\"]);\n\n/**\n * Whether a property of this tier shows without being asked for, where it\n * has an effect at all. That second half is the caller's to ask of the engine.\n */\nexport function tierShows(tier: PropertyTier, context: TierContext): boolean {\n  switch (tier) {\n    case \"common\":\n      return true;\n    case \"more\":\n      return false;\n    // Shown where it is not yet known too, as `applies` treats what it\n    // cannot read.\n    case \"common-on-media\":\n      return context.replaced !== false;\n    // Shown where the icon in force is unknown too: the block's default\n    // draws one.\n    case \"icon-drawn\":\n      return !UNDRAWN_ICONS.has(context.disclosureIcon ?? \"\");\n    case \"state\":\n      return context.state !== \"base\";\n    case \"focus-state\":\n      return context.state === \"focus\";\n    case \"content\":\n      return false;\n  }\n}\n","/**\n * What the selected block exposes for editing, and the patch that changes it.\n *\n * Pure, for the reason every rule in this package is: which controls a block\n * offers, in what order, carrying which values, is derivation — and a component\n * test in jsdom cannot separate a correct answer from a plausible wrong one,\n * because both render a column of inputs.\n *\n * **A block declares its own editable surface.** `props` on the definition maps\n * each prop name to a `PropSchema`, and the schema's `type` decides the\n * control. Nothing here holds a list of which blocks have which fields: a\n * third-party block gets an inspector by declaring its props, exactly as a\n * first-party one does.\n *\n * @module inspector\n */\n\nimport {\n  contentPropsOf,\n  getBlock,\n  findNode,\n  isLinkableUrl,\n  locateNode,\n  nodeLocks,\n  propPlace,\n  registryBlockSource,\n  type ActiveSlotLock,\n  type AnyBlockDefinition,\n  type BlockDocument,\n  type BlockNode,\n  type ComponentPath,\n  type NodeLock,\n  type PropGroup,\n  type PropSchema,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { COLUMNS_ROW } from \"../canvas/columns-layout\";\nimport type { RefusalWording } from \"../canvas/drag-refusal\";\nimport type { EditorState } from \"../editor-state\";\nimport { lockRefusalWording } from \"../lock-refusal\";\nimport { isLocked, lockBlockingEdit, lockedAncestorOf } from \"../locking\";\nimport { refusalAnnouncement } from \"../move-refusal\";\nimport type { BuilderOp, NodePatch } from \"../op-vocabulary\";\nimport { blockLabel, insertionPropSets } from \"../panels/add/inserter\";\nimport { layerLabel } from \"../panels/layers/layers\";\n\nimport { ACCORDION_BLOCK } from \"./content/accordion-icon\";\nimport {\n  CONTENT_CONTROL_TYPES,\n  hasContentControl,\n} from \"./content/content-control-types\";\nimport { GALLERY_BLOCK } from \"./content/gallery-pictures\";\nimport { holdsCustomCss } from \"./custom-css\";\nimport { INSPECTOR_SECTIONS } from \"./inspector-sections\";\n\n/**\n * The prop types this inspector can draw a control for.\n *\n * Named as a set rather than inferred from what the switch happens to handle,\n * so an unsupported prop is a KNOWN gap rather than a silent fallthrough. A\n * block declaring `type: \"array\"` still appears in the panel — the author is\n * told the prop exists and is not editable here — because omitting it entirely\n * would present an incomplete block as a complete one.\n */\nexport const SUPPORTED_PROP_TYPES: typeof CONTENT_CONTROL_TYPES =\n  CONTENT_CONTROL_TYPES;\n\nexport type SupportedPropType = (typeof SUPPORTED_PROP_TYPES)[number];\n\n/** One editable prop, with everything a control needs to draw itself. */\nexport interface EditableProp {\n  readonly name: string;\n  readonly schema: PropSchema;\n  /** The node's current value, which may be absent. */\n  readonly value: unknown;\n  /**\n   * Whether this inspector can draw a control for it.\n   *\n   * Carried rather than recomputed by the panel: the panel would have to repeat\n   * the membership test, and the two would disagree the first time this set\n   * gained a member.\n   */\n  readonly supported: boolean;\n  /** The options a `select` offers, empty for every other type. */\n  readonly options: readonly string[];\n  /**\n   * Whether the inspector draws a control for it: `false` for a prop that\n   * applies only without another that is set, as a linked button's \"Acts as\",\n   * and for a choice with nothing to pick. Listed even so, since a component\n   * may still expose it to pages that clear what hides it.\n   */\n  readonly offered: boolean;\n  /**\n   * Whether a lock fixes this prop where the block sits: it is not content,\n   * and the block is inside an area locked to its content. Shown, not hidden,\n   * so the author sees the value and is told why it holds.\n   */\n  readonly readOnly: boolean;\n  /**\n   * What the block holds when the prop was never set: its `defaultProps`\n   * entry, or `undefined`. A switch or a choice shows it until a value is\n   * stored, since it is the value that applies.\n   */\n  readonly defaultValue?: unknown;\n}\n\n/**\n * What a block is, as distinct from what it holds.\n *\n * `name` and `locked` are fields on the NODE rather than entries in `props`, so\n * no `PropSchema` describes them and the prop loop below cannot reach them.\n * They are also the two the layers panel already displays — and until this\n * existed, nothing in the editor could set either, so the panel showed\n * information the editor had no way to produce.\n */\nexport interface BlockIdentity {\n  /** The author's own name for this instance, empty when they have not given one. */\n  readonly name: string;\n  readonly locked: boolean;\n}\n\n/**\n * The block's HTML surface: what it renders AS, rather than what it holds.\n *\n * Read here with everything else the inspector shows, so one function reads the\n * document and the panels read the function. A panel reaching back for the node\n * itself would be a second reader of the same selection, free to disagree with\n * this one about which node is selected.\n */\nexport interface BlockHtml {\n  /**\n   * The element's `id`. `undefined` when the node does not carry the field at\n   * all, which is NOT the same as carrying an empty one.\n   *\n   * The rule treats the field as present whenever it is a string, so a stored\n   * `\"\"` shadows any `id` in the attribute bag and the element renders no id\n   * at all. Collapsing the two into `\"\"` here left the panel unable to tell\n   * them apart, so every\n   * attempt to clear an empty-but-present field read as no change and the\n   * field could never be removed. The distinction the document draws has to\n   * survive the reading of it.\n   */\n  readonly cssId: string | undefined;\n  /**\n   * The author's own attributes, absent when there are none.\n   *\n   * Absent rather than empty, because the node itself distinguishes them: a\n   * block that never had attributes and one whose last was removed both store\n   * nothing, and an empty record here would invite writing one back.\n   */\n  readonly attributes: Readonly<Record<string, string>> | undefined;\n}\n\n/** The selected block, as something to edit. */\n/** One section of a tab's settings: its name and its rows. @experimental */\nexport interface InspectionSection {\n  /** What the section is called. */\n  readonly label: string;\n  /** For a Style section, its key, which the Style tab draws it under. */\n  readonly key?: string;\n  /** Its settings, in the order the block declares them. */\n  readonly rows: readonly EditableProp[];\n}\n\n/** A block's settings by the tab each is edited in. @experimental */\nexport interface InspectionSections {\n  readonly content: readonly InspectionSection[];\n  readonly advanced: readonly InspectionSection[];\n  /** The block's own props a Style section draws, beside its styles. */\n  readonly styleProps: readonly InspectionSection[];\n}\n\nexport interface BlockInspection {\n  readonly nodeId: string;\n  readonly blockName: string;\n  /** What the block IS, beside what it holds. */\n  readonly identity: BlockIdentity;\n  /** What the block renders as, beside what it holds. */\n  readonly html: BlockHtml;\n  /**\n   * Whether the block holds custom CSS of its own. Only the answer, never the\n   * text: the Style tab's line reads it for everyone, and the CSS itself is\n   * shown only to a person who may change the site's code.\n   */\n  readonly hasCustomCss: boolean;\n  /** What to title the panel: the block's label, or its name. */\n  readonly label: string;\n  /**\n   * The block's one-line description, from its definition, for the card under\n   * the title. Every definition declares one.\n   */\n  readonly description: string;\n  /** The concept its icon names, from `editor.icon`, if it names one. */\n  readonly icon: string | undefined;\n  /**\n   * Props in the order the definition declares them.\n   *\n   * Declaration order rather than alphabetical: a block author writes a heading\n   * before its level and a button before its destination, and sorting that into\n   * alphabetical order rearranges a form somebody designed.\n   */\n  readonly props: readonly EditableProp[];\n  /**\n   * The same props by the tab and section each is edited in, as the block\n   * declares them (`group` and `section` on each prop): Content first in a\n   * section named after the block, Advanced in \"HTML\", and Style in the Style\n   * tab's section a prop names. Sections and their rows keep declaration\n   * order. A block that declares no places has one Content section holding\n   * every prop.\n   *\n   * @experimental\n   */\n  readonly sections: InspectionSections;\n  /**\n   * The block's own inspector component (`editor.component`), when it names\n   * one, drawn in place of the controls generated from {@link props}.\n   *\n   * Read here with everything else the panel shows, so the panel never goes\n   * back to the registry for a second reading of the same definition.\n   */\n  readonly inspector: ComponentPath | undefined;\n  /**\n   * Why the block's design and settings can't change, when it sits inside an\n   * area locked to its content; undefined where nothing fixes them. Worded as\n   * the store's refusal of the same edit is, so the read-only controls and a\n   * refused edit give one reason.\n   */\n  readonly designLock: RefusalWording | undefined;\n  /**\n   * Every set of props the block can be placed with (its defaults under its\n   * example, then each variation's), for a control that must tell a value an\n   * author set from one the block started with.\n   */\n  readonly placedWith: ReadonlyArray<Readonly<Record<string, unknown>>>;\n}\n\n/** The selected node together with the definition that describes it. */\nexport interface SelectedBlock {\n  readonly node: BlockNode;\n  readonly definition: AnyBlockDefinition;\n}\n\n/**\n * The selected NODE, whether or not the registry knows what it is.\n *\n * Separate from {@link selectedBlock} because the two tabs need different\n * things from a selection, and only one of them needs the definition. Both\n * derive from this, so \"which node is selected\" has one answer.\n */\nexport function selectedNode(\n  document: BlockDocument,\n  selectedId: string | null\n): BlockNode | null {\n  if (selectedId === null) return null;\n  return findNode(document.nodes, selectedId) ?? null;\n}\n\n/**\n * The block an inspector is describing, or `null` when there is none.\n *\n * `null` for no selection, for an id the document no longer holds, and for a\n * block the REGISTRY does not know. The last is the one worth stating, because\n * it is a policy rather than a lookup failing: an unregistered block's props\n * have no schemas, so every content control would have to be guessed from the\n * stored value's runtime type — which produces a text box for a number and\n * silently rewrites the value on save.\n *\n * The STYLE tab does not use this, and the difference is the point. It reads a\n * definition's `supports` where one exists and needs nothing from it where one\n * does not: a node whose block is unregistered still has its styles compiled,\n * because neither `validation.ts` nor `compile-page.ts` consults the registry\n * before emitting them. Withholding the style panel there would leave an author\n * looking at styling nothing can remove, so `inspectStyle` resolves the node\n * itself and treats every stored property as retained.\n */\nexport function selectedBlock(\n  document: BlockDocument,\n  selectedId: string | null\n): SelectedBlock | null {\n  const node = selectedNode(document, selectedId);\n  if (node === null) return null;\n  const definition = getBlock(node.type);\n  if (definition === undefined) return null;\n  return { node, definition };\n}\n\n// What a key and a prop are called, in their own React-free module so the\n// server-safe `ops` entry can offer the same words a server answer needs.\nexport { fieldLabel, propLabel } from \"../prop-label\";\n\n/** Read a schema's `options`, which is untyped by construction. */\nfunction optionsOf(schema: PropSchema): readonly string[] {\n  const declared = schema.options;\n  if (!Array.isArray(declared)) return [];\n  return declared.filter(\n    (option): option is string => typeof option === \"string\"\n  );\n}\n\n/**\n * How a lock reads across a whole selection.\n *\n * `\"mixed\"` is a real third state, not a rounding of the other two: some\n * selected blocks are locked and some are not, and a checkbox showing either\n * on or off there would tell the author something false about half of what\n * they have selected. ARIA models it as `aria-checked=\"mixed\"`, and the first\n * click from mixed LOCKS everything — the reading every file manager and design\n * tool gives it, because the alternative is a first click that appears to do\n * nothing to half the selection.\n */\nexport type LockState = \"locked\" | \"unlocked\" | \"mixed\";\n\n/**\n * Whether a prop is offered at all.\n *\n * Left out: a prop that applies only while others are empty\n * (`onlyWithout`), once any of them is set, as a button's \"Button type\" means\n * nothing once the button links to a URL or an entry. Each entry names one\n * prop, or several that only together are something, as an entry link is a\n * collection and an entry. Left out too: a prop that applies only to some\n * values of another (`onlyWhen`), while that one holds none of them, as a\n * list's \"Start at\" means nothing on a bulleted list. Also left out: a choice\n * with fewer than two options, which offers nothing to pick, as a column's one\n * HTML tag, unless what is stored is not that option, since the choice is then\n * how it is put back.\n */\nfunction offered(\n  schema: PropSchema,\n  value: unknown,\n  values: Readonly<Record<string, unknown>>,\n  declared: Readonly<Partial<Record<string, PropSchema>>>,\n  options: readonly string[],\n  defaults: Readonly<Record<string, unknown>> | undefined\n): boolean {\n  if (hiddenByOnlyWithout(schema, values, declared)) return false;\n  if (!appliesToValues(schema, values, declared, defaults)) return false;\n  if (schema.type !== \"select\" || options.length >= 2) return true;\n  return propIsSet(undefined, value) && !options.includes(String(value));\n}\n\n/** Whether a prop's `onlyWithout` names a prop, or a set of them, that is set. */\nfunction hiddenByOnlyWithout(\n  schema: PropSchema,\n  values: Readonly<Record<string, unknown>>,\n  declared: Readonly<Partial<Record<string, PropSchema>>>\n): boolean {\n  const without = schema.onlyWithout;\n  const entries: readonly unknown[] =\n    typeof without === \"string\"\n      ? [without]\n      : Array.isArray(without)\n        ? without\n        : [];\n  const setHere = (name: unknown): boolean =>\n    typeof name === \"string\" && propIsSet(declared[name], values[name]);\n  return entries.some(entry =>\n    Array.isArray(entry)\n      ? entry.length > 0 && entry.every(setHere)\n      : setHere(entry)\n  );\n}\n\n/**\n * The value a prop reads as while none is stored: what its schema says an\n * unset value means (`whenUnset`), where it says, else the block's default.\n *\n * The two differ where a block's new instances start with a value that its\n * older stored ones never had: an Accordion stored before \"Open\" opens each\n * question alone (\"Many\"), while a new one starts with \"One at a time\". The\n * renderer reads the unset value one way; the panel must show what it draws.\n */\nfunction unsetValueOf(\n  schema: PropSchema,\n  name: string,\n  defaults: Readonly<Record<string, unknown>> | undefined\n): unknown {\n  return Object.hasOwn(schema, \"whenUnset\")\n    ? schema.whenUnset\n    : defaults?.[name];\n}\n\n/** A prop's value as it applies: stored, else what unset reads as. */\nfunction appliedValue(\n  values: Readonly<Record<string, unknown>>,\n  name: string,\n  declared: Readonly<Partial<Record<string, PropSchema>>> | undefined,\n  defaults: Readonly<Record<string, unknown>> | undefined\n): unknown {\n  if (propIsSet(undefined, values[name])) return values[name];\n  const schema = declared?.[name];\n  return schema === undefined\n    ? defaults?.[name]\n    : unsetValueOf(schema, name, defaults);\n}\n\n/** Whether a rule `{ prop: [values] }` holds of these values. */\nfunction holdsFor(\n  when: unknown,\n  values: Readonly<Record<string, unknown>>,\n  declared: Readonly<Partial<Record<string, PropSchema>>> | undefined,\n  defaults: Readonly<Record<string, unknown>> | undefined\n): boolean {\n  if (typeof when !== \"object\" || when === null || Array.isArray(when)) {\n    return true;\n  }\n  return Object.entries(when).every(([name, allowed]) => {\n    const current = appliedValue(values, name, declared, defaults);\n    return Array.isArray(allowed) && allowed.includes(current);\n  });\n}\n\n/**\n * Whether a prop's `onlyWhen`, `{ kind: [\"ordered\"] }`, holds: each prop it\n * names has one of the values listed, read as stored, else as unset reads\n * (`whenUnset`, else the block's default), since that is the value that\n * applies. A prop without one always applies; a malformed one, naming no\n * list, never matches.\n */\nfunction appliesToValues(\n  schema: PropSchema,\n  values: Readonly<Record<string, unknown>>,\n  declared: Readonly<Partial<Record<string, PropSchema>>>,\n  defaults: Readonly<Record<string, unknown>> | undefined\n): boolean {\n  return holdsFor(schema.onlyWhen, values, declared, defaults);\n}\n\n/**\n * Whether a prop's `onlyWhenParent`, `{ openMode: [\"many\"] }`, holds of the\n * block holding this one, read as its own `onlyWhen` is, by the parent's\n * declaration: a question's \"Open by default\" shows only while its\n * Accordion opens many. A prop without one always applies; one whose block\n * has no parent never does.\n */\nfunction appliesUnderParent(\n  schema: PropSchema,\n  parent: BlockNode | undefined\n): boolean {\n  const when = schema.onlyWhenParent;\n  if (when === undefined) return true;\n  if (parent === undefined) return false;\n  const definition = getBlock(parent.type);\n  return holdsFor(\n    when,\n    parent.props,\n    definition?.props ?? {},\n    definition?.defaultProps as Record<string, unknown> | undefined\n  );\n}\n\n/**\n * Whether a stored prop value is there: anything but absent or empty text,\n * and for a URL, only one a page can follow. The engine's rule, the one the\n * renderer reads, so a refused `javascript:` link that renders no link\n * leaves the block offering what it does without one. Exported so the\n * link group asks the same question of whether a link is set.\n */\nexport function propIsSet(\n  schema: PropSchema | undefined,\n  value: unknown\n): boolean {\n  if (schema?.type === \"url\") return isLinkableUrl(value);\n  return value !== undefined && value !== null && value !== \"\";\n}\n\n/**\n * The lock across a set.\n *\n * Ids the document no longer holds are skipped rather than counted as\n * unlocked. An undo removing a selected block is routine, and counting a\n * missing one as unlocked would report `mixed` for a set that is entirely\n * locked.\n */\nexport function lockStateOf(\n  document: BlockDocument,\n  ids: readonly string[]\n): LockState {\n  let locked = 0;\n  let seen = 0;\n  for (const id of ids) {\n    const node = findNode(document.nodes, id);\n    if (node === undefined) continue;\n    seen += 1;\n    if (node.locked === true) locked += 1;\n  }\n  if (seen === 0 || locked === 0) return \"unlocked\";\n  return locked === seen ? \"locked\" : \"mixed\";\n}\n\n/**\n * Describe the selected block for editing, or `null` when there is nothing to\n * edit. See {@link selectedBlock} for what \"nothing\" covers and why.\n */\n/**\n * Whether the inspector can show anything for this selection.\n *\n * Exported because the CANVAS needs the same answer and cannot reach\n * {@link inspectSelection}'s result: when this is false the panel replaces its\n * whole tab strip, so a host still forcing an interaction state would draw the\n * selected block mid-hover with the control that explains it off screen.\n *\n * Derived from {@link selectedBlock}, which is the lookup `inspectSelection`\n * already starts with, so the two cannot disagree about what is inspectable —\n * an unregistered block type is the case that separates them, and it reads as\n * an ordinary selection to anything counting ids.\n */\nexport function selectionIsInspectable(\n  document: BlockDocument,\n  selectedId: string | null\n): boolean {\n  return selectedBlock(document, selectedId) !== null;\n}\n\nexport function inspectSelection(\n  document: BlockDocument,\n  selectedId: string | null,\n  /** The editor's lock source and composed page; see `contentOnlyAreaOf`. */\n  view?: LockView\n): BlockInspection | null {\n  const selected = selectedBlock(document, selectedId);\n  if (selected === null) return null;\n  const { node, definition } = selected;\n  const designLock = designLockOf(document, node.id, view);\n  // Content stays editable under the lock; the rest is read-only. The same\n  // set the save's lock rule keeps, read from the same declaration.\n  const content = contentPropsOf(definition.props);\n\n  const declared = definition.props ?? {};\n  const defaults = definition.defaultProps as\n    | Record<string, unknown>\n    | undefined;\n  const parent = locateNode(document.nodes, node.id)?.parent;\n  const props = Object.entries(declared).flatMap<EditableProp>(\n    ([name, schema]) => {\n      if (schema === undefined) return [];\n      return [\n        {\n          name,\n          schema,\n          value: node.props[name],\n          defaultValue: unsetValueOf(schema, name, defaults),\n          supported: hasContentControl(schema.type),\n          options: optionsOf(schema),\n          offered:\n            offered(\n              schema,\n              node.props[name],\n              node.props,\n              declared,\n              optionsOf(schema),\n              defaults\n            ) && appliesUnderParent(schema, parent),\n          readOnly: designLock !== undefined && !content.has(name),\n        },\n      ];\n    }\n  );\n\n  return {\n    nodeId: node.id,\n    blockName: node.type,\n    identity: { name: node.name ?? \"\", locked: node.locked === true },\n    /*\n     * Narrowed HERE rather than trusted. A stored document can hold anything\n     * the database returned — the engine's validator reports these but does not\n     * rewrite them — so a `cssId` that is not a string, or an `attributes`\n     * that is an array or null, must not reach a control typed for neither.\n     */\n    html: {\n      cssId: typeof node.cssId === \"string\" ? node.cssId : undefined,\n      attributes: editableAttributes(node.attributes),\n    },\n    // The one answer the Layers mark and the section's dot read too.\n    hasCustomCss: holdsCustomCss(node),\n    // The same name the palette offered and the layers panel shows. Reading\n    // `editor.label ?? node.type` here instead was a second rule that agreed\n    // only for blocks which declare a label: an unlabelled third-party block\n    // was \"Collection loop\" in the palette and `acme/collection-loop` here.\n    label: blockLabel(node.type),\n    // Narrowed for the reason the inspector component is: a definition\n    // registered from JavaScript never had its type checked.\n    description:\n      typeof definition.description === \"string\" ? definition.description : \"\",\n    icon:\n      typeof definition.editor?.icon === \"string\"\n        ? definition.editor.icon\n        : undefined,\n    props,\n    sections: sectionsOf(props, blockLabel(node.type)),\n    inspector: inspectorOf(definition),\n    designLock,\n    placedWith: insertionPropSets(definition),\n  };\n}\n\n/** One of the block panel's tabs, named as a block places a setting in it. */\nexport type InspectorTab = PropGroup;\n\n/**\n * The block panel's tabs, in the order an author reads them: what the block\n * says, how it looks, then how it is built into the page.\n */\nconst INSPECTOR_TAB_ORDER: readonly InspectorTab[] = [\n  \"content\",\n  \"style\",\n  \"advanced\",\n];\n\n/** Every row of a tab's sections, in the order the sections hold them. */\nfunction rowsIn(\n  sections: readonly InspectionSection[]\n): readonly EditableProp[] {\n  return sections.flatMap(section => section.rows);\n}\n\n/**\n * The block's own settings the Content tab draws: those it places in\n * Content, read from its sections so the tab and the placement are one\n * answer. A setting placed in Style or Advanced is drawn there instead.\n */\nexport function contentRowsOf(\n  inspection: Pick<BlockInspection, \"sections\">\n): readonly EditableProp[] {\n  return rowsIn(inspection.sections.content);\n}\n\n/**\n * The block's own settings the Advanced tab draws above the ones the builder\n * draws for every block: those it places in Advanced.\n */\nexport function advancedRowsOf(\n  inspection: Pick<BlockInspection, \"sections\">\n): readonly EditableProp[] {\n  return rowsIn(inspection.sections.advanced);\n}\n\n/**\n * The tabs the selected block has, in order: a tab that would hold nothing is\n * left out.\n *\n * Style and Advanced are there for every block. Style always offers a shared\n * style, which any block can carry, and Advanced always holds the settings\n * the builder draws for every block (where it shows, when, its CSS id and its\n * attributes). Content is there when the block declares a setting placed in\n * it, names its own inspector to draw it, or is a core block whose Content\n * sections the builder draws ({@link builderContentSectionsOf}). Judged by\n * what the block declares rather than by which settings show right now, so\n * a setting a condition hides does not make the tab come and go under the\n * author.\n */\nexport function inspectorTabsOf(\n  inspection: Pick<BlockInspection, \"sections\" | \"inspector\" | \"blockName\">\n): readonly InspectorTab[] {\n  const holdsContent =\n    inspection.inspector !== undefined ||\n    contentRowsOf(inspection).length > 0 ||\n    builderContentSectionsOf(inspection.blockName).length > 0;\n  return INSPECTOR_TAB_ORDER.filter(tab => tab !== \"content\" || holdsContent);\n}\n\n/**\n * The Content sections the builder draws itself for a core block, by block,\n * in the order they are drawn: Columns' layout, which writes the row's\n * styles and adds or removes its columns, so it is no prop a generated field\n * could draw (Content, because how many columns a row holds is its\n * structure); and a Gallery's Pictures, which adds Image children, and its\n * Layout, whose Columns and On mobile write the gallery's styles. A section\n * named as one the block places props in is drawn as one, the builder's\n * controls first.\n */\nconst BUILDER_CONTENT_SECTIONS: Readonly<Record<string, readonly string[]>> = {\n  [COLUMNS_ROW]: [\"Columns\"],\n  [GALLERY_BLOCK]: [\"Pictures\", \"Layout\"],\n  // Which icon the questions show, a style value chosen as content.\n  [ACCORDION_BLOCK]: [\"Icon\"],\n};\n\n/** The Content sections the builder draws for a block, none for most. */\nexport function builderContentSectionsOf(blockName: string): readonly string[] {\n  return Object.hasOwn(BUILDER_CONTENT_SECTIONS, blockName)\n    ? (BUILDER_CONTENT_SECTIONS[blockName] ?? [])\n    : [];\n}\n\n/** What a Style section is called, by its key, as the Style tab names it. */\nfunction styleSectionLabel(key: string): string {\n  return INSPECTOR_SECTIONS.find(section => section.key === key)?.label ?? key;\n}\n\n/** One section being filled: its rows are added as props are read. */\ninterface FillingSection {\n  readonly label: string;\n  readonly key?: string;\n  readonly rows: EditableProp[];\n}\n\n/**\n * The props by tab and section, in declaration order: a section is placed\n * where its first prop is declared, and each prop joins its section's rows.\n */\nfunction sectionsOf(\n  props: readonly EditableProp[],\n  label: string\n): InspectionSections {\n  const tabs = {\n    content: [] as FillingSection[],\n    advanced: [] as FillingSection[],\n    style: [] as FillingSection[],\n  };\n  for (const prop of props) {\n    const place = propPlace(prop.schema, label);\n    const tab = tabs[place.tab];\n    const named =\n      place.tab === \"style\"\n        ? { label: styleSectionLabel(place.section), key: place.section }\n        : { label: place.section };\n    let section = tab.find(each => each.label === named.label);\n    if (section === undefined) {\n      section = { ...named, rows: [] };\n      tab.push(section);\n    }\n    section.rows.push(prop);\n  }\n  return {\n    content: tabs.content,\n    advanced: tabs.advanced,\n    styleProps: tabs.style,\n  };\n}\n\n/**\n * The custom inspector a definition names, or `undefined`.\n *\n * Narrowed rather than trusted: a definition registered from JavaScript never\n * had its type checked, and an empty or non-string path names nothing a host\n * could resolve.\n */\nfunction inspectorOf(\n  definition: AnyBlockDefinition\n): ComponentPath | undefined {\n  const component: unknown = definition.editor?.component;\n  return typeof component === \"string\" && component.trim() !== \"\"\n    ? component\n    : undefined;\n}\n\n/**\n * Whether the block may not be changed from the inspector at all: locked in\n * Layers, itself or by a block it sits inside, or no longer in the document.\n *\n * Asked of the LIVE document at the moment a change is attempted, not of the\n * one a panel rendered with: a lock set in Layers after the panel drew must\n * still stop the next write.\n */\nexport function blockIsReadOnly(document: BlockDocument, id: string): boolean {\n  const node = findNode(document.nodes, id);\n  return node === undefined || lockBlockingEdit(document, id) !== undefined;\n}\n\n/**\n * Whether one prop of the block may be set from the inspector.\n *\n * Nothing may change on a read-only block. Inside an area locked\n * `\"contentOnly\"`, only the props its definition declares `role: \"content\"`\n * may: the lock fixes the block's design and leaves what it says editable,\n * which is the rule validation applies on save. The area and the content\n * props are read through the engine's own `nodeLocks` and `contentPropsOf`,\n * so the inspector and a save cannot disagree about either.\n */\nexport function propIsWritable(\n  document: BlockDocument,\n  id: string,\n  name: string,\n  view?: LockView\n): boolean {\n  return writablePropsOf(document, id, view)(name);\n}\n\n/**\n * {@link propIsWritable} for every prop of one block, its locks read once.\n *\n * A panel asks it of each field it draws, on each render: asked prop by prop,\n * each answer walked the page for the block's locks and composed the page\n * again, once per field and per keystroke. This reads them once, and each\n * prop's answer is then a lookup, the same answer by the same rule.\n */\nexport function writablePropsOf(\n  document: BlockDocument,\n  id: string,\n  view?: LockView\n): (name: string) => boolean {\n  if (blockIsReadOnly(document, id)) return () => false;\n  const held = contentOnlyAreaOf(document, id, view);\n  if (held === undefined) return () => true;\n  const content = contentPropsOf(lockSourceOf(view).get(held.type)?.props);\n  return name => content.has(name);\n}\n\n/**\n * Why `node`'s design is fixed, when it sits inside a `\"contentOnly\"` area.\n *\n * Read from the engine's `nodeLocks`, the walk that passes each slot's lock\n * down as validation does, against the live registry the store's lock check\n * defaults to, so the inspector holds read-only exactly what a save refuses\n * to change. The area is named by its outermost locked block, the one the\n * author sees on the canvas. The inspector and the canvas's spacing handles\n * both ask it, so the two hold the same blocks.\n */\nexport function designLockOf(\n  document: BlockDocument,\n  nodeId: string,\n  view?: LockView\n): RefusalWording | undefined {\n  const held = contentOnlyAreaOf(document, nodeId, view);\n  if (held === undefined) return undefined;\n  return lockRefusalWording({\n    code: \"locked-slot-content-only\",\n    holderType: held.area.holderType,\n    lock: \"contentOnly\",\n    childType: held.type,\n  });\n}\n\n/**\n * Where `id` sits inside a `\"contentOnly\"` area, or `undefined` outside one.\n *\n * The one reading both {@link propIsWritable} and {@link designLockOf} take,\n * so the controls the inspector holds read-only and the commits it refuses\n * are the same set. Read from the engine's `nodeLocks` against the live\n * registry, the walk validation applies on save.\n *\n * Asked of the page first, then of the composed page: content a page gives\n * a component's exposed slot keeps its own id there, and sits under the\n * component's locks, which the page alone does not hold. The save judges the\n * composed page too. Both are read against the lock source the editor judges\n * edits by, so a host's own definitions hold here as they hold on `apply`.\n */\nfunction contentOnlyAreaOf(\n  document: BlockDocument,\n  id: string,\n  view?: LockView\n): (NodeLock & { readonly area: NonNullable<NodeLock[\"area\"]> }) | undefined {\n  const source = lockSourceOf(view);\n  const trees =\n    view?.composed === undefined ? [document] : [document, view.composed];\n  for (const tree of trees) {\n    const held = nodeLocks(tree.nodes, source).get(id);\n    if (held?.area !== undefined) return { ...held, area: held.area };\n  }\n  return undefined;\n}\n\n/**\n * What the editor judges locks by, as the inspector reads it: the lock source\n * its edits are refused against, and the page with its placements composed in.\n * Absent, the live registry and the page alone.\n */\nexport interface LockView {\n  readonly definitions?: SlotDefaultSource;\n  readonly composed?: BlockDocument;\n}\n\n/** The view's lock source, or the live registry the store defaults to. */\nexport function lockSourceOf(view: LockView | undefined): SlotDefaultSource {\n  return view?.definitions ?? registryBlockSource();\n}\n\n/** An editor's {@link LockView}, read as it stands. */\nexport function lockViewOf(\n  editor: Pick<EditorState, \"composed\" | \"lockDefinitions\">\n): LockView {\n  const composed = editor.composed();\n  return {\n    definitions: editor.lockDefinitions,\n    ...(composed === undefined ? {} : { composed }),\n  };\n}\n\n/**\n * The locks that hold one block, each kept apart from the other.\n *\n * Two kinds, and the inspector says each in its own words because they are\n * lifted in different places:\n *\n * - `layers` is the block's own lock, set from Layers or the inspector's menu.\n *   It is an edit of the page, so whoever may edit the page may lift it.\n * - `slot` is the lock of the slot the block sits in, which the block that\n *   declares that slot sets in code. Nothing on the page can lift it.\n */\nexport interface BlockLockStatus {\n  /** Whether the block itself is locked in Layers. */\n  readonly layers: boolean;\n  /**\n   * The name of the block locked in Layers that this one sits inside, when\n   * it is not locked itself: a lock covers everything inside the block.\n   */\n  readonly inheritedFrom?: string | undefined;\n  /**\n   * The lock of the slot the block sits in, and the label of the block that\n   * sets it, or `undefined` where no slot lock applies.\n   */\n  readonly slot:\n    | {\n        readonly lock: ActiveSlotLock;\n        readonly holder: string;\n        /** What the lock fixes, in the words a refused edit uses. */\n        readonly reason: string;\n      }\n    | undefined;\n}\n\n/**\n * What a slot locked `all` or `insert` fixes, in an author's words. A\n * `contentOnly` area's reason is the lock refusal's own wording instead.\n */\nconst ARRANGEMENT_LOCK_WORDS = {\n  all: \"fixes which blocks it holds and their order, so this one can't be moved or removed\",\n  insert:\n    \"fixes which blocks it holds, so this one can't be removed or moved out\",\n} as const;\n\n/**\n * Whether the block's own Layers lock may be set or lifted here. Not inside a\n * `contentOnly` area, which pins the node's `locked` field with its design, so\n * the save would refuse the change.\n */\nexport function layersLockChangeable(status: BlockLockStatus): boolean {\n  return status.slot?.lock !== \"contentOnly\";\n}\n\n/**\n * Which locks hold a block.\n *\n * The slot lock is read through the engine's own `nodeLocks`, the walk a save\n * is judged by, so the inspector and the save cannot disagree about it.\n *\n * A `contentOnly` area wins wherever one applies, in the page or in the page\n * composed around it, and is found by the same reading that holds the design\n * read-only ({@link designLockOf}): a block an `all` slot holds on the page and\n * a component's `contentOnly` slot holds once composed is design-locked, and a\n * card naming only the arrangement lock would offer a Layers lock the save\n * refuses. Otherwise the first tree with a lock gives it, and the holder is the\n * nearest ancestor whose slot declares it, the block whose definition says so.\n */\nexport function lockStatusOf(\n  document: BlockDocument,\n  id: string,\n  view?: LockView\n): BlockLockStatus {\n  const node = findNode(document.nodes, id);\n  const layers = node !== undefined && isLocked(node);\n  const around =\n    node === undefined || layers ? undefined : lockedAncestorOf(document, id);\n  const inherited =\n    around === undefined ? {} : { inheritedFrom: layerLabel(around) };\n  const area = contentOnlyAreaOf(document, id, view);\n  if (area !== undefined) {\n    const held = designLockOf(document, id, view);\n    return {\n      layers,\n      ...inherited,\n      slot: {\n        lock: \"contentOnly\",\n        holder: blockLabel(area.area.holderType),\n        reason:\n          held === undefined\n            ? `${blockLabel(area.area.holderType)} fixes this block's design.`\n            : refusalAnnouncement(held),\n      },\n    };\n  }\n  // The page first, then the document the editor composes around it (a\n  // Layout's regions, a component's contents), each judged with the view's\n  // definitions: the same trees and source a save and the canvas use.\n  const source = lockSourceOf(view);\n  const trees =\n    view?.composed === undefined ? [document] : [document, view.composed];\n  const found = trees\n    .map(tree => ({ tree, at: nodeLocks(tree.nodes, source).get(id) }))\n    .find(({ at }) => at?.lock !== undefined);\n  const lock = found?.at?.lock;\n  if (found === undefined || lock === undefined || lock === \"contentOnly\") {\n    return { layers, ...inherited, slot: undefined };\n  }\n  const holderType = declaringAncestor(found.tree, id, source);\n  const holder =\n    holderType === undefined ? \"The block it sits in\" : blockLabel(holderType);\n  return {\n    layers,\n    ...inherited,\n    slot: {\n      lock,\n      holder,\n      reason: `${holder} ${ARRANGEMENT_LOCK_WORDS[lock]}.`,\n    },\n  };\n}\n\n/**\n * The type of the nearest ancestor whose own slot declares a lock over the\n * block, walking up one parent at a time. A slot that declares nothing passes\n * its parent's lock down, so the declaration may be several levels up.\n */\nfunction declaringAncestor(\n  document: BlockDocument,\n  id: string,\n  source: SlotDefaultSource\n): string | undefined {\n  let current = id;\n  // Bounded by the document's depth: each step moves one parent up.\n  for (;;) {\n    const location = locateNode(document.nodes, current);\n    const parent = location?.parent;\n    if (parent === undefined || location?.slot === undefined) return undefined;\n    const declared = source.get(parent.type)?.slots?.[location.slot]?.lock;\n    if (declared !== undefined && declared !== false) return parent.type;\n    current = parent.id;\n  }\n}\n\n/** What the inspector says while a block's own Layers lock holds it. */\nconst LAYERS_LOCK_REASON =\n  \"Locked: it can't be moved, deleted or edited. Unlock it from the block's menu.\";\n\n/**\n * Why a block's design may not be changed here, in an author's words, or\n * `undefined` while it may: its styles, classes, CSS id and attributes.\n *\n * Not on a block its Layers lock holds, and not inside a `\"contentOnly\"` area,\n * where the save refuses every one of them. Asked of the live document at the\n * moment of a write as well as when drawing, as {@link propIsWritable} is.\n */\nexport function designReadOnlyReason(\n  document: BlockDocument,\n  id: string,\n  view?: LockView\n): string | undefined {\n  if (findNode(document.nodes, id) === undefined) {\n    return \"This block is no longer on the page.\";\n  }\n  const status = lockStatusOf(document, id, view);\n  if (status.layers) return LAYERS_LOCK_REASON;\n  // Inside a block locked in Layers: that block's lock covers this one.\n  if (status.inheritedFrom !== undefined) {\n    return `Locked by ${status.inheritedFrom}: this block is inside it, so it can't be moved, deleted or edited. Unlock ${status.inheritedFrom} to change it.`;\n  }\n  // A `contentOnly` area's reason is the lock refusal's own wording, so the\n  // inspector, a refused move and a refused save say one thing.\n  const held = designLockOf(document, id, view);\n  return held === undefined ? undefined : refusalAnnouncement(held);\n}\n\n/** Whether a block's design may be changed: {@link designReadOnlyReason}, as a yes or no. */\nexport function designIsWritable(\n  document: BlockDocument,\n  id: string,\n  view?: LockView\n): boolean {\n  return designReadOnlyReason(document, id, view) === undefined;\n}\n\n/**\n * The entries of a stored attribute bag the editor can actually put in a row.\n *\n * Narrowed ENTRY BY ENTRY, not bag by bag. The renderer skips a single\n * non-string value and emits every other attribute beside it, so an\n * all-or-nothing check disagreed with the page: a bag holding\n * `{ \"data-keep\": \"yes\", \"data-bad\": 5 }` rendered `data-keep` while the panel\n * showed no rows at all — and the first attribute the author added was written\n * from that empty view, deleting `data-keep` without saying so.\n *\n * The unrepresentable entries cannot be carried through an edit: `update`\n * refuses an `attributes` bag holding a non-string, so an op preserving one\n * would never apply. They therefore survive exactly as long as the author\n * leaves the attributes alone — `htmlUpdate` names only the field that changed,\n * so editing the CSS id does not rewrite the bag — and are dropped by the first\n * edit to the attributes themselves, which is the only form that edit can take.\n */\nfunction editableAttributes(\n  value: unknown\n): Readonly<Record<string, string>> | undefined {\n  if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n    return undefined;\n  }\n  const cached = editableBags.get(value);\n  if (cached !== undefined) return cached;\n  const kept: Record<string, string> = {};\n  let dropped = false;\n  for (const [name, each] of Object.entries(value)) {\n    if (typeof each === \"string\") kept[name] = each;\n    else dropped = true;\n  }\n  // `undefined` rather than `{}` for a bag with nothing readable in it, so it\n  // compares equal to no bag at all wherever the two are asked apart.\n  if (Object.keys(kept).length === 0) return undefined;\n  // Nothing was dropped, so the stored object IS the readable one — handed back\n  // as itself rather than as a copy, which is both the common case and the one\n  // that needs no help staying identical between renders.\n  if (!dropped) return value as Readonly<Record<string, string>>;\n  editableBags.set(value, kept);\n  return kept;\n}\n\n/**\n * Filtered bags, keyed by the stored object they were read from.\n *\n * An inspection is rebuilt on EVERY render, and the attributes panel resets its\n * draft whenever the stored bag it is given changes. A copy made fresh each\n * time is a new object each time, so the panel would see the document change on\n * every render — resetting the draft under the author's cursor, and re-running\n * the effect that reset it. A node's `attributes` object is itself replaced\n * only by an op, so keying on it hands back one reference for as long as the\n * document holds one bag.\n */\nconst editableBags = new WeakMap<object, Readonly<Record<string, string>>>();\n\n/**\n * The patch that sets one prop.\n *\n * **The whole props object, not the one key.** `updateNode` merges at the top\n * level — `{ ...node, ...patch }` — so a patch carrying `{ props: { text } }`\n * REPLACES the node's props and drops every other one. Editing a heading's text\n * would silently discard its level.\n *\n * Built here rather than in the panel so that fact is stated once. A caller\n * assembling its own patch has to know a merge rule that is two files away, and\n * the failure is silent: the edit works and the other props are gone.\n */\nexport function propPatch(\n  node: BlockNode,\n  name: string,\n  value: unknown\n): NodePatch {\n  // `undefined` REMOVES the prop rather than storing it: a document holds no\n  // undefined values, and an absent prop is what \"not set\" already means.\n  if (value === undefined) {\n    const { [name]: _removed, ...rest } = node.props;\n    return { props: rest };\n  }\n  return { props: { ...node.props, [name]: value } };\n}\n\n/**\n * The op that names a block, or takes its name away.\n *\n * An empty name UNSETS the field rather than storing `\"\"`. The field is\n * optional, so absent is what \"no name\" already means everywhere else — a\n * stored empty string would be a second spelling of the same state, and\n * `layerLabel` would have to know about both to avoid rendering a blank row.\n *\n * Trimmed, because a name of spaces is the same thing wearing a disguise: it\n * satisfies a non-empty check, renders as nothing, and cannot be typed to in\n * the layers panel's typeahead.\n */\nexport function renameOp(id: string, name: string): BuilderOp {\n  const trimmed = name.trim();\n  return trimmed === \"\"\n    ? { kind: \"update\", id, patch: {}, unset: [\"name\"] }\n    : { kind: \"update\", id, patch: { name: trimmed } };\n}\n\n/**\n * The op that locks a block, or releases it.\n *\n * Unlocking UNSETS rather than storing `false`, for the reason above and one\n * more: `locked` is absent on every node in every document written so far, so\n * storing `false` on release would make an unlock a WRITE to every block an\n * author ever touched, and the documents would grow a field that means what\n * their absence already meant.\n */\nexport function lockOp(id: string, locked: boolean): BuilderOp {\n  return locked\n    ? { kind: \"update\", id, patch: { locked: true } }\n    : { kind: \"update\", id, patch: {}, unset: [\"locked\"] };\n}\n","/**\n * The canvas with visibility conditions applied for the entry a template is\n * previewed with: which of the page's own blocks a visitor would see, and the\n * page as the canvas draws it then.\n *\n * Only the blocks that read the entry are judged. A block in a list's\n * per-entry slot reads each drawn item instead, and a block inside a placed\n * component is drawn from the component's own document, so both keep the\n * \"Conditional\" mark they carry while conditions are not applied.\n *\n * Every verdict is the engine's own (`evaluateConditions`), asked with the\n * entry as a visitor reads it, so the canvas answers as the published page\n * does. A block that is hidden is drawn as a one-line marker in its place,\n * keeping its id, so it stays selectable and its conditions can be changed.\n *\n * @module applied-conditions\n */\nimport {\n  CONDITION_HIDDEN_TYPE,\n  conditionScopeIn,\n  DEFAULT_LIMITS,\n  evaluateConditions,\n  isPlainRecord,\n  mapForest,\n  placementGatesOf,\n  resolveComponentInstances,\n  revealConditioned,\n  storedVisibilityOf,\n  type BlockDocument,\n  type BlockNode,\n  type Condition,\n  type ConditionDayStart,\n  type ConditionEvaluation,\n  type ConditionOp,\n  type ConditionScope,\n  type ConditionSubject,\n  type DefinitionsById,\n  type BindingFieldShape,\n  type DocumentLimits,\n  type NodeVisibility,\n  type ResolvedBlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  liftedNode,\n  prepareDocumentAsDrawn,\n  registeredBlocks,\n  sanitizeDocument,\n  type EntryJudgement,\n  type HidingItem,\n  type ItemHiddenAs,\n} from \"@nextlyhq/blocks-react\";\n\nimport { storedGroups } from \"./condition-checks\";\nimport {\n  asStoredDefinitions,\n  gatedAsDrawn,\n  gatedAsStored,\n} from \"./condition-gate\";\nimport {\n  conditionDraftOf,\n  conditionLine,\n  conditionFieldsOfShapes,\n  conditionSentence,\n  type ConditionField,\n} from \"./condition-model\";\n\n/**\n * What a hidden block's marker shows: the block's name and why it is hidden,\n * in words, and whether that is because its conditions can't be checked.\n */\nexport type ConditionHiddenProps = {\n  readonly name: string;\n  readonly reason: string;\n  readonly unchecked: boolean;\n};\n\n/**\n * The entry the conditions are checked against, as a visitor reads it.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport interface ConditionsPreview {\n  /**\n   * The entry's published values and the fields a visitor may read, or\n   * `undefined` where a visitor reads no entry at all: one never published,\n   * or one the public may not read. The page then hides every conditioned\n   * block, as the published page does.\n   */\n  readonly subject: ConditionSubject | undefined;\n  /** What the entry is called in words, lower case: \"post\". */\n  readonly noun: string;\n  /** The entry's fields as a condition reads them, for the reasons' words. */\n  readonly fields: readonly ConditionField[];\n  /** Where a site starts its days, for a date compared by day. */\n  readonly dayStart?: ConditionDayStart;\n}\n\n/** A block the conditions hide, with what its marker says. */\nexport type HiddenBlock = ConditionHiddenProps & {\n  readonly id: string;\n};\n\n/**\n * The page with its conditions applied.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport interface AppliedConditions {\n  /** The page as the canvas draws it: hidden blocks as markers. */\n  readonly document: BlockDocument;\n  /** The judged blocks a visitor would see. */\n  readonly shown: ReadonlySet<string>;\n  /** The judged blocks a visitor would not, outermost first, in page order. */\n  readonly hidden: readonly HiddenBlock[];\n  /**\n   * Whether the page holds a conditioned block left unjudged, so what is said\n   * of the judged blocks is not said of all: one a list's item decides, where\n   * the lists do not draw what a visitor reads, or one in a region of the\n   * page's Layout.\n   */\n  readonly unjudged: boolean;\n  /**\n   * Whether the page holds conditioned blocks judged for each list entry\n   * drawn, by the renderer, which `shown` and `hidden` do not count: each\n   * one an entry hides is drawn as its marker in that entry.\n   */\n  readonly byEntry: boolean;\n  /**\n   * How the canvas's renderer judges the blocks of the components the page\n   * places, for the previewed entry, as the page's route judges them: each\n   * one they hide drawn as its marker, keeping the placement it belongs to.\n   * The page's own blocks are judged in `document` already.\n   */\n  readonly entryJudgement: EntryJudgement;\n}\n\n/** Where the page's own blocks read: the entry it is drawn for. */\nconst ENTRY_SCOPE: ConditionScope = { source: \"entry\", collection: undefined };\n\n/**\n * The page with its conditions applied for the previewed entry: every block\n * judged, every conditioned block drawn (a shown one as itself, a hidden one\n * as its marker), as the canvas shows the page while conditions apply.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function appliedConditionsOf(\n  document: BlockDocument,\n  preview: ConditionsPreview,\n  nameOf: (node: BlockNode) => string,\n  drawn: DrawnWith = {}\n): AppliedConditions {\n  const { shown, hidden, markers, itemGated, unjudged } = judgedBlocks(\n    document,\n    preview,\n    nameOf,\n    drawn\n  );\n  // A hidden block becomes its marker: matched by its id AND its stored\n  // conditions, so a duplicate id elsewhere (stored data may hold one) with\n  // conditions of its own, or none, is drawn as itself.\n  const marked =\n    markers.size === 0\n      ? document\n      : {\n          ...document,\n          nodes: mapForest(document.nodes, node => {\n            const block = gatedAsStored(node)\n              ? markers.get(occurrenceKey(node))\n              : undefined;\n            return block === undefined ? node : markerFor(block, node);\n          }),\n        };\n  // Every other conditioned block is drawn, as the canvas draws them while\n  // conditions are not applied; but one a list's item decides, where the\n  // lists draw what a visitor reads, keeps its conditions for the renderer\n  // to judge against each item.\n  const applied =\n    itemGated.size === 0\n      ? revealConditioned(marked)\n      : liftedExcept(marked, itemGated);\n  // The blocks of the components the page places, judged on the page as the\n  // canvas draws it, so a placement the page's own judgement already hid or\n  // showed is judged once.\n  const components = judgedComponentBlocks(applied, preview, nameOf, drawn);\n  return {\n    document: applied,\n    shown: new Set([...shown, ...components.shown]),\n    hidden: [...hidden, ...components.hidden],\n    unjudged: unjudged || drawsUnjudged(drawn),\n    byEntry: itemGated.size > 0 || components.byEntry,\n    entryJudgement: entryJudgementOf(preview, nameOf, drawn),\n  };\n}\n\n/** The blocks of the components a page places, judged for the entry. */\ninterface JudgedComponents {\n  readonly shown: ReadonlySet<string>;\n  readonly hidden: readonly HiddenBlock[];\n  /** Whether a placed component's block is left for a list's item. */\n  readonly byEntry: boolean;\n}\n\n/**\n * The blocks of the components `page` places, judged for the previewed\n * entry by the renderer's own preparation (`prepareDocumentAsDrawn` with an\n * entry judgement), each by the id it is drawn under: the very judgement the\n * canvas's renderer makes, and the page's route makes.\n */\nfunction judgedComponentBlocks(\n  page: BlockDocument,\n  preview: ConditionsPreview,\n  nameOf: (node: BlockNode) => string,\n  drawn: DrawnWith\n): JudgedComponents {\n  const shown = new Set<string>();\n  const hidden: HiddenBlock[] = [];\n  if (drawn.definitions === undefined || drawn.definitions.size === 0) {\n    return { shown, hidden, byEntry: false };\n  }\n  const prepared = prepareDocumentAsDrawn(page, {\n    resolver: registeredBlocks(),\n    definitions: drawn.definitions,\n    ...(drawn.limits === undefined ? {} : { limits: drawn.limits }),\n    entryJudged: {\n      ...gateOf(preview),\n      ...(drawn.itemsJudged === true ? {} : { liftItems: true }),\n      hiddenAs: node => {\n        hidden.push(hiddenBlockOf(node, preview, nameOf));\n        return undefined;\n      },\n      onJudged: (id, isShown) => {\n        if (isShown) shown.add(id);\n      },\n    },\n  });\n  return {\n    shown,\n    hidden,\n    // What is left gated is what a list's item decides.\n    byEntry:\n      prepared !== null &&\n      conditionedBlocksIn(prepared, drawn.limits).readingItems,\n  };\n}\n\n/** The route's gate for the previewed entry. */\nfunction gateOf(\n  preview: ConditionsPreview\n): Pick<EntryJudgement, \"entry\" | \"dayStart\"> {\n  return {\n    ...(preview.subject === undefined ? {} : { entry: preview.subject }),\n    ...(preview.dayStart === undefined ? {} : { dayStart: preview.dayStart }),\n  };\n}\n\n/** A block the entry hides, with what its marker says: its name and why. */\nfunction hiddenBlockOf(\n  node: BlockNode,\n  preview: ConditionsPreview,\n  nameOf: (node: BlockNode) => string\n): HiddenBlock {\n  // The whole node, as the renderer judged it, the gates of the placements\n  // it was expanded from among its conditions.\n  const verdict = evaluateConditions(node, inputOf(preview));\n  return {\n    id: node.id,\n    name: nameOf(node),\n    ...reasonOf(node, verdict, preview),\n  };\n}\n\n/**\n * How the canvas's renderer judges the page's components for the entry:\n * each block they hide drawn as its marker, worded from that very block as\n * `hidden` words it, so a repeated id in a stored definition is worded by\n * its own conditions, and keeping the placement it belongs to, so a press\n * on it selects that.\n */\nfunction entryJudgementOf(\n  preview: ConditionsPreview,\n  nameOf: (node: BlockNode) => string,\n  drawn: Pick<DrawnWith, \"itemsJudged\">\n): EntryJudgement {\n  return {\n    ...gateOf(preview),\n    hiddenAs: node =>\n      markerKeepingPlacement(hiddenBlockOf(node, preview, nameOf), node),\n    // While the lists don't draw what a visitor reads, a component's block a\n    // list's item decides is drawn for every item, as a page's own is.\n    ...(drawn.itemsJudged === true ? {} : { liftItems: true }),\n  };\n}\n\n/**\n * A hidden block's marker, keeping the placement the block belongs to when a\n * component's definition gave it, so a press on the marker selects that\n * placement, as a press on any of the component's blocks does.\n */\nfunction markerKeepingPlacement(\n  block: HiddenBlock,\n  node: BlockNode\n): ResolvedBlockNode {\n  const marker: ResolvedBlockNode = markerFor(block, node);\n  const placement = (node as ResolvedBlockNode).instanceOf;\n  return placement === undefined\n    ? marker\n    : { ...marker, instanceOf: placement };\n}\n\n/**\n * What else the canvas draws the page with, whose conditioned blocks are not\n * judged here: the definitions of the components it places, and the regions\n * of its Layout.\n */\nexport interface DrawnWith {\n  /** The limits the canvas draws under, so every block it draws is judged. */\n  readonly limits?: DocumentLimits;\n  /**\n   * Whether the canvas's lists draw the entries a visitor reads, so a block a\n   * list's item decides is judged for each item drawn, by the renderer, and\n   * keeps its conditions in the page drawn rather than being shown for every\n   * item. Otherwise such a block is left unjudged, drawn for every item.\n   */\n  readonly itemsJudged?: boolean;\n  /** The definitions of the components the page places. */\n  readonly definitions?: DefinitionsById;\n  /** The regions of the page's Layout, drawn around it, each with its own definitions. */\n  readonly regions?: readonly {\n    readonly document: BlockDocument;\n    readonly definitions?: DefinitionsById;\n  }[];\n}\n\n/**\n * Whether the canvas draws a conditioned block this does not judge: anything\n * conditioned in a region of the page's Layout, its own or its components'.\n */\nfunction drawsUnjudged(drawn: DrawnWith): boolean {\n  return (drawn.regions ?? []).some(\n    region =>\n      conditionedBlocksIn(region.document, drawn.limits).any ||\n      reachesConditioned(region.document, region.definitions, drawn.limits)\n  );\n}\n\n/**\n * Whether a document reaches a component holding a conditioned block, as the\n * resolver reaches them: through each placement, the components they place,\n * and whichever a variant or an override selects.\n */\nfunction reachesConditioned(\n  document: BlockDocument,\n  definitions: DefinitionsById | undefined,\n  limits: DocumentLimits | undefined\n): boolean {\n  if (definitions === undefined || definitions.size === 0) return false;\n  const { referenced } = resolveComponentInstances(document, definitions, {\n    conditioned: \"carry\",\n    ...(limits === undefined ? {} : { limits }),\n  });\n  return referenced.some(id => {\n    const definition = definitions.get(id);\n    return (\n      definition !== undefined && conditionedBlocksIn(definition, limits).any\n    );\n  });\n}\n\n/** One occurrence of a conditioned block: its id and its stored conditions. */\nfunction occurrenceKey(node: BlockNode): string {\n  return `${node.id}\\0${JSON.stringify(storedVisibilityOf(node.visibility) ?? null)}`;\n}\n\n/**\n * A hidden block's marker, keeping its id so the canvas selects the block,\n * and what is left of its visibility once its conditions are lifted: the\n * devices it is hidden on, which the marker is hidden on too, as the block\n * would be whatever its conditions said.\n */\nfunction markerFor(block: HiddenBlock, stored: BlockNode): BlockNode {\n  const props: ConditionHiddenProps = {\n    name: block.name,\n    reason: block.reason,\n    unchecked: block.unchecked,\n  };\n  // Its conditions lifted as the canvas lifts them, keeping its devices.\n  const devices = liftedNode(stored).visibility;\n  return {\n    id: block.id,\n    type: CONDITION_HIDDEN_TYPE,\n    version: 1,\n    props,\n    ...(devices === undefined ? {} : { visibility: devices }),\n  };\n}\n\n/**\n * What the canvas reads to say why a list's item hides a block: the fields a\n * visitor may read of a collection's entries, the same fields as the \"Show\n * when\" rows name them where the host lists them, each block's name, and\n * where the site's days start.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport interface ItemMarkerSources {\n  readonly fieldsOf: (\n    collection: string\n  ) => readonly BindingFieldShape[] | undefined;\n  readonly labelledOf?: (\n    collection: string\n  ) => readonly ConditionField[] | undefined;\n  readonly nameOf: (node: BlockNode) => string;\n  readonly dayStart?: ConditionDayStart;\n}\n\n/**\n * What the canvas draws where a list's item hides a block, while conditions\n * apply: the block's marker, saying why this entry hides it, as a hidden\n * block of the page itself says it. Judged against the item as the published\n * page judges it; an item whose fields are not known, a named query's row\n * among them, fails closed there, so its marker says the block can't be\n * checked.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function itemHiddenAsOf(sources: ItemMarkerSources): ItemHiddenAs {\n  return (node, item) => {\n    const preview = itemPreviewOf(sources, item);\n    // The whole node, as the renderer judged it: its own conditions and the\n    // gates of a placement it was expanded from (`within`), which hide a\n    // component's otherwise unconditioned root.\n    const verdict = evaluateConditions(node, inputOf(preview));\n    // The renderer asks only about a block the item hides; a verdict that\n    // says otherwise draws the block's place empty rather than a false mark.\n    if (verdict.shown) return undefined;\n    return markerKeepingPlacement(\n      {\n        id: node.id,\n        name: sources.nameOf(node),\n        ...reasonOf(node, verdict, preview),\n      },\n      node\n    );\n  };\n}\n\n/**\n * The list item as a visitor reads it: its values, and the fields its\n * conditions were judged by as the renderer handed them, a named query's own\n * row schema among them; where it handed none, the fields a visitor may read\n * of its collection's entries, and none where those are not known either.\n */\nfunction itemPreviewOf(\n  sources: ItemMarkerSources,\n  item: HidingItem\n): ConditionsPreview {\n  const { collection } = item;\n  const known =\n    collection === undefined\n      ? {}\n      : {\n          readable: sources.fieldsOf(collection),\n          labelled: sources.labelledOf?.(collection),\n        };\n  const readable = item.fields ?? known.readable ?? [];\n  return {\n    subject: {\n      fields: {\n        declared: new Set(readable.map(field => field.name)),\n        readable,\n      },\n      values: item.values,\n    },\n    noun: \"entry\",\n    fields: known.labelled ?? conditionFieldsOfShapes(readable),\n    ...(sources.dayStart === undefined ? {} : { dayStart: sources.dayStart }),\n  };\n}\n\n/** One block to visit, with what its conditions read. */\ninterface Visit {\n  readonly node: unknown;\n  readonly scope: ConditionScope;\n}\n\n/**\n * Every block of the page that reads the entry, judged: shown, or hidden with\n * its reason. A hidden block's own blocks are not judged, since none of them\n * is drawn.\n */\nfunction judgedBlocks(\n  document: BlockDocument,\n  preview: ConditionsPreview,\n  nameOf: (node: BlockNode) => string,\n  drawn: Pick<DrawnWith, \"limits\" | \"itemsJudged\">\n): {\n  shown: Set<string>;\n  hidden: HiddenBlock[];\n  markers: Map<string, HiddenBlock>;\n  /** The blocks a list's item decides, by occurrence, when items are judged. */\n  itemGated: Set<string>;\n  unjudged: boolean;\n} {\n  const shown = new Set<string>();\n  const hidden: HiddenBlock[] = [];\n  const markers = new Map<string, HiddenBlock>();\n  const itemGated = new Set<string>();\n  let unjudged = false;\n  walkScoped(document, drawn.limits, (block, scope) => {\n    if (!gatedAsStored(block)) return true;\n    if (scope.source !== \"entry\") {\n      if (drawn.itemsJudged === true) itemGated.add(occurrenceKey(block));\n      else unjudged = true;\n      return true;\n    }\n    const verdict = evaluateConditions(storedGate(block), inputOf(preview));\n    if (verdict.shown) {\n      shown.add(block.id);\n      return true;\n    }\n    const judged: HiddenBlock = {\n      id: block.id,\n      name: nameOf(block),\n      ...reasonOf(block, verdict, preview),\n    };\n    hidden.push(judged);\n    markers.set(occurrenceKey(block), judged);\n    return false;\n  });\n  return { shown, hidden, markers, itemGated, unjudged };\n}\n\n/**\n * The definitions a page reaches, the components it places and those they\n * place, with each one's conditions lifted so the canvas draws its\n * conditioned blocks; every other definition as it is. The reached ones are\n * those the resolver reads composing the page as the canvas does, so a\n * component a variant or an override selects, at any depth and through any\n * setting a placement rewrites, is lifted exactly when it is drawn. Only\n * those are walked, so a large component library costs nothing on a page\n * that places none of it.\n *\n * Exported so a surface that reads the page as the canvas draws it composes\n * it from these same definitions.\n *\n * @experimental\n */\nexport function revealedDefinitions(\n  document: BlockDocument,\n  definitions: DefinitionsById,\n  limits: DocumentLimits | undefined\n): DefinitionsById {\n  const reached = new Set(\n    resolveComponentInstances(document, definitions, {\n      conditioned: \"carry\",\n      ...(limits === undefined ? {} : { limits }),\n    }).referenced\n  );\n  if (reached.size === 0) return definitions;\n  const next = new Map(definitions);\n  for (const id of reached) {\n    const definition = definitions.get(id);\n    if (definition !== undefined) next.set(id, revealConditioned(definition));\n  }\n  return next;\n}\n\n/**\n * The page as the canvas draws it: every conditioned block drawn, its\n * conditions lifted, but, while a list's entries are judged (`byEntry`),\n * a block a list's entry decides, which keeps its conditions for the\n * renderer to judge against each entry drawn.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function revealedForCanvas(\n  document: BlockDocument,\n  applied: Pick<AppliedConditions, \"byEntry\"> | undefined,\n  limits?: DocumentLimits\n): BlockDocument {\n  if (applied?.byEntry !== true) return revealConditioned(document);\n  const kept = new Set<string>();\n  walkScoped(document, limits, (block, scope) => {\n    if (gatedAsStored(block) && scope.source !== \"entry\") {\n      kept.add(occurrenceKey(block));\n    }\n    return true;\n  });\n  return kept.size === 0\n    ? revealConditioned(document)\n    : liftedExcept(document, kept);\n}\n\n/**\n * The page with every block's conditions lifted but those of `kept`, by\n * occurrence, which the renderer judges for each list item it draws.\n */\nfunction liftedExcept(\n  document: BlockDocument,\n  kept: ReadonlySet<string>\n): BlockDocument {\n  return {\n    ...document,\n    nodes: mapForest(document.nodes, node =>\n      gatedAsStored(node) && kept.has(occurrenceKey(node))\n        ? node\n        : liftedNode(node)\n    ),\n  };\n}\n\n/**\n * Which conditioned blocks a document holds: any at all, and any that reads\n * the entry it is drawn for, which is what applying conditions judges. With\n * `definitions`, the blocks of the components it places too, read as the\n * resolver composes them, each in the scope it is drawn in.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function conditionedBlocksIn(\n  document: BlockDocument,\n  limits?: DocumentLimits,\n  definitions?: DefinitionsById\n): {\n  readonly any: boolean;\n  readonly readingEntry: boolean;\n  /** Whether any is in a list's per-entry slot, read against each item. */\n  readonly readingItems: boolean;\n} {\n  let any = false;\n  let readingEntry = false;\n  let readingItems = false;\n  // Made sound before it is composed, as the renderer does, because that\n  // pass drops every placement gate it finds: afterwards it would drop the\n  // gates the composition has just written.\n  const sound = sanitizeDocument(document, limits ?? DEFAULT_LIMITS);\n  const read =\n    definitions === undefined || definitions.size === 0\n      ? sound\n      : resolveComponentInstances(\n          sound,\n          asStoredDefinitions(definitions, limits),\n          { conditioned: \"carry\", ...(limits === undefined ? {} : { limits }) }\n        ).document;\n  // A composed tree's blocks carry the gates of the placements they were\n  // expanded from, which only that tree holds; a sound stored document holds\n  // none, so the one reader serves both.\n  walkSound(read, limits, (block, scope) => {\n    if (gatedAsDrawn(block)) {\n      any = true;\n      readingEntry ||= scope.source === \"entry\";\n      readingItems ||= scope.source !== \"entry\";\n    }\n    return !(readingEntry && readingItems);\n  });\n  return { any, readingEntry, readingItems };\n}\n\n/**\n * Every block of a document, in page order, with what its conditions read:\n * the entry, or a list's item inside its per-entry slot (`conditionScopeIn`,\n * the save's and the renderer's one rule). `visit` answers whether to go on\n * into the block's own blocks.\n *\n * Walked over the document as the renderer makes it sound to draw\n * (`sanitizeDocument`), under the limits the canvas draws with: a node the\n * renderer drops (no type, an impossible version) or never reaches (past the\n * node limit) is never judged, so applying conditions never draws a marker\n * for a block the canvas would not draw.\n */\nfunction walkScoped(\n  document: BlockDocument,\n  limits: DocumentLimits | undefined,\n  visit: (block: BlockNode, scope: ConditionScope) => boolean\n): void {\n  walkSound(\n    sanitizeDocument(document, limits ?? DEFAULT_LIMITS),\n    limits,\n    visit\n  );\n}\n\n/** {@link walkScoped} over a tree already made sound, a composed one included. */\nfunction walkSound(\n  sound: BlockDocument,\n  limits: DocumentLimits | undefined,\n  visit: (block: BlockNode, scope: ConditionScope) => boolean\n): void {\n  const roots: unknown[] = sound.nodes;\n  const stack: Visit[] = roots\n    .map(node => ({ node, scope: ENTRY_SCOPE }))\n    .reverse();\n  // The sanitized tree already holds no more than the limit; bounded again\n  // because the walk is the one that would loop on a tree that did.\n  let left = (limits ?? DEFAULT_LIMITS).maxNodes;\n  while (stack.length > 0 && left > 0) {\n    const next = stack.pop();\n    left -= 1;\n    if (next === undefined || !isBlock(next.node)) continue;\n    if (visit(next.node, next.scope)) {\n      stack.push(...childVisits(next.node, next.scope));\n    }\n  }\n}\n\n/** Whether a stored value is a block this walk can read. */\nfunction isBlock(node: unknown): node is BlockNode {\n  return isPlainRecord(node) && typeof node.id === \"string\";\n}\n\n/** A block's children, last first, each with what its conditions read. */\nfunction childVisits(block: BlockNode, scope: ConditionScope): Visit[] {\n  const slots: unknown = block.slots;\n  if (!isPlainRecord(slots)) return [];\n  const visits: Visit[] = [];\n  for (const [slot, children] of Object.entries(slots)) {\n    if (!Array.isArray(children)) continue;\n    const inner = conditionScopeIn(block, slot, scope);\n    for (const child of children as unknown[]) {\n      visits.push({ node: child, scope: inner });\n    }\n  }\n  return visits.reverse();\n}\n\n/**\n * The block's conditions as the published page judges them: a placement\n * gate stored on a block, which only the resolver writes, is removed first,\n * as the renderer removes it.\n */\nfunction storedGate(block: BlockNode): Pick<BlockNode, \"id\" | \"visibility\"> {\n  return {\n    id: block.id,\n    visibility: storedVisibilityOf(block.visibility) as NodeVisibility,\n  };\n}\n\n/** What the engine judges a block's conditions against. */\nfunction inputOf(\n  preview: ConditionsPreview\n): Parameters<typeof evaluateConditions>[1] {\n  return {\n    source: \"entry\",\n    ...(preview.subject === undefined ? {} : { subject: preview.subject }),\n    ...(preview.dayStart === undefined ? {} : { dayStart: preview.dayStart }),\n  };\n}\n\n/**\n * Why a block is hidden, as its marker says it: the conditions that don't\n * hold for the entry, worded as the \"Show when\" rows word them; or that a\n * visitor reads no entry; or that its conditions can't be checked, which the\n * published page answers by hiding the block from everyone.\n */\nfunction reasonOf(\n  block: BlockNode,\n  verdict: ConditionEvaluation,\n  preview: ConditionsPreview\n): { reason: string; unchecked: boolean } {\n  // First: with no entry a visitor reads, the engine reports its source as\n  // unavailable, which is no fault of the conditions themselves.\n  if (preview.subject === undefined) {\n    return {\n      reason: `hidden: this ${preview.noun} isn’t published yet`,\n      unchecked: false,\n    };\n  }\n  if (verdict.issues.length > 0) {\n    return {\n      reason: \"can’t be checked, so visitors never see it\",\n      unchecked: true,\n    };\n  }\n  const groups = failingGateOf(block, preview);\n  const only = groups?.length === 1 ? groups[0] : undefined;\n  const failing =\n    only === undefined\n      ? []\n      : only.filter(condition => !holds(block, condition, preview));\n  const why =\n    failing.length === 0\n      ? \"none of its condition groups hold\"\n      : failingWords(failing, preview.fields);\n  return {\n    reason: `hidden for this ${preview.noun}: ${why}`,\n    unchecked: false,\n  };\n}\n\n/**\n * The groups of the gate that hides a block, said in its marker: its own\n * conditions where they don't hold, else those of the placement it was\n * expanded from that don't (`visibility.within`, which only a composed tree\n * holds), else its own as they are.\n */\nfunction failingGateOf(\n  block: BlockNode,\n  preview: ConditionsPreview\n): readonly (readonly Condition[])[] | undefined {\n  const own = storedGroups(block);\n  const envelope = block.visibility;\n  const placements = isPlainRecord(envelope) ? placementGatesOf(envelope) : [];\n  const carried = placements.flatMap(gate =>\n    isPlainRecord(gate)\n      ? [\n          storedGroups({\n            ...block,\n            visibility: { conditions: gate.conditions } as NodeVisibility,\n          }),\n        ]\n      : []\n  );\n  const gates = [own, ...carried].filter(\n    (groups): groups is readonly (readonly Condition[])[] =>\n      groups !== undefined && groups.length > 0\n  );\n  const failing = gates.find(\n    groups =>\n      !evaluateConditions(\n        {\n          id: block.id,\n          visibility: { conditions: groups.map(group => [...group]) },\n        },\n        inputOf(preview)\n      ).shown\n  );\n  return failing ?? own;\n}\n\n/** Whether one condition holds for the entry, as the engine judges it. */\nfunction holds(\n  block: BlockNode,\n  condition: Condition,\n  preview: ConditionsPreview\n): boolean {\n  return evaluateConditions(\n    { id: block.id, visibility: { conditions: [[condition]] } },\n    inputOf(preview)\n  ).shown;\n}\n\n/**\n * The conditions that don't hold, as the first one's opposite and how many\n * more: \"Category is not Guides, and 1 more\".\n */\nfunction failingWords(\n  failing: readonly Condition[],\n  fields: readonly ConditionField[]\n): string {\n  const [first] = failing;\n  const words = first === undefined ? \"\" : oppositeWords(first, fields);\n  const more = failing.length - 1;\n  return more === 0 ? words : `${words}, and ${String(more)} more`;\n}\n\n/** Each operator's opposite, where the operators name one. */\nconst OPPOSITE: Readonly<Partial<Record<ConditionOp, ConditionOp>>> = {\n  equals: \"not_equals\",\n  not_equals: \"equals\",\n  contains: \"not_contains\",\n  not_contains: \"contains\",\n  exists: \"not_exists\",\n  not_exists: \"exists\",\n  is_true: \"is_false\",\n  is_false: \"is_true\",\n};\n\n/**\n * A condition that doesn't hold, said as what holds instead: its opposite\n * operator, worded as a row words it, or \"isn't\" before an order the\n * operators name no opposite for (\"isn't more than 5\").\n */\nfunction oppositeWords(\n  condition: Condition,\n  fields: readonly ConditionField[]\n): string {\n  const draft = conditionDraftOf(condition);\n  const field = fields.find(each => each.name === draft.field);\n  const opposite = draft.op === undefined ? undefined : OPPOSITE[draft.op];\n  if (opposite !== undefined) {\n    return conditionLine(conditionSentence({ ...draft, op: opposite }, field));\n  }\n  const sentence = conditionSentence(draft, field);\n  return conditionLine({\n    ...sentence,\n    operator: sentence.operator.replace(/^is /, \"isn’t \"),\n  });\n}\n","/**\n * What \"the selection\" is once it can hold more than one block.\n *\n * A page builder that can only ever act on one block makes every repetitive\n * job — deleting six cards, locking a whole section's children, moving a run of\n * blocks — a sequence of identical single edits. This module is the grammar for\n * the alternative, decided without a DOM.\n *\n * ## A SET plus a PRIMARY, not a set alone\n *\n * The selection is an ordered set of ids AND one primary id. The primary is the\n * block the inspector edits, the block the breadcrumb traces, and the anchor a\n * range extends from. Modelling the set alone would leave every one of those\n * surfaces inventing \"which of these did the author mean\" separately, and they\n * would each pick a different answer — the first in document order, the last\n * clicked, the deepest. It is also what lets the existing single-selection\n * surfaces keep working unchanged: `primary` IS the old `selectedId`, with a\n * name that says what it means.\n *\n * ## Document order, always\n *\n * The set is kept in document order rather than click order. Every consumer\n * that acts on a selection — delete, duplicate, an announcement counting what\n * is in it — either needs that order or is indifferent to it, and a set that\n * remembered clicks would make \"delete the selection\" produce a different\n * document depending on which block the author happened to click first.\n *\n * ## Outermost only\n *\n * A selection holding a container AND something inside it is normalised to the\n * container. This is not tidiness: deleting such a set would remove the child\n * twice, the second time from a document that no longer has it, and duplicating\n * it would produce the child both inside the copied container and beside it.\n * The engine already reads nesting this way — `lockBlockingDelete` walks\n * outermost-first for the same reason.\n *\n * ## The three gestures, which are the platform's and not ours\n *\n * Plain click REPLACES, `mod`-click TOGGLES, shift-click EXTENDS. That is the\n * grammar of every file manager, every list view and every design tool people\n * arrive already knowing, and inventing a fourth would be a thing to teach for\n * no gain.\n *\n * @module selection\n */\n\nimport type { BlockDocument, BlockNode } from \"@nextlyhq/blocks-engine\";\n\n/** How a gesture changes the selection. */\nexport type SelectionMode = \"replace\" | \"toggle\" | \"extend\";\n\n/** The selection: what is in it, and which one the surfaces answer for. */\nexport interface BlockSelection {\n  /** Every selected id, in document order, outermost only. */\n  readonly ids: readonly string[];\n  /**\n   * The block the inspector edits and a range extends from, or `null`.\n   *\n   * Always a member of `ids` when `ids` is non-empty, which callers may rely\n   * on: a primary outside the set would make the inspector edit a block the\n   * canvas does not show as selected.\n   */\n  readonly primary: string | null;\n}\n\n/** The modifier keys a pointer gesture carried. */\nexport interface SelectionModifiers {\n  readonly shiftKey: boolean;\n  readonly metaKey: boolean;\n  readonly ctrlKey: boolean;\n}\n\n/**\n * Which gesture a click's modifiers mean.\n *\n * **Shift outranks the toggle modifier**, because a shift+mod click is a slip\n * rather than a third gesture, and extending is the one whose result an author\n * can see and undo with a plain click.\n *\n * **Both Meta and Control toggle.** Resolving the platform would be the\n * apparently-correct thing and is not available: the shortcut manager's\n * `detectApplePlatform` is not on `@nextlyhq/ui`'s public entry, and spelling\n * the platform a second time here would let this disagree with the keystrokes.\n * Accepting either is what every web application does, and it is right rather\n * than merely convenient — a Mac author presses Command, a Windows author\n * presses Control, and neither ever presses the other's.\n */\nexport function selectionModeFor(modifiers: SelectionModifiers): SelectionMode {\n  if (modifiers.shiftKey) return \"extend\";\n  if (modifiers.metaKey || modifiers.ctrlKey) return \"toggle\";\n  return \"replace\";\n}\n\n/** Nothing selected. */\nexport const EMPTY_SELECTION: BlockSelection = { ids: [], primary: null };\n\n/**\n * Every id in the document, in the order a reader meets them.\n *\n * Deliberately a walk of its own rather than a flatten of `layersOf`, which\n * would compute a label, a lock badge and two style predicates per node on\n * every click. `selection.test` asserts this agrees with `layersOf`'s order, so\n * there is one VERIFIED definition of document order rather than one shared\n * implementation of it.\n */\nexport function documentOrder(document: BlockDocument): string[] {\n  const out: string[] = [];\n  const walk = (nodes: readonly BlockNode[]): void => {\n    for (const node of nodes) {\n      out.push(node.id);\n      for (const children of Object.values(node.slots ?? {})) walk(children);\n    }\n  };\n  walk(document.nodes);\n  return out;\n}\n\n/** The ids from the root down to `id`, inclusive, or `[]` when it is absent. */\nfunction pathOf(document: BlockDocument, id: string): string[] {\n  const find = (nodes: readonly BlockNode[], trail: string[]): string[] => {\n    for (const node of nodes) {\n      const here = [...trail, node.id];\n      if (node.id === id) return here;\n      for (const children of Object.values(node.slots ?? {})) {\n        const found = find(children, here);\n        if (found.length > 0) return found;\n      }\n    }\n    return [];\n  };\n  return find(document.nodes, []);\n}\n\n/**\n * The set with anything that has an ancestor in it removed, in document order.\n *\n * Ids the document no longer holds are dropped too, which an undo produces\n * routinely — a selection outliving its blocks is the normal case, not an edge\n * one.\n */\nexport function normalizeSelection(\n  document: BlockDocument,\n  ids: readonly string[]\n): string[] {\n  const paths = new Map<string, string[]>();\n  for (const id of ids) {\n    const path = pathOf(document, id);\n    if (path.length > 0) paths.set(id, path);\n  }\n\n  const kept = [...paths.keys()].filter(id => {\n    const path = paths.get(id) ?? [];\n    // Every entry but the last is an ancestor. If the set holds one of them,\n    // this node travels with it and listing it as well would act on it twice.\n    return !path.slice(0, -1).some(ancestor => paths.has(ancestor));\n  });\n\n  const order = documentOrder(document);\n  return kept.sort((a, b) => order.indexOf(a) - order.indexOf(b));\n}\n\n/**\n * The sibling run between two blocks, at the deepest level they share.\n *\n * Shift-clicking a block inside another section does NOT select across the two\n * containers, because there is no run of siblings spanning them. It selects the\n * run at the level where the two paths diverge — the sections themselves — so\n * the gesture always answers with something contiguous.\n *\n * `[]` when either id is absent, and the OUTER one alone when one contains the\n * other: a range from a container to something inside it is the container.\n */\nexport function rangeBetween(\n  document: BlockDocument,\n  anchorId: string,\n  targetId: string\n): string[] {\n  const anchor = pathOf(document, anchorId);\n  const target = pathOf(document, targetId);\n  if (anchor.length === 0 || target.length === 0) return [];\n\n  let shared = 0;\n  while (\n    shared < anchor.length &&\n    shared < target.length &&\n    anchor[shared] === target[shared]\n  ) {\n    shared += 1;\n  }\n\n  // One is on the other's path, so they are not siblings at any level.\n  if (shared === anchor.length) return [anchorId];\n  if (shared === target.length) return [targetId];\n\n  const from = anchor[shared];\n  const to = target[shared];\n  if (from === undefined || to === undefined) return [];\n\n  const parentId = shared === 0 ? undefined : anchor[shared - 1];\n  const siblings = siblingRunOf(document, parentId, from, to);\n  return siblings;\n}\n\n/** The contiguous run of siblings from `from` to `to`, whichever comes first. */\nfunction siblingRunOf(\n  document: BlockDocument,\n  parentId: string | undefined,\n  from: string,\n  to: string\n): string[] {\n  const lists =\n    parentId === undefined ? [document.nodes] : slotListsOf(document, parentId);\n\n  for (const list of lists) {\n    const ids = list.map(node => node.id);\n    const a = ids.indexOf(from);\n    const b = ids.indexOf(to);\n    // BOTH in the same list. A parent's slots are separate lists, and a run\n    // spanning two of them is not contiguous however close the indices look.\n    if (a === -1 || b === -1) continue;\n    return ids.slice(Math.min(a, b), Math.max(a, b) + 1);\n  }\n  return [];\n}\n\n/** Each of a parent's slots, as its own list. */\nfunction slotListsOf(document: BlockDocument, parentId: string): BlockNode[][] {\n  const find = (nodes: readonly BlockNode[]): BlockNode[][] | undefined => {\n    for (const node of nodes) {\n      if (node.id === parentId) return Object.values(node.slots ?? {});\n      for (const children of Object.values(node.slots ?? {})) {\n        const found = find(children);\n        if (found !== undefined) return found;\n      }\n    }\n    return undefined;\n  };\n  return find(document.nodes) ?? [];\n}\n\n/**\n * The selection after a gesture on `targetId`.\n *\n * `null` clears it, whatever the mode: a click on canvas background has no\n * subject to toggle or extend to.\n */\n/**\n * The selection with `id` in it, or out of it if it was already there.\n *\n * Adding makes the NEW block primary: it is the one the author just pointed at\n * and the one they expect the inspector to describe. Removing keeps whatever\n * primary the selection had, which {@link withPrimary} corrects when the block\n * removed WAS the primary.\n */\nfunction toggled(\n  document: BlockDocument,\n  current: BlockSelection,\n  targetId: string\n): BlockSelection {\n  const has = current.ids.includes(targetId);\n  const ids = normalizeSelection(\n    document,\n    has ? current.ids.filter(id => id !== targetId) : [...current.ids, targetId]\n  );\n  return withPrimary(ids, has ? current.primary : targetId);\n}\n\n/**\n * The run from the selection's anchor to `targetId`.\n *\n * The run REPLACES rather than unions with what was selected. Shift-click in\n * every list this grammar comes from means \"the selection is now\n * anchor-to-here\", and unioning would make a second shift-click GROW the\n * selection instead of redefining it — so an author correcting their aim would\n * have to clear and start again.\n *\n * The anchor stays primary, which is what makes a run of shift-clicks re-aim\n * from the same end rather than walking the anchor along.\n */\nfunction extended(\n  document: BlockDocument,\n  current: BlockSelection,\n  targetId: string\n): BlockSelection {\n  if (current.primary === null) return replaced(targetId);\n  const run = rangeBetween(document, current.primary, targetId);\n  // No contiguous run reaches the target — across two slots of one parent, for\n  // instance. Selecting the target alone is right; emptying the selection would\n  // read as the gesture being broken.\n  if (run.length === 0) return replaced(targetId);\n  return withPrimary(normalizeSelection(document, run), current.primary);\n}\n\n/** One block, selected on its own. */\nfunction replaced(targetId: string): BlockSelection {\n  return { ids: [targetId], primary: targetId };\n}\n\n/**\n * A selection whose primary is guaranteed to be a member of it.\n *\n * The one place that invariant is enforced, so no caller has to remember it. A\n * primary outside the set would make the inspector edit a block the canvas does\n * not show as selected.\n *\n * Falls back to the FIRST id in document order, deliberately: that is a\n * position the author can see, where \"the one next to what you just removed\" is\n * a rule they would have to be told. An earlier version chose the last survivor\n * and no test could tell the two apart, which is how the arbitrariness was\n * found.\n */\nfunction withPrimary(\n  ids: readonly string[],\n  preferred: string | null\n): BlockSelection {\n  if (ids.length === 0) return EMPTY_SELECTION;\n  return {\n    ids,\n    primary: preferred !== null && ids.includes(preferred) ? preferred : ids[0],\n  };\n}\n\n/**\n * The selection after a gesture on `targetId`.\n *\n * `null` clears it, whatever the mode: a click on canvas background has no\n * subject to toggle or extend to. A target the document does not hold is\n * IGNORED rather than treated as a deselect — a stale id is not an instruction\n * to clear, and treating it as one loses a selection for a reason the author\n * cannot see.\n *\n * A dispatcher and nothing else. Each mode is its own function above, because\n * the three were one body until a complexity gate objected — and it was right:\n * the shared shape between them is only \"normalise, then pick a primary\", which\n * {@link withPrimary} now owns for all three.\n */\nexport function applySelection(\n  document: BlockDocument,\n  current: BlockSelection,\n  targetId: string | null,\n  mode: SelectionMode = \"replace\"\n): BlockSelection {\n  if (targetId === null) return EMPTY_SELECTION;\n  if (pathOf(document, targetId).length === 0) return current;\n\n  if (mode === \"toggle\") return toggled(document, current, targetId);\n  if (mode === \"extend\") return extended(document, current, targetId);\n  return replaced(targetId);\n}\n\n/**\n * The selection with anything the document has lost dropped.\n *\n * Called after an edit rather than on read, so a surface never renders against\n * ids that are gone. An undo removing selected blocks is routine.\n */\nexport function pruneSelection(\n  document: BlockDocument,\n  selection: BlockSelection\n): BlockSelection {\n  const ids = normalizeSelection(document, selection.ids);\n  if (ids.length === 0) return EMPTY_SELECTION;\n  const primary =\n    selection.primary !== null && ids.includes(selection.primary)\n      ? selection.primary\n      : (ids[0] ?? null);\n  return { ids, primary };\n}\n","/**\n * Whether the reader asked the system for less motion.\n *\n * Asked of the window a canvas node or document belongs to, never the\n * editor's own: a frame's window answers for the frame, which is where the\n * canvas is drawn and where its media queries are read.\n *\n * @module reduced-motion\n */\n\n/**\n * Whether the window `root` belongs to asks for reduced motion; `false` where\n * there is no window to ask.\n *\n * @param root - a canvas node, or the document of the frame it draws in\n */\nexport function prefersReducedMotion(root: Document | Element): boolean {\n  const owner = \"defaultView\" in root ? root : root.ownerDocument;\n  const view = owner.defaultView;\n  if (view === null || typeof view.matchMedia !== \"function\") return false;\n  return view.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n}\n","/**\n * Bring one block into view by its id.\n *\n * One answer for every way an author asks the editor to show a block: opening\n * the editor at a section from the entry screen, a Layers row, a search\n * result. Each of those would otherwise find the element and scroll it its own\n * way, and the copies drift — one animating for a reader who asked for less\n * motion, another finding a same-id node outside the canvas.\n *\n * ## It searches the root it is handed\n *\n * Never the global `document`. The entry screen's preview draws the same\n * document beside the editor, so the same ids exist twice on one screen, and a\n * canvas drawn inside a frame keeps its nodes in the frame's own document,\n * where a global search finds nothing. The caller says where the canvas is.\n *\n * ## The node is found the way the canvas finds it\n *\n * Through `nodeElement`, the canvas's own map from a node id to the element it\n * was drawn as. That answers for a placed component too: the instance the\n * editor holds draws no element of its own, and its definition's elements\n * carry minted ids with the instance named beside them. A second lookup here\n * would be a second answer to what a node id means in the DOM.\n *\n * @module reveal-node\n */\nimport { nodeElement } from \"./canvas\";\nimport { prefersReducedMotion } from \"./reduced-motion\";\n\n/**\n * Scroll the block `id` into view inside `root`.\n *\n * `nearest` on both axes, so a block already on screen does not move and one\n * off screen moves only as far as it must. Smooth, except where the reader\n * asked for less motion, where it jumps.\n *\n * @param root - the canvas: its root element, or the document of the frame it\n *   draws in\n * @param id - the block's id, as the document stores it\n * @param options - `instant` jumps rather than scrolling smoothly\n * @returns whether the block was found; `false` scrolls nothing, which is what\n *   an address naming a block the page no longer has should do\n */\nexport function revealNode(\n  root: Document | HTMLElement,\n  id: string,\n  { instant = false }: { readonly instant?: boolean } = {}\n): boolean {\n  // A frame's document is searched from its root element, which holds all of\n  // it; `nodeElement` compares ids rather than building a selector from them.\n  const scope = \"documentElement\" in root ? root.documentElement : root;\n  const element = nodeElement(scope, id);\n  if (element === null) return false;\n  element.scrollIntoView({\n    block: \"nearest\",\n    inline: \"nearest\",\n    // Instant where the caller is about to measure or focus at the block's\n    // new place, which a smooth scroll would still be moving towards.\n    behavior: instant || prefersReducedMotion(root) ? \"auto\" : \"smooth\",\n  });\n  return true;\n}\n","/**\n * A binding, spelled the way this keyboard spells it.\n *\n * The editor stores its shortcuts as specs — `alt+ArrowUp` — because that is\n * what the shortcut manager matches against. A person reads none of that: the\n * key on their keyboard says Option or Alt depending on the machine, and the\n * arrow is a glyph rather than a word.\n *\n * ## Why this is not a fixed string\n *\n * The block toolbar records the reason it shows no hint at all: a binding\n * spelled `mod` is Command on Apple platforms and Control everywhere else, so\n * any fixed string is wrong on one of them, and teaching \"Ctrl+D\" to a Mac\n * author teaches a keystroke that does nothing. `alt` has the same problem\n * more quietly — the same physical key is labelled Alt on one platform and\n * Option on another.\n *\n * `@nextlyhq/ui` owns that decision in `detectApplePlatform`, and it is on the\n * public entry, so the hint can be resolved rather than guessed.\n *\n * ## Why it parses rather than splits\n *\n * The spec grammar is not \"split on `+`\" — a lone `+` is a key, and a trailing\n * one is too, so `mod++` is the zoom shortcut rather than a malformed chord.\n * `parseKeys` is the one implementation of that grammar, and re-deriving it\n * here would produce a hint that disagrees with the binding it describes for\n * exactly the specs that are hardest to read.\n *\n * @module key-hint\n */\n\nimport { detectApplePlatform, parseKeys, type KeyChord } from \"@nextlyhq/ui\";\n\n/**\n * Glyphs for keys whose NAME is not what a keyboard shows.\n *\n * Arrows only. A named key like `Enter` or `Escape` is written on the key in\n * words, so a symbol would be the less recognisable of the two.\n */\nconst KEY_GLYPHS: Readonly<Record<string, string>> = {\n  arrowup: \"↑\",\n  arrowdown: \"↓\",\n  arrowleft: \"←\",\n  arrowright: \"→\",\n  /*\n   * The space bar, which the parser canonicalises to the character it produces\n   * rather than to the word a spec spells it with. Passing that through would\n   * print a hint with a blank where the key should be — the one key whose name\n   * is unreadable precisely because the value IS readable to the browser.\n   */\n  \" \": \"Space\",\n};\n\n/**\n * The modifiers, in the order a keyboard shortcut is conventionally written.\n *\n * A table rather than a run of conditions: the order IS the convention, and a\n * list makes it the thing being read rather than something recoverable only by\n * following five branches in sequence. `mod` leads because it is the outermost\n * modifier wherever more than one is written.\n */\nconst MODIFIERS: ReadonlyArray<{\n  readonly held: (chord: KeyChord) => boolean;\n  readonly apple: string;\n  readonly other: string;\n  /** The Apple key's name in words, for text that is spoken. */\n  readonly appleSpoken: string;\n}> = [\n  {\n    held: chord => chord.mod,\n    apple: \"⌘\",\n    other: \"Ctrl\",\n    appleSpoken: \"Command\",\n  },\n  {\n    held: chord => chord.ctrl,\n    apple: \"⌃\",\n    other: \"Ctrl\",\n    appleSpoken: \"Control\",\n  },\n  { held: chord => chord.alt, apple: \"⌥\", other: \"Alt\", appleSpoken: \"Option\" },\n  {\n    held: chord => chord.shift,\n    apple: \"⇧\",\n    other: \"Shift\",\n    appleSpoken: \"Shift\",\n  },\n  {\n    held: chord => chord.meta,\n    apple: \"⌘\",\n    other: \"Meta\",\n    appleSpoken: \"Command\",\n  },\n];\n\n/** The modifier labels this chord carries, in that order. */\nfunction modifierLabels(chord: KeyChord, apple: boolean): string[] {\n  return MODIFIERS.filter(modifier => modifier.held(chord)).map(modifier =>\n    apple ? modifier.apple : modifier.other\n  );\n}\n\n/**\n * One binding as a person would read it, or `null` when the spec cannot be read.\n *\n * `null` rather than a best guess: a hint is a promise that pressing something\n * does something, and a spec this cannot parse is one whose keystroke it does\n * not know. Showing a wrong one is worse than showing none, which is the same\n * judgement the toolbar made when it showed none at all.\n *\n * @experimental\n */\nexport function keyHint(\n  spec: string,\n  apple: boolean = detectApplePlatform()\n): string | null {\n  let chords;\n  try {\n    chords = parseKeys(spec);\n  } catch {\n    return null;\n  }\n  return chords\n    .map(chord => {\n      const key = KEY_GLYPHS[chord.key.toLowerCase()] ?? capitalize(chord.key);\n      return [...modifierLabels(chord, apple), key].join(apple ? \"\" : \"+\");\n    })\n    .join(\" \");\n}\n\n/**\n * A single character is shown upper case; a named key keeps the spelling the\n * spec used, because that is already the name written on the key.\n */\nfunction capitalize(key: string): string {\n  return key.length === 1 ? key.toUpperCase() : key;\n}\n\n/**\n * Keys named differently in words than in the spec, for text that is spoken.\n * A Mac labels Backspace \"Delete\" and Enter \"Return\"; arrows and the space\n * bar have names rather than glyphs.\n */\nconst SPOKEN_KEYS: Readonly<\n  Record<string, { readonly apple: string; readonly other: string }>\n> = {\n  backspace: { apple: \"Delete\", other: \"Backspace\" },\n  enter: { apple: \"Return\", other: \"Enter\" },\n  arrowup: { apple: \"Up Arrow\", other: \"Up Arrow\" },\n  arrowdown: { apple: \"Down Arrow\", other: \"Down Arrow\" },\n  arrowleft: { apple: \"Left Arrow\", other: \"Left Arrow\" },\n  arrowright: { apple: \"Right Arrow\", other: \"Right Arrow\" },\n  \" \": { apple: \"Space\", other: \"Space\" },\n};\n\n/**\n * One binding in words, for text a screen reader speaks, or `null` when the\n * spec cannot be read.\n *\n * Beside {@link keyHint}, not instead of it: glyphs read well on screen and\n * badly aloud, where ⌥ and ⌫ are skipped or read as \"symbol\". Same parser,\n * same modifier table and order, so the two never name different keys.\n *\n * @experimental\n */\nexport function spokenKeyHint(\n  spec: string,\n  apple: boolean = detectApplePlatform()\n): string | null {\n  let chords;\n  try {\n    chords = parseKeys(spec);\n  } catch {\n    return null;\n  }\n  return chords\n    .map(chord => {\n      const named = SPOKEN_KEYS[chord.key.toLowerCase()];\n      const key =\n        named === undefined\n          ? capitalize(chord.key)\n          : apple\n            ? named.apple\n            : named.other;\n      const modifiers = MODIFIERS.filter(modifier => modifier.held(chord)).map(\n        modifier => (apple ? modifier.appleSpoken : modifier.other)\n      );\n      return [...modifiers, key].join(\"+\");\n    })\n    .join(\" then \");\n}\n","/**\n * Whether a value a placement drives into its component may change, and why\n * not.\n *\n * A placement's value lands on a node of its component, which only the\n * composed page shows. Two locks there hold it, and a save refuses a change to\n * either, so the editor holds the field before it is typed into:\n *\n * - a block the component locks in Layers, or one inside it, by the engine's\n *   `componentLayersLocks`, the coverage a save measures a page by;\n * - a value that is not content, inside an area its block locks to its\n *   content, by the engine's `nodeLocks`, the walk a save applies.\n *\n * One judgement for the inspector's rows and the canvas's inline text, so the\n * two cannot disagree about which field is held, and one wording per lock.\n *\n * @module component-holds\n */\nimport {\n  componentLayersLocks,\n  contentPropsOf,\n  nodeLocks,\n  type BlockDocument,\n  type NodeLock,\n  type ResolvedBlockNode,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { lockRefusalWording } from \"../lock-refusal\";\n\nimport type { RefusalWording } from \"./drag-refusal\";\n\n/** What holds one value a placement drives. */\nexport type ComposedHold =\n  | { readonly kind: \"component\" }\n  | { readonly kind: \"content-only\"; readonly lock: NodeLock };\n\n/**\n * The hold on each composed node's values, asked per node and prop: `design`\n * for a value that is never content, such as whether the node shows.\n *\n * @param composed - the editor's composition, with the resolver's markers\n * @param locks - the block definitions the editor judges slot locks by\n */\nexport function composedHolds(\n  composed: BlockDocument,\n  locks: SlotDefaultSource\n): (\n  node: ResolvedBlockNode,\n  prop: string,\n  design: boolean\n) => ComposedHold | undefined {\n  const byComponent = componentLayersLocks(composed.nodes);\n  const bySlot = nodeLocks(composed.nodes, locks);\n  return (node, prop, design) => {\n    if (byComponent.has(node.id)) return { kind: \"component\" };\n    const lock = bySlot.get(node.id);\n    if (lock?.area === undefined) return undefined;\n    if (!design && contentPropsOf(locks.get(node.type)?.props).has(prop)) {\n      return undefined;\n    }\n    return { kind: \"content-only\", lock };\n  };\n}\n\n/**\n * What a held field says: for a component's Layers lock, the component by\n * name and where to change it; for a content-only area, the area by its\n * holder, in the slot lock's own wording.\n */\nexport function composedHoldWording(\n  hold: ComposedHold,\n  componentName: string,\n  childType: string | undefined\n): RefusalWording {\n  if (hold.kind === \"component\") {\n    return lockRefusalWording({\n      code: \"layers-locked\",\n      label: componentName,\n      relation: \"component\",\n      verb: \"change\",\n    });\n  }\n  const area = hold.lock.area;\n  return lockRefusalWording({\n    code: \"locked-slot-content-only\",\n    holderType: area?.holderType ?? \"\",\n    lock: \"contentOnly\",\n    ...(childType === undefined ? {} : { childType }),\n  });\n}\n","/**\n * What a selected component INSTANCE exposes for editing, and the patch that\n * changes it.\n *\n * Pure, for the reason `inspector.ts` is: which rows an instance offers, what\n * each shows and where its value came from is derivation, and a component\n * test in jsdom cannot separate a correct answer from a plausible wrong one.\n *\n * **An instance is not a block.** Its node's type is not in the registry, so\n * the block inspector answers nothing for it; and what it holds is not props\n * but OVERRIDES — values keyed by the definition's exposed-property ids, each\n * either absent (inherit), a value (replace) or the `$unset` sentinel (clear).\n * The definition decides what may be overridden and the resolver decides what\n * is in force, so this module asks both and draws nothing of its own.\n *\n * **The rows are the resolver's answer.** `instanceExposure` applies the\n * overrides in force with the same writer the renderer uses and reads every\n * row's value back from the result, so a row here shows what the page shows.\n * A second derivation beside it — reading the override record directly — would\n * agree until two exposures pointed at one path, and then disagree silently.\n *\n * @module instance-inspector\n */\n\nimport {\n  bindablePropKind,\n  boundSettingId,\n  DOCUMENT_FORMAT_VERSION,\n  findNode,\n  getBlock,\n  instanceExposure,\n  isComponentInstance,\n  isPlainRecord,\n  keepsItsListWhenMoved,\n  outerListOf,\n  readableDefinition,\n  resolveComponentInstances,\n  settingBindingKey,\n  type Binding,\n  type BlockDocument,\n  type BlockNode,\n  type ComponentDocument,\n  type ComponentLookup,\n  type ExposedPropertyType,\n  type ExposedValueSource,\n  type OverrideValue,\n  type PropSchema,\n  type ResolvedBlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { composedHolds, composedHoldWording } from \"../canvas/component-holds\";\nimport type { RefusalWording } from \"../canvas/drag-refusal\";\nimport { refusalAnnouncement } from \"../move-refusal\";\nimport type { BuilderOp, NodePatch } from \"../op-vocabulary\";\nimport type { SavedComponent } from \"../panels/add/inserter\";\nimport { instanceProps, storedComponentId } from \"../placement-props\";\n\nimport { lockSourceOf, type BlockIdentity, type LockView } from \"./inspector\";\n\n/**\n * The exposed types this inspector can draw a control for.\n *\n * Named as a set rather than inferred from what the switch happens to handle,\n * for the reason `SUPPORTED_PROP_TYPES` is: an exposed type with no control is\n * a KNOWN gap the row states, never a silent fallthrough. A link is edited as\n * the address its prop holds, visibility as shown-or-hidden, and an image as\n * a file chosen from the host's media library, which the inspector hands the\n * panel. Rich text has no control here yet — a passage is edited on the\n * canvas — and its row still shows its value and its source, and still\n * offers a reset, because withholding the row would present a component as\n * exposing less than it does.\n */\nexport const EDITABLE_EXPOSED_TYPES = [\n  \"text\",\n  \"select\",\n  \"link\",\n  \"visibility\",\n  \"image\",\n  \"richText\",\n] as const;\n\n/** One exposed property, with everything a row needs to draw itself. */\nexport interface ExposedRow {\n  /** The definition's stable id for the property, which the override is keyed by. */\n  readonly id: string;\n  readonly label: string;\n  readonly type: ExposedPropertyType;\n  /**\n   * The value in force, read back from the resolver's own result.\n   *\n   * `undefined` for a cleared row and for a definition that holds nothing\n   * there; {@link cleared} separates the two.\n   */\n  readonly value: OverrideValue;\n  /**\n   * Which layer supplied the value IN FORCE at this row's target: the\n   * definition, a variant, or this instance.\n   *\n   * The target's, not the row's: two exposures aimed at one target share a\n   * value, and the resolver reports the winning exposure's source on both.\n   * What this row itself stores is {@link ownOverride}.\n   */\n  readonly source: ExposedValueSource;\n  /** True when the author cleared the property rather than inheriting or setting it. */\n  readonly cleared: boolean;\n  /**\n   * Whether THIS instance's record holds a value under this row's id — set\n   * or cleared. What a reset would remove, and so whether one is offered: a\n   * row shadowed by a neighbour that holds the override reads `instance` as\n   * its source and has nothing of its own to reset.\n   */\n  readonly ownOverride: boolean;\n  /** Whether this inspector can draw a control for it. Carried, not recomputed. */\n  readonly supported: boolean;\n  /** The choices, for `select` only; empty for every other type. */\n  readonly options: readonly {\n    readonly value: string;\n    readonly label: string;\n  }[];\n  /**\n   * The exposure actually in force at this row's target, when it is not this\n   * one — carried with its label so the row can NAME what shadows it rather\n   * than pointing at an id an author has never seen.\n   */\n  readonly shadowedBy?: { readonly id: string; readonly label: string };\n  /**\n   * Why this row is read-only, when a `contentOnly` lock holds what it drives:\n   * a value that is not content, inside an area locked to its content. The\n   * same rule a save applies to the composed page, so the panel holds exactly\n   * what the store would refuse. Absent where the row may change.\n   */\n  readonly heldBy?: RefusalWording;\n  /**\n   * Where the setting may be bound to data: the schema of the component\n   * block's prop it fills, named as the setting, which the binding picker\n   * lists the fitting fields for. The placement's binding is written onto\n   * that prop when the component is composed, so it is judged by that prop.\n   * Absent for a setting no field fills.\n   */\n  readonly bindable?: PropSchema;\n  /** The placement's binding of this setting, where it has one. */\n  readonly binding?: Binding;\n}\n\n/**\n * A value this instance stores for a property the definition no longer\n * exposes.\n *\n * Surfaced rather than dropped, and separately from the rows: it is not a\n * property any more, so it has no label, no type and no control — only the\n * stored value and the offer to discard it. An author whose override\n * disappeared the moment somebody else edited the component is told, and\n * chooses.\n */\nexport interface OrphanedOverride {\n  readonly id: string;\n  readonly value: OverrideValue;\n}\n\n/** The selected instance, as something to edit. */\nexport interface InstanceInspection {\n  readonly nodeId: string;\n  readonly componentId: string;\n  /** What the node IS, beside what it overrides: its own name and lock. */\n  readonly identity: BlockIdentity;\n  /**\n   * What to title the panel: the library's title for the definition, or the\n   * id when the library has no row for it.\n   */\n  readonly label: string;\n  /** How many pages place this component, when the library can say. */\n  readonly usedOn?: number;\n  /**\n   * The variant this placement chose, by its stored key, with the label the\n   * definition gives it; `label` is absent when the definition no longer\n   * offers that variant. Absent when the placement chose none.\n   */\n  readonly variant?: { readonly key: string; readonly label?: string };\n  /**\n   * Whether the lookup holds a definition for this instance.\n   *\n   * `false` is a state the panel has to draw rather than an error: the\n   * canvas draws such an instance as could-not-be-loaded, and the panel says\n   * the same thing in words. The rows are empty when this is false, and\n   * empty when the definition exposes nothing — the flag is what tells the\n   * two apart.\n   */\n  readonly definitionFound: boolean;\n  /** In the definition's own declared order, which is the order it designed. */\n  readonly rows: readonly ExposedRow[];\n  /** Overrides this instance holds for properties no longer exposed. */\n  readonly orphaned: readonly OrphanedOverride[];\n}\n\n/**\n * Describe the selected instance for editing, or `null` when the selection is\n * not an instance — no selection, an id the document no longer holds, or an\n * ordinary block, which the block inspector answers for.\n *\n * `definitions` is the lookup the CANVAS resolves against, handed in rather\n * than fetched, so a row's value is read from the same document the page is\n * drawn from. `components` is the library's list, which is the only holder of\n * a definition's title and usage; the document itself carries neither.\n */\nexport function inspectInstance(\n  document: BlockDocument,\n  selectedId: string | null,\n  definitions: ComponentLookup,\n  components: readonly SavedComponent[],\n  /**\n   * The editor's lock source and composed page, for the rows a `contentOnly`\n   * lock holds. Absent, no row is held by one.\n   */\n  view?: LockView\n): InstanceInspection | null {\n  if (selectedId === null) return null;\n  const node = findNode(document.nodes, selectedId);\n  if (node === undefined || !isComponentInstance(node)) return null;\n\n  const componentId = storedComponentId(node);\n  const row = components.find(component => component.id === componentId);\n  // Read under the resolver's OWN rule for a supplied definition, not the\n  // kind alone: what the canvas leaves standing as a placeholder — a format\n  // this build does not read, a list of nodes that is not one — must draw no\n  // editable row here, and must not be handed to the exposure to throw on.\n  const definition = readableDefinition(definitions.get(componentId));\n  const found = definition !== undefined;\n  const exposure = found ? instanceExposure(definition, node) : undefined;\n  const variant = variantOf(node, definition);\n  const label = row?.title ?? componentId;\n  const held = heldRows(node.id, view, label);\n\n  return {\n    nodeId: node.id,\n    componentId,\n    identity: { name: node.name ?? \"\", locked: node.locked === true },\n    label,\n    ...(row?.usedOn === undefined ? {} : { usedOn: row.usedOn }),\n    ...(variant === undefined ? {} : { variant }),\n    definitionFound: found,\n    rows:\n      exposure === undefined\n        ? []\n        : rowsOf(exposure.properties, node, definition, definitions).map(\n            entry => {\n              const reason = held(entry);\n              return reason === undefined\n                ? entry\n                : { ...entry, heldBy: reason };\n            }\n          ),\n    orphaned:\n      exposure === undefined\n        ? []\n        : orphanedOf(exposure.orphanedOverrideIds, node),\n  };\n}\n\n/**\n * The component a placement places, or `undefined` for a node that is not a\n * placement or names no component: what \"Edit component\" opens.\n */\nexport function placedComponentId(\n  document: BlockDocument,\n  nodeId: string\n): string | undefined {\n  const node = findNode(document.nodes, nodeId);\n  if (node === undefined || !isComponentInstance(node)) return undefined;\n  const id = storedComponentId(node);\n  return id === \"\" ? undefined : id;\n}\n\n/**\n * What an author is told after double-clicking text a component does not\n * expose: whose it is, with the variant the placement uses, and where its\n * editable fields are. The placement is selected, so the panel beside it is\n * the one this points to.\n */\nexport function partOfComponentSentence(\n  inspection: Pick<InstanceInspection, \"label\" | \"variant\" | \"rows\">,\n  /**\n   * The exposure feeding the text, when a lock the component sets holds it:\n   * the sentence is then that row's reason, the one the panel shows.\n   */\n  heldExposureId?: string\n): string {\n  const held =\n    heldExposureId === undefined\n      ? undefined\n      : inspection.rows.find(row => row.id === heldExposureId)?.heldBy;\n  if (held !== undefined) return refusalAnnouncement(held);\n  const variant =\n    inspection.variant?.label === undefined\n      ? \"\"\n      : `, ${inspection.variant.label} variant`;\n  const where =\n    inspection.rows.length === 0\n      ? \"Its content is edited on the component itself.\"\n      : \"Its fields are in the panel; the rest is edited on the component itself.\";\n  return `Part of ${inspection.label}${variant}. ${where}`;\n}\n\n/**\n * The variant the placement chose, with the definition's label for it.\n *\n * Read off the definition's own record by the stored key, own keys only, as\n * the resolver reads it: a key the definition no longer offers is still the\n * placement's choice, and the panel says it is gone rather than hiding it.\n */\nfunction variantOf(\n  node: BlockNode,\n  definition: ComponentDocument | undefined\n): InstanceInspection[\"variant\"] {\n  const key = instanceProps(node).variant;\n  if (typeof key !== \"string\" || key === \"\") return undefined;\n  const variants: unknown = definition?.variants;\n  const chosen =\n    typeof variants === \"object\" &&\n    variants !== null &&\n    Object.hasOwn(variants, key)\n      ? (variants as Record<string, unknown>)[key]\n      : undefined;\n  const label =\n    typeof chosen === \"object\" && chosen !== null\n      ? (chosen as { label?: unknown }).label\n      : undefined;\n  return typeof label === \"string\" && label.trim() !== \"\"\n    ? { key, label }\n    : chosen === undefined\n      ? { key }\n      : { key, label: key };\n}\n\n/**\n * Which rows of this placement are held, and why: a value landing on a block\n * the component locks in Layers, or one that is not content inside an area\n * locked to its content (`composedHolds`, the judgement the canvas's inline\n * text asks too).\n *\n * Asked of the COMPOSED page, where the placement's values land inside its\n * component's nodes: the resolver's exposure map names the node and prop each\n * exposure drives there. A visibility row is mapped to the node it shows or\n * hides, and showing a node is its design, never its content; a node it\n * currently hides is not composed, so its row is not held.\n */\nfunction heldRows(\n  placementId: string,\n  view: LockView | undefined,\n  componentName: string\n): (row: ExposedRow) => RefusalWording | undefined {\n  const composed = view?.composed;\n  if (composed === undefined) return () => undefined;\n  const holds = composedHolds(composed, lockSourceOf(view));\n  const targets = new Map<string, { node: ResolvedBlockNode; path: string }>();\n  for (const composedNode of composedNodesOf(composed.nodes, placementId)) {\n    const fed = composedNode.exposedProps;\n    if (fed === undefined) continue;\n    for (const path of Object.keys(fed)) {\n      const id = fed[path]?.id;\n      if (typeof id === \"string\") targets.set(id, { node: composedNode, path });\n    }\n  }\n  return row => {\n    const target = targets.get(row.id);\n    if (target === undefined) return undefined;\n    const prop = target.path.split(\".\")[0] ?? target.path;\n    const hold = holds(target.node, prop, row.type === \"visibility\");\n    return hold === undefined\n      ? undefined\n      : composedHoldWording(hold, componentName, target.node.type);\n  };\n}\n\n/** The composed nodes a placement contributed, in document order. */\nfunction composedNodesOf(\n  nodes: readonly ResolvedBlockNode[],\n  placementId: string\n): ResolvedBlockNode[] {\n  const found: ResolvedBlockNode[] = [];\n  const queue = [...nodes];\n  for (let head = 0; head < queue.length; head += 1) {\n    const entry = queue[head];\n    if (typeof entry !== \"object\" || entry === null) continue;\n    if (entry.instanceOf === placementId) found.push(entry);\n    const slots: unknown = entry.slots;\n    if (typeof slots !== \"object\" || slots === null) continue;\n    for (const children of Object.values(slots as Record<string, unknown>)) {\n      if (Array.isArray(children))\n        queue.push(...(children as ResolvedBlockNode[]));\n    }\n  }\n  return found;\n}\n\n/**\n * The setting types a placement may bind to data: those whose value a field\n * can be, text, an address and a picture. A choice is a design decision, and\n * whether a block is shown is decided by its conditions.\n */\nconst BINDABLE_SETTING_TYPES: ReadonlySet<string> = new Set([\n  \"text\",\n  \"link\",\n  \"image\",\n]);\n\n/** An exposed property, as the resolver's rows carry it. */\ntype Exposure = ReturnType<\n  typeof instanceExposure\n>[\"properties\"][number][\"property\"];\n\n/** The composed block and prop a setting feeds, as composing maps it. */\ninterface ComposedTarget {\n  readonly type: string;\n  readonly path: string;\n}\n\n/**\n * Each setting's target in the placement as composing it maps them: the\n * block of the component, or of a component inside it, and the prop the\n * setting feeds, with the variant and the values in force applied and a\n * bound setting taking the prop it fills. The resolver's own map, which the\n * canvas edits a value through, so the panel offers a binding of the prop\n * the page shows.\n */\nfunction composedTargets(\n  node: BlockNode,\n  definitions: ComponentLookup\n): ReadonlyMap<string, ComposedTarget> {\n  const composed = resolveComponentInstances(\n    { formatVersion: DOCUMENT_FORMAT_VERSION, kind: \"page\", nodes: [node] },\n    definitions,\n    { exposures: true }\n  ).document;\n  const targets = new Map<string, ComposedTarget>();\n  for (const part of composedNodesOf(composed.nodes, node.id)) {\n    for (const [path, fed] of Object.entries(part.exposedProps ?? {})) {\n      if (path !== \"visibility\") targets.set(fed.id, { type: part.type, path });\n    }\n  }\n  return targets;\n}\n\n/** How many components inside components a declared target is followed through. */\nconst MAX_DECLARED_NESTING = 8;\n\n/**\n * A setting's target as the components declare it, for one composing maps\n * to nothing here: a block hidden by a setting or a variant, or one inside a\n * component inside the component, followed through each nested placement's\n * own setting to the block prop it fills. A binding the placement holds\n * keeps its controls.\n */\nfunction ownTarget(\n  definition: ComponentDocument | undefined,\n  property: Exposure,\n  definitions: ComponentLookup\n): ComposedTarget | undefined {\n  let from = definition;\n  let setting: Exposure | undefined = property;\n  for (let hop = 0; hop <= MAX_DECLARED_NESTING; hop += 1) {\n    if (from === undefined || setting === undefined) return undefined;\n    const node = findNode(from.nodes, setting.nodeId);\n    if (node === undefined) return undefined;\n    if (!isComponentInstance(node)) {\n      return { type: node.type, path: setting.propPath };\n    }\n    const id = boundSettingId(setting.propPath);\n    from = readableDefinition(definitions.get(storedComponentId(node)));\n    setting =\n      id === undefined || from === undefined\n        ? undefined\n        : instanceExposure(from, node).properties.find(\n            state => state.property.id === id\n          )?.property;\n  }\n  return undefined;\n}\n\n/**\n * The schema of the composed block's prop a setting fills, named as the\n * setting, where a field can fill it: read from the block's own declaration,\n * the prop the composed binding lands on.\n */\nfunction bindableSchemaOf(\n  property: Exposure,\n  targets: ReadonlyMap<string, ComposedTarget>,\n  definition: ComponentDocument | undefined,\n  definitions: ComponentLookup\n): PropSchema | undefined {\n  if (!BINDABLE_SETTING_TYPES.has(property.type)) return undefined;\n  const target =\n    targets.get(property.id) ?? ownTarget(definition, property, definitions);\n  const schema = target === undefined ? undefined : declaredSchemaOf(target);\n  if (schema === undefined || bindablePropKind(schema) === undefined) {\n    return undefined;\n  }\n  return { ...schema, label: labelOf(property) };\n}\n\n/** The schema the target's block declares for its prop, if it declares one. */\nfunction declaredSchemaOf(target: ComposedTarget): PropSchema | undefined {\n  const declared = getBlock(target.type)?.props;\n  if (declared === undefined || !Object.hasOwn(declared, target.path)) {\n    return undefined;\n  }\n  return declared[target.path];\n}\n\n/**\n * The placement's stored binding of one setting, where composing applies it:\n * a record, and a list item binding only where it names its list.\n */\nfunction storedBindingOf(node: BlockNode, id: string): Binding | undefined {\n  const bindings = node.bindings;\n  if (!isPlainRecord(bindings)) return undefined;\n  const key = settingBindingKey(id);\n  const binding = Object.hasOwn(bindings, key) ? bindings[key] : undefined;\n  return isPlainRecord(binding) && keepsItsListWhenMoved(binding)\n    ? binding\n    : undefined;\n}\n\n/** The resolver's rows, as the panel draws them. */\nfunction rowsOf(\n  properties: ReturnType<typeof instanceExposure>[\"properties\"],\n  node: BlockNode,\n  definition: ComponentDocument | undefined,\n  definitions: ComponentLookup\n): ExposedRow[] {\n  const labels = new Map(\n    properties.map(\n      state => [state.property.id, labelOf(state.property)] as const\n    )\n  );\n  // Read off the node's own record rather than the resolver's source, which\n  // is the target's and is shared by every exposure aimed at it.\n  const stored = storedOverrides(node);\n  const targets = composedTargets(node, definitions);\n  const rows = properties.map(state => ({\n    id: state.property.id,\n    label: labelOf(state.property),\n    type: state.property.type,\n    value: state.value,\n    source: state.source,\n    cleared: state.cleared,\n    ownOverride: Object.hasOwn(stored, state.property.id),\n    supported: (EDITABLE_EXPOSED_TYPES as readonly string[]).includes(\n      state.property.type\n    ),\n    options: optionsOf(state.property.options),\n    ...bindingOf(state.property, node, { targets, definition, definitions }),\n    ...(state.shadowedBy === undefined\n      ? {}\n      : {\n          shadowedBy: {\n            id: state.shadowedBy,\n            label: labels.get(state.shadowedBy) ?? state.shadowedBy,\n          },\n        }),\n  }));\n  return rows;\n}\n\n/** A row's binding fields: its bindable schema and stored binding, if any. */\nfunction bindingOf(\n  property: Exposure,\n  node: BlockNode,\n  from: {\n    readonly targets: ReadonlyMap<string, ComposedTarget>;\n    readonly definition: ComponentDocument | undefined;\n    readonly definitions: ComponentLookup;\n  }\n): Pick<ExposedRow, \"bindable\" | \"binding\"> {\n  const bindable = bindableSchemaOf(\n    property,\n    from.targets,\n    from.definition,\n    from.definitions\n  );\n  if (bindable === undefined) return {};\n  const binding = storedBindingOf(node, property.id);\n  return binding === undefined ? { bindable } : { bindable, binding };\n}\n\n/**\n * What to call an exposed property: its label, or its id when the stored\n * label is not a string.\n *\n * The resolver checks the fields its own writer reads — id, node, path and\n * type — so a label reaches here as the stored or hook-shaped definition left\n * it, and one that is an object would be handed to the panel to draw as text.\n * The id is the one name the property is sure to have.\n */\nfunction labelOf(property: { id: string; label?: unknown }): string {\n  const label: unknown = property.label;\n  return typeof label === \"string\" && label !== \"\" ? label : property.id;\n}\n\n/**\n * The choices a select exposure offers, as a control can draw them.\n *\n * Normalised here, where they are consumed, for the reason {@link labelOf}\n * gives: a value that is not a list offers nothing, an entry without a string\n * value and a string label is left out, and a value offered twice is offered\n * once — the control keys its items by value, and two items with one value\n * are one choice drawn twice.\n */\nfunction optionsOf(options: unknown): ExposedRow[\"options\"] {\n  if (!Array.isArray(options)) return [];\n  const seen = new Set<string>();\n  const usable: { value: string; label: string }[] = [];\n  for (const entry of options as unknown[]) {\n    if (typeof entry !== \"object\" || entry === null) continue;\n    const { value, label } = entry as { value?: unknown; label?: unknown };\n    if (typeof value !== \"string\" || typeof label !== \"string\") continue;\n    if (seen.has(value)) continue;\n    seen.add(value);\n    usable.push({ value, label });\n  }\n  return usable;\n}\n\n/**\n * The orphaned overrides THIS INSTANCE holds.\n *\n * The resolver reports every orphaned id it applied, and it applies a\n * variant's overrides as well as the instance's own — but only the instance's\n * are this author's to discard, and only those are stored on this node. A\n * variant that carries a value for a property the definition dropped is the\n * definition's own concern.\n */\nfunction orphanedOf(\n  ids: readonly string[],\n  node: BlockNode\n): OrphanedOverride[] {\n  const stored = storedOverrides(node);\n  return ids.flatMap(id =>\n    Object.hasOwn(stored, id) ? [{ id, value: stored[id] }] : []\n  );\n}\n\n/**\n * The override record the node stores, or an empty one.\n *\n * Read defensively for the reason {@link storedComponentId} is, and through\n * an own-property view: the ids are exposed-property ids from a stored\n * definition, and a record read by plain property access answers\n * `constructor` with a function for a key it never had.\n */\nfunction storedOverrides(node: BlockNode): Record<string, OverrideValue> {\n  const overrides = instanceProps(node).overrides;\n  if (typeof overrides !== \"object\" || overrides === null) return {};\n  if (Array.isArray(overrides)) return {};\n  return overrides as Record<string, OverrideValue>;\n}\n\n/**\n * The patch that replaces the instance's override record.\n *\n * **The whole props object, not the one key**, for the reason `propPatch`\n * states: `updateNode` merges at the top level, so a patch carrying only\n * `{ props: { overrides } }` would drop `componentId` and the node would name\n * no component at all. And the KEY IS OMITTED when nothing remains: the\n * record is optional, so absent is what \"no overrides\" already means\n * everywhere else, and a stored empty record would be a second spelling of\n * the same state that every reader would have to know about.\n */\nexport function overridesPatch(\n  node: BlockNode,\n  overrides: Readonly<Record<string, OverrideValue>>\n): NodePatch {\n  const { overrides: _stored, ...rest } = instanceProps(node);\n  return {\n    props: Object.keys(overrides).length === 0 ? rest : { ...rest, overrides },\n  };\n}\n\n/**\n * The op that sets one override — a value, or the `$unset` sentinel to clear\n * the property rather than inherit it.\n *\n * Read from the node at call time rather than from a row: a control committing\n * on blur can fire after another edit replaced the node, and a record rebuilt\n * from an older copy would resurrect overrides that edit removed.\n */\nexport function setOverrideOp(\n  node: BlockNode,\n  id: string,\n  value: OverrideValue\n): BuilderOp {\n  return {\n    kind: \"update\",\n    id: node.id,\n    patch: overridesPatch(node, { ...storedOverrides(node), [id]: value }),\n  };\n}\n\n/**\n * An edit of a placement's bindings with each list item binding naming the\n * list it reads: the nearest list around the placement where it names none.\n * Composing moves a placement's binding onto the component's block, which\n * may sit in a list of the component's own, so a binding naming no list\n * would read that list there; the save refuses one, and composing skips it.\n * Any other op is handed back as it is.\n */\nexport function withPlacementLists(\n  document: BlockDocument,\n  op: BuilderOp\n): BuilderOp {\n  if (op.kind !== \"update\" || !isPlainRecord(op.patch.bindings)) return op;\n  const node = findNode(document.nodes, op.id);\n  if (node === undefined || !isComponentInstance(node)) return op;\n  const nearest = outerListOf(document.nodes, op.id)?.id;\n  if (nearest === undefined) return op;\n  const bindings = Object.fromEntries(\n    // A stored binding is copied into the edit as it was, which a save has\n    // not judged, so each is read as a record first.\n    Object.entries(op.patch.bindings).map(\n      ([key, binding]): [string, Binding] => {\n        const stored: unknown = binding;\n        return [\n          key,\n          isPlainRecord(stored) &&\n          binding.source === \"item\" &&\n          binding.list === undefined\n            ? { ...binding, list: nearest }\n            : binding,\n        ];\n      }\n    )\n  );\n  return { ...op, patch: { ...op.patch, bindings } };\n}\n\n/**\n * The op that removes one override, so the property inherits again.\n *\n * Removal rather than writing the definition's value back: an override equal\n * to the definition's value is still an override, and would go on shadowing\n * the definition the next time somebody edits the component.\n */\nexport function resetOverrideOp(node: BlockNode, id: string): BuilderOp {\n  const { [id]: _removed, ...kept } = storedOverrides(node);\n  return { kind: \"update\", id: node.id, patch: overridesPatch(node, kept) };\n}\n","/**\n * Duplicating a block: the copy, and where it goes.\n *\n * The most-reached-for verb in a page builder after inserting one. An author\n * builds a card the way they want it and then wants three of them, and without\n * this the only route is to insert a fresh block and redo every property by\n * hand — which is also how the second card ends up subtly different from the\n * first.\n *\n * ## The copy is made by the ENGINE, not here\n *\n * `reidSubtree` mints a fresh id for the node and for everything inside it.\n * That is not a detail: ids are the only thing this editor addresses by, so a\n * copy that kept them would give one id two nodes, and every op afterwards\n * would reach whichever the walk found first — an edit to the copy landing on\n * the original, silently.\n *\n * It also drops `cssId` and any `attributes.id`, because those become DOM ids\n * and two elements carrying one id is invalid HTML that breaks every\n * `getElementById` and every in-page anchor. Both rules belong to what a COPY\n * is rather than to what this command does, and restating either here would be\n * a second opinion about the same question.\n *\n * ## What this decides, because the engine deliberately does not\n *\n * **Where it goes** — immediately after the original, in the same parent and\n * slot. An author duplicating a card is building a row of them, and a copy\n * appended to the end of the page is one they then have to go and find.\n *\n * **What it is called.** A name the author typed is theirs, and two rows\n * reading \"Hero title\" in the layers panel is exactly the confusion naming\n * exists to remove — so a named block's copy is suffixed. An UNNAMED block's\n * copy stays unnamed: it shows its block's label, two rows reading \"Heading\"\n * are what an author expects from two headings, and inventing \"Heading copy\"\n * would put a name on a block whose author never gave it one.\n *\n * **The lock travels.** `locked` is copied because it is part of the block\n * being duplicated, and a copy that quietly differed from its original in one\n * field would be a worse surprise than one that matches. The copy is announced,\n * and the layers panel shows the badge, so the author is not left wondering why\n * the new block will not move.\n *\n * @module duplicate-block\n */\n\nimport {\n  findNode,\n  holdsEntryContent,\n  locateNode,\n  reidSubtree,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { positionOf, type OpPosition } from \"../op-vocabulary\";\nimport { layerLabel } from \"../panels/layers/layers\";\n\n/** The suffix that keeps two copies of a named block apart. */\nexport const COPY_SUFFIX = \" copy\";\n\n/** A duplication, ready to apply. */\nexport interface BlockDuplication {\n  /** The re-id'd copy, with its name adjusted. */\n  readonly node: BlockNode;\n  /** Immediately after the original, in the same parent and slot. */\n  readonly at: OpPosition;\n  /** What to call the block in an announcement. */\n  readonly label: string;\n}\n\n/**\n * The copy's name.\n *\n * Suffixed only when the author gave one. Repeated duplication produces \"Hero\n * title copy copy\" rather than counting, which is honest about what happened\n * and needs no scan of the document to find the highest number — a count would\n * have to decide what to do about a name the author had since edited, and there\n * is no answer to that which is not a guess.\n */\nfunction copyName(node: BlockNode): string | undefined {\n  const named = node.name?.trim();\n  if (named === undefined || named === \"\") return undefined;\n  return `${named}${COPY_SUFFIX}`;\n}\n\n/**\n * What duplicating the selected block would do, or `null` when it cannot.\n *\n * `null` for no selection and for an id the document no longer holds — which an\n * undo produces routinely — for a block holding an Entry content block, which\n * a template holds one of, and for a node whose parent has no named slot,\n * because that is a position the op vocabulary cannot express and therefore one\n * an insert could not be undone from.\n */\nexport function blockDuplication(\n  document: BlockDocument,\n  selectedId: string | null\n): BlockDuplication | null {\n  if (selectedId === null) return null;\n\n  const original = findNode(document.nodes, selectedId);\n  if (original === undefined) return null;\n  // A template holds one Entry content block, so a copy of one, or of a\n  // block around one, is refused as the save would refuse it.\n  if (holdsEntryContent(original)) return null;\n\n  const location = locateNode(document.nodes, selectedId);\n  if (location === undefined) return null;\n\n  let at: OpPosition;\n  try {\n    const here = positionOf(location);\n    at = { ...here, index: here.index + 1 };\n  } catch {\n    // `positionOf` refuses a parent with no named slot. That refusal is about\n    // the selected node's surroundings rather than anything the author did, so\n    // it is reported as \"no answer\" rather than raised at them — the same\n    // reading the inserter gives it.\n    return null;\n  }\n\n  const copy = reidSubtree(original);\n  const name = copyName(original);\n  return {\n    node: name === undefined ? copy : { ...copy, name },\n    at,\n    label: layerLabel(original),\n  };\n}\n","/**\n * Deleting the selected block: what it takes with it, and where the author is\n * left.\n *\n * Pure, and separate from the keys that ask for it, for the reason every other\n * rule in this package is: none of it needs React, and all of it is worth\n * asserting. A component test in jsdom cannot tell a correct\n * where-does-selection-go answer from a plausible wrong one, because both\n * render a canvas with one fewer block.\n *\n * **Selection is the whole difficulty.** Removing a node is one op; deciding\n * what an author is looking at afterwards is a judgement, and getting it wrong\n * is felt hardest by the keyboard-only author this axis exists for. Clearing\n * the selection is safe and costs them their place — they must find the canvas\n * again and re-select before they can do anything else, after an action they\n * took deliberately.\n *\n * @module delete-block\n */\n\nimport {\n  countNodes,\n  ForestTooLargeError,\n  locateNode,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { SlotAddress } from \"../op-vocabulary\";\n\n/** A deletion, with everything a caller needs to describe and apply it. */\nexport interface BlockDeletion {\n  /** The node to remove. */\n  readonly id: string;\n  /** The block type, for naming what was removed. */\n  readonly type: string;\n  /**\n   * The slot the block is vacating, when removing it may empty one.\n   *\n   * A request rather than a command: the store drops the slot only if it is\n   * actually empty afterwards. Without it, deleting the last child of a\n   * container leaves an empty slot the page-builder validator rejects.\n   */\n  readonly dropSlotIfEmpty?: SlotAddress;\n  /**\n   * What to select once the block is gone.\n   *\n   * Carried with the deletion rather than recomputed after applying it. Once the\n   * node is removed there is nothing left to derive a neighbour FROM, so a\n   * caller asking afterwards would be asking a document that no longer contains\n   * the subject.\n   */\n  readonly nextSelection: string | null;\n  /**\n   * How many blocks go with it, not counting the block itself.\n   *\n   * A container takes its children, and that is not visible from the block an\n   * author has selected — a collapsed section looks exactly like an empty one.\n   * Carried so the deletion can be STATED rather than gated behind a\n   * confirmation: undo covers it, and a prompt on every delete is friction\n   * people learn to click through without reading.\n   */\n  readonly descendantCount: number;\n}\n\n/**\n * Where the author is left after a block is removed.\n *\n * **Next sibling first, and the case that decides it is REPEATED deletion** —\n * which is what clearing a section actually is. From `[a, b, c]` with `b`\n * selected: choosing the previous sibling selects `a`, so a second press\n * destroys a block the author already passed and approved. Choosing the next\n * selects `c`, so a second press continues forward through what they were\n * heading toward. One gesture eats work behind you; the other does not.\n *\n * Gutenberg selects the previous block, for a reason that does not transfer:\n * its Backspace is a text-merge — you delete at the START of a block and carry\n * on typing in the one before it, so the caret must travel backward. A canvas\n * with an explicit delete key is list management rather than text editing, and\n * every list-deletion surface people already use — file managers, mail\n * clients, task lists — moves forward.\n *\n * Then the previous sibling, when the block was last. Then the parent, when it\n * was an only child: the container is where the author was working, and one\n * more press deletes it, which is a coherent next action rather than a dead\n * end.\n *\n * `null` only at the top level with nothing left, which is the one case with\n * genuinely nowhere to be.\n */\nfunction selectionAfter(\n  siblings: readonly BlockNode[],\n  index: number,\n  parent: BlockNode | undefined\n): string | null {\n  const next = siblings[index + 1];\n  if (next !== undefined) return next.id;\n  const previous = siblings[index - 1];\n  if (previous !== undefined) return previous.id;\n  return parent?.id ?? null;\n}\n\n/** The list a located node actually sits in, or undefined when it has none. */\nfunction siblingsOf(\n  nodes: BlockNode[],\n  parent: BlockNode | undefined,\n  slot: string | undefined\n): BlockNode[] | undefined {\n  if (parent === undefined) return nodes;\n  if (slot === undefined) return undefined;\n  return parent.slots?.[slot];\n}\n\n/**\n * How many descendants a subtree has, or zero when it cannot be counted.\n *\n * The engine refuses to count a forest whose entries outrun its machine bound\n * rather than answering from a partial walk. That refusal belongs to the engine\n * and is right there; here it must not become an exception, because this\n * function's answer decides whether the editor OFFERS a deletion at all.\n */\nfunction countableDescendants(node: BlockNode): number {\n  try {\n    return countNodes([node]) - 1;\n  } catch (error) {\n    if (error instanceof ForestTooLargeError) return 0;\n    throw error;\n  }\n}\n\n/**\n * Describe deleting the selected block, or `null` when there is nothing to\n * delete.\n *\n * `null` for an absent selection and for an id the document no longer holds —\n * a stale id after an undo, or a selection made against a document that has\n * since been replaced. Both mean the same thing to a caller: there is no\n * deletion to perform, so nothing should be applied or announced.\n *\n * **A returned deletion is not permission.** Validity and locking belong to the\n * store, so a caller must handle a refusal rather than assume this will apply.\n */\nexport function blockDeletion(\n  document: BlockDocument,\n  selectedId: string | null\n): BlockDeletion | null {\n  if (selectedId === null) return null;\n\n  const here = locateNode(document.nodes, selectedId);\n  if (here === undefined) return null;\n\n  const siblings = siblingsOf(document.nodes, here.parent, here.slot);\n  if (siblings === undefined) return null;\n\n  const node = siblings[here.index];\n  if (node === undefined) return null;\n\n  // The subtree's own size, less the node itself. `countNodes` walks slots, so\n  // this is every descendant at any depth rather than the immediate children —\n  // which is what actually disappears.\n  //\n  // A subtree too large to count must not stop the DELETION being offered.\n  // `blockDeletion` is called to decide whether the toolbar's Delete button is\n  // enabled, so letting the refusal escape would throw out of toolbar\n  // construction and take the editor down at the moment a node is selected —\n  // and the count is descriptive, while being able to remove the node is not.\n  //\n  // Zero is the fallback, and it is deliberately the same value a node with no\n  // descendants gets. Normally folding \"unknown\" into a real value is how a\n  // third state disappears, but the only reader is the announcement, which says\n  // \"<name> deleted\" at zero and adds \"with N blocks inside\" above it — so zero\n  // states nothing about the contents rather than claiming there were none.\n  const descendantCount = countableDescendants(node);\n\n  const dropSlotIfEmpty =\n    here.parent !== undefined && here.slot !== undefined\n      ? { parentId: here.parent.id, slot: here.slot }\n      : undefined;\n\n  return {\n    id: selectedId,\n    type: node.type,\n    ...(dropSlotIfEmpty === undefined ? {} : { dropSlotIfEmpty }),\n    nextSelection: selectionAfter(siblings, here.index, here.parent),\n    descendantCount,\n  };\n}\n","/**\n * Where a block goes when the author moves it with the keyboard.\n *\n * Dragging is the only way to reorder a block today, which means the editor is\n * unusable by anyone who does not use a pointer — a keyboard user, a switch\n * user, anyone driving the page through a screen reader. That is an\n * accessibility gap rather than a missing convenience, and it is not closed by\n * making the drag easier.\n *\n * **Two axes, not one.** Order and depth are separate questions, and each key\n * answers exactly one of them:\n *\n * - `up` / `down` — reorder among siblings. Never changes the parent.\n * - `indent` / `outdent` — change the parent. Never reorders among the blocks\n *   that stay put.\n *\n * @remarks\n * **Why this is two axes rather than one key that does both.** The tempting\n * design is a single up/down that reorders in the middle of a container and\n * steps OUT at its ends, so one key does everything. It was built that way\n * first, and its round-trip test refuted it: a block that steps out of a\n * container on `down` does not step back in on `up`, because passing a container\n * and entering it are different intents and one key cannot mean both. Every\n * press being undone by the opposite press is not a nicety here — it is what\n * lets someone driving the editor without sight of the result recover from a\n * mistaken key. A gesture with no inverse costs exactly the people this exists\n * for.\n *\n * Split across two axes, each operation has an inverse in its own axis:\n * `up` undoes `down`, and `outdent` undoes `indent`, including the nesting.\n *\n * **One asymmetry, stated because it is real and not a defect to fix here.**\n * `indent` appends to the end of the container above, so it cannot know where in\n * that container a previously-outdented block came from. Outdenting a block that\n * was NOT its container's last child therefore loses its position within the\n * slot, and a single `indent` returns it at the end. Recovering the original\n * index would mean carrying state across presses, which a pure position function\n * cannot do and which would make each key's effect depend on invisible history.\n * Every outliner behaves this way. It is pinned by a test rather than left to be\n * met in a bug report.\n *\n * **This is the outliner convention** — arrows reorder, Tab and Shift-Tab\n * change depth — which is worth following because it is what an author who has\n * used any nested-list editor already expects, and because it is the arrangement\n * that makes both axes total: every position is reachable, and every move is\n * reversible.\n *\n * **This module answers WHERE, never WHETHER.** Locking, validity and cycles are\n * enforced by the op store, which already owns them; asking here would be a\n * second implementation of a question that has one. The consequence is real and\n * repeated in {@link keyboardMovePosition}: a position returned here can still\n * be refused, so the wiring must handle a refusal rather than assume a non-null\n * result will apply.\n *\n * **Which KEYS produce these directions is not decided here.** This module names\n * intents; the binding is the wiring's, and belongs with whatever shortcut\n * resolver the editor already has rather than in a second listener.\n *\n * Pure and dependency-light: a forest, an id and a direction in, a position out.\n * No DOM, no React, no event handling.\n *\n * @module keyboard-move\n */\nimport {\n  COMPONENT_INSTANCE_TYPE,\n  DEFAULT_SLOT,\n  getBlock,\n  locateNode,\n  readableDefinition,\n  type BlockNode,\n  type ComponentLookup,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { OpPosition, SlotAddress } from \"../op-vocabulary\";\n\n/**\n * What the author asked for.\n *\n * `indent` makes the block the last child of the sibling above it; `outdent`\n * makes it the next sibling of its parent. Those two are inverses, which is the\n * property the whole design rests on.\n */\nexport type MoveDirection = \"up\" | \"down\" | \"indent\" | \"outdent\";\n\n/**\n * What a move does, beyond where it lands.\n *\n * A bare position cannot say whether the block stayed among its siblings or\n * changed parent, and the difference is the whole thing a keyboard author cannot\n * see. Someone driving the editor through a screen reader needs \"moved down\" and\n * \"moved into Group\" announced differently, and the focus draw needs to know the\n * block left its container. Deriving it in the wiring by comparing parents\n * before and after would be a second implementation of a decision this function\n * has already made.\n */\nexport type MoveEffect = \"reorder\" | \"indent\" | \"outdent\";\n\n/** Where a block goes, what that does, and what it leaves behind. */\nexport interface KeyboardMove {\n  /** The position, in the shape the op store's `move` consumes. */\n  readonly to: OpPosition;\n  readonly effect: MoveEffect;\n  /**\n   * The slot the block is leaving, when leaving it may empty it.\n   *\n   * Supplied for the depth axis only, because `up` and `down` land the block in\n   * the container it started in and vacate nothing. Without it, moving the last\n   * child out of a container leaves an empty slot the page-builder validator\n   * rejects — and a keyboard author meets that far sooner than a pointer one,\n   * because they move a single block at a time.\n   *\n   * A request rather than a command: the store drops the slot only if it is\n   * actually empty afterwards, so a slot something else has filled stays.\n   */\n  readonly dropSlotIfEmpty?: SlotAddress;\n}\n\n/** The slot a node is vacating, when it sits in one. */\nfunction vacating(\n  parent: BlockNode | undefined,\n  slot: string | undefined\n): SlotAddress | undefined {\n  if (parent === undefined || slot === undefined) return undefined;\n  return { parentId: parent.id, slot };\n}\n\n/**\n * The list a located node actually sits in.\n *\n * Derived from the location rather than re-walked: `locateNode` already decided\n * which container holds the node, and a second walk that disagreed with it would\n * produce an index into a list the node is not in.\n */\nfunction siblingsOf(\n  nodes: BlockNode[],\n  parent: BlockNode | undefined,\n  slot: string | undefined\n): BlockNode[] | undefined {\n  if (parent === undefined) return nodes;\n  if (slot === undefined) return undefined;\n  return parent.slots?.[slot];\n}\n\n/** A position addressing a container, or `null` when it cannot be addressed. */\nfunction positionIn(\n  parent: BlockNode | undefined,\n  slot: string | undefined,\n  index: number\n): OpPosition | null {\n  if (parent === undefined) return { index };\n  // A slot position must name its slot. The engine's `moveNode` silently\n  // declines one that does not, so returning it would read as a key that does\n  // nothing rather than as the malformed request it is.\n  if (slot === undefined) return null;\n  return { parentId: parent.id, slot, index };\n}\n\n/**\n * The slots `container`'s definition declares, or `undefined` when there is no\n * definition to read.\n *\n * A component instance is not a registered block: what it renders is the\n * slots its COMPONENT exposes, read from the component's definition through\n * the lookup the canvas was given. Anything else is read from the block\n * registry. A lookup that raises is no answer rather than an error, the same\n * reading the engine gives it when placing an instance.\n */\nfunction declaredSlots(\n  container: BlockNode,\n  components: ComponentLookup | undefined\n): readonly string[] | undefined {\n  return container.type === COMPONENT_INSTANCE_TYPE\n    ? exposedSlots(container, components)\n    : registeredSlots(container.type);\n}\n\n/** The slots a registered block type declares, or `undefined` for none registered. */\nfunction registeredSlots(type: string): readonly string[] | undefined {\n  const definition = getBlock(type);\n  return definition === undefined\n    ? undefined\n    : Object.keys(definition.slots ?? {});\n}\n\n/** The slots an instance's component exposes, or `undefined` when unreadable. */\nfunction exposedSlots(\n  instance: BlockNode,\n  components: ComponentLookup | undefined\n): readonly string[] | undefined {\n  const componentId = (instance.props as Record<string, unknown> | undefined)\n    ?.componentId;\n  if (typeof componentId !== \"string\") return undefined;\n  try {\n    const definition = readableDefinition(components?.get(componentId));\n    return definition === undefined\n      ? undefined\n      : Object.keys(definition.slots ?? {});\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Whether `container` has anywhere to put a block: a slot its definition\n * declares, or, with no definition to read, a slot it already holds.\n *\n * Read from the same declaration {@link indentSlot} reads, so a surface that\n * offers nesting by this answer offers it exactly where an indent could name a\n * slot. A block that declares none — a heading, a button — holds no blocks,\n * which is what lets a drag stop offering \"inside\" for it rather than offering\n * a place the placement rule would only refuse.\n */\nexport function holdsBlocks(\n  container: BlockNode,\n  components: ComponentLookup | undefined\n): boolean {\n  const declared = declaredSlots(container, components);\n  return declared === undefined\n    ? Object.keys(container.slots ?? {}).length > 0\n    : declared.length > 0;\n}\n\n/**\n * The slot a block indented into `container` enters, or `null` when no single\n * slot can be named.\n *\n * Read from the container's DEFINITION, because a slot the definition does not\n * declare is one the container never renders: a block filed there is stored\n * and invisible, selected in the inspector and gone from the canvas.\n *\n * - One declared slot: that one, whatever it is called, so a plugin container\n *   or a component exposing `items` or `default` receives the block where it\n *   draws children.\n * - Several: the engine's default slot when it is among them, the region a\n *   keyboard author reaches without choosing between regions they cannot see;\n *   otherwise `null`.\n * - None declared: the engine's default slot. Whether the target may hold\n *   children is the nesting rules' question, not this one's, and they refuse\n *   the move for a block that cannot.\n * - No definition to read: the one slot the container already holds, when it\n *   holds exactly one, since that is a slot something renders; otherwise the\n *   engine's default slot.\n */\nexport function indentSlot(\n  container: BlockNode,\n  components: ComponentLookup | undefined\n): string | null {\n  const declared = declaredSlots(container, components);\n  if (declared === undefined) {\n    const held = Object.keys(container.slots ?? {});\n    return held.length === 1 ? (held[0] ?? DEFAULT_SLOT) : DEFAULT_SLOT;\n  }\n  if (declared.length === 1) return declared[0] ?? DEFAULT_SLOT;\n  if (declared.length === 0 || declared.includes(DEFAULT_SLOT)) {\n    return DEFAULT_SLOT;\n  }\n  return null;\n}\n\n/**\n * Where the selected block lands if the author moves it one step.\n *\n * @param nodes - the document's top-level blocks\n * @param selectedId - the block the author has selected\n * @param direction - which move they asked for\n * @param components - the component definitions the canvas draws, so an\n * indent into a component instance enters a slot its component exposes\n * @returns the position to move it to, or `null` when that move is not\n * available — the id is not in the document, the block is already at the end of\n * its container, there is no sibling above it to indent into, that sibling has\n * several slots and none is the default (see `indentSlot`), or it is already\n * at the top level and cannot outdent further.\n *\n * @remarks\n * **Indices are stated as the op store consumes them, which is AFTER the node\n * has been removed.** `moveNode` removes and then re-inserts, so a same-list\n * step down to `index + 1` is a move of one place rather than two: taking the\n * node out shifts every later sibling back by one, which exactly absorbs the\n * difference. Written against a store that inserted before removing, the same\n * arithmetic would skip a sibling going down and be correct going up — a defect\n * that appears in only one direction.\n *\n * The same removal is why `indent` targets the previous sibling's child count\n * unadjusted: the node leaves a DIFFERENT list from the one it arrives in, so\n * that list's length does not change under it.\n *\n * **A returned position is not permission.** Locking and validity belong to the\n * store, so a caller must handle a refusal rather than assume this will apply.\n */\nexport function keyboardMovePosition(\n  nodes: BlockNode[],\n  selectedId: string,\n  direction: MoveDirection,\n  components?: ComponentLookup\n): KeyboardMove | null {\n  const here = locateNode(nodes, selectedId);\n  if (here === undefined) return null;\n\n  const siblings = siblingsOf(nodes, here.parent, here.slot);\n  if (siblings === undefined) return null;\n\n  if (direction === \"up\" || direction === \"down\") {\n    const target = here.index + (direction === \"up\" ? -1 : 1);\n    // Refused at the ends rather than escaping the container. Escaping is the\n    // other axis, and doing it here is what cost the inverse.\n    if (target < 0 || target >= siblings.length) return null;\n    const to = positionIn(here.parent, here.slot, target);\n    // Reordering lands in the container it started in, so nothing is vacated.\n    return to === null ? null : { to, effect: \"reorder\" };\n  }\n\n  if (direction === \"outdent\") {\n    // Already at the top level: there is no parent to become a sibling of.\n    if (here.parent === undefined) return null;\n\n    const outer = locateNode(nodes, here.parent.id);\n    if (outer === undefined) return null;\n\n    // AFTER the parent, so that indenting back in returns the block to where it\n    // started. Removing it from inside the parent does not move the parent, so\n    // this index needs no correction.\n    const to = positionIn(outer.parent, outer.slot, outer.index + 1);\n    if (to === null) return null;\n    return {\n      to,\n      effect: \"outdent\",\n      dropSlotIfEmpty: vacating(here.parent, here.slot),\n    };\n  }\n\n  // Indent: become the last child of the sibling immediately above.\n  const above = siblings[here.index - 1];\n  // Nothing above, so there is nothing to indent into. The first block in a\n  // container has no parent-to-be that would not be itself.\n  if (above === undefined) return null;\n\n  const slot = indentSlot(above, components);\n  // A container with several regions and none of them the default: which one\n  // the author meant is not something a single key press can say, so the move\n  // is not offered rather than guessed.\n  if (slot === null) return null;\n  const into = above.slots?.[slot];\n  return {\n    to: {\n      parentId: above.id,\n      slot,\n      index: into?.length ?? 0,\n    },\n    effect: \"indent\",\n    dropSlotIfEmpty: vacating(here.parent, here.slot),\n  };\n}\n","/**\n * Delete, duplicate and lock, for a selection that may hold more than one block.\n *\n * Each verb is planned as a GROUP of ops that the store applies atomically, so\n * an edit across six blocks costs one undo and either happens completely or not\n * at all.\n *\n * ## Every rule is the single-block one, asked repeatedly\n *\n * `blockDeletion`, `blockDuplication` and `lockOp` already decide what removing\n * or copying ONE block means, including what a lock forbids and where a copy\n * goes. Nothing here re-decides any of that. A second implementation would\n * eventually disagree with the toolbar and the keyboard, which act on one block\n * through those same functions.\n *\n * ## Order is load-bearing, and differently for each verb\n *\n * **Duplicating runs in REVERSE document order.** Each copy is inserted\n * immediately after its original, and inserting shifts every later sibling\n * along — so planning `[a, b, c]` forwards computes b's position against a\n * document that a's copy has already changed, and the second copy lands in the\n * wrong place. Reversed, every insert happens after the positions still to be\n * used, and each one is correct when it applies.\n *\n * **Moving runs TOWARDS the edge it is heading for**: ascending for `up`,\n * descending for `down`. A move vacates the index it leaves, so the block\n * nearest the destination has to go first — planning `up` from the bottom of\n * the run would step a block into a place its neighbour has not left yet.\n * Taken in the right order, each move swaps a pair of adjacent positions that\n * no later move in the group addresses, so every target computed against the\n * original document is still correct when it applies.\n *\n * **Deleting does not care**, and that is worth stating so nobody \"fixes\" it:\n * a remove addresses a node by id, ids do not move, and the op layer derives\n * each inverse from the document it was applied to. Both orders round-trip.\n * Document order is used anyway, so a group is deterministic.\n *\n * @module selection-ops\n */\n\nimport {\n  insertKeepingLocks,\n  siblingRun,\n  type BlockDocument,\n  type BlockNode,\n  type Placed,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { lockOp } from \"../inspector/inspector\";\nimport { lockedBlockSentence } from \"../lock-refusal\";\nimport { lockBlockingDelete, lockBlockingMove } from \"../locking\";\nimport type { BuilderOp } from \"../op-vocabulary\";\nimport { layerLabel } from \"../panels/layers/layers\";\n\nimport { blockDeletion } from \"./delete-block\";\nimport { blockDuplication } from \"./duplicate-block\";\nimport { keyboardMovePosition } from \"./keyboard-move\";\nimport { normalizeSelection } from \"./selection\";\n\n/** A planned group, with what to say about it. */\nexport interface SelectionEdit {\n  /** The ops, in the order they must apply. */\n  readonly ops: readonly BuilderOp[];\n  /** How many blocks the author selected, for phrasing. */\n  readonly count: number;\n  /**\n   * How many blocks travel INSIDE the selected ones, across the whole group.\n   *\n   * Reported because a container takes its children with it and that is\n   * invisible from the block an author had selected — a collapsed section looks\n   * exactly like an empty one. Summed across the group rather than per block,\n   * since the announcement describes one action.\n   */\n  readonly descendants: number;\n  /**\n   * What to select once the group is gone, or `null` when nothing is left.\n   *\n   * A delete that left nothing selected would drop the author out of the\n   * inspector and the toolbar for a reason they did not ask for. Taken from the\n   * single-block rule's own `nextSelection`, skipping any candidate that is\n   * itself being deleted — with a run of siblings removed together, most of\n   * them name each other.\n   */\n  readonly nextSelection: string | null;\n  /** What to call the subject: the block's name, or \"3 blocks\". */\n  readonly subject: string;\n}\n\n/** What stopped an edit, phrased for an author. */\nexport interface SelectionRefusal {\n  readonly reason: string;\n}\n\n/** Either a plan or the reason there is none. */\nexport type SelectionPlan = SelectionEdit | SelectionRefusal | null;\n\n/**\n * Whether a plan can be applied.\n *\n * Accepts any planned edit rather than only a {@link SelectionPlan}, because\n * every verb here answers with the same three-way shape and a caller should not\n * need a different guard per verb. The `reason` field is what separates a\n * refusal, and only a refusal carries one.\n */\nexport function isRefusal<T extends object>(\n  plan: T | SelectionRefusal | null\n): plan is SelectionRefusal {\n  return plan !== null && \"reason\" in plan;\n}\n\n/**\n * \"Hero title\", or \"3 blocks\" once there is more than one. Exported so every\n * verb on a selection names it the same way, copying included.\n */\nexport function subjectOf(\n  document: BlockDocument,\n  ids: readonly string[]\n): string {\n  if (ids.length !== 1) return `${ids.length} blocks`;\n  const only = ids[0];\n  const node = only === undefined ? undefined : findIn(document.nodes, only);\n  return node === undefined ? \"1 block\" : layerLabel(node);\n}\n\nfunction findIn(\n  nodes: readonly BlockNode[],\n  id: string\n): BlockNode | undefined {\n  for (const node of nodes) {\n    if (node.id === id) return node;\n    for (const children of Object.values(node.slots ?? {})) {\n      const found = findIn(children, id);\n      if (found !== undefined) return found;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Removing every selected block.\n *\n * **One lock refuses the WHOLE group**, and that follows from the group being\n * atomic rather than being a separate policy: there is no half-done delete to\n * fall back to, so the choice is all or nothing, and silently skipping the\n * locked one would leave an author who selected six blocks looking at one they\n * did not notice surviving.\n */\n/**\n * The lock that stops this group being deleted, phrased, or `null`.\n *\n * Scanned across the WHOLE group before anything is planned, because the group\n * is atomic: the answer is all or nothing, so it has to be known before the\n * first op exists.\n */\nfunction lockRefusal(\n  document: BlockDocument,\n  ids: readonly string[]\n): SelectionRefusal | null {\n  for (const id of ids) {\n    const blocked = lockBlockingDelete(document, id);\n    if (blocked === undefined) continue;\n    return { reason: lockedBlockSentence(blocked, id, \"delete\") };\n  }\n  return null;\n}\n\n/** The removals themselves, with what the announcement and the selection need. */\nfunction removals(\n  document: BlockDocument,\n  ids: readonly string[]\n): {\n  ops: BuilderOp[];\n  descendants: number;\n  nextSelection: string | null;\n} {\n  const ops: BuilderOp[] = [];\n  const candidates: string[] = [];\n  const removing = new Set(ids);\n  let descendants = 0;\n\n  for (const id of ids) {\n    const deletion = blockDeletion(document, id);\n    // `null` means the document no longer holds it, which `normalizeSelection`\n    // has already excluded — so this is unreachable rather than tolerated, and\n    // skipping is the safe reading if it ever is not.\n    if (deletion === null) continue;\n    descendants += deletion.descendantCount;\n    if (\n      deletion.nextSelection !== null &&\n      !removing.has(deletion.nextSelection)\n    ) {\n      candidates.push(deletion.nextSelection);\n    }\n    ops.push({\n      kind: \"remove\",\n      id: deletion.id,\n      ...(deletion.dropSlotIfEmpty === undefined\n        ? {}\n        : { dropSlotIfEmpty: deletion.dropSlotIfEmpty }),\n    });\n  }\n\n  return { ops, descendants, nextSelection: candidates[0] ?? null };\n}\n\n/**\n * Removing every selected block.\n *\n * **One lock refuses the WHOLE group**, and that follows from the group being\n * atomic rather than being a separate policy: there is no half-done delete to\n * fall back to, so the choice is all or nothing, and silently skipping the\n * locked one would leave an author who selected six blocks looking at one they\n * did not notice surviving.\n */\nexport function selectionDeletion(\n  document: BlockDocument,\n  selectedIds: readonly string[]\n): SelectionPlan {\n  const ids = normalizeSelection(document, selectedIds);\n  if (ids.length === 0) return null;\n\n  const refusal = lockRefusal(document, ids);\n  if (refusal !== null) return refusal;\n\n  const { ops, descendants, nextSelection } = removals(document, ids);\n  if (ops.length === 0) return null;\n\n  return {\n    ops,\n    count: ids.length,\n    descendants,\n    nextSelection,\n    subject: subjectOf(document, ids),\n  };\n}\n\n/** A duplication, with the ids the copies will have. */\nexport interface SelectionDuplication extends SelectionEdit {\n  /** The copies, in document order, for selecting them afterwards. */\n  readonly newIds: readonly string[];\n}\n\n/**\n * Copying every selected block, each beside its original.\n *\n * A lock does NOT refuse this: duplicating neither moves nor removes the\n * original, and refusing would mean an author could not copy the blocks they\n * had most deliberately protected. The copies carry the lock, as they do for a\n * single block. A lock AROUND the copy's place is another matter: putting a\n * block into a locked one is refused, as any insert there is.\n */\nexport function selectionDuplication(\n  document: BlockDocument,\n  selectedIds: readonly string[]\n): SelectionDuplication | null {\n  const ids = normalizeSelection(document, selectedIds);\n  if (ids.length === 0) return null;\n\n  const placed: Placed[] = [];\n  const newIds: string[] = [];\n  // Reversed — see the module docblock. Forwards, the second copy's position is\n  // computed against a document the first copy has already shifted.\n  for (const id of [...ids].reverse()) {\n    const duplication = blockDuplication(document, id);\n    if (duplication === null) continue;\n    placed.push({ node: duplication.node, at: duplication.at });\n    // Unshifted, so the ids come back in document order even though the ops go\n    // out in reverse. A caller selecting the copies wants them the way a reader\n    // meets them, not the way they were planned.\n    newIds.unshift(duplication.node.id);\n  }\n\n  if (placed.length === 0) return null;\n  return {\n    // A copy keeps the locks its original carries: it arrives unlocked and is\n    // locked where it lands, the sequence every copy into a document uses, so\n    // the insert is accepted and its undo still works.\n    ops: insertKeepingLocks(placed),\n    newIds,\n    count: ids.length,\n    descendants: 0,\n    nextSelection: null,\n    subject: subjectOf(document, ids),\n  };\n}\n\n/**\n * Locking or unlocking every selected block.\n *\n * Order-independent: each op addresses one node and changes only its own flag.\n */\nexport function selectionLock(\n  document: BlockDocument,\n  selectedIds: readonly string[],\n  locked: boolean\n): SelectionEdit | null {\n  const ids = normalizeSelection(document, selectedIds);\n  if (ids.length === 0) return null;\n\n  /*\n   * Only the blocks this would actually change.\n   *\n   * `applyOp` REFUSES an update that writes what a node already holds — \"a\n   * history entry for it would undo to no visible effect\" — and a group is\n   * applied atomically, so a single already-locked block would abort the whole\n   * edit and lock nothing. That is not hypothetical: locking a MIXED selection\n   * is the ordinary case, and every one of them contains a block already in the\n   * target state.\n   *\n   * Filtering here rather than loosening the op layer, because that rule is\n   * right: an op that changes nothing does not belong on the undo stack. What\n   * was wrong was planning one.\n   */\n  const changing = ids.filter(id => {\n    const node = findIn(document.nodes, id);\n    return node !== undefined && (node.locked === true) !== locked;\n  });\n  if (changing.length === 0) return null;\n\n  return {\n    ops: changing.map(id => lockOp(id, locked)),\n    count: ids.length,\n    descendants: 0,\n    nextSelection: null,\n    subject: subjectOf(document, ids),\n  };\n}\n\n/** A planned reorder, with what to say about it. */\nexport interface SelectionMove {\n  /** The moves, in the order they must apply. */\n  readonly ops: readonly BuilderOp[];\n  /** How many blocks the author selected, for phrasing. */\n  readonly count: number;\n  /** What to call the subject: the block's name, or \"3 blocks\". */\n  readonly subject: string;\n}\n\n/** Either a reorder, the reason there is none, or `null` for nothing to say. */\nexport type SelectionMovePlan = SelectionMove | SelectionRefusal | null;\n\n/**\n * Blocks that do not share one sibling list cannot travel together.\n *\n * Phrased as the remedy rather than the rule. \"Different containers\" describes\n * the document; selecting within one container is the thing an author can do\n * about it.\n */\nconst SPLIT_REFUSAL: SelectionRefusal = {\n  reason:\n    \"These blocks sit in different containers. Move blocks that share one.\",\n};\n\n/**\n * The lock that stops this group being moved, phrased, or `null`.\n *\n * Separate from the deletion refusal because the verb reaches the author: a\n * lock that forbids moving is not the same sentence as one that forbids\n * deleting, though `lockBlockingMove` and `lockBlockingDelete` find the same\n * locked block.\n */\nfunction moveLockRefusal(\n  document: BlockDocument,\n  ids: readonly string[]\n): SelectionRefusal | null {\n  for (const id of ids) {\n    const blocked = lockBlockingMove(document, id);\n    if (blocked === undefined) continue;\n    return { reason: lockedBlockSentence(blocked, id, \"move\") };\n  }\n  return null;\n}\n\n/**\n * Moving every selected block one step, keeping their order and their spacing.\n *\n * **A set moves only within one container.** Duplicate and delete are the\n * single-block verb repeated and need nothing of each other; a move is a step\n * through a list, so blocks in different lists are not doing the same thing.\n * That is a refusal an author is told about, because nothing on the page says\n * the selection straddles a boundary.\n *\n * **One block at the edge refuses the WHOLE group**, like a lock. Letting the\n * others move would close the gaps between them, and the set would come back\n * differently arranged than it went, so `up` would no longer be undone by\n * `down`. Preserving that inverse is what the two move axes exist to protect,\n * and a group edit is where it is easiest to lose.\n *\n * **Every position is the single-block rule's**, asked once per block. Nothing\n * here re-decides what one step means.\n */\nexport function selectionMove(\n  document: BlockDocument,\n  selectedIds: readonly string[],\n  direction: \"up\" | \"down\"\n): SelectionMovePlan {\n  const ids = normalizeSelection(document, selectedIds);\n  if (ids.length === 0) return null;\n\n  const refusal = moveLockRefusal(document, ids);\n  if (refusal !== null) return refusal;\n\n  // The ENGINE's rule, not a copy of it. Every composition planner asks the\n  // same question — a pattern, a component and a converted selection are each\n  // one run lifted out of one place — and a planner runs in a plugin's server\n  // action where this package cannot be imported. Two implementations of \"do\n  // these share a list\" would disagree the first time either moved.\n  //\n  // `siblingRun` also refuses an empty selection and an id the document does\n  // not hold. Neither reaches here: `normalizeSelection` has already dropped\n  // every absent id and the length guard above has returned. So a split is the\n  // only cause left, and it keeps the sentence it always had.\n  const found = siblingRun(document.nodes, ids);\n  if (found.run === undefined) return SPLIT_REFUSAL;\n\n  // Towards the destination first, so each block steps into an index its\n  // neighbour has already left.\n  const places = found.run.places;\n  const order = direction === \"up\" ? places : [...places].reverse();\n\n  const ops: BuilderOp[] = [];\n  for (const place of order) {\n    const step = keyboardMovePosition(document.nodes, place.id, direction);\n    // At the edge of the container. Silent, like the single-block move: a\n    // selection that cannot go further has said so by not going.\n    if (step === null) return null;\n    ops.push({ kind: \"move\", id: place.id, to: step.to });\n  }\n\n  return { ops, count: ids.length, subject: subjectOf(document, ids) };\n}\n","/**\n * \"Turn into\" for the selected block: which types it can become, whether\n * each is open, what each would remove, and the one verb every surface runs.\n *\n * The block menu, the bar's More menu, the command palette and the floating\n * format bar all read {@link turnIntoOffers} and run {@link runTurnInto}, so\n * one surface cannot offer a turn another refuses, or say a different thing\n * about what it removes. What a block becomes is the block's own converter,\n * planned by the engine (`planTurnInto`); this module adds what an editing\n * surface needs on top: the locks, the placement rule, and the words.\n *\n * Only Text, Rich text and Heading turn into each other today, so the verbs\n * are named for them: a menu verb has a fixed id, and a block offering a\n * target outside these three is offered nothing for it.\n *\n * @module turn-into-verb\n */\n\nimport {\n  applyOp,\n  findNode,\n  getBlock,\n  placementRefusal,\n  planTurnInto,\n  registryBlockSource,\n  registryNestingSource,\n  turnIntoTargets,\n  type BlockDocument,\n  type BuilderOp,\n  type DocumentLimits,\n  type NamedClass,\n  type NestingSource,\n  type TurnIntoDefinitions,\n  type TurnIntoPlan,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  lockedBlockWording,\n  lockRefusalWording,\n  type LockRefusalFacts,\n} from \"../lock-refusal\";\nimport { lockBlockingDelete } from \"../locking\";\nimport { refusalAnnouncement } from \"../move-refusal\";\nimport { blockLabel } from \"../panels/add/inserter-catalog\";\n\nimport { placementWording } from \"./drag-refusal\";\n\n/** The menu verbs, by the type each turns the block into. */\nexport const TURN_INTO_TARGETS = {\n  \"turn-into-text\": \"core/text\",\n  \"turn-into-rich-text\": \"core/rich-text\",\n  \"turn-into-heading\": \"core/heading\",\n} as const;\n\n/** One of the menu verbs. */\nexport type TurnIntoActionId = keyof typeof TURN_INTO_TARGETS;\n\n/** Whether an action id is one of the \"Turn into\" verbs. */\nexport function isTurnIntoAction(id: string): id is TurnIntoActionId {\n  return Object.hasOwn(TURN_INTO_TARGETS, id);\n}\n\n/** The words \"Turn into\" says, in one place. */\nconst TURN_INTO_WORDS = {\n  menu: \"Turn into\",\n  /** Said when a binding cannot move to the new block. */\n  unbound: \"Its bound field is removed\",\n  /** Said when part of a block style gives way to a shared style. */\n  lookTrimmed: \"Part of its block style gives way to its other styles\",\n  /** Said when the block takes the new type's default block style. */\n  defaultLook: (name: string): string =>\n    `Its block style changes to ${name}'s default`,\n  /** Said when the page refused the edit for a reason nothing judged first. */\n  refused: \"The page refused this edit, so nothing changed.\",\n  label: (name: string): string => `Turn into ${name}`,\n  done: (name: string): string => `Turned into ${name}`,\n} as const;\n\n/** One type the selected block can become. */\nexport interface TurnIntoOffer {\n  readonly id: TurnIntoActionId;\n  /** The type it becomes: `\"core/heading\"`. */\n  readonly to: string;\n  /** What the type is called: \"Heading\". */\n  readonly name: string;\n  /** The verb: \"Turn into Heading\". */\n  readonly label: string;\n  readonly enabled: boolean;\n  /** Why it is not open, for an author, when it is not. */\n  readonly reason?: string;\n  /** What the turn removes, said before it is chosen. */\n  readonly note?: string;\n}\n\n/** The editor's own lock question, asked of the op a turn would apply. */\nexport type TurnIntoLockQuestion = (\n  ops: readonly BuilderOp[]\n) => LockRefusalFacts | undefined;\n\n/** What judging a turn may ask beyond the document. */\nexport interface TurnIntoJudging {\n  /** The editor's lock question; absent, a slot's lock is not asked. */\n  readonly ask?: TurnIntoLockQuestion;\n  /**\n   * Whether to judge the turn in full: the slot locks and the placement rule,\n   * which apply the op to answer. False for what a surface shows as the\n   * selection changes; a menu that opens, and the verb, judge in full.\n   */\n  readonly planned?: boolean;\n  readonly nesting?: NestingSource;\n  readonly definitions?: TurnIntoDefinitions;\n  /**\n   * The site's styles, so a block style the new type cannot wear is kept as\n   * its own styles (`planTurnInto`). Absent, its id is carried as is.\n   */\n  readonly library?: readonly NamedClass[];\n  /**\n   * The editor's size limits, which the trial edit the placement rule is\n   * asked of is judged by, as the editor's own apply is. Absent, the\n   * defaults.\n   */\n  readonly limits?: DocumentLimits;\n}\n\n/** What a turn removes, as one line: the converter's words, then a binding. */\nfunction turnIntoNote(plan: TurnIntoPlan, name: string): string | undefined {\n  const said = [\n    plan.dropped,\n    plan.unbound.length > 0 ? TURN_INTO_WORDS.unbound : undefined,\n    plan.lookTrimmed === true ? TURN_INTO_WORDS.lookTrimmed : undefined,\n    plan.defaultLookChanges === true\n      ? TURN_INTO_WORDS.defaultLook(name)\n      : undefined,\n  ].filter((each): each is string => each !== undefined);\n  return said.length === 0 ? undefined : said.join(\". \");\n}\n\n/** A judged turn: the offer, and the plan when there is one. */\ninterface Judged {\n  readonly offer: TurnIntoOffer;\n  readonly plan?: TurnIntoPlan;\n}\n\n/** Why the placement rule refuses the turned block where it stands. */\nfunction placementReason(\n  document: BlockDocument,\n  plan: TurnIntoPlan,\n  nesting: NestingSource,\n  limits: DocumentLimits | undefined\n): string | undefined {\n  let after: BlockDocument;\n  try {\n    after = applyOp(document, plan.op, limits).document;\n  } catch {\n    // Not one this rule can judge (the trial was refused, a cap say): the\n    // editor's own apply, with the host's limits, decides when it runs.\n    return undefined;\n  }\n  const found = placementRefusal(\n    document,\n    after,\n    { nesting, definitions: registryBlockSource() },\n    limits\n  );\n  if (found === undefined) return undefined;\n  const parent =\n    found.parentId === undefined\n      ? undefined\n      : findNode(document.nodes, found.parentId)?.type;\n  return refusalAnnouncement(\n    placementWording(found.verdict, plan.op.node.type, parent)\n  );\n}\n\n/** Why a planned turn may not run here, or `undefined` when it may. */\nfunction judgedReason(\n  document: BlockDocument,\n  plan: TurnIntoPlan,\n  judging: TurnIntoJudging\n): string | undefined {\n  if (judging.planned !== true) return undefined;\n  const locked = judging.ask?.([plan.op]);\n  if (locked !== undefined) {\n    return refusalAnnouncement(lockRefusalWording(locked));\n  }\n  return placementReason(\n    document,\n    plan,\n    judging.nesting ?? registryNestingSource(),\n    judging.limits\n  );\n}\n\n/** One turn, judged: open, or closed with the reason. */\nfunction judge(\n  document: BlockDocument,\n  id: string,\n  action: TurnIntoActionId,\n  judging: TurnIntoJudging\n): Judged {\n  const to = TURN_INTO_TARGETS[action];\n  const name = blockLabel(to, judging.definitions ?? getBlock);\n  const base = { id: action, to, name, label: TURN_INTO_WORDS.label(name) };\n  const locked = lockBlockingDelete(document, id);\n  if (locked !== undefined) {\n    const reason = lockedBlockWording(locked, id, \"change\").headline;\n    return { offer: { ...base, enabled: false, reason } };\n  }\n  const plan = planTurnInto(\n    document,\n    id,\n    to,\n    judging.definitions,\n    judging.library\n  );\n  if (\"refused\" in plan) {\n    return { offer: { ...base, enabled: false, reason: plan.refused } };\n  }\n  const note = turnIntoNote(plan, name);\n  const reason = judgedReason(document, plan, judging);\n  return {\n    offer: {\n      ...base,\n      enabled: reason === undefined,\n      ...(reason === undefined ? {} : { reason }),\n      ...(note === undefined ? {} : { note }),\n    },\n    plan,\n  };\n}\n\n/** The menu verb that turns a block into `to`, if there is one. */\nfunction actionFor(to: string): TurnIntoActionId | undefined {\n  return (Object.keys(TURN_INTO_TARGETS) as TurnIntoActionId[]).find(\n    action => TURN_INTO_TARGETS[action] === to\n  );\n}\n\n/**\n * Every type the block `id` can be turned into, in the order its block\n * declares them, each open or closed with the reason; nothing for a block\n * that declares none, or that is not in the document.\n */\nexport function turnIntoOffers(\n  document: BlockDocument,\n  id: string,\n  judging: TurnIntoJudging = {}\n): TurnIntoOffer[] {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return [];\n  return turnIntoTargets(node.type, judging.definitions ?? getBlock)\n    .map(actionFor)\n    .filter((action): action is TurnIntoActionId => action !== undefined)\n    .map(action => judge(document, id, action, judging).offer);\n}\n\n/** The editor, as the verb uses it. */\nexport interface TurnIntoEditor {\n  /** The document to turn the block in: the latest the editor holds. */\n  readonly document: BlockDocument;\n  readonly apply: (op: BuilderOp) => BlockDocument | null;\n  readonly lockRefusalFor?: TurnIntoLockQuestion;\n}\n\n/**\n * Turn the block `id` into `to`, as one undo step, saying what happened: why\n * it did not, or that it did and what it removed. Answers whether it did.\n */\nexport function runTurnInto(\n  editor: TurnIntoEditor,\n  id: string,\n  to: string,\n  say: (words: string) => void,\n  judging: Omit<TurnIntoJudging, \"ask\" | \"planned\"> = {}\n): boolean {\n  const action = actionFor(to);\n  if (action === undefined) return false;\n  const { offer, plan } = judge(editor.document, id, action, {\n    ...judging,\n    planned: true,\n    ...(editor.lockRefusalFor === undefined\n      ? {}\n      : { ask: editor.lockRefusalFor }),\n  });\n  if (!offer.enabled || plan === undefined) {\n    say(offer.reason ?? TURN_INTO_WORDS.refused);\n    return false;\n  }\n  if (editor.apply(plan.op) === null) {\n    say(TURN_INTO_WORDS.refused);\n    return false;\n  }\n  const done = TURN_INTO_WORDS.done(offer.name);\n  say(offer.note === undefined ? done : `${done}. ${offer.note}`);\n  return true;\n}\n","/**\n * What the editor's command palette can run.\n *\n * The palette is the third way to reach the same verbs, after the keystrokes\n * and the floating toolbar, and it is the one that answers \"what can this\n * editor even do\". A toolbar shows five icons at the block; a palette lists\n * every action by NAME, which is what someone who has never used this editor\n * searches with.\n *\n * ## Availability comes from the toolbar's rule, not a second one\n *\n * Whether a block can move, whether a lock forbids deleting it — every one of\n * those questions is already answered by `toolbarActions`, and asking them a\n * second time here is how a palette ends up offering a command that the button\n * beside it shows as unavailable. So the block verbs are DERIVED from that\n * list: same order, same enabling, same reasons.\n *\n * ## Why the labels differ from the toolbar's\n *\n * A toolbar button sits on the block it acts on, so \"Duplicate\" is unambiguous\n * there. A palette row is read in a list with no such context, so it names its\n * subject: \"Duplicate block\". The keywords carry the shorter word, so searching\n * \"duplicate\" still finds it.\n *\n * @module builder-commands\n */\n\nimport type { ToolbarAction, ToolbarActionId } from \"../canvas/toolbar-actions\";\nimport { TURN_INTO_TARGETS } from \"../canvas/turn-into-verb\";\nimport { CONVERSION_WORDS } from \"../editor-words\";\n\nimport type { BuilderCommand } from \"./command-palette\";\n\n/** The verbs a palette command needs, as `BlockKeyboardActions` publishes them. */\nexport interface CommandVerbs {\n  readonly move: (direction: \"up\" | \"down\") => void;\n  readonly delete: () => void;\n  readonly duplicate: () => void;\n  /** Copy, Cut and Paste of blocks, through the clipboard. */\n  readonly copy: () => void;\n  readonly cut: () => void;\n  readonly paste: () => void;\n  /**\n   * Copy one block's look, and give it to every selected block. Optional,\n   * so a host built before them keeps compiling; absent, they do nothing.\n   */\n  readonly copyStyle?: () => void;\n  readonly pasteStyle?: () => void;\n  readonly selectParent: () => void;\n  /**\n   * Begin storing the selection in the pattern library.\n   *\n   * REQUIRED, like the four above it, and that is a decision rather than an\n   * oversight. Nothing else here is a capability a host may lack, and making\n   * this one optional produces the shape the totalised runner map exists to\n   * prevent: a verb the bar offers with nothing bound to it, which reaches an\n   * author as a button that does nothing. Required, the compiler names every\n   * host that has to wire it.\n   *\n   * A host with no library to save into is a real case and not one there is a\n   * second example of yet. Designing an availability model against a guess is\n   * how a surface ends up with a control that is dimmed for a reason nobody can\n   * phrase; when there is a second host it can be designed against that.\n   */\n  readonly saveAsPattern: () => void;\n  /**\n   * Open the selected placement's component in its own view. Silent when the\n   * selection is not one placement or the host does not offer it, so it may\n   * be pressed without asking first. Optional, so a host built before it\n   * keeps compiling; absent, the verb does nothing.\n   */\n  readonly editComponent?: () => void;\n  /**\n   * Begin turning the selection into a component, replacing it with a\n   * placement or keeping it and saving a copy; the host owns the form.\n   */\n  readonly turnIntoComponent?: () => void;\n  /** Begin detaching the selected placement from its component. */\n  readonly detachComponent?: () => void;\n  /** Begin duplicating the selected placement's component. */\n  readonly duplicateComponent?: () => void;\n  /** Put the selected blocks in a new Box at their place. */\n  readonly wrapInBox?: () => void;\n  /** Replace the selected container by its blocks. */\n  readonly unwrap?: () => void;\n  /** Begin replacing a pattern's content with the selection. */\n  readonly updatePattern?: () => void;\n  /** Begin saving the block's look as a shared style; the host owns the form. */\n  readonly saveAsSharedStyle?: () => void;\n  /**\n   * Turn the selected block into another type (`\"core/heading\"`), as one undo\n   * step, saying what it removes. Optional, so a host built before it keeps\n   * compiling; absent, the verb does nothing.\n   */\n  readonly turnInto?: (to: string) => void;\n}\n\n/** Everything the command list is built from. */\nexport interface BuilderCommandsInput {\n  /**\n   * What the bar would offer for this selection, from `toolbarActions`.\n   *\n   * Taken rather than derived, and that is what keeps availability DERIVED in\n   * the sense that matters: the palette now shows exactly the list the toolbar\n   * and the context menu are drawing, because it is the same array. Asked\n   * separately it was a second call — one that could be given a narrower\n   * question, which is how this surface came to offer a verb the bar refused —\n   * and not a cheap one either, since deciding whether a selection can be saved\n   * builds the document a save would store.\n   */\n  readonly actions: readonly ToolbarAction[];\n  readonly verbs: CommandVerbs;\n  readonly undo: () => void;\n  readonly redo: () => void;\n  readonly canUndo: boolean;\n  readonly canRedo: boolean;\n  /**\n   * Leaving the editor, when the host has somewhere to go.\n   *\n   * Optional for the same reason the shell's exit affordance is: the editor\n   * mounts both standalone and embedded in a form that is already on screen,\n   * and a palette offering \"Close the editor\" where nothing closes is a command\n   * that does nothing.\n   */\n  readonly onExit?: () => void;\n}\n\n/** How each block verb is named and found in a list with no block beside it. */\nconst BLOCK_COMMAND_COPY: Record<\n  ToolbarActionId,\n  { label: string; keywords: readonly string[] }\n> = {\n  \"select-parent\": {\n    label: \"Select parent block\",\n    keywords: [\"parent\", \"container\", \"up\", \"outer\", \"enclosing\"],\n  },\n  \"move-up\": {\n    label: \"Move block up\",\n    keywords: [\"move\", \"up\", \"before\", \"earlier\", \"reorder\"],\n  },\n  \"move-down\": {\n    label: \"Move block down\",\n    keywords: [\"move\", \"down\", \"after\", \"later\", \"reorder\"],\n  },\n  duplicate: {\n    label: \"Duplicate block\",\n    keywords: [\"duplicate\", \"copy\", \"clone\", \"repeat\"],\n  },\n  // \"Copy\" and \"Cut\" put blocks on the clipboard; \"Paste\" places them where\n  // a clicked block would land, on this page or another.\n  copy: {\n    label: \"Copy block\",\n    keywords: [\"copy\", \"clipboard\"],\n  },\n  cut: {\n    label: \"Cut block\",\n    keywords: [\"cut\", \"clipboard\", \"move\"],\n  },\n  paste: {\n    label: \"Paste blocks\",\n    keywords: [\"paste\", \"clipboard\", \"insert\"],\n  },\n  // Named exactly as the menu names them: the words say what is copied.\n  \"copy-style\": {\n    label: \"Copy style\",\n    keywords: [\"copy style\", \"look\", \"format\", \"painter\", \"appearance\"],\n  },\n  \"paste-style\": {\n    label: \"Paste style\",\n    keywords: [\"paste style\", \"look\", \"format\", \"painter\", \"apply\", \"match\"],\n  },\n  // Changing which of the three text blocks it is, kept apart in words from\n  // turning a selection into a component.\n  \"turn-into-text\": {\n    label: \"Turn block into Text\",\n    keywords: [\"turn into\", \"convert\", \"change\", \"text\", \"paragraph\"],\n  },\n  \"turn-into-rich-text\": {\n    label: \"Turn block into Rich text\",\n    keywords: [\"turn into\", \"convert\", \"change\", \"rich text\", \"formatted\"],\n  },\n  \"turn-into-heading\": {\n    label: \"Turn block into Heading\",\n    keywords: [\"turn into\", \"convert\", \"change\", \"heading\", \"title\"],\n  },\n  // The conversions are named with the bar's own words, so the palette and\n  // the menus offer one verb for each.\n  \"save-as-pattern\": {\n    label: CONVERSION_WORDS.saveAsSection,\n    // \"pattern\", \"reuse\" and \"template\" are what an author who has used\n    // another builder searches with; they find it by those words too.\n    keywords: [\n      \"save\",\n      \"section\",\n      \"saved sections\",\n      \"pattern\",\n      \"library\",\n      \"reuse\",\n      \"template\",\n      \"snippet\",\n    ],\n  },\n  \"save-as-shared-style\": {\n    label: \"Save block as shared style\",\n    keywords: [\"save\", \"shared style\", \"class\", \"reuse\", \"style\", \"preset\"],\n  },\n  \"edit-component\": {\n    label: \"Edit component\",\n    keywords: [\"component\", \"edit\", \"open\", \"original\", \"definition\"],\n  },\n  // One verb for both ways of making a component, so the palette finds it\n  // by the words of either.\n  \"turn-into-component\": {\n    label: CONVERSION_WORDS.turnIntoComponent,\n    keywords: [\n      \"turn into\",\n      \"convert\",\n      \"save\",\n      \"component\",\n      \"library\",\n      \"reuse\",\n      \"symbol\",\n      \"synced\",\n    ],\n  },\n  \"detach-component\": {\n    label: CONVERSION_WORDS.detachFromComponent,\n    keywords: [\"detach\", \"unlink\", \"component\", \"plain\", \"break\"],\n  },\n  \"duplicate-component\": {\n    label: \"Duplicate component\",\n    keywords: [\"duplicate\", \"copy\", \"component\", \"fork\", \"variant\"],\n  },\n  \"update-pattern\": {\n    label: \"Update a saved section from the selection\",\n    keywords: [\n      \"update\",\n      \"section\",\n      \"pattern\",\n      \"replace\",\n      \"overwrite\",\n      \"save over\",\n    ],\n  },\n  \"wrap-in-box\": {\n    label: \"Wrap blocks in a box\",\n    keywords: [\"wrap\", \"box\", \"group\", \"container\", \"nest\"],\n  },\n  unwrap: {\n    label: \"Unwrap block (keep what's inside)\",\n    keywords: [\"unwrap\", \"ungroup\", \"unnest\", \"remove container\", \"flatten\"],\n  },\n  delete: {\n    label: \"Delete block\",\n    keywords: [\"delete\", \"remove\", \"destroy\", \"clear\"],\n  },\n};\n\n/** The group the block verbs are listed under. */\nexport const BLOCK_GROUP = \"Block\";\n/** The group undo and redo are listed under. */\nexport const HISTORY_GROUP = \"History\";\n/** The group leaving the editor is listed under. */\nexport const EDITOR_GROUP = \"Editor\";\n\n/**\n * What each toolbar action id actually RUNS.\n *\n * Published rather than kept inside the palette because the palette is no\n * longer the only surface over these verbs: the right-click menu offers the\n * same list, and a second copy of this map is how one surface comes to move a\n * block while another duplicates it. The AVAILABILITY of an action is\n * `toolbarActions`'s answer and the LABEL is the surface's own; this is the\n * third and last thing a surface needs, and the only one they can all share.\n *\n * Total over {@link ToolbarActionId}, so a verb added to the bar cannot reach a\n * surface with nothing bound to it — the compiler names the omission here.\n */\nexport function blockActionRunners(\n  verbs: CommandVerbs\n): Record<ToolbarActionId, () => void> {\n  return {\n    \"select-parent\": verbs.selectParent,\n    \"move-up\": () => verbs.move(\"up\"),\n    \"move-down\": () => verbs.move(\"down\"),\n    duplicate: verbs.duplicate,\n    copy: verbs.copy,\n    cut: verbs.cut,\n    paste: verbs.paste,\n    \"copy-style\": () => verbs.copyStyle?.(),\n    \"paste-style\": () => verbs.pasteStyle?.(),\n    \"turn-into-text\": () =>\n      verbs.turnInto?.(TURN_INTO_TARGETS[\"turn-into-text\"]),\n    \"turn-into-rich-text\": () =>\n      verbs.turnInto?.(TURN_INTO_TARGETS[\"turn-into-rich-text\"]),\n    \"turn-into-heading\": () =>\n      verbs.turnInto?.(TURN_INTO_TARGETS[\"turn-into-heading\"]),\n    \"save-as-pattern\": verbs.saveAsPattern,\n    \"save-as-shared-style\": () => verbs.saveAsSharedStyle?.(),\n    \"edit-component\": () => verbs.editComponent?.(),\n    \"turn-into-component\": () => verbs.turnIntoComponent?.(),\n    \"detach-component\": () => verbs.detachComponent?.(),\n    \"duplicate-component\": () => verbs.duplicateComponent?.(),\n    \"update-pattern\": () => verbs.updatePattern?.(),\n    \"wrap-in-box\": () => verbs.wrapInBox?.(),\n    unwrap: () => verbs.unwrap?.(),\n    delete: verbs.delete,\n  };\n}\n\n/**\n * The palette's commands for the current state.\n *\n * Unavailable commands are OMITTED rather than listed and disabled, which is\n * the opposite of what the toolbar does — and deliberately. A toolbar keeps one\n * shape so the control an author is aiming at does not move; a palette is\n * searched rather than aimed at, and a row that matches the search and then\n * refuses to run is worse there than one that was never offered.\n */\nexport function builderCommands({\n  actions,\n  verbs,\n  undo,\n  redo,\n  canUndo,\n  canRedo,\n  onExit,\n}: BuilderCommandsInput): BuilderCommand[] {\n  const run = blockActionRunners(verbs);\n\n  // Paste is offered whatever is selected, since with nothing selected it\n  // lands at the end of the page; so it is added once, below, and not taken\n  // from the selection's verbs.\n  const blockCommands = actions\n    .filter(action => action.enabled && action.id !== \"paste\")\n    .map(action => {\n      const copy = BLOCK_COMMAND_COPY[action.id];\n      return {\n        id: `block.${action.id}`,\n        label: copy.label,\n        group: BLOCK_GROUP,\n        keywords: copy.keywords,\n        run: run[action.id],\n      };\n    });\n\n  blockCommands.push({\n    id: \"block.paste\",\n    label: BLOCK_COMMAND_COPY.paste.label,\n    group: BLOCK_GROUP,\n    keywords: BLOCK_COMMAND_COPY.paste.keywords,\n    run: run.paste,\n  });\n\n  const history: BuilderCommand[] = [];\n  if (canUndo) {\n    history.push({\n      id: \"history.undo\",\n      label: \"Undo\",\n      group: HISTORY_GROUP,\n      keywords: [\"undo\", \"revert\", \"back\"],\n      run: undo,\n    });\n  }\n  if (canRedo) {\n    history.push({\n      id: \"history.redo\",\n      label: \"Redo\",\n      group: HISTORY_GROUP,\n      keywords: [\"redo\", \"again\", \"forward\"],\n      run: redo,\n    });\n  }\n\n  const editor: BuilderCommand[] =\n    onExit === undefined\n      ? []\n      : [\n          {\n            id: \"editor.exit\",\n            label: \"Close the editor\",\n            group: EDITOR_GROUP,\n            keywords: [\"close\", \"exit\", \"leave\", \"done\", \"back\"],\n            run: onExit,\n          },\n        ];\n\n  return [...blockCommands, ...history, ...editor];\n}\n","/**\n * Turning a permitted-types list into words an author reads.\n *\n * The nesting rule answers with registry SPECIFIERS — `core/columns`,\n * `acme/card`, or a namespace wildcard like `core/*` — and none of those is\n * something to put in front of a person. Told that a block \"goes inside\n * core/columns\", an author has to know how this project names its modules\n * before they can act on the sentence.\n *\n * One home, because two surfaces now say it. The drag refusal has said it since\n * drops were explained; the composition refusal says it about a selection that\n * cannot be saved. Written twice they would agree today and differ the first\n * time either learned about a new kind of entry — and a wildcard is exactly that\n * kind of entry, which is why the naive reading produces \"goes inside *\".\n *\n * @module permitted-prose\n */\n\nimport {\n  asPermittedList,\n  permittedLabel as permittedLabelWith,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { blockLabel } from \"../panels/add/inserter\";\n\n/**\n * One entry of a permitted list, as an author reads it: a block's label, or\n * \"any core block\" for a namespace. The engine words it, so a refusal read on\n * the canvas and one read from a save name the same set the same way; this\n * binds it to the editor's labels.\n */\nexport function permittedLabel(entry: string): string {\n  return permittedLabelWith(entry, blockLabel);\n}\n\n/** \"A\", \"A and B\", \"A, B and C\", as the engine joins a permitted list. */\nexport { asPermittedList };\n","/**\n * Why a composition verb refused, in words an author can act on.\n *\n * The planners answer with a CAUSE — `\"gap\"`, `\"restricted-at-root\"`,\n * `\"exceeds-limits\"` — and never with a sentence, deliberately: `PlanResult`'s\n * own docblock says the cause travels unchanged \"so the sentence shown to an\n * author is composed once per surface rather than once per planner\". This is\n * that one composition. The toolbar, the context menu, the palette and the save\n * dialog all reach it, so a refusal reads the same wherever an author meets it.\n *\n * ## Remedies, not rules\n *\n * Every sentence says what to do, following the refusals already in\n * `selection-ops.ts`: \"These blocks sit in different containers. Move blocks\n * that share one.\" describes the document AND the fix. A sentence that only\n * names the rule leaves an author correct and stuck.\n *\n * ## Total over the causes, not over the ones reachable today\n *\n * A `Record<PlanProblem, …>` rather than a lookup with a fallback. A fallback is\n * a sentence nobody wrote for a cause nobody classified, and it appears in front\n * of an author the first time a planner learns a new way to say no. The compiler\n * naming the omission is the whole point.\n *\n * That means causes no PATTERN save can reach are phrased here too, and they are\n * not dead copy: they are the causes `planSaveAsComponent` and\n * `planConvertToComponent` produce, which arrive at these same surfaces. One map\n * for the family is what the engine's docblock asks for.\n *\n * @module composition-refusal\n */\n\nimport type { PlanProblem, PlanRefusal } from \"@nextlyhq/blocks-engine\";\n\nimport { asPermittedList, permittedLabel } from \"./permitted-prose\";\n\n/**\n * The sentence for each cause, with no subject and no block name.\n *\n * Written to sit in a toolbar tooltip, a disabled menu row and a dialog alike,\n * so none of them names the selection: the surface is already drawn against it.\n */\nconst REFUSAL_COPY: Record<PlanProblem, string> = {\n  // From the selection itself.\n  empty: \"Select a block first.\",\n  unknown: \"That selection is no longer on the page. Select a block again.\",\n  split:\n    \"These blocks sit in different containers. Select blocks that share one.\",\n  gap: \"These blocks have others between them. Select a run with no gaps.\",\n\n  // From the nesting rule.\n  \"wrong-parent\": \"This block cannot sit in that container.\",\n  \"restricted-at-root\":\n    \"This block only works inside another one. Include the container it sits in.\",\n  \"not-allowed-in-slot\": \"That container does not accept this block.\",\n\n  // From the shape of what would be stored.\n  \"invalid-node\": \"Part of this selection cannot be copied. Try a smaller one.\",\n  \"duplicate-dom-id\":\n    \"Two of these blocks share one HTML id. Give one of them a different id.\",\n  \"dom-id-collision\":\n    \"An HTML id here keeps colliding. Change it and try again.\",\n  \"unusable-document\":\n    \"This page cannot be read well enough to copy from. Reload and try again.\",\n  \"exceeds-limits\": \"This selection is too large to save. Try a smaller one.\",\n\n  // From the destination, for the verbs that write back to the page.\n  \"not-a-pattern\": \"That library entry is not a saved section.\",\n  \"duplicate-destination\":\n    \"Two blocks on this page share one id. Reload and try again.\",\n  \"destination-locked\":\n    \"A locked block is in the way. Unlock it and try again.\",\n  \"invalid-position\": \"That is not somewhere a block can go.\",\n  \"invalid-source\":\n    \"That library entry is missing the details needed to place it.\",\n\n  // From a component's exposure, for the verbs that create one.\n  \"invalid-exposure\":\n    \"One of the values chosen can’t be changed per use. Untick it and try again.\",\n  \"ambiguous-exposure\":\n    \"Two blocks here answer to one name. Rename one and try again.\",\n  \"self-reference\":\n    \"This selection already uses the component being created. Remove that instance first.\",\n  \"not-a-component\": \"That library entry is not a component.\",\n  \"condition-gated\":\n    \"This selection is shown conditionally and holds conditions of its own. Simplify one of them first.\",\n  \"composed-depth\":\n    \"As a component, this selection would nest deeper than the page allows. Select less, or fewer components inside it.\",\n};\n\n/**\n * What to tell an author about a refusal.\n *\n * The `permitted` set is spelled out where the planner supplies one, because\n * \"this block only works inside another one\" sends an author looking while\n * naming the containers tells them where. The refusal carries the set rather\n * than leaving it to be looked up again — `NestingVerdict` says why — so this\n * never asks the rule source a second question.\n *\n * **What the set MEANS depends on the cause**, which is the reading\n * `refusalWording` already takes of the same list. For `not-allowed-in-slot`\n * the planner answers with what the SLOT ACCEPTS — the children it will hold —\n * and for the other two with the CONTAINERS the refused block may sit in.\n * Read as containers either way, a narrowed slot produces \"It belongs inside\n * Heading or Text\" about blocks that are neither containers nor where anything\n * belongs.\n *\n * The joiner follows from that: containers are alternatives an author picks\n * between, and a slot's list is an enumeration of what it holds.\n *\n * Through the SAME prose the drag refusal uses. The set holds registry\n * specifiers, and a namespace wildcard is not a block name: read naively,\n * `core/*` announces that a block \"belongs inside *\".\n */\nexport function compositionRefusalReason(refusal: PlanRefusal): string {\n  const sentence = REFUSAL_COPY[refusal.problem];\n  const permitted = (refusal.permitted ?? []).map(permittedLabel);\n  if (permitted.length === 0) return sentence;\n  return refusal.problem === \"not-allowed-in-slot\"\n    ? `${sentence} It takes ${asPermittedList(permitted, \"and\")}.`\n    : `${sentence} It belongs inside ${asPermittedList(permitted, \"or\")}.`;\n}\n\n/**\n * Whether a string is a cause this vocabulary knows.\n *\n * Derived from the copy map, which is total over {@link PlanProblem}, so this\n * recognises exactly the causes a sentence exists for and cannot drift from\n * them. It exists because a cause can arrive from OUTSIDE the process: a save\n * refused by the server carries its `PlanProblem` on the wire, and the surface\n * that has to phrase it is holding a string rather than a typed union.\n */\nexport function isPlanProblem(value: unknown): value is PlanProblem {\n  return (\n    typeof value === \"string\" &&\n    Object.prototype.hasOwnProperty.call(REFUSAL_COPY, value)\n  );\n}\n","/**\n * Who owns Escape while the editor is on screen.\n *\n * The page builder mounts as a full-screen surface INSIDE an entry form, and\n * the admin binds Escape on that form to \"cancel and go back\". Both use the\n * same shortcut manager, so with nothing claiming Escape for the editor the\n * form's binding wins by default — and an author who pressed Escape over a\n * canvas full of work was navigated away from the entry entirely, discarding\n * every block edit made since the editor was opened. Nothing warned them,\n * because the form was never told the document had changed.\n *\n * ## Why this is a PRIORITY question, not a depth one\n *\n * The shell renders its own `ShortcutProvider`, which the manager resolves to\n * the parent's manager when it sits on the same target — so the editor's\n * layers and the host page's layers are in ONE stack, ordered by\n * `(priority, depth, sequence)`. Depth cannot settle it: the editor's provider\n * takes the parent's depth rather than adding to it, and the host decides how\n * deeply its own shortcuts are scoped, so any depth chosen here can be tied or\n * beaten by a host that nests one scope further. `sequence` — which layer\n * registered later — happens to favour the editor today because the form is on\n * screen before the editor opens, but the manager's own documentation calls\n * equal-depth ordering incidental and says to express real requirements as\n * precedence. So this is precedence, deliberately.\n *\n * ## The editor claims it; a MODAL still outranks the editor\n *\n * Escape's meaning is \"dismiss the innermost thing\", which is why a rule that\n * simply took the key for the canvas would be wrong: with the command palette\n * open, Escape belongs to the palette. Rather than couple to that one\n * component, the claim stands down whenever an open dialog is in the document.\n * Any modal a host adds inherits the same deference, and there is no list to\n * keep in step with the components.\n *\n * ## Where the press STARTED decides what it does\n *\n * Escape moves the canvas selection only when the press starts on the canvas,\n * or with nothing focused at all. Pressed on a control in the inspector or a\n * side panel, it leaves that control instead: focus goes back to the canvas\n * and the selection stays, so the next Escape starts on the canvas and goes up\n * from there.\n *\n * The case that needed it: picking a colour variable closes the picker and\n * hands focus back to the field's button. An author pressing Escape there is\n * done with the panel, and moving the selection under them emptied the very\n * inspector they were working in. Popovers and menus that are still open\n * already answer Escape themselves (they mark it handled, which the shortcut\n * manager honours), so what was left was a press from a panel control with\n * nothing open, and that is the press this rule gives a meaning of its own.\n *\n * Read from the EVENT, never from the page afterwards: by the time a binding\n * runs, a layer that closed on the same keystroke has already moved focus, so\n * where focus is then says nothing about where the press began.\n *\n * @module canvas-escape\n */\n\nimport { isElement, isInput, isTextArea } from \"./dom-kind\";\nimport { CANVAS_FRAME_BOX_ATTRIBUTE } from \"./geometry-dom\";\n\n/** The priority that puts the editor's claim above a host page's bindings. */\nexport const CANVAS_ESCAPE_PRIORITY = 1;\n\n/**\n * Whether a modal is open, and therefore owns Escape.\n *\n * Read from the DOM rather than from editor state, because the components that\n * matter — the command palette today, whatever a host mounts tomorrow — portal\n * to the body and are outside every React tree this could subscribe to. The\n * attribute pair is what the dialog primitive already publishes, so this reads\n * a contract rather than a convention.\n */\nexport function modalIsOpen(root: Document | undefined): boolean {\n  if (root === undefined) return false;\n  return root.querySelector('[role=\"dialog\"][data-state=\"open\"]') !== null;\n}\n\n/**\n * Whether focus is somewhere that Escape means something else.\n *\n * A field's own dismissal — closing a combobox, abandoning an IME composition,\n * reverting an edit in progress — is what Escape means while typing, and\n * clearing the canvas selection out from under it would answer a question the\n * author did not ask.\n *\n * The claim is still made in that case, and that is the point: standing down\n * would let the keystroke fall through to the form's \"cancel and go back\",\n * which is the data loss this module exists to stop. So the answer here decides\n * what Escape DOES, never whether the editor consumes it.\n */\nexport function isTextEntry(element: Element | null): boolean {\n  if (element === null) return false;\n  // By tag rather than by `instanceof`: a field inside a canvas mounted in an\n  // iframe was built by that window, whose constructors are not this one's.\n  if (isTextArea(element)) return true;\n  /*\n   * `closest`, not `isContentEditable`.\n   *\n   * Editability is INHERITED, and a rich-text editor puts focus on whichever\n   * inner node the caret is in rather than on the element carrying the\n   * attribute — so reading the attribute off the focused element alone answers\n   * \"no\" for most of the time an author is actually typing. `closest` follows\n   * the inheritance the same way the browser does.\n   */\n  if (isEditableText(element)) return true;\n  if (!isInput(element)) return false;\n  // Buttons, checkboxes and radios are inputs that nobody types into, and\n  // Escape over one of those is an ordinary \"clear the selection\".\n  return !NON_TEXT_INPUT_TYPES.has(element.type);\n}\n\n/**\n * Whether `contenteditable` makes an element editable, read the way the\n * browser reads the attribute.\n *\n * The NEAREST recognised value decides: a `false` island inside editable text\n * makes a control inside it a control again. The recognised values are ASCII\n * case-insensitive (`TRUE` is `true`), and `plaintext-only` is editable too:\n * it is how the canvas's own line editor is. Any other value is the inherit\n * state, so the walk carries on outwards past it.\n */\nexport function isEditableText(element: Element): boolean {\n  for (\n    let host = element.closest(\"[contenteditable]\");\n    host !== null;\n    host = host.parentElement?.closest(\"[contenteditable]\") ?? null\n  ) {\n    const value = host.getAttribute(\"contenteditable\")?.toLowerCase();\n    if (value === \"\" || value === \"true\" || value === \"plaintext-only\") {\n      return true;\n    }\n    if (value === \"false\") return false;\n  }\n  return false;\n}\n\nconst NON_TEXT_INPUT_TYPES: ReadonlySet<string> = new Set([\n  \"button\",\n  \"checkbox\",\n  \"color\",\n  \"file\",\n  \"image\",\n  \"radio\",\n  \"range\",\n  \"reset\",\n  \"submit\",\n]);\n\n/**\n * Whether a press started inside something floating over the editor: a\n * picker's list, a unit menu, a select's options.\n *\n * Each closes on Escape, and the editor acting on the same press would do two\n * things for one key. Most of them mark the key as handled, which the shortcut\n * manager already honours; this covers every one that does not, by where the\n * press began rather than by a list of components. The wrapper is the one\n * every floating layer of the design system is positioned in, so a new menu\n * inherits the rule.\n */\nfunction inFloatingLayer(element: Element): boolean {\n  return element.closest(\"[data-radix-popper-content-wrapper]\") !== null;\n}\n\n/**\n * Where an Escape press started, and the canvas it may have started on.\n *\n * Both halves come from outside the DOM's present state on purpose: the origin\n * from the keydown itself, and the frame from the editor's own record of the\n * canvas, so the answer cannot depend on what a closing layer did to focus\n * between the keystroke and the rule reading it.\n */\nexport interface EscapePress {\n  /**\n   * The element the keydown was dispatched on, from {@link pressOrigin};\n   * `null` when it was dispatched on no element at all.\n   */\n  readonly origin: Element | null;\n  /**\n   * The frame the canvas is drawn in, or `null` while the canvas shares the\n   * editor's own document and there is no separate place to send focus.\n   */\n  readonly canvasFrame: HTMLIFrameElement | null;\n}\n\n/**\n * The element a keydown started on.\n *\n * The composed path first, because an event leaving an open shadow root is\n * retargeted to its host, and a field inside a custom element would otherwise\n * read as the element around it. Read by node type rather than `instanceof`,\n * since a press on the canvas was built by the frame's window, whose\n * constructors are not this one's.\n */\nexport function pressOrigin(event: Event): Element | null {\n  const path =\n    typeof event.composedPath === \"function\" ? event.composedPath() : [];\n  const first = path[0] ?? event.target;\n  return isElement(first) ? first : null;\n}\n\n/**\n * Whether a press started on the canvas.\n *\n * Three places count. Anything in the frame's own document is the page\n * itself. The box holding the frame counts too: the block toolbar and the\n * canvas's own add buttons are drawn over the page in the editor's document,\n * and they act on what is selected there, so Escape on them moves the\n * selection as it does on the page beneath. And an element holding the frame:\n * the canvas's region takes focus itself while the page is zoomed past it (F6\n * stops there so the keyboard can scroll it), and it is the canvas as much as\n * the page inside it is. The body holds the frame as well, and answers the\n * same through \"nothing focused\".\n */\nfunction startedOnCanvas(\n  origin: Element,\n  canvasFrame: HTMLIFrameElement\n): boolean {\n  if (origin.closest(`[${CANVAS_FRAME_BOX_ATTRIBUTE}]`) !== null) return true;\n  if (origin.contains(canvasFrame)) return true;\n  return origin.ownerDocument === canvasFrame.contentDocument;\n}\n\n/**\n * Whether a press started with nothing focused: the browser then delivers it\n * to the document's body, or to its root element where there is no body.\n */\nfunction startedOnNothing(origin: Element | null): boolean {\n  if (origin === null) return true;\n  const owner = origin.ownerDocument;\n  return origin === owner.body || origin === owner.documentElement;\n}\n\n/** What pressing Escape over the editor should do. */\nexport type EscapeOutcome =\n  | \"defer-to-modal\"\n  | \"leave-to-field\"\n  | \"return-to-canvas\"\n  | \"navigate-selection\";\n\n/**\n * The whole rule, as one decision a test can make without a keyboard.\n *\n * Everything but `\"defer-to-modal\"` is CONSUMED by the editor, and they differ\n * only in what happens afterwards: the focused field or floating layer keeps\n * the key's meaning, focus goes back to the canvas, or the selection moves.\n * Only `\"defer-to-modal\"` declines the key, and it declines to something that\n * is itself dismissing on Escape.\n *\n * **The selection is deliberately not an input.** This answers who OWNS the\n * key, and the editor owns it whether or not a block is selected — an editor\n * that released Escape once the canvas happened to have nothing selected would\n * lose the author's work in exactly the state a click on background produces.\n * What it does with the selection — up to the block holding it, or clear at\n * the top — and whether there is a selection at all are the caller's\n * questions, asked after this one.\n */\nexport function escapeOutcome(\n  root: Document | undefined,\n  press: EscapePress\n): EscapeOutcome {\n  if (modalIsOpen(root)) return \"defer-to-modal\";\n  const { origin, canvasFrame } = press;\n  // A field, or a menu or list floating over the editor: Escape belongs to\n  // that control, and is still consumed so the page cannot take it. A field\n  // on the canvas, such as a block's text being edited in place, is the same:\n  // its own Escape finishes the edit.\n  if (origin !== null && (isTextEntry(origin) || inFloatingLayer(origin))) {\n    return \"leave-to-field\";\n  }\n  // On the canvas, or with nothing focused: the selection moves. Moving it\n  // with nothing selected is a no-op that still consumes the key — which is\n  // the whole point, since an editor that let Escape through there would lose\n  // the author's work in exactly the state where they had clicked away from a\n  // block before pressing it. With no frame there is nowhere separate to send\n  // focus, so every press moves the selection, as it always has.\n  if (\n    canvasFrame === null ||\n    startedOnNothing(origin) ||\n    (origin !== null && startedOnCanvas(origin, canvasFrame))\n  ) {\n    return \"navigate-selection\";\n  }\n  // On a control anywhere else in the editor, with nothing open: the press\n  // leaves the control, and the selection stays for the next one.\n  return \"return-to-canvas\";\n}\n\n/**\n * The attribute the canvas's frame carries while focus has been brought back\n * to it from the keyboard, which the editor's stylesheet draws as a focus\n * outline.\n *\n * An attribute rather than `:focus-visible` because, while focus is inside a\n * frame, the browser matches the frame element only with `:focus-within`, and\n * that holds after a click into the page just as much: drawn from it, every\n * click on a block would show a keyboard outline.\n */\nexport const CANVAS_KEYBOARD_FOCUS_ATTRIBUTE = \"data-nx-keyboard-focus\";\n\n/**\n * Send focus back to the canvas's frame, and show that it went there.\n *\n * Without scrolling, because an author who has scrolled the canvas to the\n * block they are styling would otherwise be thrown back to the frame's top\n * edge. The outline stays while the keyboard works the canvas and goes when\n * focus leaves the frame or a pointer is pressed in it, which is when\n * `:focus-visible` would stop matching too.\n */\nexport function returnFocusToCanvas(canvasFrame: HTMLIFrameElement): void {\n  canvasFrame.focus({ preventScroll: true });\n  // Marked only once focus has really landed: an outline with no focus behind\n  // it would never see the blur that clears it.\n  if (canvasFrame.ownerDocument.activeElement !== canvasFrame) return;\n  if (canvasFrame.hasAttribute(CANVAS_KEYBOARD_FOCUS_ATTRIBUTE)) return;\n  canvasFrame.setAttribute(CANVAS_KEYBOARD_FOCUS_ATTRIBUTE, \"\");\n  const page = canvasFrame.contentDocument;\n  const clear = (): void => {\n    canvasFrame.removeAttribute(CANVAS_KEYBOARD_FOCUS_ATTRIBUTE);\n    canvasFrame.removeEventListener(\"blur\", clear);\n    page?.removeEventListener(\"pointerdown\", clear, true);\n  };\n  canvasFrame.addEventListener(\"blur\", clear);\n  page?.addEventListener(\"pointerdown\", clear, true);\n}\n","/**\n * What the editor's two class surfaces show, and what an edit to them produces.\n *\n * A projection over {@link named-class}, which owns what a class IS. This owns\n * only the authoring questions the engine has no opinion about: which classes a\n * selected node carries, which remain applicable, whether a typed name can\n * become one, and what a rename or a removal leaves behind.\n *\n * The split follows {@link tokens-studio}: rules here, presentation in the\n * panels, so every decision below is testable without a DOM. It also keeps the\n * two surfaces answering from ONE set of rules — a selector that decided\n * applicability differently from the manager would let an author apply a class\n * the manager does not list.\n *\n * ## Nothing here writes\n *\n * Every function returns a new value and stores nothing. Persistence belongs to\n * whoever owns the document, which in the page builder is the section-scoped\n * site-style write this package cannot reach. The same reason the tokens studio\n * lifts its edits.\n *\n * ## The listed set is the set the compiler emits\n *\n * A stored library is not the library that renders. `compilePageCss` bounds it\n * to `MAX_NAMED_CLASSES` in STORED order, then drops entries that are malformed\n * or that reuse a slug or an id an earlier entry already claimed. A surface\n * built on the stored array would therefore offer classes that reach no\n * stylesheet: applying one would change nothing and give no reason why.\n *\n * So {@link siteClasses} reproduces that bound, and every list here derives\n * from it. Repairing an entry the compiler dropped is not this module's job —\n * the compile warnings carry the position and the reason, which is the only\n * place that can distinguish two entries holding the same slug.\n *\n * ## A usage count is a LOWER BOUND, in both directions\n *\n * The counts handed in are read from an index maintained on write, and that\n * index has no concurrency control. It can over-count, and — this is the part\n * that decides the design — it can also UNDER-count: two saves to one document\n * can each plan to remove the other's row, and if both removals land the class\n * keeps rendering with no row left to say so. `class-usage-maintenance` records\n * that case at the point the diff is computed.\n *\n * A zero therefore means \"nothing known\", never \"nothing\". That is why\n * {@link deletionWarning} confirms unconditionally rather than treating zero as\n * permission, and why the filter is named for the absence of EVIDENCE rather\n * than for the absence of usage.\n *\n * @module class-library\n */\nimport {\n  BASE_BREAKPOINT,\n  breakpointContexts,\n  MAX_CLASSES_PER_NODE,\n  MAX_NAMED_CLASSES,\n  MAX_NAMED_CLASS_NAME_LENGTH,\n  NAMED_CLASS_SLUG_RE,\n  STYLE_STATES,\n  compileStyleValues,\n  isPlainRecord,\n  classNameOf,\n  isLook,\n  namedClassesRead,\n  usableNamedClasses,\n  type Declaration,\n  type NamedClass,\n  type NodeStyles,\n  type StyleCompileContext,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * How many documents are KNOWN to reference a class, keyed by class id.\n *\n * Keyed by ID rather than by name for the reason documents are: a rename must\n * not orphan a count, and a name is free to change under it.\n */\nexport type ClassUsageCounts = Readonly<Record<string, number>>;\n\n/**\n * How a usage figure is described, wherever it appears.\n *\n * One vocabulary, derived once. A row saying \"3 known\" beside a confirmation\n * saying the same number may be wrong in either direction is two uncertainty\n * policies for one value, and the shorter one is the one an author reads most.\n * Everything here names the INDEX and claims nothing about usage.\n */\nexport function usageSummary(row: Pick<ClassRow, \"indexedDocuments\">): string {\n  return row.indexedDocuments === 0\n    ? \"Not in index\"\n    : `${row.indexedDocuments} in index`;\n}\n\n/**\n * How many classes the selector offers at once.\n *\n * A library may hold `MAX_NAMED_CLASSES`, and an empty query matches all of\n * them. Rendering that is neither usable — nobody reads two thousand rows —\n * nor cheap, and it puts every one of them in front of an author who is\n * typing to narrow. The remainder is REPORTED rather than dropped quietly:\n * a list that silently stops is a list an author believes is complete.\n */\nexport const MAX_SELECTOR_OPTIONS = 50;\n\n/** Which classes the manager lists. */\nexport type ClassFilter = \"all\" | \"not-in-index\" | \"on-this-page\";\n\n/**\n * A class as the surfaces name it, carrying nothing about where it is used.\n *\n * Separate from {@link ClassRow} so that a list which has not been given usage\n * data cannot present a fabricated zero. A selector offering classes knows\n * nothing about the index, and a type that made it say `indexedDocuments: 0`\n * would have it contradict the manager for the same class.\n */\nexport interface ClassChoice {\n  /** Stable identity, which documents reference and rename never changes. */\n  id: string;\n  /** The CSS-facing slug, as stored. */\n  slug: string;\n  /** The emitted class name, which is what appears in a page's markup. */\n  className: string;\n}\n\n/** A class together with what is known about the documents using it. */\nexport interface ClassRow extends ClassChoice {\n  /**\n   * Documents the usage index records for this class.\n   *\n   * Named for the INDEX rather than for usage, because that is all it can\n   * report. The index loses rows to interleaved saves and retains them when a\n   * removal fails, so it errs in both directions — this is neither a count nor\n   * a bound on one. Absent means zero, because a filter has no third answer to\n   * give, and nothing may read that zero as permission.\n   */\n  indexedDocuments: number;\n  /** Whether the document currently open applies this class to any node. */\n  onThisPage: boolean;\n}\n\n/**\n * The classes the compiler will actually emit rules for, in precedence order.\n *\n * The bound is the compiler's, read through the compiler's own function: the\n * cap slices the STORED order, before any sorting, and counts shared styles and\n * looks each under a cap of its own, so a tail entry is never offered as though\n * applying it would do something, and a look past the shared styles' cap still\n * is.\n */\nexport function usableSiteClasses(\n  library: readonly NamedClass[]\n): NamedClass[] {\n  // The engine's own read: shared styles and looks each under their cap.\n  return usableNamedClasses(namedClassesRead(library));\n}\n\nexport function siteClasses(library: readonly NamedClass[]): ClassChoice[] {\n  return usableSiteClasses(library).map(entry => ({\n    id: entry.id,\n    slug: entry.slug,\n    // A look's class under its own prefix, as the compiler writes it.\n    className: classNameOf(entry),\n  }));\n}\n\n/**\n * What is known about one class's usage, as a number a filter can read.\n *\n * Read as an OWN property. A class id is any string the library accepted, which\n * includes `constructor` and `toString`, and an ordinary record answers those\n * from its prototype — the count would arrive as a function, compare false\n * against every threshold, and quietly hide the class from the very filter that\n * exists to surface it. A value that is not a usable count is treated as\n * nothing known, which is safe here only because nothing decides on zero.\n */\nfunction indexedUsage(usage: ClassUsageCounts, classId: string): number {\n  if (!Object.hasOwn(usage, classId)) return 0;\n  const count = usage[classId];\n  // A document count is a whole number of documents. A fraction is as much a\n  // sign of a corrupted row as a negative one, and admitting it would put a\n  // number on screen that cannot describe anything the index counted.\n  if (!Number.isInteger(count) || count < 0) return 0;\n  return count;\n}\n\n/**\n * The path handed to the compiler for a SUMMARY compile.\n *\n * Short, constant, and deliberately not the class's own identity. `basePath` is\n * only ever repeated into diagnostics, and this module discards them — but it is\n * also charged against the style-issue budget, and an exhausted budget refuses\n * the WHOLE map rather than the property that exhausted it.\n *\n * So path length decides what compiles. Measured on one map of 150 long unknown\n * keys beside one valid `color`, with a 128-character slug:\n *\n *     compileStyleValues(values, `class:${slug}/hover/md`) -> 0 declarations\n *     compileStyleValues(values, \"class\")                  -> 1 declaration\n *\n * `compilePageCss` compiles the same class under `/classes/<position>/styles/...`,\n * so a longer path here would let the panel report \"nothing\" for styling the page\n * does emit — a disagreement produced by the diagnostic string rather than by the\n * styles. Kept shorter than the page's own path, so this can only ever be at\n * least as permissive as what the visitor gets.\n */\nconst SUMMARY_PATH = \"class\";\n\n/**\n * Every (state, breakpoint) pair this class stores values under.\n *\n * The WALK, separated from the judgement below, because a nested loop carrying\n * three different reasons to skip a pair is the shape the cognitive gate exists\n * to catch. Iterating `STYLE_STATES` rather than the record's own keys keeps\n * the walk to states the engine defines.\n */\nexport function storedContexts(\n  styles: NodeStyles\n): { state: string; breakpoint: string; values: Record<string, unknown> }[] {\n  const pairs: {\n    state: string;\n    breakpoint: string;\n    values: Record<string, unknown>;\n  }[] = [];\n  for (const state of STYLE_STATES) {\n    const byBreakpoint: unknown = styles[state];\n    // GUARDED at both levels, the way `compilePageCss` guards the same two.\n    //\n    // The type says these are records; the stored document only promises to be\n    // JSON. A persisted `{ base: { base: null } }` passes `usableSiteClasses`,\n    // and `Object.keys(null)` throws — which took the whole class manager down\n    // rather than hiding one row. Three shapes reached it: a null state map, a\n    // null values map under any state, and a null base that went on to\n    // `compileStyleValues` and threw inside the engine instead.\n    //\n    // `isPlainRecord` rather than a null check, because it is the predicate the\n    // compiler already uses for exactly this and it also excludes the shapes\n    // that do not throw and still style nothing — a number, a string, an array.\n    // Skipping silently is right HERE and not in the compiler: this is a\n    // summary of what a class does, and a context that writes no rule does\n    // nothing. `compilePageCss` is where the author is told why.\n    if (!isPlainRecord(byBreakpoint)) continue;\n    for (const breakpoint of Object.keys(byBreakpoint)) {\n      const values: unknown = byBreakpoint[breakpoint];\n      if (!isPlainRecord(values)) continue;\n      pairs.push({ state, breakpoint, values });\n    }\n  }\n  return pairs;\n}\n\n/**\n * How many of those pairs are a place the class behaves DIFFERENTLY.\n *\n * Three things disqualify a pair, and each is a separate fact rather than a\n * step in a walk: it is the base the row already shows; the compiler emits no\n * context for that breakpoint, so it writes no rule; or it sets nothing.\n */\nfunction contextsElsewhere(\n  styles: NodeStyles,\n  emitted: ReadonlySet<string>,\n  context?: StyleCompileContext\n): number {\n  return storedContexts(styles).filter(\n    pair =>\n      !(pair.state === \"base\" && pair.breakpoint === BASE_BREAKPOINT) &&\n      emitted.has(pair.breakpoint) &&\n      // COMPILED, not counted. A stored key is not a declaration: a property\n      // the catalog does not define, or a value whose grammar it refuses,\n      // writes nothing — so counting keys claimed \"1 more elsewhere\" for\n      // styling the page does not have, which is the same class of lie as\n      // counting a breakpoint the site has since deleted. The one implementation\n      // of \"stored values become declarations\" is asked instead.\n      compileStyleValues(\n        pair.values,\n        SUMMARY_PATH,\n        undefined,\n        undefined,\n        undefined,\n        { mayFetchUrl: context?.mayFetchUrl }\n      ).declarations.length > 0\n  ).length;\n}\n\n/**\n * What a class DOES, as the declarations it writes.\n *\n * A row named the class and counted its documents and never said what it was\n * for, which is the half of the complaint a list cannot answer by being better\n * organised.\n *\n * COMPILED, never formatted here. `compileStyleValues` is the one\n * implementation of \"stored style values become CSS declarations\" — it knows\n * which properties the engine writes, how a token reference becomes a `var()`,\n * and which values it refuses. A second formatter in this panel would agree\n * with it on the day it was written and describe a different stylesheet\n * afterwards.\n *\n * ONE state at ONE breakpoint, and a count of the rest. `NodeStyles` is states\n * by breakpoints, both sparse, and a row has space for neither the product nor\n * a fair sample of it. Showing the base silently would misdescribe a class\n * whose real behaviour is responsive; saying how much is not shown is the\n * honest half of the same sentence.\n */\nexport function classDeclarations(\n  styles: NodeStyles,\n  /**\n   * The context the PAGE is compiled with, so the summary describes the same\n   * stylesheet the visitor gets.\n   *\n   * Two things come from it and neither can be guessed here. `mayFetchUrl` is\n   * the site's remote-host policy, and compiling without it lists a\n   * declaration the real compile drops. `breakpoints` decides which contexts\n   * are emitted at all, so a class holding styles for a breakpoint the site\n   * has since deleted writes no rule — counting that key would claim behaviour\n   * the page does not have.\n   *\n   * Absent is coherent rather than a gap: `breakpointContexts` answers with\n   * the base context alone, which is what a site with no configured\n   * breakpoints emits.\n   */\n  context?: StyleCompileContext\n): { shown: readonly Declaration[]; elsewhere: number } {\n  const base: unknown = styles.base?.[BASE_BREAKPOINT];\n  const shown =\n    // The same guard the walk below uses, for the same reason: a stored `null`\n    // here reached `Object.hasOwn` inside `compileStyleValues` and threw.\n    !isPlainRecord(base)\n      ? []\n      : compileStyleValues(\n          base,\n          SUMMARY_PATH,\n          undefined,\n          undefined,\n          undefined,\n          { mayFetchUrl: context?.mayFetchUrl }\n        ).declarations;\n  const emitted = new Set(\n    breakpointContexts(context?.breakpoints).map(entry => entry.id)\n  );\n  const elsewhere = contextsElsewhere(styles, emitted, context);\n  return { shown, elsewhere };\n}\n\n/**\n * Every declaration a class writes, in every state and at every breakpoint it\n * stores values for, compiled as the summary above compiles its base.\n *\n * What a search by property or value reads: a class that sets a padding only\n * on hover, or only on phones, still sets a padding.\n */\nexport function everyClassDeclaration(\n  styles: NodeStyles,\n  context?: StyleCompileContext\n): Declaration[] {\n  return storedContexts(styles).flatMap(\n    pair =>\n      compileStyleValues(\n        pair.values,\n        SUMMARY_PATH,\n        undefined,\n        undefined,\n        undefined,\n        { mayFetchUrl: context?.mayFetchUrl }\n      ).declarations\n  );\n}\n\n/**\n * Every class the site renders, in the order that decides precedence.\n *\n * Ordered by the library's own precedence rather than by name, because that\n * order is what resolves a conflict between two classes on one node — sorting\n * the list alphabetically for display would show an override relationship that\n * is not the one the page renders.\n */\nexport function classRows(\n  library: readonly NamedClass[],\n  usage: ClassUsageCounts,\n  documentClassIds: readonly string[]\n): ClassRow[] {\n  const onPage = new Set(documentClassIds);\n  return siteClasses(library).map(choice => ({\n    ...choice,\n    indexedDocuments: indexedUsage(usage, choice.id),\n    onThisPage: onPage.has(choice.id),\n  }));\n}\n\n/**\n * The rows one filter shows.\n *\n * \"No known usage\" asks the index and \"on this page\" asks the open document,\n * and they are different questions rather than two views of one: a class\n * applied only by an unpublished draft is referenced while appearing on no page\n * an author has open. Keeping them separate is what lets the manager report an\n * absence of evidence without contradicting the canvas.\n */\nexport function filterClassRows(\n  rows: readonly ClassRow[],\n  filter: ClassFilter\n): ClassRow[] {\n  if (filter === \"not-in-index\") {\n    return rows.filter(row => row.indexedDocuments === 0);\n  }\n  if (filter === \"on-this-page\") return rows.filter(row => row.onThisPage);\n  return [...rows];\n}\n\n/**\n * The class ids on a node that the compiler will actually read.\n *\n * The engine applies the first `MAX_CLASSES_PER_NODE` and warns about the rest,\n * so a node holding more is a node whose tail styles nothing. `styleSubjectFor`\n * bounds its own read the same way; this is the same bound, not a second one.\n */\nfunction readableNodeClassIds(nodeClassIds: readonly string[]): string[] {\n  return nodeClassIds.slice(0, MAX_CLASSES_PER_NODE);\n}\n\n/**\n * The classes a node carries, in library order.\n *\n * Ordered by the library and not by the node's own array, because two nodes\n * listing the same classes in a different order resolve identically — showing\n * them in the stored order would imply a precedence the renderer does not\n * apply.\n *\n * An id the site does not render is dropped rather than shown as an unnamed\n * chip, whether the library never held it or the compiler declined it. A chip\n * for one would offer to edit something no page can display.\n */\nexport function appliedClasses(\n  library: readonly NamedClass[],\n  nodeClassIds: readonly string[]\n): ClassChoice[] {\n  const applied = new Set(readableNodeClassIds(nodeClassIds));\n  return siteClasses(library).filter(choice => applied.has(choice.id));\n}\n\n/**\n * The classes a node could still be given, narrowed to those `matches` keeps.\n *\n * The match is the caller's: the picker asks the Shared styles tab's own\n * search (name, class name, property or value), so a style is found the same\n * way in both places.\n */\nexport function applicableClasses(\n  library: readonly NamedClass[],\n  nodeClassIds: readonly string[],\n  matches: (choice: ClassChoice) => boolean\n): ClassChoice[] {\n  /*\n   * The WHOLE stored array, deliberately not the readable prefix that\n   * {@link appliedClasses} uses. The two answer different questions: that one\n   * asks what the page renders, this one asks what applying would ADD. A class\n   * stored past the cap renders nothing and yet is already on the node, so\n   * offering it would append a second copy of an id the node already holds.\n   */\n  const applied = new Set(nodeClassIds);\n  return siteClasses(library)\n    .filter(choice => !applied.has(choice.id))\n    .filter(matches);\n}\n\n/**\n * One row the selector offers: a shared style the block may wear. Styles are\n * made from a block (\"Save as shared style…\"), never typed into being here, so\n * an empty one cannot be created by a stray Enter.\n */\nexport type ClassOption = {\n  readonly kind: \"apply\";\n  readonly choice: ClassChoice;\n};\n\nexport interface SelectorOptions {\n  /** The rows to draw, in the order Enter would take them. */\n  readonly options: ClassOption[];\n  /**\n   * Applicable classes NOT offered, because the list is capped.\n   *\n   * Reported so the surface can say so. A truncated list that says nothing\n   * reads as \"these are all of them\", which is the one thing it is not.\n   */\n  readonly hidden: number;\n}\n\n/** What the selector offers: the styles `matches` keeps, capped. */\nexport function selectorOptions(\n  library: readonly NamedClass[],\n  nodeClassIds: readonly string[],\n  matches: (choice: ClassChoice) => boolean\n): SelectorOptions {\n  const applicable = applicableClasses(library, nodeClassIds, matches);\n  const shown = applicable.slice(0, MAX_SELECTOR_OPTIONS);\n  const options: ClassOption[] = shown.map(choice => ({\n    kind: \"apply\",\n    choice,\n  }));\n  return { options, hidden: applicable.length - shown.length };\n}\n\n/** Why a name cannot become a class. */\nexport type NameRefusal =\n  | \"empty\"\n  | \"too-long\"\n  | \"not-a-slug\"\n  | \"already-taken\"\n  | \"library-full\";\n\n/**\n * A name's verdict, carrying the slug to store when there is one.\n *\n * The accepted slug is RETURNED rather than left for the caller to re-derive.\n * This function trims before it validates, so a caller that stored the typed\n * text after being told it was acceptable would persist a value the engine's\n * own grammar rejects — a class held in the library that no selector ever\n * matches. One normalization, owned here.\n */\nexport type ClassNameOutcome =\n  | { readonly ok: true; readonly slug: string }\n  | { readonly ok: false; readonly refusal: NameRefusal };\n\n/**\n * Whether the library has room for another class.\n *\n * Exported because two surfaces need the answer and only one of them is naming\n * a class. `newClassName` refuses a name when there is no room; the manager\n * panel has to decide whether to tell an author a class can be made at all,\n * and inferring that from an empty drawn list is wrong in exactly the case\n * that matters — `siteClasses` drops entries the compiler cannot use, so a\n * library of malformed entries draws nothing while every slot is taken.\n *\n * Counts the STORED entries, which is what capacity is about. The drawn list\n * is a different question and answering one with the other is the bug. Only\n * shared styles count: looks come from code under a cap of their own, and a\n * new class here is always a shared style.\n */\nfunction classLibraryHasRoom(library: readonly NamedClass[]): boolean {\n  return library.filter(entry => !isLook(entry)).length < MAX_NAMED_CLASSES;\n}\n\n/**\n * Whether a typed name can become a new class, and what to store if it can.\n *\n * The grammar is the engine's, not a second one: a slug reaches a CSS selector,\n * and a name this module accepted but the compiler refused would be stored as a\n * class no renderer ever puts on an element.\n *\n * A collision is refused rather than merged. Two classes with one slug emit the\n * same selector, so the compiler drops the later one outright and the author\n * would be left with an entry that styles nothing.\n */\nexport function newClassName(\n  name: string,\n  library: readonly NamedClass[]\n): ClassNameOutcome {\n  const slug = name.trim();\n  if (slug.length === 0) return { ok: false, refusal: \"empty\" };\n  if (slug.length > MAX_NAMED_CLASS_NAME_LENGTH) {\n    return { ok: false, refusal: \"too-long\" };\n  }\n  if (!NAMED_CLASS_SLUG_RE.test(slug)) {\n    return { ok: false, refusal: \"not-a-slug\" };\n  }\n  if (library.some(entry => entry.slug === slug)) {\n    return { ok: false, refusal: \"already-taken\" };\n  }\n  /*\n   * Capacity last, so a name that is ALSO malformed or taken reports the\n   * problem the author can act on rather than one about the library.\n   *\n   * A class added to a full library becomes the first entry outside the\n   * compiler's prefix, so it emits no rule — and `checkStoredClasses` refuses\n   * the save outright rather than storing it quietly. Accepting the name here\n   * would offer an author a class that cannot be saved OR rendered.\n   */\n  if (!classLibraryHasRoom(library)) {\n    return { ok: false, refusal: \"library-full\" };\n  }\n  return { ok: true, slug };\n}\n\n/**\n * Whether a class may take a new name, and what to store if it may.\n *\n * The same grammar, and the same collision rule, except that a class keeping\n * its own slug is not a collision with itself — an author opening a rename and\n * confirming it unchanged is not an error.\n */\nexport function renamedClassName(\n  name: string,\n  classId: string,\n  library: readonly NamedClass[]\n): ClassNameOutcome {\n  const others = library.filter(entry => entry.id !== classId);\n  return newClassName(name, others);\n}\n\n/** Why a class cannot go on a node. */\nexport type ApplyRefusal = \"node-full\";\n\n/**\n * Whether a node can take one more class at all.\n *\n * Asked BEFORE a class exists, which is the case {@link withClassApplied}\n * cannot answer: creating a class and putting it on the selected node is one\n * intent, and the id it would use does not exist yet. Without this the create\n * path would reach a host that must either append a reference validation\n * rejects, or rediscover this same limit on its own.\n */\nexport function nodeHasRoom(nodeClassIds: readonly string[]): boolean {\n  return nodeClassIds.length < MAX_CLASSES_PER_NODE;\n}\n\n/**\n * How many stored references the page does not apply.\n *\n * Zero for every node in a valid document. A legacy or hand-edited one can\n * store more, and those references style nothing while still being on the\n * node — a state the author has no way to discover from the canvas, and one\n * that makes a removal look as though it applied a class it never touched.\n */\nexport function unappliedNodeClassCount(\n  nodeClassIds: readonly string[]\n): number {\n  return Math.max(nodeClassIds.length - MAX_CLASSES_PER_NODE, 0);\n}\n\n/** A node's new class ids, or why the class cannot go on it. */\nexport type ClassApplyOutcome =\n  | { readonly ok: true; readonly classIds: string[] }\n  | { readonly ok: false; readonly refusal: ApplyRefusal };\n\n/**\n * A node's class ids with one added, or a refusal.\n *\n * Appended rather than inserted in library order. The stored order does not\n * decide precedence, so rewriting it would produce a document change that\n * renders identically — a diff an author cannot explain and a version history\n * entry that means nothing.\n *\n * A node already holding `MAX_CLASSES_PER_NODE` classes REFUSES rather than\n * appending. The compiler reads only that many and strict validation rejects\n * the document outright, so an appended reference would be recorded as an\n * application that neither renders nor can be published — the worst of the\n * three outcomes, because the editor would show it as done.\n *\n * A class the node already carries is not a refusal: nothing is wrong, and the\n * answer is simply the ids unchanged.\n */\nexport function withClassApplied(\n  nodeClassIds: readonly string[],\n  classId: string\n): ClassApplyOutcome {\n  if (nodeClassIds.includes(classId)) {\n    return { ok: true, classIds: [...nodeClassIds] };\n  }\n  if (nodeClassIds.length >= MAX_CLASSES_PER_NODE) {\n    return { ok: false, refusal: \"node-full\" };\n  }\n  return { ok: true, classIds: [...nodeClassIds, classId] };\n}\n\n/** A node's class ids with one removed. */\nexport function withClassRemoved(\n  nodeClassIds: readonly string[],\n  classId: string\n): string[] {\n  return nodeClassIds.filter(id => id !== classId);\n}\n\n/** What an author is told before a class is deleted. */\nexport interface DeletionWarning {\n  /** Documents the index records. Not a count, and not a bound on one. */\n  indexedDocuments: number;\n  /**\n   * Whether there is a number worth naming in the prompt.\n   *\n   * This chooses the WORDING, never whether to ask. False means the index holds\n   * no row, which is not the same as there being no document.\n   */\n  hasIndexedUsage: boolean;\n  /**\n   * Always. Typed as the literal so no caller can make it conditional without\n   * the change being visible in this file.\n   */\n  requiresConfirmation: true;\n}\n\n/**\n * What deleting a class would cost, in the terms the confirmation states.\n *\n * Deleting a class REMOVES it from every document that references it, rather\n * than leaving those nodes pointing at a definition that no longer exists.\n * Detaching instead — copying the styles onto each node so the appearance\n * survives — is a separate action an author asks for explicitly, because a\n * delete that silently preserved the look would be a delete the author cannot\n * see the effect of.\n *\n * The confirmation is unconditional. Skipping it when the count is zero would\n * put the whole weight of an irreversible edit on the one value the index is\n * known to produce wrongly: a class live on the site reads as zero whenever two\n * concurrent saves each removed the other's row. Zero is the cheapest case to\n * confirm and the only one that can be silently wrong, so it is the last one\n * that should be waved through.\n */\nexport function deletionWarning(\n  row: Pick<ClassRow, \"indexedDocuments\">\n): DeletionWarning {\n  return {\n    indexedDocuments: row.indexedDocuments,\n    hasIndexedUsage: row.indexedDocuments > 0,\n    requiresConfirmation: true,\n  };\n}\n","/**\n * The site's colours in named groups and in the order its authors put them:\n * what the Design panel's Colours tab lists, what every colour picker lists,\n * and the moves that change them.\n *\n * Display only. A colour's group is a label, as its name is, and the order is\n * a list of identities on the set. Neither reaches the site's CSS or changes a\n * code name, so a colour moved anywhere is the same variable it was.\n *\n * Pure, so the order the panel and the pickers show is one answer, tested\n * apart from either.\n *\n * @module colour-groups\n */\nimport {\n  tokenIdentity,\n  type SiteToken,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\n\n/** What a group is called where no colour before it names one. */\nconst DEFAULT_COLOUR_GROUP = \"Colours\";\n\n/** One named group and its colours, by identity, in order. */\nexport interface ColourGroup {\n  readonly name: string;\n  readonly identities: readonly string[];\n}\n\nfunction isColour(token: SiteToken): boolean {\n  return token.kind === \"color\";\n}\n\n/**\n * The site's colours, by identity, in the order they are stored: those the\n * site's order names first, in that order, then the rest in the set's own\n * order. An identity the order names that the site no longer has is skipped.\n * The groups are read from this; what is listed is `colourOrder`.\n */\nfunction storedOrder(tokens: SiteTokenSet | undefined): string[] {\n  const colours = (tokens?.tokens ?? []).filter(isColour).map(tokenIdentity);\n  const present = new Set(colours);\n  const named = (tokens?.order ?? []).filter(identity => present.has(identity));\n  const first = new Set(named);\n  return [...new Set([...named, ...colours.filter(id => !first.has(id))])];\n}\n\n/**\n * The colours in their groups, in order. A colour's group is its own, else\n * the group of the colour before it, so a colour added with none joins the\n * group it is listed in. Groups are listed in the order their colours are.\n */\nexport function colourGroups(tokens: SiteTokenSet | undefined): ColourGroup[] {\n  const byIdentity = new Map(\n    (tokens?.tokens ?? []).map(token => [tokenIdentity(token), token])\n  );\n  const groups: { name: string; identities: string[] }[] = [];\n  let current = DEFAULT_COLOUR_GROUP;\n  for (const identity of storedOrder(tokens)) {\n    const own = byIdentity.get(identity)?.group;\n    current = own ?? current;\n    const group =\n      groups.find(candidate => candidate.name === current) ??\n      pushed(groups, { name: current, identities: [] });\n    group.identities.push(identity);\n  }\n  return groups;\n}\n\n/**\n * The site's colours, by identity, in the order the panel lists them: group\n * by group. Every colour picker lists them in this order, derived from the\n * groups, so a colour the stored order misses sits in both where its group\n * puts it.\n */\nexport function colourOrder(tokens: SiteTokenSet | undefined): string[] {\n  return colourGroups(tokens).flatMap(group => group.identities);\n}\n\nfunction pushed<T>(list: T[], item: T): T {\n  list.push(item);\n  return item;\n}\n\n/**\n * The set laid out as the groups say: each colour carries the group it is\n * listed in, written only where it differs, and the order is every colour in\n * turn. Nothing but those display fields changes.\n */\nfunction laidOut(\n  tokens: SiteTokenSet,\n  groups: readonly ColourGroup[]\n): SiteTokenSet {\n  const groupOf = new Map<string, string>();\n  for (const group of groups) {\n    for (const identity of group.identities) groupOf.set(identity, group.name);\n  }\n  return {\n    ...tokens,\n    tokens: tokens.tokens.map(token => {\n      const group = isColour(token)\n        ? groupOf.get(tokenIdentity(token))\n        : undefined;\n      return group === undefined || token.group === group\n        ? token\n        : { ...token, group };\n    }),\n    order: groups.flatMap(group => group.identities),\n  };\n}\n\n/** Where a colour is listed: its group's place and its own within it. */\nfunction placeOf(\n  groups: readonly ColourGroup[],\n  identity: string\n): { group: number; at: number } | undefined {\n  for (const [group, candidate] of groups.entries()) {\n    const at = candidate.identities.indexOf(identity);\n    if (at !== -1) return { group, at };\n  }\n  return undefined;\n}\n\n/** The groups with one colour taken out. */\nfunction without(\n  groups: readonly ColourGroup[],\n  identity: string\n): ColourGroup[] {\n  return groups.map(group => ({\n    ...group,\n    identities: group.identities.filter(id => id !== identity),\n  }));\n}\n\n/** The groups with a colour put into one of them at a place. */\nfunction inserted(\n  groups: readonly ColourGroup[],\n  identity: string,\n  group: number,\n  at: number\n): ColourGroup[] {\n  return groups.map((candidate, index) =>\n    index === group\n      ? {\n          ...candidate,\n          identities: [\n            ...candidate.identities.slice(0, at),\n            identity,\n            ...candidate.identities.slice(at),\n          ],\n        }\n      : candidate\n  );\n}\n\n/**\n * The set with a colour moved one place up (-1) or down (1). Past the top\n * of its group it joins the end of the group above, and past the end the\n * start of the group below; at the very top or end the set is returned as\n * it was.\n */\nexport function moveColour(\n  tokens: SiteTokenSet,\n  identity: string,\n  by: -1 | 1\n): SiteTokenSet {\n  const groups = colourGroups(tokens);\n  const place = placeOf(groups, identity);\n  if (place === undefined) return tokens;\n  const size = groups[place.group]?.identities.length ?? 0;\n  const at = place.at + by;\n  const rest = without(groups, identity);\n  if (at >= 0 && at < size) {\n    return laidOut(tokens, inserted(rest, identity, place.group, at));\n  }\n  const next = place.group + by;\n  const target = rest[next];\n  if (target === undefined) return tokens;\n  return laidOut(\n    tokens,\n    inserted(rest, identity, next, by === -1 ? target.identities.length : 0)\n  );\n}\n\n/**\n * The set with the variable at a place put into a named group, where it is a\n * colour and a group is named; otherwise the set as it was. A colour added\n * from a group's add row joins that group, an empty new one included.\n */\nexport function inColourGroup(\n  tokens: SiteTokenSet,\n  at: number,\n  group: string | undefined\n): SiteTokenSet {\n  const token = tokens.tokens[at];\n  if (group === undefined || token === undefined || !isColour(token)) {\n    return tokens;\n  }\n  const next = [...tokens.tokens];\n  next[at] = { ...token, group };\n  return { ...tokens, tokens: next };\n}\n\n/** The set with a colour moved to the end of a group. */\nexport function moveColourToGroup(\n  tokens: SiteTokenSet,\n  identity: string,\n  group: string\n): SiteTokenSet {\n  return placeColour(tokens, identity, group, undefined);\n}\n\n/**\n * The set with a colour put into a group: before another colour in it, as a\n * drag drops it on that colour's row, or at its end where `before` is\n * absent. A group no colour is in yet is made with this one in it.\n */\nexport function placeColour(\n  tokens: SiteTokenSet,\n  identity: string,\n  group: string,\n  before: string | undefined\n): SiteTokenSet {\n  const groups = colourGroups(tokens);\n  if (before === identity || placeOf(groups, identity) === undefined) {\n    return tokens;\n  }\n  const rest = without(groups, identity);\n  const index = rest.findIndex(candidate => candidate.name === group);\n  const target =\n    index === -1 ? [...rest, { name: group, identities: [] }] : rest;\n  const at = index === -1 ? target.length - 1 : index;\n  const members = target[at]?.identities ?? [];\n  const position = before === undefined ? -1 : members.indexOf(before);\n  return laidOut(\n    tokens,\n    inserted(target, identity, at, position === -1 ? members.length : position)\n  );\n}\n\n/** The set with a group renamed on every colour listed in it. */\nexport function renameColourGroup(\n  tokens: SiteTokenSet,\n  from: string,\n  to: string\n): SiteTokenSet {\n  const groups = colourGroups(tokens);\n  if (!groups.some(group => group.name === from)) return tokens;\n  return laidOut(\n    tokens,\n    groups.map(group => (group.name === from ? { ...group, name: to } : group))\n  );\n}\n\n/**\n * The set with a group gone, its colours joining the end of the group above,\n * or the start of the group below where it is the first. The only group is\n * left in place, since a colour is always listed in one.\n */\nexport function removeColourGroup(\n  tokens: SiteTokenSet,\n  name: string\n): SiteTokenSet {\n  const groups = colourGroups(tokens);\n  const index = groups.findIndex(group => group.name === name);\n  const removed = groups[index];\n  if (removed === undefined || groups.length < 2) return tokens;\n  const into = index === 0 ? 1 : index - 1;\n  const merged = groups.map((group, at) => {\n    if (at !== into) return group;\n    return {\n      ...group,\n      identities:\n        index === 0\n          ? [...removed.identities, ...group.identities]\n          : [...group.identities, ...removed.identities],\n    };\n  });\n  return laidOut(\n    tokens,\n    merged.filter((_, at) => at !== index)\n  );\n}\n\n/**\n * The site's colour order with a copy listed right after the colour it\n * copies, where the order names that colour; otherwise nothing, and the copy\n * is listed where its group puts it.\n */\nexport function orderWithCopy(\n  tokens: SiteTokenSet,\n  token: SiteToken,\n  copies: readonly SiteToken[]\n): { order?: readonly string[] } {\n  const copy = copies[0];\n  // A colour removed before may have left the copy's free name in the order:\n  // it is listed once, here.\n  const order =\n    copy === undefined ? tokens.order : withoutIdentity(tokens.order, copy);\n  const at = order?.indexOf(tokenIdentity(token)) ?? -1;\n  if (order === undefined || at === -1 || copy === undefined) return {};\n  return {\n    order: [\n      ...order.slice(0, at + 1),\n      tokenIdentity(copy),\n      ...order.slice(at + 1),\n    ],\n  };\n}\n\n/** The colour order without a variable's identity, where it has one. */\nexport function withoutIdentity(\n  order: readonly string[] | undefined,\n  token: SiteToken\n): readonly string[] | undefined {\n  return order?.filter(identity => identity !== tokenIdentity(token));\n}\n\n/**\n * The colour order with one identity renamed in its place, listed there\n * once: a colour removed before may have left the new name in the order.\n */\nexport function renamedInOrder(\n  order: readonly string[] | undefined,\n  from: string,\n  to: string\n): readonly string[] | undefined {\n  return order\n    ?.filter(identity => identity !== to)\n    .map(identity => (identity === from ? to : identity));\n}\n","/**\n * The colour view of a stored style value, and the choices a control may offer\n * over it.\n *\n * Pure, for the reason `style-numeric.ts` is: which tokens a leaf may hold,\n * what a value resolves to, and whether a pair has enough contrast are all\n * derivation, and a jsdom test of the rendered field cannot separate a correct\n * answer from a plausible wrong one — both draw a swatch with a colour in it.\n *\n * ## A colour is a PROJECTION over the string, never a model of it\n *\n * A `color` leaf carries no rules of its own, but the value it holds is far\n * wider than a hex: `checkColorValue` accepts the CSS named colours, the system\n * colours, `transparent`, `currentcolor`, the CSS-wide keywords, and sixteen\n * functions including `oklch()`, `color-mix()`, `light-dark()` and `var()` — as\n * well as a `{ $token }` reference, which is a record and nonetheless a scalar.\n *\n * A picker that MODELLED the value as RGBA could represent one of those and\n * would write the rest away the moment it opened. So the text field remains the\n * control and the swatch, the picker and the readout are affordances layered on\n * it, each answering `undefined` rather than guessing.\n *\n * ## Three questions, three domains, and they genuinely differ\n *\n * Conflating them would be the tempting simplification and the wrong one:\n *\n * - what may be STORED is `checkColorValue`'s question, and the write path\n *   already asks it;\n * - what a contrast figure may be computed from is `parseColor`'s, which reads\n *   hex and `rgb()`/`rgba()` ONLY and says why: a figure from a colour it\n *   misread \"is worse than no figure, because it is a number somebody will act\n *   on\";\n * - what the PICKER can open on is narrower still, because it is seeded from a\n *   hex.\n *\n * Nothing here restates any of them. The engine is asked in every case.\n *\n * ## What a swatch may be painted with, and why it is narrower than CSS\n *\n * A swatch is painted only with a colour this module resolved ITSELF — a token\n * looked up in the site's table, or a literal `parseColor` reads. That is\n * narrower than what a browser can paint, and the exclusion is principled\n * rather than incidental: every value it leaves out means \"resolve this\n * somewhere else\", and the inspector is not that somewhere.\n *\n * `var(--site-color-primary)` painted into the panel resolves against the\n * PANEL's custom properties rather than the canvas's, so it lands on a\n * different colour or on none. `currentcolor` takes the panel's own text\n * colour. `inherit` takes the swatch's parent. Each would show an author a\n * colour their page does not have, which is the one failure a colour control\n * must not have. Telling those apart from `oklch()` and the named colours —\n * which a browser would paint correctly — needs a grammar this package has no\n * business owning, so the honest line is drawn at what can be resolved here.\n *\n * The cost is a named colour showing no swatch. The value is still displayed,\n * still typeable and never rewritten, which is the cheap direction to be wrong\n * in.\n *\n * @module style-colour\n */\n\nimport {\n  checkContrast,\n  emitTokenBlocks,\n  isPlainRecord,\n  isStyleLeaf,\n  isTokenRef,\n  leafAcceptsValue,\n  locateNode,\n  parseColor,\n  resolveSiteTokens,\n  STYLE_CATALOG,\n  styleUnionVariant,\n  tokenCustomProperty,\n  tokenDisplayLabel,\n  trimCssWhitespace,\n  tokenIdentity,\n  type BlockNode,\n  type ContrastResult,\n  type Rgb,\n  type NodeStyles,\n  type SiteToken,\n  type SiteTokenSet,\n  type TokenKind,\n  type TokenMode,\n  type StyleLeaf,\n  type StyleValue,\n  type UnionShape,\n} from \"@nextlyhq/blocks-engine\";\nimport { toHex } from \"@nextlyhq/ui/color\";\n\nimport { colourOrder } from \"../panels/design/colour-groups\";\nimport {\n  lengthFamilyOf,\n  type LengthFamily,\n} from \"../panels/design/tokens-studio\";\n\nimport { CSS_NUMBER } from \"./style-numeric\";\n\n/**\n * One site variable a control may offer, in the forms it is needed in.\n *\n * Every kind, not only colours: a font size, a spacing step and a shadow are\n * offered through this same record, so \"which variables does the site have\n * here\" is answered once for every field. The swatch fields are filled for a\n * colour and left `undefined` for the rest.\n *\n * The split between {@link identity} and {@link name} is the whole point of the\n * type and is not a convenience. A stored `{ $token }` holds the IDENTITY:\n * `emitTokenBlocks` writes each token's custom property from\n * `tokenCustomProperty(tokenIdentity(token), prefix)`, while the compiler turns\n * a reference into `var(...)` from the stored string verbatim, with no lookup\n * against the table. So the two agree only when the stored string is the\n * identity — and after a rename an identity and a name differ.\n *\n * Storing the name instead would compile to a custom property nothing declares.\n * That invalidates the declaration rather than reporting, so the page keeps\n * rendering with the style missing and nothing says what happened: exactly the\n * failure `SiteToken.id` was added to prevent, reintroduced by the control that\n * writes the reference.\n */\nexport interface SiteVariable {\n  /** What a reference STORES, and what a rename never changes. */\n  readonly identity: string;\n  /** What the author reads and edits. Free to change. */\n  readonly name: string;\n  /**\n   * What the token is CALLED where an author picks it: the label they gave\n   * it, else words made from its name (\"Brand\" for `color.brand`), as the\n   * Variables tab shows it.\n   */\n  readonly label: string;\n  /** Its light and dark values as swatches paint them. See {@link colourPairOf}. */\n  readonly pair: ColourPairValues;\n  /** What the token holds, so a leaf can be asked whether it admits one. */\n  readonly kind: TokenKind;\n  /** The literal this token holds in the mode asked for, as the site recorded it. */\n  readonly value: string;\n  /**\n   * The colour a preset swatch may be PAINTED with, or `undefined` when this\n   * package cannot resolve one.\n   *\n   * Carried rather than left to the call site, because a token's value is a\n   * string like any other and may be `var(--brand)`, `currentcolor` or a\n   * CSS-wide keyword. Painted raw into a preset button those resolve against\n   * the INSPECTOR rather than the canvas — the exact failure\n   * {@link colourHexOf} exists to prevent for the main swatch, arrived at by a\n   * second route. Resolving here means both swatches answer the same way.\n   */\n  readonly swatch: string | undefined;\n}\n\n/** A colour variable's two values, resolved for painting, or `undefined` each. */\nexport interface ColourPairValues {\n  readonly light: string | undefined;\n  readonly dark: string | undefined;\n}\n\n/**\n * A colour variable's light and dark values as a swatch may paint them.\n *\n * A token with no dark value shows its light one for dark, because that is\n * what the page does: no dark declaration is written for it. Resolved with an\n * empty table, for the reason {@link siteVariableOf} gives.\n */\nexport function colourPairOf(token: SiteToken): ColourPairValues {\n  return {\n    light: colourHexOf(token.values.light, undefined),\n    dark: colourHexOf(token.values.dark ?? token.values.light, undefined),\n  };\n}\n\n/**\n * Which mode's value a token resolves to on the canvas right now.\n *\n * The site sheet writes every dark value under\n * `@media (prefers-color-scheme:dark)`, so a viewer whose device prefers dark\n * sees the dark value with nothing else having to happen. A control resolving\n * `values.light` regardless would then paint a swatch and report a ratio for a\n * colour the canvas is not showing — the one failure this module exists to\n * prevent, reached through the mode rather than through the notation.\n *\n * The sheet also honours a `data-nx-theme` marker, which the editor does not\n * set on its canvas, so the device preference is the whole answer here.\n */\nexport function activeTokenMode(prefersDark: boolean): TokenMode {\n  return prefersDark ? \"dark\" : \"light\";\n}\n\n/**\n * The variables a control may offer at this leaf: a colour field's colours, a\n * font size's type sizes and lengths, a shadow's shadows.\n *\n * The first two halves of the filter are the ENGINE's answer rather than this\n * module's.\n * Which kinds a leaf admits is `leaf.tokenKinds`, taken from the catalog, so a\n * leaf that admits no token offers no picker without a rule being written here;\n * and a token's own `kind` is what the site recorded. A control that offered a\n * token the write path then refused would be the visible half of a drift, and\n * the invisible half is a token wrongly withheld.\n *\n * `undefined` tokens means the question was never asked — the host supplied no\n * table — and answers empty, which is the same shape a site with no colour\n * tokens produces. The two are deliberately not distinguished HERE: what\n * differs is what the panel should SAY about an empty list, and that is the\n * panel's to decide from the same `undefined` it already has.\n *\n * The light-mode value is what a swatch carries, because `values.light` is the\n * one a token is guaranteed to have and the one a document with no mode\n * resolves. A dark-only preview would be a second question and is not this\n * control's.\n */\nexport function variablesFor(\n  leaf: StyleLeaf,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode = \"light\"\n): readonly SiteVariable[] {\n  return offeredTokens(tokens, mode).filter(\n    token =>\n      leaf.tokenKinds.includes(token.kind) &&\n      // Each field its own family: a font size the type sizes, a line height\n      // the line heights, margin, padding and gap the spacing steps, a radius\n      // the radii. A type size and its line height share a name, and a\n      // spacing step and a radius often do (\"Md\"), so a list of every length\n      // named one variable twice; any other length takes every length.\n      madeFor(token, leaf) &&\n      // A variable whose value the field would refuse, such as a negative\n      // length for a padding or 1.5 for an opacity, is not offered: picked,\n      // it would be stored and then dropped by the browser with no refusal.\n      valueFits(token, leaf)\n  );\n}\n\n/**\n * The variables a picker lists, without the colours the site hides (its\n * unused built-in colours, while it hides them), keeping the one the field\n * holds, so a field never stops naming its own value.\n */\nexport function shownVariables(\n  offered: readonly SiteVariable[],\n  hidden: ReadonlySet<string>,\n  held: string | null\n): readonly SiteVariable[] {\n  if (hidden.size === 0) return offered;\n  return offered.filter(\n    variable =>\n      variable.kind !== \"color\" ||\n      variable.identity === held ||\n      !hidden.has(variable.identity)\n  );\n}\n\n/**\n * Whether the leaf accepts this variable's value, in the mode asked for, by\n * the engine's own rule for the leaf, the one a typed value goes through.\n *\n * Kept wherever this cannot judge: a value through a function (`calc()`,\n * `clamp()`, `var()`) resolves only on the page, and a value whose kind is not\n * the leaf's own (a length offered on a line height's number form, which the\n * field writes as its length form) is the other form's to judge.\n */\nfunction valueFits(token: SiteVariable, leaf: StyleLeaf): boolean {\n  const folded = FOLDED_ARMS.get(leaf);\n  const text = trimCssWhitespace(token.value);\n  // A number variable holds its number as text; a number form takes a number.\n  const asNumber = CSS_NUMBER.test(text) ? Number(text) : text;\n  // A folded field's forms: the variable is judged by the form the ENGINE\n  // picks for its value, the one the compiler will judge it by, so a font\n  // weight holding \"bold\" is judged by the keyword form and one holding 700\n  // by the number form's 1 to 1000.\n  const arm =\n    folded === undefined\n      ? judgedAt(token.kind, leaf.kind)\n        ? leaf\n        : undefined\n      : armForValue(folded, token.kind, asNumber);\n  if (arm === undefined) return true;\n  // A length or a number through a function resolves only on the page.\n  if (arm.kind !== \"cssValue\" && throughFunction(token.value)) return true;\n  return leafAcceptsValue(arm, arm.kind === \"number\" ? asNumber : text);\n}\n\n/**\n * The form of a folded field that judges a value: the engine's own choice of\n * the union's arm for it, when the field's union is known, else the form a\n * variable of its kind is written in.\n */\nfunction armForValue(\n  folded: { readonly arms: readonly StyleLeaf[]; readonly union?: UnionShape },\n  kind: TokenKind,\n  value: unknown\n): StyleLeaf | undefined {\n  if (folded.union !== undefined) {\n    const index = styleUnionVariant(folded.union, value);\n    const chosen = index === undefined ? undefined : folded.union.of[index];\n    if (chosen !== undefined && isStyleLeaf(chosen)) return chosen;\n  }\n  return folded.arms.find(each => judgedAt(kind, each.kind));\n}\n\n/**\n * Whether a value goes through a function (`clamp()`, `calc()`, `min()`,\n * `var()`), whose result this cannot judge before the page draws it.\n */\nfunction throughFunction(value: string): boolean {\n  return value.includes(\"(\");\n}\n\n/** Whether a variable of this kind is written in the form this leaf judges. */\nfunction judgedAt(kind: TokenKind, leafKind: StyleLeaf[\"kind\"]): boolean {\n  switch (leafKind) {\n    case \"dimension\":\n      return kind === \"dimension\";\n    case \"number\":\n      return kind === \"number\" || kind === \"fontWeight\";\n    case \"color\":\n      return kind === \"color\";\n    case \"cssValue\":\n      return true;\n    default:\n      return false;\n  }\n}\n\n/**\n * The forms behind a leaf drawn as one field over a union, by the leaf\n * {@link foldedLeaf} made for them.\n */\nconst FOLDED_ARMS = new WeakMap<\n  StyleLeaf,\n  { readonly arms: readonly StyleLeaf[]; readonly union?: UnionShape }\n>();\n\n/**\n * One leaf for a field drawn over a union's forms (a line height's number or\n * length, a font weight's keyword or number): it takes every token kind any\n * form takes, and each variable offered there is judged by the form its kind\n * is written in, not by whichever form the field happens to show.\n */\nexport function foldedLeaf(\n  arms: readonly StyleLeaf[],\n  union?: UnionShape\n): StyleLeaf {\n  const [first] = arms;\n  if (first === undefined) throw new Error(\"a folded field has no forms\");\n  const tokenKinds = [...new Set(arms.flatMap(arm => arm.tokenKinds))];\n  const leaf: StyleLeaf = { ...first, tokenKinds };\n  // With the union they came from, when known, so a variable is judged by\n  // the arm the engine picks for its value.\n  FOLDED_ARMS.set(leaf, union === undefined ? { arms } : { arms, union });\n  return leaf;\n}\n\n/** Whether a variable belongs to the family this leaf's field offers. */\nfunction madeFor(token: SiteVariable, leaf: StyleLeaf): boolean {\n  const family = fieldFamilyOf(leaf.cssProperty);\n  const own = lengthFamilyOf(token);\n  // A line height that is a plain number is made for line height alone:\n  // offered on an opacity field, H1's line height says nothing true there.\n  if (own === \"line-height\" && token.kind === \"number\") return own === family;\n  return family === undefined || own === family;\n}\n\n/**\n * The family of length variables a CSS property's field offers, or\n * `undefined` for a field that offers every variable of its kinds.\n *\n * By the property the leaf writes, so every side of a margin or a padding and\n * every corner of a radius is answered by one rule.\n */\nfunction fieldFamilyOf(cssProperty: string): LengthFamily | undefined {\n  if (cssProperty === \"font-size\" || cssProperty === \"line-height\") {\n    return cssProperty;\n  }\n  if (/^(margin|padding)(-|$)/.test(cssProperty)) return \"spacing\";\n  if (/(^|-)gap$/.test(cssProperty)) return \"spacing\";\n  if (/radius$/.test(cssProperty)) return \"radius\";\n  return undefined;\n}\n\n/**\n * Every token the canvas will resolve, in the mode it is showing.\n *\n * THE one projection, and everything else here reads it. Which tokens exist,\n * which of them the canvas actually declares, and what each resolves to are one\n * question asked once — so the list a picker offers, the table a stored\n * reference is looked up in, and the colours a contrast figure is measured from\n * cannot disagree. Each of those was a separate search before, and each was\n * wrong in a different way.\n *\n * `resolveSiteTokens` FIRST, because that is what the renderer does:\n * `PageRenderer` compiles with `resolveSiteTokens(siteInput?.tokens)`, which\n * layers the engine's own defaults under the site's overrides. A site that\n * defines nothing still emits `color.text`, `color.primary` and the rest, so a\n * picker reading the raw override set offered none of them and could not\n * resolve a document that referenced one.\n *\n * `undefined` still means the question was never asked and answers empty — NOT\n * the defaults. A host that has not said what the site holds has not said that\n * it holds the defaults either.\n */\nfunction offeredTokens(\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): readonly SiteVariable[] {\n  if (tokens === undefined) return [];\n  const byMode = cache.get(tokens) ?? new Map<TokenMode, SiteVariable[]>();\n  const hit = byMode.get(mode);\n  if (hit !== undefined) return hit;\n  const resolved = resolveSiteTokens(tokens);\n  const built = inColourOrder(\n    emittableTokens(resolved, mode).map(token => siteVariableOf(token, mode)),\n    colourOrder(resolved)\n  );\n  byMode.set(mode, built);\n  cache.set(tokens, byMode);\n  return built;\n}\n\n/**\n * The variables with their colours in the site's colour order, the one the\n * Design panel lists them in; every other variable keeps its place.\n */\nfunction inColourOrder(\n  variables: readonly SiteVariable[],\n  order: readonly string[]\n): SiteVariable[] {\n  const rank = new Map(order.map((identity, at) => [identity, at]));\n  const colours = variables\n    .filter(variable => variable.kind === \"color\")\n    .sort(\n      (a, b) =>\n        (rank.get(a.identity) ?? order.length) -\n        (rank.get(b.identity) ?? order.length)\n    );\n  let next = 0;\n  return variables.map(variable =>\n    variable.kind === \"color\" ? (colours[next++] ?? variable) : variable\n  );\n}\n\n/**\n * Built projections, by the set they came from.\n *\n * Held because building one emits every token individually to ask the engine\n * whether it accepts it, and a control rebuilds on every render of every colour\n * field. Keyed on the set's identity, which is safe for the same reason the\n * engine's own `memoizeTokenLookup` is: these are immutable props, so a set\n * that is the same object is the same data.\n */\nconst cache = new WeakMap<SiteTokenSet, Map<TokenMode, SiteVariable[]>>();\n\n/**\n * The tokens the canvas will actually declare a custom property for.\n *\n * `emitTokenBlocks` drops a token for more reasons than are obvious from\n * outside, and a partial copy of that list is worse than none: it reads as\n * complete, agrees with the engine on the cases someone thought of, and offers\n * a token the canvas silently drops for any case they did not — which stores a\n * reference to a property nothing declares and loses the style with no symptom.\n */\nfunction emittableTokens(\n  set: SiteTokenSet,\n  mode: TokenMode\n): readonly SiteToken[] {\n  const seen = new Set<string>();\n  const emittable: SiteToken[] = [];\n  for (const token of set.tokens) {\n    // The REFUSAL decides who takes the property, because it is the emitter's\n    // own rule for the same question: the engine skips a refused token before\n    // it reaches the collision check, and writes an accepted one even when its\n    // kind is wrong. Asking the kind here instead would drop a token the engine\n    // wrote, hand its property to the token the engine REFUSED as a collision,\n    // and offer that one — painted with its own colour, resolving to the\n    // other's. Measured: `color.primary-dark` holding `16px` and\n    // `color-primary.dark` holding `#123456` compose one property, the engine\n    // writes `16px`, and the picker offered `#123456`.\n    if (!written(token)) continue;\n    // Which of two ACCEPTED tokens actually gets the property is the one thing\n    // the emitter cannot be asked, because both are individually fine and only\n    // their order decides. `tokenCustomProperty` composes the key, so the\n    // normalisation is still the engine's; only first-one-wins is repeated.\n    //\n    // The prefix is omitted deliberately: it is the same string in front of\n    // every property, so it can neither create a collision nor prevent one, and\n    // the site's real prefix is resolved by a function the engine keeps private.\n    const property = tokenCustomProperty(tokenIdentity(token), \"\");\n    if (seen.has(property)) continue;\n    seen.add(property);\n    // Asked only once the property is claimed. A kind mismatch is mode-local\n    // and does NOT stop the engine writing the declaration, so it withholds the\n    // token from this picker without releasing the property to anything else.\n    if (!kindMatches(token, mode)) continue;\n    emittable.push(token);\n  }\n  return emittable;\n}\n\n/**\n * Whether the emitter writes anything at all for this token.\n *\n * The REFUSALS, and the reason they are a separate question from the kind\n * check: an unusable name or id, a missing or non-string light value, a value\n * that is not safe CSS, a value that would make the page fetch a file. Each is\n * scanned across BOTH mode values and skips the whole token, so a dark `url(…)`\n * leaves the light value with no custom property either.\n *\n * ASKED, by emitting the token and seeing whether anything came out, rather\n * than by restating that list here where it would drift from the engine's. The\n * OUTPUT is read rather than the issue list, because a future refusal that\n * forgot to report would otherwise arrive as an accepted token declaring\n * nothing.\n *\n * The set's prefix is deliberately not passed. It cannot decide any of these\n * rules, and supplying an unusable one would add an issue about the SET to\n * every token in it — turning one bad prefix into an empty picker.\n */\nfunction written(token: SiteToken): boolean {\n  return emitTokenBlocks({ tokens: [token] }, \":root\").css !== \"\";\n}\n\n/**\n * Whether the value this mode resolves is the kind the token claims.\n *\n * The other verdict the emitter reaches, and the one with the narrower scope.\n * A mismatch is reported and the value written ANYWAY — deliberately, because\n * refusing it would cost the author the token on a judgement the engine is not\n * certain enough to act on — so it costs only the mode whose value is wrong,\n * and never the token's claim on its custom property.\n *\n * It still withholds the token here, because the browser drops the declaration\n * where the token is USED rather than where it is defined: a colour token\n * holding `16px` is written, resolves, and does nothing, so a picker offering\n * it hands over a reference with no symptom to follow.\n *\n * Asked by emitting the active value alone and reading the silence. Every other\n * objection belongs to {@link written}, which runs first — and the emptiness\n * check is kept even so, cheap and over a value already in hand, so that a\n * caller reaching here in the other order gets a wrong answer rather than a\n * confident misattribution.\n */\nfunction kindMatches(token: SiteToken, mode: TokenMode): boolean {\n  const active = token.values[mode] ?? token.values.light;\n  const alone = emitTokenBlocks(\n    { tokens: [{ ...token, values: { light: active } }] },\n    \":root\"\n  );\n  return alone.css !== \"\" && alone.issues.length === 0;\n}\n\n/**\n * What to CALL a token in a list where two of them may share a name.\n *\n * A rename FREEZES the old name as the identity and moves only the label, so\n * nothing stops a second token taking the name the first one left — and both go\n * on emitting, because they compose their properties from identities that still\n * differ. Two choices then arrive with one label, and if their colours match or\n * neither resolves to a swatch there is nothing at all to tell them apart. The\n * author picks one and the document stores an identity they could not have\n * predicted.\n *\n * Qualified only where the collision is REAL, so the ordinary list stays\n * readable: a name unique among the tokens offered beside it is shown as the\n * author wrote it, and the identity appears only when it is the sole thing that\n * distinguishes two entries.\n *\n * Judged against the list the reader is actually looking at rather than the\n * whole site, because that is where the ambiguity exists. A token qualified for\n * a collision the reader cannot see would be explaining a distinction that is\n * not on screen.\n */\nexport function variableLabel(\n  token: SiteVariable,\n  among: readonly SiteVariable[]\n): string {\n  const shared = among.some(\n    other => other.label === token.label && other.identity !== token.identity\n  );\n  return shared ? `${token.label} (${token.identity})` : token.label;\n}\n\n/**\n * One site token in the forms a control needs it in.\n *\n * Shared by every reader rather than written at each, so the identity rule is\n * applied once: a second copy is one edit from storing the NAME, which compiles\n * to a custom property nothing declares and loses the style with no symptom.\n */\nfunction siteVariableOf(token: SiteToken, mode: TokenMode): SiteVariable {\n  // `light` is required and `dark` is not, so a token defined only for light\n  // resolves to it in either mode — which is what the canvas does too: no dark\n  // declaration is emitted for it, so the light one goes on applying.\n  const value = token.values[mode] ?? token.values.light;\n  return {\n    identity: tokenIdentity(token),\n    name: token.name,\n    label: tokenDisplayLabel(token),\n    pair: colourPairOf(token),\n    kind: token.kind,\n    value,\n    // Resolved with an EMPTY table, which is what stops this recursing: a token\n    // whose value is itself a reference would otherwise re-enter the lookup that\n    // is building this record. Unresolvable then means unpainted, which is the\n    // honest answer for a value this package cannot follow.\n    swatch: colourHexOf(value, undefined),\n  };\n}\n\n/**\n * The token a stored reference names, or `undefined` when the site defines\n * none by that identity.\n *\n * Looked up by identity because that is what the reference holds. A site that\n * renamed the token still answers, and answers with its CURRENT name — which is\n * what makes a renamed token readable in the panel rather than showing the\n * label it carried when the reference was written.\n *\n * `undefined` for a reference to a token this site does not define. That is a\n * warning rather than an error in the engine's own issue table, so the value\n * goes on compiling and the control must go on showing it.\n */\nexport function variableFor(\n  identity: string,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode = \"light\"\n): SiteVariable | undefined {\n  // The OFFERED projection, not the raw set. Searching the raw set resolved a\n  // reference the canvas never declares — an imported document naming a token\n  // the emitter rejects painted its value anyway — and, for two identities that\n  // collide, showed the loser while the page resolves the winner's declaration.\n  return offeredTokens(tokens, mode).find(token => token.identity === identity);\n}\n\n/**\n * The channels a stored colour resolves to, or `undefined` when nothing here\n * can read it.\n *\n * The one place a value becomes channels, so the swatch, the picker seed and\n * the contrast readout cannot disagree about what a value IS — they differ only\n * in what they do with the answer. A token is resolved through the table first,\n * so a reference is as readable as the literal it points at; everything else is\n * handed to the engine.\n *\n * A non-string that is not a token reference — an object at a scalar position\n * from an import or the API — is refused here rather than coerced, for the\n * reason `measurementOf` refuses one: a control that offered to edit it would\n * be offering to replace it with something else entirely.\n */\nfunction colourChannelsOf(\n  value: StyleValue | undefined,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): Rgb | undefined {\n  const literal = resolvedColourOf(value, tokens, mode);\n  return literal === undefined ? undefined : parseColor(literal);\n}\n\n/**\n * The literal CSS colour a stored value denotes, as far as this package can\n * resolve it.\n *\n * A token reference becomes the colour the site's table holds for it. A string\n * is already a literal and is returned as written — including the spellings\n * `parseColor` cannot read, because whether a value can be MEASURED is a\n * different question from what it says, and the two have different callers.\n *\n * Not exported: every caller wants one of the two narrower answers below, and a\n * third caller taking the raw literal would be a fourth domain to keep straight.\n */\nfunction resolvedColourOf(\n  value: StyleValue | undefined,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): string | undefined {\n  if (typeof value === \"string\") return value;\n  // The ENGINE's own test for a reference, which is also what\n  // {@link colourShowable} routes on — so what counts as a token here and what\n  // the panel sends to a colour control cannot drift apart.\n  if (isTokenRef(value)) {\n    return variableFor(value.$token, tokens, mode)?.value;\n  }\n  return undefined;\n}\n\n/**\n * The hex a stored colour denotes, or `undefined` when nothing here can read it.\n *\n * ONE function for the swatch, the picker seed and the contrast readout, rather\n * than one named for each. They are three uses of a single question — what hex\n * is this value — and giving each its own function would be three expressions\n * that agree today and drift apart silently, because each looks correct on its\n * own. A use that genuinely diverges gets its own function THEN, when there is\n * a difference to express.\n *\n * Composed as hex from the channels rather than passed through as written, and\n * that is what makes the module note's rule hold by construction rather than by\n * a check that could be forgotten: `var()`, `currentcolor` and the CSS-wide\n * keywords all fail to become channels, so none of them can reach a `style`\n * attribute through here and resolve against the panel instead of the canvas.\n */\nexport function colourHexOf(\n  value: StyleValue | undefined,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode = \"light\"\n): string | undefined {\n  const channels = colourChannelsOf(value, tokens, mode);\n  return channels === undefined ? undefined : hexOf(channels);\n}\n\n/**\n * The engine's channels as the hex notation the picker reads and writes.\n *\n * THE ONE PLACE THE TWO SCALES MEET, and the reason it is a function rather\n * than an expression at each call site. `@nextlyhq/blocks-engine`'s `Rgb` is\n * 0-255 and `@nextlyhq/ui`'s is [0, 1] — two types with the same name, both in\n * scope in this file. `toHex` CLAMPS to [0, 1], so handing it the engine's\n * shape does not fail: every channel above 1 becomes 255 and the answer is\n * `#ffffff`, silently, for every colour but black. A scale factor written twice\n * is one edit away from that.\n *\n * Alpha crosses as it is, since both packages already carry it as [0, 1], and\n * `toHex` omits the pair at 1 so an opaque colour comes back in the six-digit\n * form an author typed.\n */\nfunction hexOf(rgb: Rgb): string {\n  return toHex({ r: rgb.r / 255, g: rgb.g / 255, b: rgb.b / 255 }, rgb.a);\n}\n\n/**\n * Whether a colour control can show this stored value at all.\n *\n * A colour surface has two shapes — a literal string it puts in a text field,\n * and a `{ $token }` reference it names — plus the unset case. Anything else is\n * a value no colour control can represent: an object at a scalar position from\n * an import or the API, or a number. Those keep the panel's own read-only\n * surface, which shows the value and offers to clear it, rather than being\n * projected to an empty field that reads as unset while the value goes on\n * compiling.\n *\n * Asked HERE rather than in the panel so that the routing question and the\n * resolution below cannot disagree about what a colour value is.\n */\nexport function colourShowable(value: StyleValue | undefined): boolean {\n  return value === undefined || typeof value === \"string\" || isTokenRef(value);\n}\n\n/**\n * Which side of a contrast pair a leaf sits on, or `undefined` when it sits on\n * neither.\n *\n * Read from the leaf's own `cssProperty` rather than from a list of catalog\n * keys, which is what makes it cover `linkColor` and `linkColorHover` — both of\n * which write `color`, at ` a` and ` a:hover` — without naming them, and what\n * keeps a sixth colour property working with no edit here.\n *\n * `border-color` is deliberately neither. A border is not text and has no\n * background of its own in this pairing, so reporting it against the block's\n * background would answer a question nobody asked with a threshold that does\n * not apply to it.\n */\nexport function contrastRoleOf(\n  leaf: StyleLeaf\n): \"foreground\" | \"background\" | undefined {\n  if (leaf.kind !== \"color\") return undefined;\n  if (leaf.cssProperty === \"color\") return \"foreground\";\n  if (leaf.cssProperty === \"background-color\") return \"background\";\n  return undefined;\n}\n\n/**\n * The catalog property holding the other half of this leaf's contrast pair, or\n * `undefined` when it has none.\n *\n * FOUND in the catalog rather than named here. Writing `\"backgroundColor\"` as a\n * string would be this package asserting a catalog key it does not own — the\n * proxy `derived-checks.md` warns about — and it would go on compiling after a\n * rename while quietly pairing against nothing. Searching for the leaf that\n * emits the partner CSS property asks the structural question instead.\n *\n * Only a leaf with no `descendant` is eligible. `linkColor` emits `color` at\n * ` a`, so a search that ignored the selector could pair the block's background\n * against a link's colour, or return `linkColor` as the partner OF the\n * background — reporting a ratio for two things that are not drawn on top of\n * each other.\n */\nexport function contrastPartnerOf(leaf: StyleLeaf): string | undefined {\n  const role = contrastRoleOf(leaf);\n  if (role === undefined) return undefined;\n  const wanted = role === \"foreground\" ? \"background-color\" : \"color\";\n  const entries = STYLE_CATALOG as unknown as readonly {\n    property: string;\n    shape: StyleLeaf;\n  }[];\n  const found = entries.find(candidate =>\n    emitsContrastPartner(candidate.shape, wanted)\n  );\n  return found?.property;\n}\n\n/**\n * Whether a leaf is the one a contrast pair should read its partner from.\n *\n * Exported so the descendant rule can be OBSERVED. Inside\n * {@link contrastPartnerOf} it is invisible: `color` precedes `linkColor` in\n * `STYLE_CATALOG`, so the search returns the right property by array order\n * whether or not the selector is considered, and removing the rule changes no\n * result. A guard nothing can see is one a later edit removes as redundant.\n *\n * The rule itself is worth keeping despite that. Three catalog entries emit\n * `color` and two of them attach to ` a` and ` a:hover`, so the correct answer\n * depends on catalog ORDER unless the selector is read — and order is not\n * something this package should be relying on.\n *\n * A leaf with a descendant styles something INSIDE the block. A block's\n * background and a link's colour are not drawn on top of one another in any\n * way this pairing models, so a ratio between them describes nothing.\n */\nexport function emitsContrastPartner(\n  leaf: StyleLeaf,\n  cssProperty: string\n): boolean {\n  return (\n    leaf.kind === \"color\" &&\n    leaf.cssProperty === cssProperty &&\n    leaf.descendant === undefined\n  );\n}\n\n/**\n * How a foreground fares against a background, or `undefined` when either\n * cannot be read.\n *\n * The verdict is the ENGINE's — `checkContrast` — and is never recomputed here.\n * A contrast ratio is a property of two colours rather than of this panel, and a\n * second implementation would drift from the one the compiler and the validator\n * already answer with, silently, because both spellings look correct. What this\n * adds is only the resolution step in front of it, so a pair written as tokens\n * is judged rather than declined: both sides go through\n * {@link colourChannelsOf} first, which is the same resolution the swatch used.\n *\n * `undefined` propagates rather than being softened, and the caller is expected\n * to render NOTHING for it. That is the engine's own reasoning applied one\n * level up: a ratio computed from a colour that was misread, or defaulted, is a\n * number an author will act on. There is no honest approximation of a contrast\n * against `var(--brand)`, whose value is not known until the page renders.\n *\n * Measured against the LIGHT mode value of any token involved, because that is\n * the mode a document with no mode resolves. A site whose dark values differ\n * has a second answer this does not give.\n */\nexport function contrastOf(\n  foreground: StyleValue | undefined,\n  background: StyleValue | undefined,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode = \"light\"\n): ContrastResult | undefined {\n  // Through the same function the swatch is painted from, so a pair the panel\n  // drew two swatches for is a pair this can measure — and a value that shows\n  // no swatch shows no figure. Asking `parseColor` separately here would be a\n  // second answer to what a value resolves to, and the two would disagree first\n  // on tokens, where one of them consults the table and the other does not.\n  const fg = colourHexOf(foreground, tokens, mode);\n  const back = colourChannelsOf(background, tokens, mode);\n  if (fg === undefined || back === undefined) return undefined;\n  // A TRANSLUCENT background has no contrast this can compute, because what\n  // shows through it is not known here. `checkContrast` composites the\n  // background over WHITE, which is a reasonable default for a page and wrong\n  // for a block sitting on another block, on a site background, or on a dark\n  // canvas — and it fails in the direction that matters: white text on\n  // `rgba(0,0,0,.5)` reports as PASSING after white compositing while\n  // rendering nearly invisible over a dark backdrop. Withheld rather than\n  // reported, for the same reason the engine withholds a figure for a colour it\n  // cannot read.\n  //\n  // A translucent FOREGROUND is fine and is not refused: it composites over the\n  // background, which is a colour this does know.\n  if (back.a < 1) return undefined;\n  return checkContrast(fg, hexOf(back));\n}\n\n/**\n * Catalog properties whose value changes what colour actually reaches the eye.\n *\n * A contrast figure is about two colours drawn on top of each other. Each of\n * these puts something else between them or over them: a background image or\n * gradient covers the background colour, `opacity` and `filter` change both,\n * and `mixBlendMode` makes the result depend on what is underneath the node\n * entirely. A ratio computed from the two colour properties alone is then a\n * number about a rendering that does not happen — black text on `#ffffff` with\n * an opaque black gradient over it reports 21:1 and renders black on black.\n *\n * A list rather than a catalog-derived set, and the honest reason is that the\n * catalog does not record this: nothing marks a property as pixel-altering, so\n * there is no structural question to ask. It is therefore a floor rather than a\n * proof — a property added later that also obscures will not appear here until\n * someone adds it — and it errs toward WITHHOLDING, which is the safe direction\n * for a figure an author acts on.\n */\nconst OBSCURING_PROPERTIES: readonly string[] = [\n  \"background\",\n  \"backgroundGradient\",\n  \"opacity\",\n  \"filter\",\n  \"mixBlendMode\",\n  // An INSET shadow is painted over the background and can replace the colour\n  // behind the text entirely — black text on `#ffffff` under an opaque black\n  // inset shadow reports 21:1 and renders black on black. Counted whether or\n  // not the value says `inset`, because telling the two apart means reading\n  // the grammar of a shadow, and a `cssValue` leaf is validated for SYNTAX\n  // only: the catalog does not decide what a shadow means, so neither can\n  // this. An outer shadow therefore withholds a verdict it need not, which is\n  // the direction everything else in this list errs in.\n  \"boxShadow\",\n];\n\n/**\n * The obscuring properties whose effect reaches every DESCENDANT.\n *\n * A subset, because most of the list above is local: an ancestor's background\n * or gradient is painted BEHIND this node and stops mattering the moment this\n * node paints an opaque one of its own, and a shadow is drawn within the box\n * that declares it. These three are different — `opacity` and `filter`\n * composite the whole rendered subtree, and `mixBlendMode` makes it depend on\n * whatever lies beneath the ancestor — so both of the colours a control is\n * comparing arrive at the eye altered, and the ratio between the two stored\n * values describes a rendering that does not happen.\n *\n * Split from the list rather than reusing it whole, because applying the local\n * entries to ancestors would withhold a verdict for a background nothing can\n * see, on almost every page: a section with a background colour is the ordinary\n * case, and every control inside it would go quiet.\n */\nconst SUBTREE_OBSCURING_PROPERTIES: readonly string[] = [\n  \"opacity\",\n  \"filter\",\n  \"mixBlendMode\",\n];\n\n/**\n * The property standing between this pair, or `undefined` when none is set.\n *\n * Takes a READER rather than the stored values, so the caller keeps ownership\n * of which node, state and breakpoint is being asked about — the same address\n * the control is reading its own value at — and this stays a pure question\n * about a set of property names.\n */\nexport function contrastObscuredBy(\n  valueAt: (property: string) => StyleValue | undefined\n): string | undefined {\n  return OBSCURING_PROPERTIES.find(property => valueAt(property) !== undefined);\n}\n\n/**\n * The property standing between a pair anywhere on this node, or `undefined`.\n *\n * Every state and every breakpoint, not the one address being edited. A base\n * `backgroundGradient` goes on covering the background while a hover rule sets\n * only the two colours, so an address-scoped look sees no gradient and reports\n * a ratio for pixels the gradient hides — the guard failing OPEN, which is the\n * one direction it must not fail in.\n *\n * This OVER-withholds, and that is the deliberate trade: a gradient set only at\n * a narrow breakpoint suppresses the verdict at every width. Answering exactly\n * needs `styleOrigin`, which has already settled tier order, both breakpoint\n * axes, states and specificity — and needs a trace of compiled declarations\n * that nothing supplies to this panel. Between a verdict that is sometimes\n * absent and a verdict that is sometimes wrong, this takes the first.\n *\n * A named class carrying one of these is still not seen, for the same reason,\n * and that limit is not closed here. Nor is a stored breakpoint the site no\n * longer defines: its values never compile, so counting them withholds a\n * verdict that would have been correct. Both err the same way as the rest of\n * this function, which is why neither is treated as urgent.\n */\nexport function contrastObscuredIn(\n  styles: NodeStyles | undefined\n): string | undefined {\n  return obscuringAnywhereIn(styles, OBSCURING_PROPERTIES);\n}\n\n/**\n * What on one node stands over a pair, split by how far it reaches: `local`\n * (a background image or gradient, a shadow) is painted behind the node's\n * content and stops mattering under a child that paints an opaque\n * background of its own; `subtree` (opacity, a filter, a blend) alters\n * everything inside. Any state or width, as {@link contrastObscuredIn} reads.\n */\nexport function contrastObscuringIn(styles: NodeStyles | undefined): {\n  readonly local?: string;\n  readonly subtree?: string;\n} {\n  const subtree = obscuringAnywhereIn(styles, SUBTREE_OBSCURING_PROPERTIES);\n  const local = obscuringAnywhereIn(\n    styles,\n    OBSCURING_PROPERTIES.filter(\n      property => !SUBTREE_OBSCURING_PROPERTIES.includes(property)\n    )\n  );\n  return {\n    ...(local === undefined ? {} : { local }),\n    ...(subtree === undefined ? {} : { subtree }),\n  };\n}\n\n/**\n * Any of `properties` set at any address on one node, or `undefined`.\n *\n * The sweep both callers need, written once: the node's own verdict asks it\n * over the whole list, and the ancestor walk asks it over the propagating\n * subset. Two copies differing only in which list they close over is the shape\n * that drifts, and the drift would be silent in the failing-open direction.\n */\nfunction obscuringAnywhereIn(\n  styles: unknown,\n  properties: readonly string[]\n): string | undefined {\n  // Every tier is tested for being a record before it is enumerated, rather\n  // than only for being defined. Styles arrive from storage — a migration, a\n  // DTCG import, a hand-edited row — and `documentFrom` admits anything whose\n  // `nodes` is an array, so a node holding `styles: { base: null }` reaches\n  // here intact. `Object.values(null)` throws, and a throw during render takes\n  // the whole Style tab down, which is the failure `documentFrom` exists to\n  // prevent: an editor that crashes on open leaves the author no way to repair\n  // the value that crashed it.\n  //\n  // `isPlainRecord` is the ENGINE's own guard, the one its style validator and\n  // token emitter apply to the same stored shapes. A local `!== null` would\n  // agree with it today and diverge the moment either side learns about arrays\n  // or exotic objects — and it already refuses both, which a null check does\n  // not.\n  if (!isPlainRecord(styles)) return undefined;\n  for (const breakpoints of Object.values(styles)) {\n    if (!isPlainRecord(breakpoints)) continue;\n    for (const values of Object.values(breakpoints)) {\n      if (!isPlainRecord(values)) continue;\n      const found = properties.find(\n        property =>\n          Object.hasOwn(values, property) && values[property] !== undefined\n      );\n      if (found !== undefined) return found;\n    }\n  }\n  return undefined;\n}\n\n/**\n * An ANCESTOR putting something over this node's pair, or `undefined`.\n *\n * The node's own styles are not the whole rendering. `opacity`, `filter` and\n * `mixBlendMode` on any ancestor composite this node along with everything else\n * inside it, so black text on white beneath a parent at `opacity: 0.1` still\n * measures 21:1 here and reaches the eye at a small fraction of it. That is the\n * guard failing OPEN — reporting a figure that is wrong rather than withholding\n * one — which is the single direction the rest of this file refuses to fail in.\n *\n * Walks by repeated {@link locateNode} rather than by a second traversal of the\n * tree. Children live in named slots rather than one list, so a hand-written\n * walk would be a second implementation of the engine's own descent, and the\n * copy that drifts here goes quiet about an ancestor instead of reporting.\n */\nexport function contrastObscuredAbove(\n  nodes: readonly BlockNode[],\n  nodeId: string\n): string | undefined {\n  // The ids already visited. A document holding a cycle would otherwise spin\n  // here forever, and this costs a set membership over values in hand — the\n  // guard is cheap precisely because it never has to look anything up.\n  const seen = new Set<string>([nodeId]);\n  let current = nodeId;\n  for (;;) {\n    const parent = locateNode(nodes as BlockNode[], current)?.parent;\n    if (parent === undefined || seen.has(parent.id)) return undefined;\n    seen.add(parent.id);\n    const found = obscuringAnywhereIn(\n      parent.styles,\n      SUBTREE_OBSCURING_PROPERTIES\n    );\n    if (found !== undefined) return found;\n    current = parent.id;\n  }\n}\n\n/**\n * The contrast at one leaf against its partner, in the order the two are drawn.\n *\n * A control knows its own value and its partner's; which of them is the\n * FOREGROUND is a fact about the leaf. Kept here with {@link contrastRoleOf}\n * rather than at the call site, because the order is not cosmetic:\n * `checkContrast` composites the background over white and then the foreground\n * over that, so passing a translucent pair the wrong way round produces a\n * different number rather than the same one.\n */\nexport function contrastAtLeaf(\n  leaf: StyleLeaf,\n  own: StyleValue | undefined,\n  partner: StyleValue | undefined,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode = \"light\"\n): ContrastResult | undefined {\n  const role = contrastRoleOf(leaf);\n  if (role === undefined) return undefined;\n  return role === \"background\"\n    ? contrastOf(partner, own, tokens, mode)\n    : contrastOf(own, partner, tokens, mode);\n}\n\n/**\n * How a ratio reads to an author, at the precision the figure supports.\n *\n * One decimal place, which is what every accessibility tool reports and what\n * the thresholds themselves are written to: 4.5 and 3 and 7. More digits would\n * imply a precision the input does not have, since the ratio moves with the\n * eighth of a percent that rounding a channel introduces.\n *\n * Rounded rather than truncated, so a figure is never reported below what it\n * is — but the LEVEL beside it is the engine's, computed from the unrounded\n * ratio, so a value at 4.49 reads as \"4.5\" and still reports as failing body\n * text. That pair looks contradictory and is the honest reading: the threshold\n * is on the ratio, not on its display.\n */\nexport function contrastRatioText(result: ContrastResult): string {\n  return `${result.ratio.toFixed(1)}:1`;\n}\n","/**\n * What the Design panel's Shared styles tab shows, and the rules behind each\n * edit it offers: a style's name and the class name derived from it, the\n * search, and how widely a style is used, said in words.\n *\n * Rules here, presentation in {@link shared-styles-panel}, so each is tested\n * without a DOM. Built on {@link class-library}: the rows are the classes the\n * compiler emits, and a declaration is what the compiler writes.\n *\n * @module shared-style-library\n */\nimport {\n  classNameOf,\n  isLook,\n  isTextStyle,\n  MAX_NAMED_CLASS_NAME_LENGTH,\n  tokenLabelIssue,\n  type NamedClass,\n  type NodeStyles,\n  type SiteTokenSet,\n  type StyleCompileContext,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { EDITOR_WORDS } from \"../editor-words\";\nimport type { TokenMode } from \"../panels/design/font-library\";\n\nimport {\n  classDeclarations,\n  everyClassDeclaration,\n  usableSiteClasses,\n} from \"./class-library\";\nimport { colourHexOf, contrastOf } from \"./style-colour\";\n\n/** The kinds of document a shared style is counted on. */\nexport type SharedStyleKind = \"pages\" | \"components\" | \"patterns\" | \"layouts\";\n\n/** How widely one shared style is used across the site, from the index. */\nexport interface SharedStyleReach {\n  /** How many documents apply it. */\n  readonly documents: number;\n  /** The same documents, by kind. */\n  readonly byKind: Readonly<Record<SharedStyleKind, number>>;\n  /**\n   * How many blocks wear it across those documents, as saved. Optional, so a\n   * host written before it existed still compiles; absent, the sentence names\n   * the open page's blocks and the documents apart.\n   */\n  readonly blocks?: number;\n  /**\n   * What the open document contributes as saved, when the host could name it,\n   * in the parts the sentence needs to count the open field from its live\n   * copy instead, so an unsaved edit counts at once. Absent while the open\n   * document is saved nowhere yet.\n   */\n  readonly here?: SharedStyleHereParts;\n  /** False makes every number a floor: \"at least\". */\n  readonly complete: boolean;\n}\n\n/**\n * The open document's saved blocks wearing a style, in parts. With the open\n * field's saved rows set aside: `alongside` is the largest saved copy the\n * open field is part of (its language, or each language for a field they\n * all share), `elsewhere` the largest of the document's other copies (its\n * other languages, its other stored form, and the open copy as saved where\n * that stays live until the edit is published), so with the live blocks\n * the document counts `max(alongside + live, elsewhere)`. `saved` is what\n * the document adds to `SharedStyleReach.blocks` as saved, 0 when it holds\n * none. `null` where a count is not known.\n */\nexport interface SharedStyleHereParts {\n  readonly saved: number | null;\n  readonly alongside: number | null;\n  readonly elsewhere: number | null;\n  /** The kind of document it is, which its place is counted under. */\n  readonly kind: SharedStyleKind;\n}\n\n/** One read of how widely some shared styles are used. */\nexport interface SharedStylesUsage {\n  /** Whether every page has been counted, so counts can be exact. */\n  readonly whole: boolean;\n  /**\n   * Whether counts that are not whole may still become whole, so they are\n   * worth asking for again. False when something the index cannot reach\n   * keeps them floors for good.\n   *\n   * Optional, so a host written before it existed still compiles. Absent\n   * means unknown, and the tab asks again as it does while counting: every\n   * 15 seconds while the counts are not whole, until 20 asks in a row change\n   * nothing (`USAGE_RECOUNT_MS` and `USAGE_RECOUNT_IDLE_MAX` in the panel), so\n   * it neither stops while the counts still move nor asks for ever where they\n   * cannot finish.\n   */\n  readonly counting?: boolean;\n  /** Whether this author may lock and unlock shared styles. */\n  readonly mayLock: boolean;\n  /**\n   * Whether this author may ask for the pages to be counted now\n   * ({@link SharedStylesAccess.count}). Optional, so a host written before it\n   * existed still compiles; absent means no.\n   *\n   * @experimental Settles with the Shared styles tab.\n   */\n  readonly mayCount?: boolean;\n  /** Each style asked about, by id. */\n  readonly styles: ReadonlyMap<string, SharedStyleReach>;\n}\n\n/**\n * What asking for the pages to be counted now answered: how far the counting\n * got, in the usage read's terms, or why it was refused.\n *\n * @experimental Settles with the Shared styles tab.\n */\nexport type SharedStylesCount =\n  | {\n      readonly kind: \"counted\";\n      /** Every page is counted now, so the counts can be exact. */\n      readonly whole: boolean;\n      /** Pages are left that a further count would reach. */\n      readonly counting: boolean;\n    }\n  | { readonly kind: \"refused\"; readonly reason: string };\n\n/** One document a shared style is used on. */\nexport interface SharedStyleUse {\n  /** Unique only within its collection. */\n  readonly id: string;\n  readonly title: string;\n  /** The collection holding it: with `id`, what tells one document from another. */\n  readonly collection: string;\n  readonly kind: SharedStyleKind;\n}\n\n/** One page of the documents a shared style is used on. */\nexport interface SharedStyleUsesPage {\n  readonly items: readonly SharedStyleUse[];\n  /** Every document this author may open, across all pages. */\n  readonly total: number;\n  /** Documents using it that this author may not open. */\n  readonly hidden: number;\n  /** Whether another page follows. */\n  readonly hasNext: boolean;\n  /** False while some pages are still being counted. */\n  readonly complete: boolean;\n}\n\n/**\n * A removal the host refused, with whether the route said the style is still\n * used (its in-use refusal) rather than refusing for another reason, such as\n * a lock or a count no longer whole.\n *\n * @experimental Settles with the Shared styles tab.\n */\nexport interface SharedStyleRefusal {\n  readonly reason: string;\n  readonly inUse: boolean;\n}\n\n/**\n * A host's answer to a removal as a refusal, or nothing when it was stored.\n * Words alone are a refusal that does not say the style is used.\n */\nexport function sharedStyleRefusalOf(\n  answer: string | undefined\n): SharedStyleRefusal | undefined {\n  return answer === undefined ? undefined : { reason: answer, inUse: false };\n}\n\n/** One shared style as the tab lists it. */\nexport interface SharedStyleRow {\n  readonly id: string;\n  /** The name an author gave it, or its slug when it has none. */\n  readonly name: string;\n  readonly slug: string;\n  /** The class the page carries, as hand-written CSS selects it: `.nx-c-card`. */\n  readonly className: string;\n  readonly locked: boolean;\n  /** Supplied by the site's code: shown, never renamed, locked or removed. */\n  readonly inCode: boolean;\n  /** A look, bound to one block type, rather than a shared style. */\n  readonly look?: boolean;\n  /**\n   * A text style, worn from the Style tab's \"Text style\" picker rather than\n   * as a shared style.\n   */\n  readonly text?: boolean;\n  readonly styles: NodeStyles;\n}\n\n/** The tab's own name inside a sentence. */\nexport const SHARED_STYLES_WORD: string =\n  EDITOR_WORDS.sharedStyles.toLowerCase();\n\n/** Every shared style the site renders, in the order that decides precedence. */\nexport function sharedStyleRows(\n  library: readonly NamedClass[],\n  suppliedIds: ReadonlySet<string>\n): SharedStyleRow[] {\n  return usableSiteClasses(library).map(entry => ({\n    id: entry.id,\n    name: sharedStyleName(entry),\n    slug: entry.slug,\n    // A look's class is written under its own prefix.\n    className: `.${classNameOf(entry)}`,\n    locked: entry.locked === true,\n    inCode: suppliedIds.has(entry.id),\n    ...(isLook(entry) ? { look: true } : {}),\n    ...(isTextStyle(entry) ? { text: true } : {}),\n    styles: entry.styles,\n  }));\n}\n\n/**\n * The library without its looks and text styles: the shared styles an author\n * applies to any block, as the Shared styles tab and the picker list them. A\n * look is bound to one block type and is picked from that block's own tiles;\n * a text style is picked from the Style tab's \"Text style\" and listed in\n * Design's Type tab.\n */\nexport function sharedStylesOnly(library: readonly NamedClass[]): NamedClass[] {\n  return library.filter(entry => !isLook(entry) && !isTextStyle(entry));\n}\n\n/** A style's name: its label, or its slug for a style made before labels. */\n/** A class's name as the surfaces show it: its label, or its slug when blank. */\nexport function sharedStyleName(\n  entry: Pick<NamedClass, \"slug\" | \"label\">\n): string {\n  const label = entry.label?.trim();\n  return label === undefined || label === \"\" ? entry.slug : label;\n}\n\n/**\n * The class name a name gives: lowercase letters, digits and dashes, starting\n * with a letter, as the engine's slug grammar requires. Empty when the name\n * holds no letter or digit at all.\n */\nexport function sharedStyleSlug(name: string): string {\n  const words = name\n    .normalize(\"NFKD\")\n    .toLowerCase()\n    .replaceAll(/[^a-z0-9]+/g, \"-\")\n    .replaceAll(/^-+|-+$/g, \"\");\n  if (words === \"\") return \"\";\n  // A class name may not start with a digit, so \"2 columns\" reads as a style.\n  const slug = /^[a-z]/.test(words) ? words : `style-${words}`;\n  return slug.slice(0, MAX_NAMED_CLASS_NAME_LENGTH).replace(/-+$/, \"\");\n}\n\n/** A rename's verdict: the label and slug to store, or why not. */\nexport type SharedStyleRename =\n  | { readonly ok: true; readonly label: string; readonly slug: string }\n  | { readonly ok: false; readonly reason: string };\n\n/**\n * Whether a style may take a new name, and the label and class name to store\n * if it may. The class name is derived from the name, and a class name\n * another style already has is refused, since two styles with one class name\n * would write one selector and the later would be dropped.\n */\nexport function renameSharedStyle(\n  name: string,\n  classId: string,\n  library: readonly NamedClass[]\n): SharedStyleRename {\n  const label = name.trim();\n  if (label === \"\")\n    return { ok: false, reason: \"A shared style needs a name.\" };\n  const labelIssue = tokenLabelIssue(label);\n  if (labelIssue !== undefined) {\n    return { ok: false, reason: labelIssue.replace(\"A label\", \"A name\") };\n  }\n  const slug = sharedStyleSlug(label);\n  if (slug === \"\") {\n    return {\n      ok: false,\n      reason: \"Use at least one letter or digit in the name.\",\n    };\n  }\n  if (library.some(entry => entry.id !== classId && entry.slug === slug)) {\n    return {\n      ok: false,\n      reason: `“${slug}” is already a shared style. Choose another name.`,\n    };\n  }\n  return { ok: true, label, slug };\n}\n\n/** Text for a search: lowercase, with dashes, dots and runs of space as one space. */\nfunction searchable(text: string): string {\n  return text.toLowerCase().replaceAll(/[\\s\\-_.]+/g, \" \");\n}\n\n/**\n * What a row is found by: its name, its class name as written and as the page\n * emits it, and every property and value it sets, in every state and at every\n * breakpoint. A value naming a variable is found by the variable's name,\n * since the reference compiles to that name.\n */\nexport function sharedStyleSearchText(\n  row: SharedStyleRow,\n  context?: StyleCompileContext\n): string {\n  const declarations = everyClassDeclaration(row.styles, context).map(\n    entry => `${entry.property}: ${entry.value}`\n  );\n  return searchable(\n    [row.name, row.slug, row.className, ...declarations].join(\"\\n\")\n  );\n}\n\n/**\n * The rows a search finds, by name, class name, property or value, in their\n * order. Any row a shared style's row extends, so a look's row comes back as\n * the row it was.\n */\nexport function searchSharedStyles<Row extends SharedStyleRow>(\n  rows: readonly Row[],\n  query: string,\n  textOf: (row: Row) => string\n): Row[] {\n  const needle = searchable(query.trim());\n  if (needle === \"\") return [...rows];\n  return rows.filter(row => textOf(row).includes(needle));\n}\n\n/** What a style declares at the base, as lines, and how much more elsewhere. */\nexport function sharedStyleDeclares(\n  styles: NodeStyles,\n  context?: StyleCompileContext\n): { lines: string[]; elsewhere: number } {\n  const { shown, elsewhere } = classDeclarations(styles, context);\n  return {\n    lines: shown.map(entry => `${entry.property}: ${entry.value}`),\n    elsewhere,\n  };\n}\n\n/**\n * The base declarations a row's \"Aa\" is drawn with: its colours and type,\n * where the value stands alone. A value reading a variable or a file is left\n * out, since the panel has neither the site's variables nor its hosts.\n */\nconst PREVIEWED: Readonly<Record<string, string>> = {\n  color: \"color\",\n  \"background-color\": \"backgroundColor\",\n  \"font-family\": \"fontFamily\",\n  \"font-weight\": \"fontWeight\",\n  \"font-style\": \"fontStyle\",\n};\n\nexport function sharedStylePreview(\n  styles: NodeStyles,\n  context?: StyleCompileContext\n): Record<string, string> {\n  const preview: Record<string, string> = {};\n  for (const entry of classDeclarations(styles, context).shown) {\n    const key = Object.hasOwn(PREVIEWED, entry.property)\n      ? PREVIEWED[entry.property]\n      : undefined;\n    if (key === undefined || entry.descendant !== undefined) continue;\n    if (/\\b(?:var|url)\\(/i.test(entry.value)) continue;\n    preview[key] = entry.value;\n  }\n  return preview;\n}\n\n/**\n * The tile a row's \"Aa\" is drawn on: the site's page, its background and text\n * colours in the mode the canvas shows, so a style's own colours read as they\n * do on a page rather than against the panel. Resolved through the colour\n * controls' own reading of the site's variables ({@link colourHexOf}), by the\n * identities the engine gives the page's two colours.\n *\n * Empty without the site's variables, or for a colour that cannot be read:\n * the tile then keeps its neutral look.\n */\nexport function sharedStylePageTile(\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): { backgroundColor?: string; color?: string } {\n  const backgroundColor = colourHexOf(\n    { $token: \"color.background\" },\n    tokens,\n    mode\n  );\n  const color = colourHexOf({ $token: \"color.text\" }, tokens, mode);\n  return {\n    ...(backgroundColor === undefined ? {} : { backgroundColor }),\n    ...(color === undefined ? {} : { color }),\n  };\n}\n\n/**\n * The contrast under which a tile's text counts as hard to read: WCAG AA for\n * normal text, since the \"Aa\" is small, regular-weight text.\n */\nconst READABLE_RATIO = 4.5;\n\n/**\n * The engine's own variables, for readable text when the site's are not to\n * hand: a colour the tile can always fall back on.\n */\nconst ENGINE_TOKENS: SiteTokenSet = { tokens: [] };\n\n/** One row's tile: the page under the preview, the preview, and a dark-mode flag. */\nexport interface SharedStyleTile {\n  /** The page the preview stands on; empty for the neutral tile. */\n  readonly page: { backgroundColor?: string; color?: string };\n  /** The \"Aa\": the style's own colours, with readable text where it sets none. */\n  readonly specimen: Readonly<Record<string, string>>;\n  /**\n   * The style's text is under 4.5:1 on the site's dark page, so the tile\n   * shows the light page instead and says so.\n   */\n  readonly darkUnreadable: boolean;\n  /**\n   * The \"Aa\" is not shown to read on its background, a colour this cannot\n   * measure, so it carries an outline in the page's colour: visible on any\n   * background, without measuring it.\n   */\n  readonly outlined: boolean;\n}\n\n/** A canvas 2D context's colour slot, which is all the normaliser reads. */\ninterface FillStyleSlot {\n  fillStyle: unknown;\n}\n\n/** The context colours are normalised through, by the constructor it came from. */\nlet canvasSlot: { maker: unknown; slot: FillStyleSlot | null } | undefined;\n\n/**\n * The browser's 2D context, when there is one: an `OffscreenCanvas`, which\n * needs no document. Absent under a server render and in a test DOM, where\n * colours stay as written.\n */\nfunction fillStyleSlot(): FillStyleSlot | null {\n  if (typeof OffscreenCanvas === \"undefined\") return null;\n  if (canvasSlot?.maker !== OffscreenCanvas) {\n    canvasSlot = {\n      maker: OffscreenCanvas,\n      slot: new OffscreenCanvas(1, 1).getContext(\"2d\"),\n    };\n  }\n  return canvasSlot.slot;\n}\n\n/**\n * A colour as the browser resolves it, hex or rgba(), so the contrast verdict\n * can read a name, hsl() or any other colour CSS takes: a 2D context's\n * `fillStyle` normalises what it accepts and keeps its old value for what it\n * does not, so the value is set over two different colours and kept only\n * when both read back alike. The colour as written where there is no canvas.\n */\nfunction resolvedColour(colour: string): string {\n  const slot = fillStyleSlot();\n  if (slot === null) return colour;\n  slot.fillStyle = \"#000\";\n  slot.fillStyle = colour;\n  const overBlack = slot.fillStyle;\n  slot.fillStyle = \"#fff\";\n  slot.fillStyle = colour;\n  const overWhite = slot.fillStyle;\n  return typeof overBlack === \"string\" && overBlack === overWhite\n    ? overBlack\n    : colour;\n}\n\n/**\n * The contrast between two colours, each resolved by the browser first\n * ({@link resolvedColour}), by the verdict the colour field shows\n * ({@link contrastOf}); `undefined` when either still cannot be measured.\n * Nothing is guessed: two colours either side of a light/dark line can be\n * all but the same.\n */\nfunction ratioOf(fg: string, bg: string): number | undefined {\n  return contrastOf(resolvedColour(fg), resolvedColour(bg), undefined)?.ratio;\n}\n\n/**\n * Whether text drawn with `fg` on `bg` reads, by a measured ratio; unknown\n * where the pair cannot be measured, which is never taken as readable.\n */\nfunction readability(fg: string, bg: string): boolean | undefined {\n  const ratio = ratioOf(fg, bg);\n  return ratio === undefined ? undefined : ratio >= READABLE_RATIO;\n}\n\n/**\n * Text that reads on a style's own background when it sets no colour: the\n * page's, else the site's light or dark text, else the engine's own light or\n * dark text, the first that reads. The engine's come last so a site whose\n * text fails on that background in both modes still gets readable text.\n */\nfunction readableText(\n  background: string,\n  page: { color?: string },\n  tokens: SiteTokenSet | undefined\n): string | undefined {\n  const candidates = [\n    page.color,\n    sharedStylePageTile(tokens, \"light\").color,\n    sharedStylePageTile(tokens, \"dark\").color,\n    sharedStylePageTile(ENGINE_TOKENS, \"light\").color,\n    sharedStylePageTile(ENGINE_TOKENS, \"dark\").color,\n  ];\n  return candidates.find(\n    colour => colour !== undefined && readability(colour, background) === true\n  );\n}\n\n/**\n * A row's tile in the mode the canvas shows. In dark mode a style whose text\n * (its own, or the page's where it sets none) would be under 4.5:1 on its\n * background (its own, or the dark page's) is drawn on the light page\n * instead and marked, since on the site it is hard to read in dark mode. A\n * style with a background and no text colour gets text that reads on that\n * background, so it never draws as a blank square.\n */\nexport function sharedStyleTile(\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode,\n  preview: Readonly<Record<string, string>>\n): SharedStyleTile {\n  const shown = sharedStylePageTile(tokens, mode);\n  const darkUnreadable =\n    mode === \"dark\" &&\n    unreadablePair(\n      preview.color ?? shown.color,\n      preview.backgroundColor ?? shown.backgroundColor\n    );\n  const page = darkUnreadable ? sharedStylePageTile(tokens, \"light\") : shown;\n  const background = preview.backgroundColor;\n  const text =\n    background !== undefined && preview.color === undefined\n      ? readableText(background, page, tokens)\n      : undefined;\n  const specimen = text === undefined ? preview : { ...preview, color: text };\n  const outlined = notShownToRead(preview, specimen, page);\n  return {\n    page,\n    specimen: outlined\n      ? outlinedSpecimen(\n          specimen,\n          page,\n          preview.backgroundColor ?? page.backgroundColor\n        )\n      : specimen,\n    darkUnreadable,\n    outlined,\n  };\n}\n\n/**\n * Whether a style that sets a colour is not shown to read on its tile: its\n * text (or the page's) against its background (or the page's) is under the\n * bar, or a pair this cannot judge. A style setting no colour draws as the\n * page does.\n */\nfunction notShownToRead(\n  preview: Readonly<Record<string, string>>,\n  specimen: Readonly<Record<string, string>>,\n  page: { backgroundColor?: string; color?: string }\n): boolean {\n  if (preview.color === undefined && preview.backgroundColor === undefined) {\n    return false;\n  }\n  const fg = specimen.color ?? page.color;\n  const bg = preview.backgroundColor ?? page.backgroundColor;\n  if (fg === undefined || bg === undefined) return true;\n  return readability(fg, bg) !== true;\n}\n\n/**\n * The \"Aa\" with an outline it shows by on its own background. Where that\n * background can be measured, one stroke painted under the fill, in the\n * colour that measures best against it of the page's background and text and\n * the engine's light and dark text. Where it cannot, a light and a dark halo\n * together, which show on any colour.\n */\nfunction outlinedSpecimen(\n  specimen: Readonly<Record<string, string>>,\n  page: { backgroundColor?: string; color?: string },\n  background: string | undefined\n): Readonly<Record<string, string>> {\n  const light = sharedStylePageTile(ENGINE_TOKENS, \"dark\").color;\n  const dark = sharedStylePageTile(ENGINE_TOKENS, \"light\").color;\n  const outline =\n    background === undefined\n      ? undefined\n      : bestAgainst(background, [\n          page.backgroundColor,\n          page.color,\n          dark,\n          light,\n        ]);\n  if (outline !== undefined) {\n    return {\n      ...specimen,\n      WebkitTextStroke: `2px ${outline}`,\n      paintOrder: \"stroke fill\",\n    };\n  }\n  return {\n    ...specimen,\n    textShadow: `0 0 1px ${dark ?? \"currentcolor\"}, 0 0 3px ${light ?? \"currentcolor\"}`,\n    // No stroke over the halos, whatever a class supplies: one would hide the\n    // inner dark halo, and could be the very colour of a background this\n    // cannot measure.\n    WebkitTextStroke: \"0\",\n  };\n}\n\n/** The candidate that measures best against `background`, if any measures. */\nfunction bestAgainst(\n  background: string,\n  candidates: readonly (string | undefined)[]\n): string | undefined {\n  let best: { colour: string; ratio: number } | undefined;\n  for (const colour of candidates) {\n    if (colour === undefined) continue;\n    const ratio = ratioOf(colour, background);\n    if (ratio !== undefined && (best === undefined || ratio > best.ratio)) {\n      best = { colour, ratio };\n    }\n  }\n  return best?.colour;\n}\n\n/**\n * Whether a pair is not shown to read: under the bar, or one this cannot\n * judge, which is drawn on the light page rather than risked blank. A pair\n * missing a colour (no site variables) has nothing to judge.\n */\nfunction unreadablePair(\n  fg: string | undefined,\n  bg: string | undefined\n): boolean {\n  if (fg === undefined || bg === undefined) return false;\n  return readability(fg, bg) !== true;\n}\n\n/** What a marked tile says, in its tooltip and the row's accessible name. */\nexport const SHARED_STYLE_DARK_UNREADABLE = \"Hard to read in dark mode\";\n\nconst KIND_WORDS: Record<SharedStyleKind, readonly [string, string]> = {\n  pages: [\"page\", \"pages\"],\n  components: [\"component\", \"components\"],\n  patterns: [\"saved section\", \"saved sections\"],\n  layouts: [\"header & footer set\", \"header & footer sets\"],\n};\n\n/** A kind as a document is labelled in a list: \"Page\", \"Component\". */\nexport function sharedStyleKindName(kind: SharedStyleKind): string {\n  const [one] = KIND_WORDS[kind];\n  return one.charAt(0).toUpperCase() + one.slice(1);\n}\n\n/** \"1 page\", \"4 pages\". */\nfunction counted(\n  count: number,\n  [one, many]: readonly [string, string]\n): string {\n  return `${count} ${count === 1 ? one : many}`;\n}\n\n/** \"a\", \"a and b\", \"a, b and c\". */\nexport function listedWords(parts: readonly string[]): string {\n  if (parts.length <= 1) return parts.join(\"\");\n  return `${parts.slice(0, -1).join(\", \")} and ${parts.at(-1) ?? \"\"}`;\n}\n\n/** The blocks on the open page that carry a style. */\nexport interface BlocksOnThisPage {\n  readonly count: number;\n  /** False when the page has more blocks than could be read. */\n  readonly complete: boolean;\n}\n\n/** What a reach sentence says before the site has answered. */\nexport const SHARED_STYLE_COUNTING = \"Counting where it’s used…\";\n\n/**\n * How widely a style is used, in words: \"Used on 12 blocks on 4 pages and 1\n * component\". The site's saved counts, with the open page counted from its\n * live copy in place of its saved one, so an unsaved edit counts at once and\n * none is counted twice. \"At least\" goes before a floor; \"Counting where it’s\n * used…\" before the site has answered; \"Not used anywhere\" only when every\n * count is whole. Empty where there is nothing to count from.\n */\nexport function sharedStyleReachSentence(\n  blocks: BlocksOnThisPage | undefined,\n  reach: SharedStyleReach | undefined\n): string {\n  if (reach === undefined) {\n    return blocks === undefined ? \"\" : SHARED_STYLE_COUNTING;\n  }\n  if (reach.blocks !== undefined) {\n    return siteWideSentence(blocks, reach, reach.blocks);\n  }\n  return pageAndPlacesSentence(blocks, reach);\n}\n\n/**\n * The sentence from a host that counts no blocks: the open page's blocks and\n * the site's documents said apart, \"3 blocks on this page · on 4 pages\".\n */\nfunction pageAndPlacesSentence(\n  blocks: BlocksOnThisPage | undefined,\n  reach: SharedStyleReach\n): string {\n  const parts = onThisPage(blocks);\n  const kinds = placesIn(reach.byKind);\n  if (kinds.length > 0) {\n    parts.push(`on ${reach.complete ? \"\" : \"at least \"}${listedWords(kinds)}`);\n  }\n  if (parts.length > 0) {\n    const sentence = parts.join(\" · \");\n    return sentence.charAt(0).toUpperCase() + sentence.slice(1);\n  }\n  const exact = reach.complete && (blocks?.complete ?? true);\n  return exact ? \"Not used anywhere\" : \"No uses counted yet\";\n}\n\n/** The open page's blocks, \"3 blocks on this page\", or nothing when none. */\nfunction onThisPage(blocks: BlocksOnThisPage | undefined): string[] {\n  if (blocks === undefined || blocks.count === 0) return [];\n  const count = counted(blocks.count, [\"block\", \"blocks\"]);\n  return [`${blocks.complete ? \"\" : \"at least \"}${count} on this page`];\n}\n\n/** Each kind of place that holds the style, counted: \"4 pages\", \"1 component\". */\nfunction placesIn(byKind: Readonly<Record<SharedStyleKind, number>>): string[] {\n  return (Object.keys(KIND_WORDS) as SharedStyleKind[])\n    .filter(kind => byKind[kind] > 0)\n    .map(kind => counted(byKind[kind], KIND_WORDS[kind]));\n}\n\n/**\n * The site-wide sentence, from a host that counts blocks: the saved counts\n * with the open document counted from the open page's live field.\n */\nfunction siteWideSentence(\n  live: BlocksOnThisPage | undefined,\n  reach: SharedStyleReach,\n  /** The blocks the site's saved documents hold: `reach.blocks`, present. */\n  saved: number\n): string {\n  const counts = reachWithLivePage(live, reach, saved);\n  const kinds = placesIn(counts.byKind);\n  if (counts.blocks <= 0 || kinds.length === 0) {\n    return counts.complete ? \"Not used anywhere\" : \"No uses counted yet\";\n  }\n  const many = counted(counts.blocks, [\"block\", \"blocks\"]);\n  const floor = counts.complete ? \"\" : \"at least \";\n  return `Used on ${floor}${many} on ${listedWords(kinds)}`;\n}\n\n/** A style's site-wide counts, with the open page counted as it stands. */\ninterface ReachCounts {\n  readonly blocks: number;\n  readonly byKind: Readonly<Record<SharedStyleKind, number>>;\n  /** False makes every number a floor. */\n  readonly complete: boolean;\n}\n\n/**\n * The site's saved counts with the open document counted once, from the open\n * page's live field: its saved count swapped for `max(alongside + live,\n * elsewhere)`, and its place counted while that is above 0. A document saved\n * nowhere yet (no `here`) is added as a page. Where any part is unknown, the\n * saved counts stand as a floor: the document is in them already, so it is\n * neither added again nor taken away.\n */\nfunction reachWithLivePage(\n  live: BlocksOnThisPage | undefined,\n  reach: SharedStyleReach,\n  /** The blocks the site's saved documents hold: `reach.blocks`. */\n  saved: number\n): ReachCounts {\n  const counts: ReachCounts = {\n    blocks: saved,\n    byKind: reach.byKind,\n    complete: reach.complete && (live?.complete ?? true),\n  };\n  // Without the open page's live count (a caller that has none), the saved\n  // counts stand as they are.\n  if (live === undefined) return counts;\n  const here = reach.here;\n  if (here === undefined) return swapped(counts, \"pages\", 0, live.count);\n  const { saved: was, alongside, elsewhere } = here;\n  if (was === null || alongside === null || elsewhere === null) {\n    return { ...counts, complete: false };\n  }\n  const now = Math.max(alongside + live.count, elsewhere);\n  return swapped(counts, here.kind, was, now);\n}\n\n/** The counts with one document's blocks `was` replaced by `now`. */\nfunction swapped(\n  counts: ReachCounts,\n  kind: SharedStyleKind,\n  was: number,\n  now: number\n): ReachCounts {\n  const byKind = { ...counts.byKind };\n  byKind[kind] += (now > 0 ? 1 : 0) - (was > 0 ? 1 : 0);\n  return { ...counts, blocks: counts.blocks - was + now, byKind };\n}\n\n/** A row's count in words, and whether it is a zero not counted yet. */\nexport interface SharedStyleReachChip {\n  readonly words: string;\n  /** No use found so far on a site not counted in full: drawn muted. */\n  readonly uncounted: boolean;\n}\n\n/**\n * A row's count: its documents, with \"+\" when that is a floor, and what they\n * are. A bare number was read as uses, 17 blocks on 2 pages reading \"2\", so\n * the chip names the kind it counts: \"4 pages\", or \"5 places\" across several\n * kinds, which the row's name says one by one. A zero that is a floor says\n * \"Not counted yet\" rather than \"0+ pages\", a number that says nothing.\n */\nexport function sharedStyleReachChip(\n  reach: SharedStyleReach\n): SharedStyleReachChip {\n  if (reach.documents === 0 && !reach.complete) {\n    return { words: \"Not counted yet\", uncounted: true };\n  }\n  const kinds = (Object.keys(KIND_WORDS) as SharedStyleKind[]).filter(\n    kind => reach.byKind[kind] > 0\n  );\n  const [only] = kinds;\n  // Nothing used reads in pages, the kind a style is most often on.\n  const words: readonly [string, string] =\n    kinds.length > 1 ? [\"place\", \"places\"] : KIND_WORDS[only ?? \"pages\"];\n  const plus = reach.complete ? \"\" : \"+\";\n  const [one, many] = words;\n  const noun = reach.documents === 1 && plus === \"\" ? one : many;\n  return { words: `${reach.documents}${plus} ${noun}`, uncounted: false };\n}\n\n/**\n * Whether a style may be removed from its popover: only when it is stored\n * here, unlocked, every page has been counted, and nothing uses it, this open\n * page included (its unsaved blocks are not in the index yet).\n *\n * `quiet` when the popover already says why elsewhere (locked, set in code)\n * or while the usage is still being read.\n */\nexport type SharedStyleRemoval =\n  | { readonly kind: \"removable\" }\n  | { readonly kind: \"refused\"; readonly reason: string }\n  | { readonly kind: \"quiet\" };\n\n/** Why a style in use, on the open page or a saved document, can't go. */\nconst SHARED_STYLE_IN_USE_REMOVAL =\n  \"In use, so it can’t be removed. Take it off the blocks that use it first.\";\n\n/**\n * Why a style a block on the open page wears can't go, saying where, since\n * the site's saved counts may not hold that block yet.\n */\nexport const USED_ON_THIS_PAGE_REMOVAL =\n  \"Used on this page, so it can’t be removed. Take it off the blocks that use it first.\";\n\n/**\n * Whether the open page keeps a style from being removed: a block on it wears\n * the style, or the page could not be read in full, which reads as worn. The\n * saved documents are the route's to judge; this is what the route can't see,\n * an unsaved edit, so it is asked before the route is.\n */\nexport function heldByThisPage(blocks: BlocksOnThisPage | undefined): boolean {\n  return blocks === undefined || !blocks.complete || blocks.count > 0;\n}\n\nexport function sharedStyleRemoval(\n  row: Pick<SharedStyleRow, \"locked\" | \"inCode\">,\n  blocks: BlocksOnThisPage | undefined,\n  reach: SharedStyleReach | undefined,\n  whole: boolean | undefined\n): SharedStyleRemoval {\n  if (row.inCode || row.locked) return { kind: \"quiet\" };\n  if (reach === undefined || whole === undefined) return { kind: \"quiet\" };\n  if (!whole)\n    return { kind: \"refused\", reason: SHARED_STYLE_NOT_WHOLE_REMOVAL };\n  if (!isUnused(blocks, reach)) {\n    return { kind: \"refused\", reason: SHARED_STYLE_IN_USE_REMOVAL };\n  }\n  return { kind: \"removable\" };\n}\n\n/**\n * Whether nothing uses a style: no document the index counted, in full, and\n * no block on the open page, read in full. Unknown reads as used.\n */\nexport function isUnused(\n  blocks: BlocksOnThisPage | undefined,\n  reach: SharedStyleReach\n): boolean {\n  return (\n    blocks !== undefined &&\n    blocks.complete &&\n    blocks.count === 0 &&\n    reach.complete &&\n    reach.documents === 0\n  );\n}\n\n/**\n * Where a style stands for the Used and Unused filters: \"used\" once any use\n * has been counted, on a block of the open page or a document in the index,\n * complete or not; \"unused\" only when it certainly is ({@link isUnused}, the\n * one rule removal also reads). Undefined otherwise: not read yet, or a zero\n * while some count is incomplete, which is \"none counted yet\", not unused.\n */\nexport function sharedStyleUse(\n  blocks: BlocksOnThisPage | undefined,\n  reach: SharedStyleReach | undefined\n): \"used\" | \"unused\" | undefined {\n  if (reach === undefined) return undefined;\n  if ((blocks?.count ?? 0) > 0 || reach.documents > 0) return \"used\";\n  return isUnused(blocks, reach) ? \"unused\" : undefined;\n}\n\n/** Which styles the tab lists: every one, or those used, unused or locked. */\nexport type SharedStyleFilter = \"all\" | \"used\" | \"unused\" | \"locked\";\n\n/** The filters in the order the tab offers them, with their words. */\nexport const SHARED_STYLE_FILTERS: readonly {\n  readonly filter: SharedStyleFilter;\n  readonly word: string;\n}[] = [\n  { filter: \"all\", word: \"All\" },\n  { filter: \"used\", word: \"Used\" },\n  { filter: \"unused\", word: \"Unused\" },\n  { filter: \"locked\", word: \"Locked\" },\n];\n\n/**\n * Whether a row belongs under a filter. A style whose usage has not been read\n * yet is under neither Used nor Unused until it has.\n */\nexport function inSharedStyleFilter(\n  row: Pick<SharedStyleRow, \"locked\">,\n  filter: SharedStyleFilter,\n  use: \"used\" | \"unused\" | undefined\n): boolean {\n  if (filter === \"all\") return true;\n  if (filter === \"locked\") return row.locked;\n  return use === filter;\n}\n\n/** What the tab says when a filter, with or without a search, lists nothing. */\nexport function sharedStyleFilterEmpty(\n  filter: Exclude<SharedStyleFilter, \"all\">,\n  query: string\n): string {\n  const word = SHARED_STYLE_FILTERS.find(entry => entry.filter === filter);\n  const kind = `${(word?.word ?? filter).toLowerCase()} ${SHARED_STYLES_WORD}`;\n  return query === \"\" ? `No ${kind}.` : `No ${kind} match “${query}”.`;\n}\n\n/**\n * The words the remove route refuses with while the index is not whole, so\n * the tab says the same before it is asked.\n */\nexport const SHARED_STYLE_NOT_WHOLE_REMOVAL =\n  \"Some pages haven't been counted yet, so no shared style can be removed.\";\n\n/**\n * Why Lock, Remove and Remove unused wait: a rename writes the whole list of\n * styles, and so does each of them, so whichever landed second would put the\n * other's list back.\n */\nexport const SHARED_STYLE_RENAME_PENDING =\n  \"Wait until the name change is saved.\";\n\n/**\n * The one note while the tab's counts are floors and Unused holds rows back:\n * it covers the minimums, the withheld rows and Remove unused waiting.\n */\nexport const SHARED_STYLE_COUNTING_NOTE =\n  \"Some pages haven't been counted yet, so the numbers are minimums and no style can be called unused or removed.\";\n\n/**\n * The note while counts are floors for good: content the index cannot reach\n * keeps them so, so it promises no wait.\n */\nexport const SHARED_STYLE_UNCOUNTABLE_NOTE =\n  \"Some pages can't be counted, so these numbers are minimums.\";\n\n/** Why Remove unused waits when counts are floors for good. */\nexport const SHARED_STYLE_UNCOUNTABLE_REMOVAL =\n  \"Some pages can't be counted, so no shared style can be removed.\";\n\n/**\n * What Unused says when every page is counted but some style's count was cut\n * short, so it holds that style back, beside any rows it does list.\n */\nexport const SHARED_STYLE_UNUSED_UNCERTAIN =\n  \"Some uses could not all be counted, so some styles can't be called unused yet.\";\n\n/**\n * What a removal's confirmation says the count cannot see. The count reads\n * only the styles chosen in the editor; a class written by hand elsewhere is\n * invisible to it, so a zero is what the editor knows, not a promise.\n */\nexport const SHARED_STYLE_UNCOUNTED_USES =\n  \"A class written by hand, in custom code, an HTML attribute or another plugin, isn't counted.\";\n\n/** The note under counts that are floors. */\nexport const SHARED_STYLE_NOT_WHOLE_NOTE =\n  \"Some pages haven't been counted yet, so these numbers are minimums.\";\n","/**\n * The rules behind a block's shared style: which shared styles a block wears,\n * whether its look may be saved as a new one, and the edits that move values\n * between the block and its style (save as, Move to, Detach).\n *\n * Pure, so each rule is tested without a DOM. The writes themselves are the\n * host's (a shared style lives in the site style, a block in the page), so\n * every plan here answers with what to store, never stores it.\n *\n * A shared style is stored as a class (`NamedClass`) and a block wears one by\n * listing its id in `node.classes`; the interface calls it a shared style.\n *\n * @module shared-style-target\n */\nimport {\n  breakpointContexts,\n  findNode,\n  isPlainRecord,\n  isTokenRef,\n  newId,\n  overlaidStyles,\n  STYLE_STATES,\n  type BlockDocument,\n  type BlockNode,\n  type BreakpointSet,\n  type NamedClass,\n  type NodeStyles,\n  type StyleState,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { designReadOnlyReason, type LockView } from \"../inspector/inspector\";\nimport { stateLabel } from \"../inspector/style-inspector/state-switcher\";\nimport { sameStyleValue, type BuilderOp } from \"../op-vocabulary\";\n\nimport { liveBreakpointsFor } from \"./breakpoints\";\nimport {\n  appliedClasses,\n  newClassName,\n  withClassApplied,\n  withClassRemoved,\n} from \"./class-library\";\nimport {\n  renameSharedStyle,\n  sharedStyleRows,\n  sharedStylesOnly,\n  sharedStyleSlug,\n  type SharedStyleRow,\n} from \"./shared-style-library\";\nimport {\n  readStyleValue,\n  styleClearOp,\n  styleWriteOp,\n  type StyleAddress,\n  type StylePolicy,\n  type StyleWrite,\n} from \"./style-values\";\n\n/** What an author without the right to change the site's design is told. */\nexport const NO_DESIGN_RIGHT = \"You can't change this site's design.\";\n\n/** No code-supplied ids, as one value: the rows here never ask. */\nconst NO_SUPPLIED: ReadonlySet<string> = new Set();\n\n/**\n * The shared styles a block wears that the page renders, in library order\n * (the order that decides which wins), with their names. Classes the site\n * does not define, or stored past the page's limit, are not listed: they\n * style nothing.\n */\nexport function nodeSharedStyles(\n  library: readonly NamedClass[],\n  nodeClassIds: readonly string[]\n): SharedStyleRow[] {\n  // The rows the Shared styles tab lists, so a style is named the same in\n  // the tab and on the block.\n  const rows = new Map(\n    sharedStyleRows(library, NO_SUPPLIED).map(row => [row.id, row])\n  );\n  return appliedClasses(library, nodeClassIds).flatMap(choice => {\n    const row = rows.get(choice.id);\n    return row === undefined ? [] : [row];\n  });\n}\n\n/** Whether an envelope sets any value at all, in any state or breakpoint. */\nexport function hasOwnStyles(styles: NodeStyles | undefined): boolean {\n  // Through the guarded walk, so a malformed tier reads as holding nothing.\n  return ownEntries<unknown>(styles).some(([, byBreakpoint]) =>\n    ownEntries<unknown>(byBreakpoint).some(\n      ([, values]) => ownEntries(values).length > 0\n    )\n  );\n}\n\n/** What the host knows about the site's shared styles and the author's right. */\nexport interface SharedStyleOffer {\n  /** The site's library, or `undefined` while it has not been read. */\n  readonly library: readonly NamedClass[] | undefined;\n  /** Whether the author may change the site's design (`update-site-style`). */\n  readonly mayChange: boolean;\n  /**\n   * The editor's lock view (`lockViewOf`), so a block inside an area locked\n   * to its content is refused here as the dialog refuses it. The registry's\n   * locks alone when omitted.\n   */\n  readonly view?: LockView;\n}\n\n/**\n * Why the block's look cannot be saved as a shared style, in words, or\n * `undefined` when it can. The first release lets a block wear one shared\n * style, so a block already wearing one is refused; the reason names it.\n */\nexport function saveAsSharedStyleRefusal(\n  document: BlockDocument,\n  nodeId: string,\n  offer: SharedStyleOffer,\n  view?: LockView\n): string | undefined {\n  if (!offer.mayChange) return NO_DESIGN_RIGHT;\n  const node = findNode(document.nodes, nodeId);\n  // The Layers lock's own words, the ones the inspector shows for it; they\n  // also cover a block that is no longer on the page.\n  const locked = designReadOnlyReason(document, nodeId, view ?? offer.view);\n  if (node === undefined || locked !== undefined) {\n    return locked ?? \"This block is no longer on the page.\";\n  }\n  if (offer.library === undefined) {\n    return \"This site's shared styles haven't been read yet.\";\n  }\n  // A look is worn beside a shared style, so only a shared style refuses.\n  const [worn] = nodeSharedStyles(\n    sharedStylesOnly(offer.library),\n    node.classes ?? []\n  );\n  if (worn !== undefined) return `This block already uses ${worn.name}.`;\n  if (!hasOwnStyles(node.styles)) {\n    // Said as what to do next: a value changed is what makes a save useful.\n    return \"Change a style first, then save it to reuse it.\";\n  }\n  // The page's per-block limit, asked of the one rule that owns it.\n  if (!withClassApplied(node.classes ?? [], \"\").ok) {\n    return \"This block already lists as many shared styles as the page applies.\";\n  }\n  return undefined;\n}\n\n/** One past the highest position in the library, so a new style wins. */\nfunction nextOrderIndex(library: readonly NamedClass[]): number {\n  return library.reduce(\n    (highest, entry) =>\n      Number.isFinite(entry.orderIndex)\n        ? Math.max(highest, entry.orderIndex + 1)\n        : highest,\n    0\n  );\n}\n\n/** A plan's answer: what to store, or why not. */\nexport type SharedStylePlan<T> =\n  | ({ readonly ok: true } & T)\n  | { readonly ok: false; readonly reason: string };\n\n/**\n * Why a new style's name can't be used because another style already has its\n * class name, in words naming it as the author typed it, or `undefined`. One\n * rule for the dialog, which asks it of the library it read, and for the host,\n * which asks it again of the library its queue holds just before it stores.\n */\nexport function sharedStyleNameTaken(\n  name: string,\n  slug: string,\n  library: readonly Pick<NamedClass, \"slug\">[]\n): string | undefined {\n  if (slug === \"\" || !library.some(entry => entry.slug === slug)) {\n    return undefined;\n  }\n  return `“${name}” is already a shared style. Choose another name.`;\n}\n\n/** The name typed in the save dialog, checked: the label and class name, or why not. */\nexport function newSharedStyleName(\n  name: string,\n  library: readonly NamedClass[]\n): SharedStylePlan<{ label: string; slug: string }> {\n  // A name whose class name another style has is refused naming it as the\n  // author typed it, which is the name they will look for.\n  const typed = name.trim();\n  const taken = sharedStyleNameTaken(typed, sharedStyleSlug(typed), library);\n  if (taken !== undefined) return { ok: false, reason: taken };\n  // Otherwise the rename rule with no style excluded: one rule for a name, so\n  // a name refused on rename is refused here in the same words.\n  const named = renameSharedStyle(name, \"\", library);\n  if (!named.ok) return named;\n  const room = newClassName(named.slug, library);\n  if (!room.ok && room.refusal === \"library-full\") {\n    return {\n      ok: false,\n      reason: \"This site has as many shared styles as it can hold.\",\n    };\n  }\n  return { ok: true, label: named.label, slug: named.slug };\n}\n\n/**\n * \"Save as shared style\": a new style made of the block's own styles, whole\n * (every state and breakpoint, variable references as they are), and the op\n * that clears them from the block and puts the style on it. The block looks\n * the same after, because a class's rules and a block's have one specificity\n * and the class comes first: with the block's values gone, the class's apply.\n *\n * The style must be stored before the op is applied, since a page may not\n * reference a style the site does not define.\n */\nexport function planSaveAsSharedStyle(\n  document: BlockDocument,\n  nodeId: string,\n  name: string,\n  offer: SharedStyleOffer,\n  view?: LockView,\n  mintId: () => string = newId\n): SharedStylePlan<{ entry: NamedClass; ops: BuilderOp[] }> {\n  const refused = saveAsSharedStyleRefusal(document, nodeId, offer, view);\n  const node = findNode(document.nodes, nodeId);\n  const library = offer.library;\n  if (refused !== undefined || node === undefined || library === undefined) {\n    return { ok: false, reason: refused ?? \"This block can't be saved.\" };\n  }\n  const named = newSharedStyleName(name, library);\n  if (!named.ok) return named;\n  const entry: NamedClass = {\n    id: mintId(),\n    slug: named.slug,\n    label: named.label,\n    orderIndex: nextOrderIndex(library),\n    styles: node.styles ?? {},\n  };\n  return {\n    ok: true,\n    entry,\n    ops: saveAsSharedStyleOps(node, entry),\n  };\n}\n\n/**\n * Save as's page half: the new style put on the block, and the values it took\n * cleared from it. Built from the block as it stands once the style is stored,\n * so a value the block gained meanwhile (one the style does not hold) is kept.\n */\nexport function saveAsSharedStyleOps(\n  node: Pick<BlockNode, \"id\" | \"styles\" | \"classes\">,\n  entry: Pick<NamedClass, \"id\" | \"styles\">\n): BuilderOp[] {\n  return [\n    nodeStylesAndClassesOp(\n      node.id,\n      // Only what still equals what the style took: a value the author has\n      // set since, at the same place, is the block's own now.\n      uncoveredStyles(node.styles ?? {}, entry.styles, true),\n      [...(node.classes ?? []), entry.id]\n    ),\n  ];\n}\n\n/**\n * What the save dialog says will move: \"Moves this block's 6 values (2\n * devices, Hover) into Card.\" A value is one property set in one state at one\n * breakpoint; the devices are named only when there is more than one.\n */\nexport function sharedStyleMoveSummary(\n  styles: NodeStyles | undefined,\n  name: string\n): string {\n  const into = name.trim() === \"\" ? \"the new shared style\" : name.trim();\n  return `Moves ${sharedStyleMoveWhat(styles)} into ${into}.`;\n}\n\n/**\n * What a save would move, in words: \"this block's 6 values (2 devices,\n * Hover)\". The summary's subject, also said on its own while the name in\n * the dialog cannot be used.\n */\nexport function sharedStyleMoveWhat(styles: NodeStyles | undefined): string {\n  const { values, devices, states } = countValues(styles);\n  const extras = [\n    ...(devices > 1 ? [`${devices} devices`] : []),\n    ...states.map(stateLabel),\n  ];\n  const what = `${values} ${values === 1 ? \"value\" : \"values\"}`;\n  const detail = extras.length > 0 ? ` (${extras.join(\", \")})` : \"\";\n  return `this block's ${what}${detail}`;\n}\n\n/**\n * The values an envelope sets, how many breakpoints they sit at, and the\n * states other than Normal that hold any, for the move summary.\n */\nfunction countValues(styles: NodeStyles | undefined): {\n  values: number;\n  devices: number;\n  states: StyleState[];\n} {\n  let values = 0;\n  const devices = new Set<string>();\n  const states: StyleState[] = [];\n  for (const [state, byBreakpoint] of ownEntries<object>(styles)) {\n    const sets = ownEntries<object>(byBreakpoint).filter(\n      ([, set]) => ownEntries(set).length > 0\n    );\n    for (const [breakpoint, set] of sets) {\n      values += ownEntries(set).length;\n      devices.add(breakpoint);\n    }\n    if (sets.length > 0 && state !== \"base\") states.push(state as StyleState);\n  }\n  return { values, devices: devices.size, states };\n}\n\n/** Whether a stored value holds named sub-values (a token reference does not). */\nfunction isComposite(\n  value: StyleValue | undefined\n): value is { readonly [key: string]: StyleValue } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    !Array.isArray(value) &&\n    !isTokenRef(value)\n  );\n}\n\n/** A record's own entries, with `__proto__` read as a key like any other. */\nfunction ownEntries<T>(record: unknown): [string, T][] {\n  // The envelope guard the style readers use at every level (`isPlainRecord`,\n  // as `stateHasOwnValues` asks it): a stored tier that is null, a primitive\n  // or an array holds nothing the compiler emits, and is read as empty here\n  // rather than thrown on.\n  return isPlainRecord(record) ? (Object.entries(record) as [string, T][]) : [];\n}\n\n/** A copy of a record defining one more own key, whatever its name. */\nfunction withKey<T>(\n  record: Record<string, T>,\n  key: string,\n  value: T\n): Record<string, T> {\n  const copy = { ...record };\n  Object.defineProperty(copy, key, {\n    value,\n    enumerable: true,\n    writable: true,\n    configurable: true,\n  });\n  return copy;\n}\n\n/**\n * The op that stores a block's styles and classes, removing a field that\n * empties rather than storing an empty one, so its undo puts back exactly\n * what was there.\n */\nfunction nodeStylesAndClassesOp(\n  nodeId: string,\n  styles: NodeStyles,\n  classes: readonly string[]\n): BuilderOp {\n  const patch: { styles?: NodeStyles; classes?: string[] } = {};\n  const unset: (\"styles\" | \"classes\")[] = [];\n  if (hasOwnStyles(styles)) patch.styles = styles;\n  else unset.push(\"styles\");\n  if (classes.length > 0) patch.classes = [...classes];\n  else unset.push(\"classes\");\n  return unset.length > 0\n    ? { kind: \"update\", id: nodeId, patch, unset }\n    : { kind: \"update\", id: nodeId, patch };\n}\n\n/**\n * The block a page edit of its design would change, or why it may not be\n * changed: its lock's words, the ones the inspector shows for it.\n */\nfunction editableNode(\n  document: BlockDocument,\n  nodeId: string,\n  view: LockView | undefined\n): SharedStylePlan<{ node: BlockNode }> {\n  const locked = designReadOnlyReason(document, nodeId, view);\n  const node = findNode(document.nodes, nodeId);\n  if (locked !== undefined || node === undefined) {\n    return {\n      ok: false,\n      reason: locked ?? \"This block is no longer on the page.\",\n    };\n  }\n  return { ok: true, node };\n}\n\n/**\n * One value with what another sets at the same place removed: a composite\n * keeps the sides the other leaves alone; anything else is gone once the\n * other sets it.\n */\nfunction uncoveredValue(\n  under: StyleValue,\n  over: StyleValue | undefined,\n  onlyEqual: boolean\n): StyleValue | undefined {\n  if (over === undefined) return under;\n  if (!isComposite(under) || !isComposite(over)) {\n    // Taken out where `over` sets it, or, asked for equal values only, where\n    // it sets the very same value (the op layer's own comparison).\n    return onlyEqual && !sameStyleValue(under, over) ? under : undefined;\n  }\n  let left: Record<string, StyleValue> = {};\n  for (const [key, value] of ownEntries<StyleValue>(under)) {\n    const kept = uncoveredValue(\n      value,\n      Object.hasOwn(over, key) ? over[key] : undefined,\n      onlyEqual\n    );\n    if (kept !== undefined) left = withKey(left, key, kept);\n  }\n  return Object.keys(left).length > 0 ? left : undefined;\n}\n\n/** A record's own entry at a key, or an empty one, `__proto__` included. */\nfunction ownRecord<T>(record: unknown, key: string): Record<string, T> {\n  // Guarded as `ownEntries` is: anything but a plain record reads as empty.\n  if (!isPlainRecord(record) || !Object.hasOwn(record, key)) return {};\n  const value = record[key];\n  return isPlainRecord(value) ? (value as Record<string, T>) : {};\n}\n\n/** One breakpoint's values with what another sets taken out, property by property. */\nfunction uncoveredValues(\n  under: object,\n  over: Record<string, StyleValue>,\n  onlyEqual: boolean\n): Record<string, StyleValue> {\n  let left: Record<string, StyleValue> = {};\n  for (const [property, value] of ownEntries<StyleValue>(under)) {\n    const kept = uncoveredValue(\n      value,\n      Object.hasOwn(over, property) ? over[property] : undefined,\n      onlyEqual\n    );\n    if (kept !== undefined) left = withKey(left, property, kept);\n  }\n  return left;\n}\n\n/**\n * An envelope with every value another envelope sets at the same state,\n * breakpoint and property taken out: what `under` still shows once `over`,\n * coming after it, has applied. With `onlyEqual`, only the values `over` sets\n * to the very same value are taken out.\n */\nfunction uncoveredStyles(\n  under: NodeStyles,\n  over: NodeStyles,\n  onlyEqual = false\n): NodeStyles {\n  let left: Record<string, Record<string, Record<string, StyleValue>>> = {};\n  for (const [state, byBreakpoint] of ownEntries<object>(under)) {\n    const overBreakpoints = ownRecord<Record<string, StyleValue>>(over, state);\n    for (const [breakpoint, values] of ownEntries<object>(byBreakpoint)) {\n      const set = uncoveredValues(\n        values,\n        ownRecord<StyleValue>(overBreakpoints, breakpoint),\n        onlyEqual\n      );\n      if (Object.keys(set).length === 0) continue;\n      left = withKey(\n        left,\n        state,\n        withKey(ownRecord(left, state), breakpoint, set)\n      );\n    }\n  }\n  return left;\n}\n\n/** One value a tier sets for one property: a composite's sides one by one. */\ninterface StyleLeafValue {\n  /** The property and the path inside it, as one comparable key. */\n  readonly key: string;\n  readonly path: readonly string[];\n  readonly value: StyleValue;\n}\n\n/** One breakpoint's values as leaves, a composite's sides each their own. */\nfunction leavesOf(\n  values: unknown,\n  path: readonly string[] = []\n): StyleLeafValue[] {\n  const leaves: StyleLeafValue[] = [];\n  for (const [key, value] of ownEntries<StyleValue>(values)) {\n    const at = [...path, key];\n    if (isComposite(value)) leaves.push(...leavesOf(value, at));\n    else leaves.push({ key: JSON.stringify(at), path: at, value });\n  }\n  return leaves;\n}\n\n/**\n * One state at one width band: the rules that apply there, in the order the\n * compiler writes them inside a tier (`STYLE_STATES` outer, then the site's\n * contexts widest first), so the last that sets a value is the one shown.\n */\ninterface LookSituation {\n  readonly state: StyleState;\n  readonly breakpoint: string;\n  readonly states: readonly StyleState[];\n  readonly breakpoints: readonly string[];\n}\n\n/**\n * Every state at every band the site defines, in an order where a value\n * written at one situation's own place reaches only situations after it.\n *\n * A band is a viewport width band crossed with a query-container band, or\n * with no query container at all, since the browser applies both axes at\n * once. Its place is the last context that applies there in the order the\n * compiler writes them, which is where a rule on the block wins it. Bands\n * are taken by that place, and base before the interaction states.\n */\nfunction lookSituations(set: BreakpointSet | undefined): LookSituation[] {\n  const contexts = breakpointContexts(set);\n  const ids = contexts.map(context => context.id);\n  const onAxis = (axis: string): string[] =>\n    contexts\n      .filter(context => context.axis === axis)\n      .map(context => context.id);\n  const containers: (string | undefined)[] = [\n    undefined,\n    ...onAxis(\"container\"),\n  ];\n  const bands = onAxis(\"viewport\").flatMap(viewport =>\n    containers.map(container => {\n      // The contexts that match within the band, by the reader the\n      // inspector asks the same question with, one axis at a time.\n      const live = new Set<string>([\n        ...liveBreakpointsFor(set, viewport),\n        ...(container === undefined ? [] : liveBreakpointsFor(set, container)),\n      ]);\n      const breakpoints = ids.filter(id => live.has(id));\n      return { breakpoint: breakpoints.at(-1) ?? viewport, breakpoints };\n    })\n  );\n  // Stable, so bands sharing a place keep the viewport's own order.\n  bands.sort((a, b) => ids.indexOf(a.breakpoint) - ids.indexOf(b.breakpoint));\n  return STYLE_STATES.flatMap(state =>\n    bands.map(band => ({\n      state,\n      ...band,\n      states: state === \"base\" ? [\"base\"] : [\"base\", state],\n    }))\n  );\n}\n\n/**\n * The value each leaf shows in one situation, from tiers in the order the\n * page writes them: every rule has one weight (a state's selector is\n * wrapped in `:where()`), so the last applying rule wins.\n */\nfunction shownIn(\n  tiers: readonly NodeStyles[],\n  situation: LookSituation\n): Map<string, StyleLeafValue> {\n  const shown = new Map<string, StyleLeafValue>();\n  for (const tier of tiers) {\n    for (const state of situation.states) {\n      const byBreakpoint = ownRecord<unknown>(tier, state);\n      for (const breakpoint of situation.breakpoints) {\n        for (const leaf of leavesOf(ownRecord(byBreakpoint, breakpoint))) {\n          shown.set(leaf.key, leaf);\n        }\n      }\n    }\n  }\n  return shown;\n}\n\n/** An envelope holding one leaf at one state and breakpoint. */\nfunction styleOfLeaf(\n  state: string,\n  breakpoint: string,\n  leaf: StyleLeafValue\n): NodeStyles {\n  let value: StyleValue = leaf.value;\n  for (const key of [...leaf.path.slice(1)].reverse()) {\n    value = withKey<StyleValue>({}, key, value);\n  }\n  const values = withKey<StyleValue>({}, leaf.path[0] ?? \"\", value);\n  return withKey({}, state, withKey({}, breakpoint, values));\n}\n\n/**\n * The block's styles once a set of shared styles stops applying, holding\n * what the page shows today in every state and at every width.\n *\n * Each situation is compared before and after, and where a leaf would show\n * something else, the value it shows today is written on the block at that\n * situation's own place: the last rule to apply there, since the block's\n * rules come after every style's. Situations are taken in an order where\n * such a write reaches only those still to come, so each is settled once.\n * The block's own values always win already, so they are kept as they are.\n */\nfunction lookKept(\n  before: readonly NodeStyles[],\n  after: readonly NodeStyles[],\n  own: NodeStyles,\n  set: BreakpointSet | undefined\n): NodeStyles | undefined {\n  let kept = own;\n  const situations = lookSituations(set);\n  for (const situation of situations) {\n    const now = shownIn([...after, kept], situation);\n    for (const [key, was] of shownIn([...before, own], situation)) {\n      const shown = now.get(key);\n      if (shown !== undefined && sameStyleValue(shown.value, was.value)) {\n        continue;\n      }\n      kept = overlaidStyles(\n        kept,\n        styleOfLeaf(situation.state, situation.breakpoint, was)\n      );\n    }\n  }\n  /*\n   * Checked as a whole once written: a look that depends on a viewport and a\n   * container width together can need two values at one place, which the\n   * block's own rules, having no combined queries, cannot hold. Detach then\n   * keeps nothing rather than a look that differs somewhere.\n   */\n  const keeps = situations.every(situation =>\n    sameLook(\n      shownIn([...before, own], situation),\n      shownIn([...after, kept], situation)\n    )\n  );\n  return keeps ? kept : undefined;\n}\n\n/** Whether two situations show every leaf alike, none missing from either. */\nfunction sameLook(\n  was: ReadonlyMap<string, StyleLeafValue>,\n  now: ReadonlyMap<string, StyleLeafValue>\n): boolean {\n  if (was.size !== now.size) return false;\n  for (const [key, leaf] of was) {\n    const shown = now.get(key);\n    if (shown === undefined || !sameStyleValue(shown.value, leaf.value)) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/** Why a style can't be detached when its look can't be kept exactly. */\nexport const DETACH_LOOK_NOT_KEPT =\n  \"This look depends on screen and container width together, so it can't be detached yet.\";\n\n/**\n * \"Detach\": keep the look on this block only. The style is taken off the\n * block, and the block is given what it needs to show what it shows today, in\n * every state and at every width: the detached style's values where they win,\n * and, since the block's own rules come after every style's, a later style's\n * narrower or interaction-state value wherever the copy would otherwise beat\n * it. The block's own values are kept as they are. Where that can't be done\n * exactly (a look that depends on a viewport and a container width\n * together), it refuses and the style stays worn. A page edit, so a locked\n * style may be detached; the block's own lock refuses.\n *\n * @param worn - every shared style the block wears, in library order\n */\nexport function planDetachSharedStyle(\n  document: BlockDocument,\n  nodeId: string,\n  style: Pick<NamedClass, \"id\" | \"styles\">,\n  worn: readonly Pick<NamedClass, \"id\" | \"styles\">[],\n  view?: LockView,\n  breakpoints?: BreakpointSet\n): SharedStylePlan<{ ops: BuilderOp[] }> {\n  const held = editableNode(document, nodeId, view);\n  if (!held.ok) return held;\n  const node = held.node;\n  // The styles in the order the page writes them, the detached one among\n  // them (first, should the list not hold it), and the same without it.\n  const listed = worn.some(row => row.id === style.id);\n  const before = [...(listed ? [] : [style]), ...worn].map(row => row.styles);\n  const after = worn.filter(row => row.id !== style.id).map(row => row.styles);\n  const kept = lookKept(before, after, node.styles ?? {}, breakpoints);\n  // Refused, the style still worn, rather than a look changed quietly.\n  if (kept === undefined) return { ok: false, reason: DETACH_LOOK_NOT_KEPT };\n  return {\n    ok: true,\n    ops: [\n      nodeStylesAndClassesOp(\n        nodeId,\n        kept,\n        withClassRemoved(node.classes ?? [], style.id)\n      ),\n    ],\n  };\n}\n\n/** Take a shared style off a block, leaving the block's own values. */\nexport function planRemoveSharedStyle(\n  document: BlockDocument,\n  nodeId: string,\n  styleId: string,\n  view?: LockView\n): SharedStylePlan<{ ops: BuilderOp[] }> {\n  const held = editableNode(document, nodeId, view);\n  if (!held.ok) return held;\n  const node = held.node;\n  const classes = withClassRemoved(node.classes ?? [], styleId);\n  return {\n    ok: true,\n    ops: [\n      classes.length > 0\n        ? { kind: \"update\", id: nodeId, patch: { classes } }\n        : { kind: \"update\", id: nodeId, patch: {}, unset: [\"classes\"] },\n    ],\n  };\n}\n\n/**\n * One edit to a shared style, applied to whatever its styles are when the\n * host stores it: an edit is a change at one address, never a whole envelope,\n * so two edits made before the first is stored both survive.\n */\nexport interface SharedStyleChange {\n  (styles: NodeStyles): SharedStyleWrite;\n  /**\n   * The change that puts back what this one replaced, given the styles it was\n   * applied to: the same address, its previous value (or cleared, where it\n   * held none). An undo is then a change at that address too, applied to the\n   * style as it stands when undone, so nothing else changed meanwhile is\n   * put back with it.\n   */\n  readonly invert: (before: NodeStyles) => SharedStyleChange;\n}\n\n/** The change that sets (or with `null`, clears) one control's value. */\nexport function sharedStyleChange(\n  address: StyleAddress,\n  value: StyleValue | null,\n  policy?: StylePolicy\n): SharedStyleChange {\n  return sharedStyleChanges([{ address, value }], policy);\n}\n\n/** One address of a {@link sharedStyleChanges} change, and its value or `null`. */\nexport interface SharedStyleSet {\n  readonly address: StyleAddress;\n  readonly value: StyleValue | null;\n}\n\n/**\n * The change that sets (or clears) several addresses as one: the sides of a\n * margin set together in a shared style, stored by the host as one change and\n * so undone as one. Each write is judged on its own leaf, folded onto the\n * last, and the first refusal refuses the whole; its inverse puts back every\n * address's previous value at once.\n */\nexport function sharedStyleChanges(\n  sets: readonly SharedStyleSet[],\n  policy?: StylePolicy\n): SharedStyleChange {\n  return Object.assign(\n    (styles: NodeStyles): SharedStyleWrite => foldSets(styles, sets, policy),\n    {\n      invert: (before: NodeStyles) =>\n        sharedStyleChanges(\n          sets.map(set => ({\n            address: set.address,\n            value: readStyleValue(before, set.address) ?? null,\n          })),\n          policy\n        ),\n    }\n  );\n}\n\n/** Several writes folded onto one style's styles, each onto the last. */\nfunction foldSets(\n  styles: NodeStyles,\n  sets: readonly SharedStyleSet[],\n  policy: StylePolicy | undefined\n): SharedStyleWrite {\n  let current = styles;\n  let changed = false;\n  for (const set of sets) {\n    const write = sharedStyleWrite(current, set.address, set.value, policy);\n    if (write.kind === \"refused\") return write;\n    if (write.kind === \"write\") {\n      current = write.styles;\n      changed = true;\n    }\n  }\n  return changed ? { kind: \"write\", styles: current } : { kind: \"unchanged\" };\n}\n\n/** A style write's answer: the styles to store, no change, or the refusal. */\nexport type SharedStyleWrite =\n  | { readonly kind: \"write\"; readonly styles: NodeStyles }\n  | { readonly kind: \"unchanged\" }\n  | { readonly kind: \"refused\"; readonly reason: string };\n\n/** The styles an op over a style's envelope stores, read off the op. */\nfunction stylesOfWrite(write: StyleWrite): SharedStyleWrite {\n  if (!write.ok) {\n    return {\n      kind: \"refused\",\n      reason: write.issues[0]?.message ?? \"This value cannot be used here.\",\n    };\n  }\n  if (write.op === null) return { kind: \"unchanged\" };\n  const patch = write.op.kind === \"update\" ? write.op.patch : undefined;\n  const styles =\n    patch !== undefined && \"styles\" in patch ? patch.styles : undefined;\n  return { kind: \"write\", styles: styles ?? {} };\n}\n\n/**\n * One control's value written into a shared style's envelope: the block's\n * own write path (`styleWriteOp`, `styleClearOp`), judged under the same\n * policy, so a value a block may hold is a value its style may hold. `null`\n * clears, as it does for a block.\n */\nexport function sharedStyleWrite(\n  styles: NodeStyles,\n  address: StyleAddress,\n  value: StyleValue | null,\n  policy?: StylePolicy\n): SharedStyleWrite {\n  // The id only names the op this reads the envelope back out of; no node\n  // is written.\n  return stylesOfWrite(\n    value === null\n      ? styleClearOp(\"\", styles, address, policy)\n      : styleWriteOp(\"\", styles, address, value, policy)\n  );\n}\n\n/**\n * \"Move to Card\": the block's value at one control written into the style\n * and cleared from the block. Two writes (the style, then the page), so the\n * style is stored first and the op applied after it lands. The style's part\n * is a change at that address, applied to the style as it is when stored.\n */\nexport function planMoveToSharedStyle(\n  node: Pick<BlockNode, \"id\" | \"styles\">,\n  style: Pick<NamedClass, \"styles\">,\n  address: StyleAddress,\n  policy?: StylePolicy\n): SharedStylePlan<{ change: SharedStyleChange; moved: StyleValue }> {\n  const value = readStyleValue(node.styles, address);\n  if (value === undefined) {\n    return { ok: false, reason: \"This block sets no value here to move.\" };\n  }\n  const change = sharedStyleChange(address, value, policy);\n  // Judged now against the styles in hand, so a value the style may not hold\n  // is refused before anything is stored.\n  const write = change(style.styles);\n  if (write.kind === \"refused\") return { ok: false, reason: write.reason };\n  return { ok: true, change, moved: value };\n}\n\n/**\n * Move to's page half: the block's value cleared at one address, built from\n * the block as it stands when the style has taken the value, so an edit made\n * to the block meanwhile is kept, at another address or at this one. Nothing\n * for a block that is gone or no longer holds the moved value there.\n */\nexport function moveToSharedStyleClear(\n  node: Pick<BlockNode, \"id\" | \"styles\"> | undefined,\n  address: StyleAddress,\n  moved: StyleValue,\n  policy?: StylePolicy\n): BuilderOp[] {\n  if (node === undefined) return [];\n  // Only the value that was moved: one the author has set here since, while\n  // the style's write was on its way, is the block's new value and stays.\n  const now = readStyleValue(node.styles, address);\n  if (now === undefined || !sameStyleValue(now, moved)) return [];\n  const cleared = styleClearOp(node.id, node.styles, address, policy);\n  return cleared.ok && cleared.op !== null ? [cleared.op] : [];\n}\n","/**\n * What the editor holds an Entry content block to, from the engine's own\n * reading of the block, so the Add panel, the toolbar and the keys refuse\n * what the save refuses before an author meets the refusal there.\n *\n * - The Add panel offers it only while a template is open: anywhere else the\n *   save refuses it, so offering it would be offering a refusal.\n * - A template holds one, so with one placed the tile stays, refused with\n *   its reason, and Duplicate is refused with the same words.\n * - Placed, it names a field at once: the first of the collection's\n *   top-level blocks fields, the only one where there is one, so the stored\n *   choice is always explicit.\n *\n * @experimental Settles when collection templates ship.\n * @module entry-content-rules\n */\nimport {\n  ENTRY_CONTENT_FIELD_PROP,\n  ENTRY_CONTENT_TYPE,\n  entryContentFieldOf,\n  entryContentIssues,\n  entryContentPlacements,\n  findNode,\n  holdsEntryContent,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * Why a second Entry content block cannot be added: the words the Add panel's\n * tile and the toolbar's Duplicate say.\n */\nexport const ENTRY_CONTENT_ONE_REASON =\n  \"A template holds one Entry content block.\";\n\n/**\n * Why an Entry content block cannot be added yet: the template's\n * collection's blocks fields are still being read, and one placed now would\n * name no field for anything to fill.\n */\nconst ENTRY_CONTENT_LOADING_REASON = \"Loading the collection’s fields…\";\n\n/**\n * Whether the Add panel offers a block of `blockName` in a document of\n * `kind`: every block anywhere, but Entry content in a template only.\n */\nexport function offeredIn(kind: unknown, blockName: string): boolean {\n  return blockName !== ENTRY_CONTENT_TYPE || kind === \"template\";\n}\n\n/**\n * Why a block of `blockName` cannot be added to `document`, or `undefined`\n * when nothing about Entry content stands in the way: the template's one is\n * already placed, or the collection's blocks fields are not known yet\n * (`fieldsKnown`), so the block would be placed naming none.\n */\nexport function entryContentRefusal(\n  document: BlockDocument,\n  blockName: string,\n  fieldsKnown = true\n): string | undefined {\n  if (blockName !== ENTRY_CONTENT_TYPE) return undefined;\n  if (entryContentPlacements(document.nodes).length > 0) {\n    return ENTRY_CONTENT_ONE_REASON;\n  }\n  return fieldsKnown ? undefined : ENTRY_CONTENT_LOADING_REASON;\n}\n\n/**\n * Why the block `id` cannot be duplicated, or `undefined` where nothing about\n * Entry content refuses it: a copy of a block holding one is a second.\n */\nexport function duplicationRefusal(\n  document: BlockDocument,\n  id: string\n): string | undefined {\n  // The block itself, or one around one, which copies it too.\n  const node = findNode(document.nodes, id);\n  return node !== undefined && holdsEntryContent(node)\n    ? ENTRY_CONTENT_ONE_REASON\n    : undefined;\n}\n\n/** Where a refused selection would have been saved, in the author's words. */\nconst KIND_PLACE: Readonly<Record<\"pattern\" | \"component\", string>> = {\n  pattern: \"to Saved sections\",\n  component: \"in a component\",\n};\n\n/**\n * Why the blocks `ids` of `document` cannot become a `kind`, a pattern or a\n * component (Save as section…, Update a saved section, Turn into component…), or\n * `undefined` where none of them holds Entry content. Asked of the save's own\n * rule (`entryContentIssues`), with the blocks as that kind would hold them:\n * it refuses Entry content anywhere but a template, and neither is one.\n */\nexport function compositionEntryContentRefusal(\n  document: BlockDocument,\n  ids: readonly string[],\n  kind: \"pattern\" | \"component\"\n): string | undefined {\n  const selected = ids.flatMap(id => {\n    const node = findNode(document.nodes, id);\n    return node === undefined ? [] : [node];\n  });\n  const refused = entryContentIssues(selected, { documentKind: kind }).some(\n    issue => issue.code === \"entry-content-outside-template\"\n  );\n  return refused\n    ? `Entry content belongs in its template, so it can’t be saved ${KIND_PLACE[kind]}.`\n    : undefined;\n}\n\n/**\n * `node` with the field an Entry content block draws filled where it names\n * none: `field`, the collection's first top-level blocks field. Any other\n * node, or one that already names a field, is returned as it was.\n */\nexport function withEntryContentField(\n  node: BlockNode,\n  field: string | undefined\n): BlockNode {\n  if (node.type !== ENTRY_CONTENT_TYPE || field === undefined) return node;\n  if (entryContentFieldOf(node) !== undefined) return node;\n  return {\n    ...node,\n    props: { ...node.props, [ENTRY_CONTENT_FIELD_PROP]: field },\n  };\n}\n","/**\n * Wrapping selected blocks in a Box, and unwrapping a container while keeping\n * what is inside it.\n *\n * Both are groups of the ordinary ops, applied together as ONE step to undo:\n *\n * - **Wrap in a box.** The selected blocks must sit side by side in one list,\n *   with no unselected block between them (the engine's `contiguousRun`). A new\n *   Box is put where the first of them is, and each is moved into it in the\n *   order a reader meets them.\n * - **Unwrap (keep what's inside).** A Box, Section, Column or Card is replaced\n *   by its blocks, in order, at its own place, and removed.\n *\n * Each result is judged by the engine's one placement rule\n * (`placementVerdict`) before anything is planned: a Box where it would land,\n * the wrapped blocks inside a Box, and an unwrapped container's blocks where\n * the container was. A refusal says why in the words a refused drop uses, so\n * a Column is never left outside Columns.\n *\n * @module selection-wrap\n */\nimport {\n  contiguousRun,\n  findNode,\n  getBlock,\n  locateNode,\n  makeNode,\n  placementVerdict,\n  type BlockDocument,\n  type BlockNode,\n  type NestingSource,\n  type PlacementTarget,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport { refusalWording } from \"./drag-refusal\";\nimport { normalizeSelection } from \"./selection\";\nimport type { SelectionRefusal } from \"./selection-ops\";\n\n/** The block a wrap puts the selection into. */\nconst BOX = \"core/box\";\n\n/** The slot a container holds its blocks in. */\nconst CHILDREN = \"children\";\n\n/** The containers that can be unwrapped, keeping their blocks. */\nconst UNWRAPPABLE: ReadonlySet<string> = new Set([\n  \"core/box\",\n  \"core/section\",\n  \"core/column\",\n  \"core/card\",\n]);\n\n/** The verbs' words, in one place. */\nexport const WRAP_WORDS = {\n  wrap: \"Wrap in a box\",\n  unwrap: \"Unwrap (keep what's inside)\",\n  notSideBySide:\n    \"Select blocks side by side in one place to wrap them in a box.\",\n} as const;\n\n/** A wrap or an unwrap, planned: its ops and what to select after it. */\nexport interface WrapPlan {\n  readonly ops: readonly BuilderOp[];\n  /** What to select once it lands: the new Box, or the unwrapped blocks. */\n  readonly select: readonly string[];\n}\n\n/** Where a node's list is, as a placement target. */\nfunction targetOf(\n  parent: BlockNode | undefined,\n  slot: string | undefined\n): PlacementTarget {\n  return parent === undefined || slot === undefined\n    ? { kind: \"root\" }\n    : { kind: \"slot\", parentType: parent.type, slot };\n}\n\n/**\n * The refusal for `types` at `where`, in a refused drop's words, if any:\n * the first type the rule refuses, named with the reason and where it may go.\n */\nfunction placementRefusal(\n  types: readonly string[],\n  where: PlacementTarget,\n  nesting: NestingSource\n): SelectionRefusal | null {\n  for (const type of types) {\n    const verdict = placementVerdict([type], where, nesting);\n    if (verdict.allowed) continue;\n    const words = refusalWording(\n      { reason: verdict.reason, permitted: verdict.permitted },\n      type,\n      where.kind === \"slot\" ? where.parentType : undefined\n    );\n    // Both lines, as a refused drop draws them: why, and what goes there.\n    return {\n      reason:\n        words.remedy === null\n          ? words.headline\n          : `${words.headline} ${words.remedy}`,\n    };\n  }\n  return null;\n}\n\n/**\n * Wrapping the selection in a new Box at its place. `null` for nothing\n * selected or no Box block in this editor; a refusal when the blocks are not\n * side by side or the placement rules forbid the result.\n */\nexport function planWrap(\n  document: BlockDocument,\n  selectedIds: readonly string[],\n  nesting: NestingSource\n): WrapPlan | SelectionRefusal | null {\n  const ids = normalizeSelection(document, selectedIds);\n  const box = getBlock(BOX);\n  if (ids.length === 0 || box === undefined) return null;\n  // Side by side with nothing unselected between them: wrapping blocks with\n  // a gap would carry the later ones ahead of what stays outside.\n  const found = contiguousRun(document.nodes, ids);\n  if (found.run === undefined) return { reason: WRAP_WORDS.notSideBySide };\n  const { run } = found;\n  const parent =\n    run.parentId === undefined\n      ? undefined\n      : findNode(document.nodes, run.parentId);\n  const refused =\n    placementRefusal([BOX], targetOf(parent, run.slot), nesting) ??\n    placementRefusal(\n      run.places.map(place => place.node.type),\n      { kind: \"slot\", parentType: BOX, slot: CHILDREN },\n      nesting\n    );\n  if (refused !== null) return refused;\n  const first = run.places[0];\n  if (first === undefined) return null;\n  const wrapper = makeNode(\n    box.name,\n    box.version,\n    structuredClone((box.defaultProps ?? {}) as Record<string, unknown>),\n    { [CHILDREN]: [] }\n  );\n  const at =\n    run.parentId === undefined || run.slot === undefined\n      ? { index: first.index }\n      : { parentId: run.parentId, slot: run.slot, index: first.index };\n  return {\n    ops: [\n      { kind: \"insert\", node: wrapper, at },\n      ...run.places.map(\n        (place, index): BuilderOp => ({\n          kind: \"move\",\n          id: place.id,\n          to: { parentId: wrapper.id, slot: CHILDREN, index },\n        })\n      ),\n    ],\n    select: [wrapper.id],\n  };\n}\n\n/** Whether a block can be unwrapped, keeping what is inside it. */\nexport function isUnwrappable(node: BlockNode | undefined): boolean {\n  return node !== undefined && UNWRAPPABLE.has(node.type);\n}\n\n/**\n * Unwrapping one container: its blocks moved to its place, in order, and the\n * container removed. `null` for a block that is not a container one can\n * unwrap; a refusal when its blocks may not sit where it was.\n */\nexport function planUnwrap(\n  document: BlockDocument,\n  id: string,\n  nesting: NestingSource\n): WrapPlan | SelectionRefusal | null {\n  const node = findNode(document.nodes, id);\n  if (node === undefined || !isUnwrappable(node)) return null;\n  const location = locateNode(document.nodes, id);\n  if (location === undefined) return null;\n  const children = node.slots?.[CHILDREN] ?? [];\n  const refused = placementRefusal(\n    children.map(child => child.type),\n    targetOf(location.parent, location.slot),\n    nesting\n  );\n  if (refused !== null) return refused;\n  const placeAt = (index: number) =>\n    location.parent === undefined || location.slot === undefined\n      ? { index }\n      : { parentId: location.parent.id, slot: location.slot, index };\n  return {\n    ops: [\n      // Each before the container, in order: the container shifts right as\n      // they arrive, so the next index is always the one after the last.\n      ...children.map(\n        (child, offset): BuilderOp => ({\n          kind: \"move\",\n          id: child.id,\n          to: placeAt(location.index + offset),\n        })\n      ),\n      { kind: \"remove\", id },\n    ],\n    select: children.map(child => child.id),\n  };\n}\n","/**\n * What the floating toolbar offers for the selected block, and where it sits.\n *\n * The structural verbs — select the container, move up, move down, duplicate,\n * delete — exist already and are reachable only by keystroke. An author who has\n * never read a shortcut list has no way to discover that this editor can\n * duplicate a block at all, so the verbs are effectively absent for most of the\n * people using them. This module is the half of that fix which can be decided\n * without a DOM.\n *\n * ## Two questions, both pure\n *\n * **Which actions, and can they run.** Every answer is delegated: whether a\n * move is possible is `keyboardMovePosition`, whether a lock forbids it is\n * `lockBlockingMove` and `lockBlockingDelete`, whether a duplicate has a\n * position is `blockDuplication`. Nothing here re-derives any of those, because\n * a toolbar that decided for itself would eventually disagree with the\n * keystroke that does the same thing — and the author would meet the\n * disagreement as a button that looks available and does nothing.\n *\n * **Where the bar goes.** Above the block, falling back to below it, clamped\n * into the canvas. Separated from the rendering so the placement rules can be\n * asserted at sizes a jsdom test cannot produce: every rectangle in jsdom is\n * zero, so a placement computed inside a component is a placement no test can\n * see.\n *\n * ## Why a disabled button rather than a hidden one\n *\n * A toolbar whose buttons come and go changes width and order as the selection\n * moves, so the control an author is aiming at is somewhere else by the time\n * they arrive. Disabled buttons keep the bar one shape, and the reason is\n * carried with the action so the surface can say why rather than leaving the\n * author to guess.\n *\n * @module toolbar-actions\n */\n\nimport {\n  findNode,\n  isComponentInstance,\n  planConvertToComponent,\n  planDetach,\n  registryNestingSource,\n  saveAsPatternRefusal,\n  type BlockDocument,\n  type BlockNode,\n  type DefinitionsById,\n  type DocumentLimits,\n  type NamedClass,\n  type NestingSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { CONVERSION_WORDS } from \"../editor-words\";\nimport type { Rect } from \"../geometry\";\nimport { placedComponentId } from \"../inspector/instance-inspector\";\nimport {\n  lockedBlockWording,\n  lockRefusalWording,\n  type LockedVerb,\n  type LockRefusalFacts,\n} from \"../lock-refusal\";\nimport {\n  lockBlockingDelete,\n  lockBlockingEdit,\n  lockBlockingMove,\n} from \"../locking\";\nimport { refusalAnnouncement } from \"../move-refusal\";\nimport type { BuilderOp, OpPosition } from \"../op-vocabulary\";\nimport { pathTo } from \"../panels/layers/layers\";\nimport {\n  saveAsSharedStyleRefusal,\n  type SharedStyleOffer,\n} from \"../styles/shared-style-target\";\n\nimport { compositionRefusalReason } from \"./composition-refusal\";\nimport { blockDeletion } from \"./delete-block\";\nimport type { RefusalWording } from \"./drag-refusal\";\nimport {\n  compositionEntryContentRefusal,\n  duplicationRefusal,\n} from \"./entry-content-rules\";\nimport {\n  keyboardMovePosition,\n  type KeyboardMove,\n  type MoveDirection,\n} from \"./keyboard-move\";\nimport {\n  isRefusal,\n  selectionDeletion,\n  selectionDuplication,\n  selectionMove,\n} from \"./selection-ops\";\nimport {\n  isUnwrappable,\n  planUnwrap,\n  planWrap,\n  WRAP_WORDS,\n} from \"./selection-wrap\";\nimport { turnIntoOffers, type TurnIntoActionId } from \"./turn-into-verb\";\n\n/** The editor's own lock question, asked of the ops a verb would apply. */\ntype LockQuestion = (ops: readonly BuilderOp[]) => LockRefusalFacts | undefined;\n\n/**\n * Why a slot's lock refuses the ops, in the words every lock refusal uses, or\n * undefined when it does not, or when the caller asked nothing.\n */\nfunction lockReason(\n  ask: LockQuestion | undefined,\n  ops: readonly BuilderOp[]\n): string | undefined {\n  const found = ask?.(ops);\n  return found === undefined\n    ? undefined\n    : refusalAnnouncement(lockRefusalWording(found));\n}\n\n/** An action enabled, or dimmed with the lock's reason when one refuses it. */\nfunction heldByLock<A extends Pick<ToolbarAction, \"enabled\" | \"reason\">>(\n  action: A,\n  ask: LockQuestion | undefined,\n  ops: readonly BuilderOp[] | undefined\n): A {\n  if (!action.enabled || ops === undefined) return action;\n  const reason = lockReason(ask, ops);\n  return reason === undefined ? action : { ...action, enabled: false, reason };\n}\n\n/** The verbs the bar offers, in the order it draws them. */\nexport type ToolbarActionId =\n  | \"select-parent\"\n  | \"move-up\"\n  | \"move-down\"\n  | \"duplicate\"\n  | \"copy\"\n  | \"cut\"\n  | \"paste\"\n  | \"copy-style\"\n  | \"paste-style\"\n  | TurnIntoActionId\n  | \"save-as-pattern\"\n  | \"save-as-shared-style\"\n  | \"edit-component\"\n  | \"turn-into-component\"\n  | \"detach-component\"\n  | \"duplicate-component\"\n  | \"update-pattern\"\n  | \"wrap-in-box\"\n  | \"unwrap\"\n  | \"delete\";\n\n/** One button's worth of decision. */\nexport interface ToolbarAction {\n  readonly id: ToolbarActionId;\n  /**\n   * The accessible name, which is also the tooltip.\n   *\n   * Fixed per verb rather than naming the block: the bar is drawn against the\n   * block it acts on, so \"Duplicate\" is unambiguous there, and a name that grew\n   * with the block's would reflow the bar on every selection.\n   */\n  readonly label: string;\n  /** Whether pressing it would do anything. */\n  readonly enabled: boolean;\n  /**\n   * Why it is disabled, phrased for an author, or `undefined` when enabled.\n   *\n   * Set for every disabled item, so nothing is dimmed without a word: a lock,\n   * which nothing on the canvas explains and whose remedy is one field away,\n   * and the plain edges too (\"Already the first block here\"), since a dimmed\n   * item with no reason reads as broken rather than as finished.\n   */\n  readonly reason?: string;\n  /**\n   * Offered from a menu rather than as a button of its own: the block\n   * toolbar keeps these behind its \"More\" button, and the context menu groups\n   * them, so the bar stays one short row however many verbs the host adds.\n   */\n  readonly inMenu?: true;\n  /**\n   * What the verb removes, said beside it before it is chosen: \"Turn into\n   * Heading\" removes bold and links. Visible text under the label, as a\n   * reason is.\n   */\n  readonly note?: string;\n}\n\n/**\n * \"Turn into Text\", \"Turn into Rich text\" and \"Turn into Heading\" for one\n * selected block that can become them, from the one offer every surface\n * reads (`turnIntoOffers`); nothing for any other block. Menu verbs, kept in\n * a group of their own, apart from \"Turn into component…\".\n */\nfunction turnIntoActions(\n  document: BlockDocument,\n  selectedId: string,\n  nesting: NestingSource,\n  ask: LockQuestion | undefined,\n  planned: boolean,\n  library: readonly NamedClass[] | undefined,\n  limits: DocumentLimits | undefined\n): ToolbarAction[] {\n  // Judged by the placement rules the rest of the menu is, which are the\n  // ones the verb runs by, and under the editor's limits the verb runs with.\n  return turnIntoOffers(document, selectedId, {\n    ...(ask === undefined ? {} : { ask }),\n    planned,\n    nesting,\n    ...(limits === undefined ? {} : { limits }),\n    // The site's styles, so a block style that gives way is said here too.\n    ...(library === undefined ? {} : { library }),\n  }).map(offer => ({\n    id: offer.id,\n    label: offer.label,\n    enabled: offer.enabled,\n    inMenu: true,\n    ...(offer.reason === undefined ? {} : { reason: offer.reason }),\n    ...(offer.note === undefined ? {} : { note: offer.note }),\n  }));\n}\n\n/**\n * What the host offers for making components from a selection.\n *\n * Absent where the host has no component library to write to, and then\n * neither verb is offered at all.\n */\nexport interface ComponentVerbsOffer {\n  /**\n   * Whether the author may create and publish components, which both verbs\n   * need: the component is created published. `false` dims both, with\n   * {@link MAKE_COMPONENT_GRANT_REFUSAL}.\n   */\n  readonly mayCreate: boolean;\n  /**\n   * The component definitions the canvas draws, which a detach inlines.\n   * Absent, Detach is not offered.\n   */\n  readonly definitions?: DefinitionsById;\n  /**\n   * Whether the author may update and publish patterns. Absent, \"Update\n   * pattern\" is not offered; `false` dims it with the reason.\n   */\n  readonly mayUpdatePattern?: boolean;\n}\n\n/** What an author without the grant to update a saved section is told. */\nconst UPDATE_PATTERN_GRANT_REFUSAL =\n  \"You do not have permission to update and publish saved sections.\";\n\n/** What an author without the grant to make a component is told. */\nconst MAKE_COMPONENT_GRANT_REFUSAL =\n  \"You do not have permission to create and publish components.\";\n\n/** The id a convert is planned under before the component exists. */\nconst PLANNED_COMPONENT_ID = \"planned-component\";\n\n/**\n * What \"Turn into component…\" may do with a selection: replace the blocks\n * with a placement of the new component, or keep them and save a copy. Each\n * way is asked of its planner rather than restated: keeping shares the\n * pattern save's selection rules; replacing is planned in full, and the ops\n * it would apply are put to the editor's lock question, since a slot's lock\n * can refuse the placement that replaces the run. A way that is refused\n * carries its reason; both open, the object is empty.\n */\nexport interface TurnIntoChoice {\n  /** Why the blocks cannot be replaced, so only a copy can be saved. */\n  readonly replaceRefused?: string;\n  /** Why no copy can be saved leaving them, so only replacing is open. */\n  readonly keepRefused?: string;\n}\n\n/** Each way \"Turn into component…\" may go, and why not where it may not. */\nexport function turnIntoChoice(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  ask?: LockQuestion\n): TurnIntoChoice {\n  // Entry content first: neither way makes a component that may hold it.\n  const entryContent = compositionEntryContentRefusal(\n    document,\n    ids,\n    \"component\"\n  );\n  if (entryContent !== undefined) {\n    return { replaceRefused: entryContent, keepRefused: entryContent };\n  }\n  const saving = saveAsPatternRefusal(document, ids, nesting);\n  const converting = planConvertToComponent(\n    document,\n    ids,\n    { collection: \"\", fields: {} },\n    PLANNED_COMPONENT_ID,\n    {},\n    nesting\n  );\n  const replaceRefused =\n    converting.problem !== undefined\n      ? compositionRefusalReason(converting)\n      : converting.pageOps === undefined\n        ? undefined\n        : lockReason(ask, converting.pageOps);\n  return {\n    ...(replaceRefused === undefined ? {} : { replaceRefused }),\n    ...(saving === undefined\n      ? {}\n      : { keepRefused: compositionRefusalReason(saving) }),\n  };\n}\n\n/**\n * \"Turn into component…\": ONE item for both ways of making a component from\n * the selection, the choice between them made in its dialog. Offered while\n * either way is open; dimmed, with the reason, when neither is.\n */\nfunction componentActions(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  offer: ComponentVerbsOffer | undefined,\n  ask: LockQuestion | undefined,\n  planned: boolean\n): ToolbarAction[] {\n  if (offer === undefined) return [];\n  const turn: ToolbarAction = {\n    id: \"turn-into-component\",\n    label: CONVERSION_WORDS.turnIntoComponent,\n    enabled: true,\n    inMenu: true,\n  };\n  if (!offer.mayCreate) {\n    return [{ ...turn, enabled: false, reason: MAKE_COMPONENT_GRANT_REFUSAL }];\n  }\n  if (!planned) return [turn];\n  const choice = turnIntoChoice(document, ids, nesting, ask);\n  if (choice.replaceRefused !== undefined && choice.keepRefused !== undefined) {\n    return [{ ...turn, enabled: false, reason: choice.replaceRefused }];\n  }\n  return [turn];\n}\n\n/**\n * \"Detach\" and \"Duplicate component\" for one selected placement, and nothing\n * for any other selection, so a menu over a heading does not grow verbs that\n * could never apply to it. Detach is planned in full against the definitions\n * the canvas draws, and its ops are put to the editor's lock question.\n */\nfunction placementActions(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  offer: ComponentVerbsOffer | undefined,\n  ask: LockQuestion | undefined,\n  planned: boolean\n): ToolbarAction[] {\n  const only = ids.length === 1 ? ids[0] : undefined;\n  if (offer === undefined || only === undefined) return [];\n  const node = findNode(document.nodes, only);\n  if (node === undefined || !isComponentInstance(node)) return [];\n  const actions: ToolbarAction[] =\n    offer.definitions === undefined\n      ? []\n      : [\n          detachAction(\n            document,\n            only,\n            offer.definitions,\n            nesting,\n            planned ? ask : null\n          ),\n        ];\n  const duplicate: ToolbarAction = {\n    id: \"duplicate-component\",\n    label: \"Duplicate component\",\n    enabled: true,\n    inMenu: true,\n  };\n  if (!offer.mayCreate) {\n    actions.push({\n      ...duplicate,\n      enabled: false,\n      reason: MAKE_COMPONENT_GRANT_REFUSAL,\n    });\n    return actions;\n  }\n  // The copy is made from the component as this author may read it; one the\n  // canvas could not load for them is not one they can copy.\n  const source = (node.props as { componentId?: unknown }).componentId;\n  if (\n    offer.definitions !== undefined &&\n    (typeof source !== \"string\" || !offer.definitions.has(source))\n  ) {\n    actions.push({\n      ...duplicate,\n      enabled: false,\n      reason: \"This component is not available to copy.\",\n    });\n    return actions;\n  }\n  // The re-point is an edit of the placement, so a Layers lock on it or around\n  // it refuses Duplicate as it refuses any edit (`lockBlockingEdit`), in the\n  // one wording; a slot's lock is the lock question's, through `heldByLock`.\n  const held = lockBlockingEdit(document, only);\n  actions.push(\n    held === undefined\n      ? heldByLock(duplicate, ask, [\n          {\n            kind: \"update\",\n            id: only,\n            patch: {\n              props: { ...node.props, componentId: PLANNED_COMPONENT_ID },\n            },\n          },\n        ])\n      : {\n          ...duplicate,\n          enabled: false,\n          reason: lockedBy(held, only, \"change\"),\n        }\n  );\n  return actions;\n}\n\n/**\n * \"Detach from component\" for one placement: planned in full against the\n * definitions the canvas draws, its ops put to the editor's lock question,\n * where `ask` is not `null`; offered as it stands where it is (the plan is\n * then made when a menu opens, or when the verb runs).\n */\nfunction detachAction(\n  document: BlockDocument,\n  only: string,\n  definitions: DefinitionsById,\n  nesting: NestingSource,\n  ask: LockQuestion | undefined | null\n): ToolbarAction {\n  const detach: ToolbarAction = {\n    id: \"detach-component\",\n    label: CONVERSION_WORDS.detachFromComponent,\n    enabled: true,\n    inMenu: true,\n  };\n  if (ask === null) return detach;\n  const plan = planDetach(document, only, definitions, nesting);\n  return plan.problem === undefined\n    ? heldByLock(detach, ask, plan.pageOps)\n    : { ...detach, enabled: false, reason: compositionRefusalReason(plan) };\n}\n\n/**\n * \"Update pattern\" for a selection that could be saved as one, where the host\n * offers it: the selection replaces a pattern's content.\n */\nfunction updatePatternAction(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  offer: ComponentVerbsOffer | undefined,\n  planned: boolean\n): ToolbarAction[] {\n  if (offer?.mayUpdatePattern === undefined) return [];\n  const action: ToolbarAction = {\n    id: \"update-pattern\",\n    label: \"Update a saved section\",\n    enabled: true,\n    inMenu: true,\n  };\n  if (!offer.mayUpdatePattern) {\n    return [\n      { ...action, enabled: false, reason: UPDATE_PATTERN_GRANT_REFUSAL },\n    ];\n  }\n  const reason = patternRefusal(document, ids, nesting, planned);\n  return [\n    reason === undefined ? action : { ...action, enabled: false, reason },\n  ];\n}\n\n/** Every verb of the menu's component group, in the order it lists them. */\nfunction compositionActions(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  offer: ComponentVerbsOffer | undefined,\n  ask: LockQuestion | undefined,\n  planned: boolean\n): ToolbarAction[] {\n  return [\n    ...componentActions(document, ids, nesting, offer, ask, planned),\n    ...placementActions(document, ids, nesting, offer, ask, planned),\n    ...updatePatternAction(document, ids, nesting, offer, planned),\n  ];\n}\n\n/**\n * What a Layers-lock refusal says on a button or a menu item: the headline of\n * the one wording every surface uses, the locked block by name and where it\n * sits relative to the selected one. Short, because it is said beside the\n * verb; the way forward is in the block card and in what a keystroke says.\n */\nfunction lockedBy(\n  locked: BlockNode,\n  selectedId: string,\n  verb: LockedVerb\n): string {\n  return lockedBlockWording(locked, selectedId, verb).headline;\n}\n\n/**\n * Where a block's move in one direction goes: the keyboard move's own answer.\n *\n * Passed in by a caller that runs the move, so the availability it shows is\n * asked with the very function, and the very component definitions, its verb\n * moves by. The default reads no definitions, as the bar's Move up and Move\n * down always have — a step within one list needs none.\n */\nexport type MovePosition = (\n  document: BlockDocument,\n  id: string,\n  direction: MoveDirection\n) => KeyboardMove | null;\n\n/**\n * Whether the placement rule refuses a block's move to `to`, and its words,\n * or `null` when it allows it. Passed in by a caller that runs the move, so\n * an item it offers is judged by the very call its verb judges by.\n */\nexport type MoveJudge = (\n  document: BlockDocument,\n  id: string,\n  to: OpPosition\n) => RefusalWording | null;\n\nconst POSITION_WITHOUT_DEFINITIONS: MovePosition = (document, id, direction) =>\n  keyboardMovePosition(document.nodes, id, direction);\n\n/** Why a verb that acts on one block is not offered for a set. */\nfunction oneAtATime(count: number): string {\n  return `Only one block at a time. ${count} are selected.`;\n}\n\n/**\n * One block's move in one direction, as an action: dimmed when the block is\n * locked or has nowhere to go that way, and when a slot's lock refuses it.\n *\n * Where it goes is the keyboard move's own answer (`keyboardMovePosition`), so\n * an action offered here is the step its keystroke takes. Whether the\n * placement rule allows it there is asked when it runs, by the same verb the\n * keystroke runs, which says why when it does not.\n */\nfunction singleMove<Id extends string>(\n  document: BlockDocument,\n  selectedId: string,\n  id: Id,\n  label: string,\n  direction: MoveDirection,\n  ask: LockQuestion | undefined,\n  position: MovePosition = POSITION_WITHOUT_DEFINITIONS,\n  judge?: MoveJudge\n): Omit<ToolbarAction, \"id\"> & { readonly id: Id } {\n  const moveLock = lockBlockingMove(document, selectedId);\n  if (moveLock !== undefined) {\n    return {\n      id,\n      label,\n      enabled: false,\n      reason: lockedBy(moveLock, selectedId, \"move\"),\n    };\n  }\n  const to = position(document, selectedId, direction);\n  // The placement rule's refusal, said where the author would press.\n  const refused =\n    to === null || judge === undefined\n      ? null\n      : judge(document, selectedId, to.to);\n  if (refused !== null) {\n    return { id, label, enabled: false, reason: refusalAnnouncement(refused) };\n  }\n  return heldByLock(\n    to === null\n      ? { id, label, enabled: false, reason: EDGE_REASONS[direction] }\n      : { id, label, enabled: true },\n    ask,\n    to === null\n      ? undefined\n      : [\n          {\n            kind: \"move\",\n            id: selectedId,\n            to: to.to,\n            dropSlotIfEmpty: to.dropSlotIfEmpty,\n          },\n        ]\n  );\n}\n\n/**\n * Why a block, or a set moving as one, cannot move one step when there is\n * simply nowhere to go: said as plainly as a lock is, since a dimmed item with\n * no reason reads as broken. Worded to stay true for every `null` the keyboard\n * move gives: an indent is refused both with no block above and with one\n * whose several regions leave none to name, and the set's edge is its first\n * or last block's.\n */\nconst EDGE_REASONS: Record<MoveDirection, string> = {\n  up: \"Already at the top here\",\n  down: \"Already at the bottom here\",\n  indent: \"No block just above that it can go into\",\n  outdent: \"Already at the top level of the page\",\n};\n\n/**\n * Whether a set can move one step, and what to say when it cannot.\n *\n * The plan itself is the answer: `selectionMove` already decides that a set\n * straddling two containers has nowhere to go and that one block at the edge\n * holds the rest, and asking it here keeps the bar agreeing with the keyboard\n * rather than testing those rules a second time.\n *\n * `null` is the edge of the container, which is dimmed with the same reason\n * a single block at the end of its list gives.\n */\nfunction moveAction(\n  document: BlockDocument,\n  ids: readonly string[],\n  id: \"move-up\" | \"move-down\",\n  label: string,\n  direction: \"up\" | \"down\",\n  ask?: LockQuestion\n): ToolbarAction {\n  const plan = selectionMove(document, ids, direction);\n  if (plan === null)\n    return { id, label, enabled: false, reason: EDGE_REASONS[direction] };\n  if (isRefusal(plan))\n    return { id, label, enabled: false, reason: plan.reason };\n  return heldByLock({ id, label, enabled: true }, ask, plan.ops);\n}\n\n/**\n * Whether this selection could be stored in the library, and why not.\n *\n * ASKED OF THE PLANNER, never restated. The ways a selection can be unsavable\n * are not a short list a toolbar should keep its own copy of — a run with a gap,\n * a block that may not be a document root, a node the op layer will not carry,\n * one HTML id on two of the run's nodes, a document past the byte cap — and a\n * surface enumerating them drifts the first time the planner learns a new way to\n * say no. It drifts SILENTLY: the button stays enabled and the save fails.\n *\n * Offered for a SET as readily as for one block, because saving several blocks\n * as one pattern is the ordinary case rather than the exception — a hero is a\n * heading, a paragraph and a button.\n *\n * The refusal carries a reason whatever the cause, unlike a move at the edge of\n * its container. There is nothing on the canvas that explains why a selection\n * cannot be saved, so leaving it dimmed and silent would be a control an author\n * can only guess at.\n */\n/**\n * What an author is told when they hold no grant to save a pattern.\n *\n * Names the OPERATION the author attempted, not a permission. Saving needs more\n * than one grant — the pattern is stored and published in the same act — so a\n * message naming any single one is wrong for somebody: an author who may create\n * a pattern but not publish it would be told they cannot create, and would go\n * and ask for the grant they already hold. \"Save\" is also the word on the\n * control they pressed, which is the thing they can describe when they ask.\n *\n * Which grant is missing is deliberately NOT reported. The answer arrives as\n * one boolean because that is the question the verb asks, and a message\n * enumerating server-side permission names would tie this copy to slugs the\n * browser has no other reason to know — the same coupling the resolved-slug\n * lookup exists to avoid.\n *\n * ONE string, exported, because two surfaces say it: this list, which dims the\n * control and titles it, and the runner in `keyboard-actions`, which announces\n * it when a dimmed control is pressed anyway. Written twice they would drift,\n * and the drift would be invisible — each reads correctly on its own.\n */\nexport const SAVE_PATTERN_GRANT_REFUSAL =\n  \"You do not have permission to save to Saved sections.\";\n\nfunction saveAction(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  mayCreate: boolean,\n  planned: boolean\n): ToolbarAction {\n  const label = CONVERSION_WORDS.saveAsSection;\n  // The GRANT first, and it is the one refusal not asked of the planner —\n  // because it is not about this selection. Every other reason a save is\n  // refused describes the blocks in hand, so a planner that learns a new one\n  // is still describing them; whether the author may create a pattern at all\n  // is true of the next selection too. Asked first so an author who cannot\n  // save is told that, rather than told why these particular blocks are\n  // unsuitable for a thing they could not have saved either way.\n  if (!mayCreate)\n    return {\n      id: \"save-as-pattern\",\n      label,\n      enabled: false,\n      reason: SAVE_PATTERN_GRANT_REFUSAL,\n    };\n  const reason = patternRefusal(document, ids, nesting, planned);\n  if (reason === undefined)\n    return { id: \"save-as-pattern\", label, enabled: true };\n  return { id: \"save-as-pattern\", label, enabled: false, reason };\n}\n\n/**\n * Why the selection cannot be saved as a pattern, in the words the menu and\n * the keys say, or `undefined` where it can: Entry content first, which a\n * pattern may not hold (`compositionEntryContentRefusal`), then the save's\n * planner. One answer for Save as pattern and Update a pattern, whichever\n * route asks.\n */\nexport function patternSaveRefusal(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource\n): string | undefined {\n  const entryContent = compositionEntryContentRefusal(document, ids, \"pattern\");\n  if (entryContent !== undefined) return entryContent;\n  const refusal = saveAsPatternRefusal(document, ids, nesting);\n  return refusal === undefined ? undefined : compositionRefusalReason(refusal);\n}\n\n/**\n * {@link patternSaveRefusal} where the save is `planned`; otherwise only the\n * Entry content rule, which reads the selection without building the pattern\n * a save would store. The planner's other refusals are then said when the\n * verb runs, or in a menu, which plans it as it opens.\n */\nfunction patternRefusal(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  planned: boolean\n): string | undefined {\n  return planned\n    ? patternSaveRefusal(document, ids, nesting)\n    : compositionEntryContentRefusal(document, ids, \"pattern\");\n}\n\n/**\n * \"Save as shared style…\" for one block, where the host offers shared\n * styles: dimmed with the reason the save rule gives (one style per block in\n * the first release, a block with no styles of its own, the author's right,\n * the block's lock), asked of that rule rather than restated.\n */\nfunction sharedStyleActions(\n  document: BlockDocument,\n  ids: readonly string[],\n  offer: SharedStyleOffer | undefined\n): ToolbarAction[] {\n  if (offer === undefined) return [];\n  const action: ToolbarAction = {\n    id: \"save-as-shared-style\",\n    label: \"Save as shared style…\",\n    enabled: true,\n    inMenu: true,\n  };\n  const only = ids.length === 1 ? ids[0] : undefined;\n  if (only === undefined) {\n    return [{ ...action, enabled: false, reason: oneAtATime(ids.length) }];\n  }\n  const reason = saveAsSharedStyleRefusal(document, only, offer);\n  return [\n    reason === undefined ? action : { ...action, enabled: false, reason },\n  ];\n}\n\n/**\n * The bar for a selection holding more than one block.\n *\n * **Duplicate, delete and move keep their meaning; select-parent loses it.**\n * Copying six blocks is six copies each beside its own original, removing six\n * is removing six, and moving six that share a list is one step for each — all\n * three are the single-block verb repeated, which is what `selection-ops`\n * plans. \"The parent\" of blocks with different parents is not a block, so\n * select-parent has no answer to give and does not invent one.\n *\n * Move is offered but not always available: a set spread across two containers\n * has no shared list to step through, and that refusal carries a reason because\n * nothing on the page shows that the selection straddles a boundary.\n *\n * The bar keeps its five buttons and its one shape rather than shrinking. A\n * control that vanishes when a second block is selected moves every button\n * after it, so the one an author was aiming at is somewhere else by the time\n * they arrive — the same reason unavailable actions are dimmed rather than\n * hidden with a single block.\n */\nfunction manyBlockActions(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  mayCreate: boolean,\n  ask: LockQuestion | undefined,\n  components: ComponentVerbsOffer | undefined,\n  sharedStyles: SharedStyleOffer | undefined,\n  planned: boolean\n): ToolbarAction[] {\n  const many = oneAtATime(ids.length);\n  const deleteLock = ids\n    .map(id => ({ id, locked: lockBlockingDelete(document, id) }))\n    .find(held => held.locked !== undefined);\n  const deleteItem: ToolbarAction =\n    deleteLock?.locked === undefined\n      ? heldByLock(\n          { id: \"delete\", label: \"Delete\", enabled: true },\n          ask,\n          opsOf(selectionDeletion(document, ids))\n        )\n      : {\n          id: \"delete\",\n          label: \"Delete\",\n          enabled: false,\n          // ONE lock refuses the whole delete, because the group is applied\n          // atomically and there is no half-done delete to fall back to.\n          reason: lockedBy(deleteLock.locked, deleteLock.id, \"delete\"),\n        };\n\n  return [\n    {\n      id: \"select-parent\",\n      label: \"Select parent\",\n      enabled: false,\n      reason: many,\n    },\n    moveAction(document, ids, \"move-up\", \"Move up\", \"up\", ask),\n    moveAction(document, ids, \"move-down\", \"Move down\", \"down\", ask),\n    // A node's lock never stops a duplication, for a set as for one block:\n    // the originals stay where they are. A slot's lock can.\n    heldByLock(\n      { id: \"duplicate\", label: \"Duplicate\", enabled: true },\n      ask,\n      opsOf(selectionDuplication(document, ids))\n    ),\n    ...clipboardActions(deleteItem, ids.length),\n    saveAction(document, ids, nesting, mayCreate, planned),\n    ...sharedStyleActions(document, ids, sharedStyles),\n    ...compositionActions(document, ids, nesting, components, ask, planned),\n    ...wrapActions(document, ids, nesting, ask),\n    deleteItem,\n  ];\n}\n\n/**\n * The toolbar's buttons for the current selection, or `[]` when there is none.\n *\n * `[]` also covers a selected id the document no longer holds, which an undo\n * produces routinely — the bar is drawn against an element, and there is no\n * element for a node that is gone.\n */\nexport function toolbarActions(\n  document: BlockDocument,\n  selectedId: string | null,\n  /**\n   * Every selected id. Defaults to the primary alone.\n   *\n   * Optional so a caller with one block — the command palette, a host that has\n   * not adopted the set — keeps the same answer it had. What changes for a\n   * SET is which verbs are well defined, not which rules decide them.\n   */\n  selectedIds?: readonly string[],\n  /**\n   * The nesting rule source, for asking whether a selection can be saved.\n   *\n   * Optional and defaulted to the registry, which is how the insert panel and\n   * the keyboard route already default it — so a refusal reads the same whether\n   * an author dragged the block, moved it with the keyboard, or tried to save\n   * it. Present as an option only so a test can supply a rule set without\n   * registering blocks globally.\n   */\n  nesting?: NestingSource,\n  /**\n   * Whether the caller may create a pattern at all. Defaults to true.\n   *\n   * The HOST's answer, because it is the host's question: the grant is seeded\n   * against the collection a pattern goes in, a site may have renamed it, and\n   * nothing here knows either. The same reason `onSaveAsPattern` is supplied\n   * rather than performed here.\n   *\n   * PERMISSIVE by default, unlike every other refusal in this file. The others\n   * are computed from the document in hand and an absent answer means the\n   * question was not asked; this one arrives over the network, and \"not yet\"\n   * would dim the verb on every mount for every author. A wrong `true` costs\n   * the late refusal that already happens; a wrong `false` hides a feature the\n   * author has, and there is nothing on the canvas to explain it.\n   */\n  mayCreatePattern: boolean = true,\n  /**\n   * The editor's `lockRefusalFor`, so a verb a slot's lock refuses is dimmed\n   * with the lock's reason before it is pressed. Optional for a caller that\n   * holds no editor; the editor's apply refuses the same ops regardless.\n   */\n  lockRefusalFor?: LockQuestion,\n  /**\n   * What the host offers for making components, or nothing where it has no\n   * component library: then neither verb appears.\n   */\n  components?: ComponentVerbsOffer,\n  /**\n   * Whether the host opens a placed component in its own view. Offered only\n   * for one selected placement, and only by a host that answers it; the host\n   * also withholds it from an author who may not update components.\n   */\n  offersEditComponent: boolean = false,\n  /**\n   * What the host knows about the site's shared styles and the author's\n   * right to change them, or nothing where it has none: then \"Save as shared\n   * style…\" is not offered.\n   */\n  sharedStyles?: SharedStyleOffer,\n  /**\n   * Whether to plan the verbs whose availability is answered by planning\n   * them in full: saving as a pattern, and the component verbs, which build\n   * the document they would store. Defaults to true. False for what a\n   * surface shows as the selection changes, so a click plans nothing; the\n   * grant and Entry content still dim them, and a menu that opens, or the\n   * verb when it runs, plans them and says why it refuses.\n   */\n  planned: boolean = true,\n  /**\n   * The editor's size limits, so a \"Turn into\" choice is judged on a page as\n   * large as the editor allows, as the verb that runs it is. Absent, the\n   * default limits.\n   */\n  limits?: DocumentLimits\n): ToolbarAction[] {\n  if (selectedId === null) return [];\n\n  const path = pathTo(document, selectedId);\n  if (path.length === 0) return [];\n\n  const rules = nesting ?? registryNestingSource();\n  const ids = selectedIds ?? [selectedId];\n  if (ids.length > 1)\n    return manyBlockActions(\n      document,\n      ids,\n      rules,\n      mayCreatePattern,\n      lockRefusalFor,\n      components,\n      sharedStyles,\n      planned\n    );\n\n  const deleteLock = lockBlockingDelete(document, selectedId);\n\n  // The very ops the Duplicate verb applies, so what the bar offers and what\n  // a press does cannot disagree.\n  const duplication = selectionDuplication(document, [selectedId]);\n  const deletion = blockDeletion(document, selectedId);\n  const deleteItem: ToolbarAction =\n    deleteLock === undefined\n      ? heldByLock(\n          { id: \"delete\", label: \"Delete\", enabled: deletion !== null },\n          lockRefusalFor,\n          deletion === null\n            ? undefined\n            : [\n                {\n                  kind: \"remove\",\n                  id: deletion.id,\n                  dropSlotIfEmpty: deletion.dropSlotIfEmpty,\n                },\n              ]\n        )\n      : {\n          id: \"delete\",\n          label: \"Delete\",\n          enabled: false,\n          reason: lockedBy(deleteLock, selectedId, \"delete\"),\n        };\n\n  return [\n    {\n      id: \"select-parent\",\n      label: \"Select parent\",\n      // The path always ends at the selection itself, so a length of one means\n      // a top-level block with no container to step out to: the outdent's\n      // reason, since it is the same fact.\n      enabled: path.length > 1,\n      ...(path.length > 1 ? {} : { reason: EDGE_REASONS.outdent }),\n    },\n    singleMove(\n      document,\n      selectedId,\n      \"move-up\",\n      \"Move up\",\n      \"up\",\n      lockRefusalFor\n    ),\n    singleMove(\n      document,\n      selectedId,\n      \"move-down\",\n      \"Move down\",\n      \"down\",\n      lockRefusalFor\n    ),\n    // A node's lock deliberately does not stop this. Duplicating neither moves\n    // nor removes the original, and refusing would mean an author could not\n    // take a copy of the one block they had most deliberately protected — the\n    // same reading the keyboard duplicate takes. A slot's lock is another\n    // matter: a copy changes what a slot whose blocks are fixed holds.\n    heldByLock(\n      duplicateAction(document, selectedId, duplication !== null),\n      lockRefusalFor,\n      duplication?.ops\n    ),\n    ...clipboardActions(deleteItem, 1),\n    ...turnIntoActions(\n      document,\n      selectedId,\n      rules,\n      lockRefusalFor,\n      planned,\n      sharedStyles?.library,\n      limits\n    ),\n    saveAction(document, ids, rules, mayCreatePattern, planned),\n    ...sharedStyleActions(document, ids, sharedStyles),\n    ...editComponentAction(document, selectedId, offersEditComponent),\n    ...compositionActions(\n      document,\n      ids,\n      rules,\n      components,\n      lockRefusalFor,\n      planned\n    ),\n    ...wrapActions(document, ids, rules, lockRefusalFor),\n    deleteItem,\n  ];\n}\n\n/**\n * \"Wrap in a box\" for a selection side by side in one place, and \"Unwrap\n * (keep what's inside)\" for one Box, Section, Column or Card, each from the\n * menu. A result the placement rules forbid is offered dimmed with the\n * reason, and a lock that holds a block it moves dims it too.\n */\nfunction wrapActions(\n  document: BlockDocument,\n  ids: readonly string[],\n  nesting: NestingSource,\n  ask: LockQuestion | undefined\n): ToolbarAction[] {\n  const items: ToolbarAction[] = [];\n  const wrap = planWrap(document, ids, nesting);\n  if (wrap !== null) {\n    items.push(\n      isRefusal(wrap)\n        ? {\n            id: \"wrap-in-box\",\n            label: WRAP_WORDS.wrap,\n            enabled: false,\n            reason: wrap.reason,\n            inMenu: true,\n          }\n        : heldByLock(\n            {\n              id: \"wrap-in-box\",\n              label: WRAP_WORDS.wrap,\n              enabled: true,\n              inMenu: true,\n            },\n            ask,\n            wrap.ops\n          )\n    );\n  }\n  const [only] = ids;\n  if (\n    ids.length === 1 &&\n    only !== undefined &&\n    isUnwrappable(findNode(document.nodes, only))\n  ) {\n    const unwrap = planUnwrap(document, only, nesting);\n    if (unwrap !== null) {\n      items.push(\n        isRefusal(unwrap)\n          ? {\n              id: \"unwrap\",\n              label: WRAP_WORDS.unwrap,\n              enabled: false,\n              reason: unwrap.reason,\n              inMenu: true,\n            }\n          : heldByLock(\n              {\n                id: \"unwrap\",\n                label: WRAP_WORDS.unwrap,\n                enabled: true,\n                inMenu: true,\n              },\n              ask,\n              unwrap.ops\n            )\n      );\n    }\n  }\n  return items;\n}\n\n/**\n * \"Edit component\" for a selected placement, where the host offers it; nothing\n * for any other block, so a bar over a heading does not grow a dimmed button\n * that could never apply to it.\n */\nfunction editComponentAction(\n  document: BlockDocument,\n  selectedId: string,\n  offered: boolean\n): ToolbarAction[] {\n  // Asked as the verb asks: a placement naming no component has nothing to\n  // open, so it is not offered a control that would do nothing.\n  if (!offered || placedComponentId(document, selectedId) === undefined) {\n    return [];\n  }\n  return [{ id: \"edit-component\", label: \"Edit component\", enabled: true }];\n}\n\n/**\n * The smallest rectangle containing all of them, or `undefined` for none.\n *\n * What a floating bar anchors to once a selection can hold several blocks. The\n * PRIMARY's rectangle would be the easy choice and is the wrong one: with two\n * blocks selected at opposite ends of a page, a bar drawn at one of them\n * describes an action that is about to happen to both, and the author cannot\n * see the other. The union is the shape the selection actually occupies.\n */\nexport function unionRect(rects: readonly Rect[]): Rect | undefined {\n  const [first, ...rest] = rects;\n  if (first === undefined) return undefined;\n\n  let left = first.x;\n  let top = first.y;\n  let right = first.x + first.width;\n  let bottom = first.y + first.height;\n\n  for (const rect of rest) {\n    left = Math.min(left, rect.x);\n    top = Math.min(top, rect.y);\n    right = Math.max(right, rect.x + rect.width);\n    bottom = Math.max(bottom, rect.y + rect.height);\n  }\n\n  return { x: left, y: top, width: right - left, height: bottom - top };\n}\n\n/** How big the bar measured, in canvas content pixels. */\nexport interface ToolbarSize {\n  readonly width: number;\n  readonly height: number;\n}\n\n/** Where the bar is drawn, and which side of the block it landed on. */\nexport interface ToolbarPlacement {\n  readonly x: number;\n  readonly y: number;\n  /**\n   * Above the block; inside its top-left corner where there is no room above\n   * it on screen; or pinned to the top of the screen over a tall block whose\n   * own top is scrolled out of view.\n   */\n  readonly side: \"above\" | \"inside\" | \"pinned\";\n}\n\n/**\n * The part of the canvas on screen, in its coordinates: top and bottom, and\n * the left and right edges where the canvas scrolls sideways too.\n */\nexport interface ToolbarScreen {\n  readonly top: number;\n  readonly bottom: number;\n  readonly left?: number;\n  readonly right?: number;\n}\n\n/** No screen to keep to: the whole page, from its top down. */\nconst WHOLE_PAGE: ToolbarScreen = {\n  top: 0,\n  bottom: Number.POSITIVE_INFINITY,\n};\n\n/** The gap between the bar and the block it names, in pixels. */\nexport const TOOLBAR_GAP_PX = 6;\n\n/** How far inside the block's top-left corner an `inside` bar is drawn. */\nexport const TOOLBAR_INSET_PX = 4;\n\n/**\n * Where to draw the bar for a block, in the canvas's own content coordinates.\n *\n * **Above by default, inside the block when there is no room.** Above keeps\n * the bar off the block's own content, which is what an author is looking at.\n * The first block on a page has nothing above it, and there the bar is drawn\n * just inside the block's top-left corner: over the block it names, and never\n * below it, where it would cover the next block. Whatever is drawn above the\n * block on the canvas counts as room, a Layout's header included, since the\n * bar may cover that but no other block of the page.\n *\n * **Left-aligned to the block, never centred.** A centred bar moves whenever\n * the block's width changes — which happens while an author is editing its\n * padding — so the button they are reaching for slides out from under the\n * pointer. The leading edge is the one part of a block that stays put.\n *\n * **Clamped horizontally, never vertically.** A bar pushed off the right edge\n * is unreachable, so it slides back in. Vertical overflow is handled by the\n * side chosen rather than by clamping.\n *\n * **Kept to what is on screen** (`screen`, the whole page when not given):\n * room above is room above on screen, so a block just below the screen's top\n * takes its bar inside; and a tall block whose top is scrolled away keeps its\n * bar pinned at the top of the screen, over the block, where an author\n * working in its middle can reach it.\n */\nexport function toolbarPlacement(\n  block: Rect,\n  toolbar: ToolbarSize,\n  canvas: ToolbarSize,\n  gap: number = TOOLBAR_GAP_PX,\n  screen: ToolbarScreen = WHOLE_PAGE,\n  parts: readonly Rect[] = [block]\n): ToolbarPlacement {\n  const above = block.y - toolbar.height - gap;\n  const side = toolbarSide(block, toolbar, gap, screen, above);\n  const inset = side === \"inside\" ? TOOLBAR_INSET_PX : 0;\n\n  // Kept to the canvas, and to the part of it on screen where that is given\n  // and the block crosses it: a block wholly off the side keeps its bar with\n  // it, rather than one at the screen's edge over another block. The clamp is\n  // skipped when the bar is wider than that, because there is no position that\n  // satisfies both edges and clamping would silently choose the right one —\n  // leaving the first buttons, which are the ones an author reaches for,\n  // off-screen.\n  const left = screen.left ?? Number.NEGATIVE_INFINITY;\n  const right = screen.right ?? Number.POSITIVE_INFINITY;\n  // Judged by each selected block, not by their union: two blocks off\n  // opposite sides have a union that crosses the screen through the gap.\n  const crosses = parts.some(\n    part => part.x < right && part.x + part.width > left\n  );\n  const minX = Math.max(0, crosses ? left : 0);\n  const maxX =\n    Math.min(canvas.width, crosses ? right : Number.POSITIVE_INFINITY) -\n    toolbar.width;\n  const start = block.x + inset;\n  const x = maxX <= minX ? minX : Math.min(Math.max(start, minX), maxX);\n\n  const y =\n    side === \"above\"\n      ? above\n      : side === \"inside\"\n        ? block.y + inset\n        : screen.top + gap;\n  return { x, y, side };\n}\n\n/**\n * Which side the bar takes. Above wherever that is on screen. Inside the block\n * when above would leave the screen and the block's top is on it. Pinned to\n * the screen's top over a block whose top is scrolled away while enough of it\n * is still on screen to hold the bar. Above for anything else: a block wholly\n * out of view, or a short end of one too little to pin the bar over, which\n * takes its bar out of view with its top rather than over the next block.\n */\nfunction toolbarSide(\n  block: Rect,\n  toolbar: ToolbarSize,\n  gap: number,\n  screen: ToolbarScreen,\n  above: number\n): ToolbarPlacement[\"side\"] {\n  if (above >= screen.top) return \"above\";\n  if (block.y >= screen.top) return \"inside\";\n  const stillShown =\n    block.y + block.height >= screen.top + toolbar.height + gap;\n  return stillShown ? \"pinned\" : \"above\";\n}\n\n/** A plan's ops, or undefined for no plan or a refusal. */\nfunction opsOf(\n  plan:\n    | { readonly ops: readonly BuilderOp[] }\n    | { readonly reason: string }\n    | null\n): readonly BuilderOp[] | undefined {\n  return plan === null || !(\"ops\" in plan) ? undefined : plan.ops;\n}\n\n/** The block menu's moves across depth: into the block above, and out. */\nexport type DepthMoveId = \"move-in\" | \"move-out\";\n\n/** One of them, and the keyboard move it runs. */\nexport interface DepthMoveAction extends Omit<ToolbarAction, \"id\"> {\n  readonly id: DepthMoveId;\n  readonly direction: Extract<MoveDirection, \"indent\" | \"outdent\">;\n}\n\nconst DEPTH_MOVES: ReadonlyArray<\n  Pick<DepthMoveAction, \"id\" | \"label\" | \"direction\">\n> = [\n  { id: \"move-in\", label: \"Move in\", direction: \"indent\" },\n  { id: \"move-out\", label: \"Move out\", direction: \"outdent\" },\n];\n\n/**\n * Move in and Move out for the current selection, or `[]` when there is none.\n *\n * The menu path to what Alt+ArrowRight and Alt+ArrowLeft do, so every move a\n * drag in Layers makes has a way without dragging. Decided as the bar decides\n * Move up and Move down — the keyboard move's position, the node's lock and a\n * slot's — and run through the same verb the keystroke runs. Kept off the bar\n * itself, whose five buttons are fixed so the one an author aims at does not\n * move.\n *\n * A set is offered them dimmed with the reason, as the bar dims a verb that\n * has no meaning for several blocks.\n */\nexport function depthMoveActions(\n  document: BlockDocument,\n  selectedId: string | null,\n  selectedIds?: readonly string[],\n  lockRefusalFor?: LockQuestion,\n  /**\n   * The position the verb these run moves by. A caller that runs them passes\n   * its own, so an item is offered exactly when pressing it would move.\n   */\n  position?: MovePosition,\n  /** The placement rule as the verb asks it, so a refused move is dimmed. */\n  judge?: MoveJudge\n): DepthMoveAction[] {\n  if (selectedId === null || pathTo(document, selectedId).length === 0) {\n    return [];\n  }\n  const ids = selectedIds ?? [selectedId];\n  // A locked block, one inside the selected one or one it sits inside is the\n  // single move's own question (`lockBlockingMove`), answered with its reason.\n  return DEPTH_MOVES.map(move =>\n    ids.length > 1\n      ? { ...move, enabled: false, reason: oneAtATime(ids.length) }\n      : {\n          ...singleMove(\n            document,\n            selectedId,\n            move.id,\n            move.label,\n            move.direction,\n            lockRefusalFor,\n            position,\n            judge\n          ),\n          direction: move.direction,\n        }\n  );\n}\n\n/**\n * Copy, Cut and Paste, kept in the menu so the bar stays one short row.\n *\n * Copy is always offered: copying changes nothing on the page, so no lock\n * stands in its way. Cut removes what it copies, so it is Delete's item under\n * another name: offered, or dimmed with the reason, exactly where Delete is,\n * by every lock Delete asks. Paste is always offered, since what the\n * clipboard holds is read only when it is pressed; a paste the page refuses\n * says why then.\n */\nfunction clipboardActions(\n  deleteItem: ToolbarAction,\n  count: number\n): ToolbarAction[] {\n  return [\n    { id: \"copy\", label: \"Copy\", enabled: true, inMenu: true },\n    { ...deleteItem, id: \"cut\", label: \"Cut\", inMenu: true },\n    { id: \"paste\", label: \"Paste\", enabled: true, inMenu: true },\n    ...styleClipboardActions(count),\n  ];\n}\n\n/**\n * Copy style and Paste style, beside Copy and Paste in the same group.\n *\n * Copy style takes one block's look, so it is dimmed for several. Paste style\n * gives that look to every selected block, and like Paste it is always\n * offered: what was copied is read when it is pressed, and a paste with\n * nothing copied, or onto a held block, says why then.\n */\nfunction styleClipboardActions(count: number): ToolbarAction[] {\n  return [\n    count > 1\n      ? {\n          id: \"copy-style\",\n          label: \"Copy style\",\n          enabled: false,\n          reason: oneAtATime(count),\n          inMenu: true,\n        }\n      : { id: \"copy-style\", label: \"Copy style\", enabled: true, inMenu: true },\n    { id: \"paste-style\", label: \"Paste style\", enabled: true, inMenu: true },\n  ];\n}\n\n/**\n * The Duplicate item for one selected block: refused, with the words the\n * Add panel's tile uses, where the block is or holds a template's one Entry\n * content block, since a copy would be a second.\n */\nfunction duplicateAction(\n  document: BlockDocument,\n  selectedId: string,\n  duplicable: boolean\n): ToolbarAction {\n  const reason = duplicationRefusal(document, selectedId);\n  return reason === undefined\n    ? { id: \"duplicate\", label: \"Duplicate\", enabled: duplicable }\n    : { id: \"duplicate\", label: \"Duplicate\", enabled: false, reason };\n}\n","/**\n * Which style values the Style tab withholds until web.dev's Baseline marks\n * them \"widely available\".\n *\n * The first release offers only CSS every core browser has shipped for thirty\n * months, so a page an author builds today looks the same for every visitor.\n * Newer properties and keywords join as the data moves, one reviewed bump of\n * the pinned release at a time.\n *\n * **Only the answer ships, never the data.** The web-features dataset is\n * several megabytes and the editor needs one bit per value from it, so this\n * module holds the short list of what is withheld and\n * `style-baseline.test.ts` holds that list to the pinned release in both\n * directions: everything offered must be widely available, and everything\n * withheld must still not be. The package imports `web-features` from that\n * test alone, and the layering test refuses it anywhere else, so it cannot\n * reach the admin bundle.\n *\n * **Withheld is not removed.** A stored value the gate withholds is still on\n * the page — written before the gate, or through the API, which never asks the\n * editor — so the panel keeps showing it, clear-only, and says why it is no\n * longer offered.\n *\n * @module style-baseline\n */\n\n/**\n * The web-features release this list was checked against: the exact version\n * the package's `devDependencies` pins, which the test asserts.\n */\nexport const BASELINE_DATA_RELEASE = \"3.44.0\";\n\n/**\n * A withheld property, or one withheld keyword of it.\n *\n * Addressed by the CSS property a catalog leaf emits rather than by the\n * catalog key, because that is what the data tracks: `width` and `maxWidth`\n * are two catalog keys, and Baseline answers for `width` and `max-width`.\n */\nexport interface WithheldStyleValue {\n  readonly cssProperty: string;\n  /** Omitted to withhold the whole property, every keyword with it. */\n  readonly keyword?: string;\n}\n\n/**\n * Everything the catalog declares that web-features 3.44.0 does not mark\n * widely available, each with the feature that holds it back.\n *\n * A keyword of several words is withheld when any one of its words is, so\n * `display: block ruby` and `container-type: inline-size scroll-state` need no\n * entry of their own.\n */\nexport const BASELINE_WITHHELD: readonly WithheldStyleValue[] = [\n  // Not on iOS Safari, so the feature is not Baseline at all.\n  { cssProperty: \"background-attachment\" },\n  // Anchor positioning.\n  { cssProperty: \"align-items\", keyword: \"anchor-center\" },\n  // Tracked on its own, and not yet everywhere.\n  { cssProperty: \"align-content\", keyword: \"last baseline\" },\n  // Overflow alignment: newly available, widely available later. Each is a\n  // word of a keyword (`safe center`) rather than a value of its own.\n  { cssProperty: \"justify-content\", keyword: \"safe\" },\n  { cssProperty: \"justify-content\", keyword: \"unsafe\" },\n  { cssProperty: \"align-items\", keyword: \"safe\" },\n  { cssProperty: \"align-items\", keyword: \"unsafe\" },\n  { cssProperty: \"align-content\", keyword: \"safe\" },\n  { cssProperty: \"align-content\", keyword: \"unsafe\" },\n  // Supported everywhere, but the feature is held back by accessibility\n  // defects in how browsers expose the element's own role.\n  { cssProperty: \"display\", keyword: \"contents\" },\n  // Ruby layout.\n  { cssProperty: \"display\", keyword: \"ruby\" },\n  { cssProperty: \"display\", keyword: \"ruby-base\" },\n  { cssProperty: \"display\", keyword: \"ruby-base-container\" },\n  { cssProperty: \"display\", keyword: \"ruby-text\" },\n  { cssProperty: \"display\", keyword: \"ruby-text-container\" },\n  // The `stretch` sizing keyword.\n  { cssProperty: \"width\", keyword: \"stretch\" },\n  { cssProperty: \"height\", keyword: \"stretch\" },\n  { cssProperty: \"min-width\", keyword: \"stretch\" },\n  { cssProperty: \"min-height\", keyword: \"stretch\" },\n  { cssProperty: \"max-width\", keyword: \"stretch\" },\n  { cssProperty: \"max-height\", keyword: \"stretch\" },\n  // MathML's own keywords.\n  { cssProperty: \"font-size\", keyword: \"math\" },\n  { cssProperty: \"text-transform\", keyword: \"math-auto\" },\n  // Not yet in every core browser.\n  { cssProperty: \"text-align\", keyword: \"match-parent\" },\n  { cssProperty: \"text-transform\", keyword: \"full-size-kana\" },\n  { cssProperty: \"text-transform\", keyword: \"full-width\" },\n  { cssProperty: \"mix-blend-mode\", keyword: \"plus-darker\" },\n  // Scroll-state container queries.\n  { cssProperty: \"container-type\", keyword: \"scroll-state\" },\n];\n\n/** Whether the gate withholds a whole property, every keyword of it included. */\nexport function propertyWithheld(cssProperty: string): boolean {\n  return BASELINE_WITHHELD.some(\n    entry => entry.cssProperty === cssProperty && entry.keyword === undefined\n  );\n}\n\n/**\n * Whether the gate withholds one keyword of a property: the keyword itself,\n * any word of it, or the property as a whole.\n */\nexport function keywordWithheld(cssProperty: string, keyword: string): boolean {\n  if (propertyWithheld(cssProperty)) return true;\n  const words = new Set([keyword, ...keyword.split(\" \")]);\n  return BASELINE_WITHHELD.some(\n    entry =>\n      entry.cssProperty === cssProperty &&\n      entry.keyword !== undefined &&\n      words.has(entry.keyword)\n  );\n}\n\n/**\n * Why a stored value is shown clear-only, in an author's words.\n *\n * One sentence for every withheld value, because the reason is the same for\n * each: the value works in some browsers and not in all of them.\n */\nexport const BASELINE_WITHHELD_HINT =\n  \"No longer offered: not every major browser supports it yet. It can be cleared.\";\n","/**\n * Which controls a style property offers, derived from the catalog alone.\n *\n * Pure, for the reason `inspector.ts` is: which controls a property offers, in\n * what order, carrying which value shape, is derivation — and a component test\n * in jsdom cannot separate a correct answer from a plausible wrong one, because\n * both render a column of inputs.\n *\n * **The catalog decides, and nothing here holds a second list.** A property's\n * `shape` names its value form; this walks that shape and answers with one\n * descriptor per editable leaf. Adding a property to `catalog.ts` gives it\n * controls with no edit here, which is the property worth protecting — and the\n * mapping from leaf kind to control kind is a mapped type, so a leaf kind added\n * to the engine is a compile error in exactly one place rather than a silent\n * fallthrough at runtime.\n *\n * **Which arm of a union a value is shown in is ASKED, not decided.**\n * `styleUnionVariant` is the engine's own arm selection — the same answer\n * validation uses to pick the arm it judges a value against — so the control an\n * author sees and the error they read describe one arm by construction.\n * Predicting it here instead means restating every rule the engine applies, and\n * each of these is a rule that is easy to miss and invisible when missed: the\n * three all-scalar unions, the site's token kind table, a token kind no arm\n * declares, keyword case and ASCII whitespace and CSS escapes, the CSS-wide\n * keywords that every leaf accepts, a union nested as another union's arm,\n * composite arms that share a field name, and a record naming no known field at\n * all. Nothing here holds any of them.\n *\n * **The Baseline gate applies here, once.** A control carries its catalog leaf\n * with every keyword the gate withholds taken out (`style-baseline.ts`), so the\n * menu, the toggle and the field's hint offer only widely available CSS without\n * any of them asking. A withheld property draws no control at all until a\n * value is stored there; a stored withheld value is kept and marked, so the\n * panel shows it clear-only rather than hiding styling that is on the page.\n *\n * **What this module does NOT do.** It does not decide which properties a block\n * offers (that is `supports`, read through the catalog's own group helpers), it\n * does not hold the active state or breakpoint, and it does not validate. A\n * control's value is written through `style-values.ts`, which delegates every\n * check to `validateStyleValues`.\n *\n * @module style-controls\n */\n\nimport {\n  isStyleLeaf,\n  isTokenRef,\n  styleUnionVariant,\n  type StyleLeaf,\n  type StyleProperty,\n  type StyleShape,\n  type StyleUnionVariantOptions,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { keywordWithheld, propertyWithheld } from \"./style-baseline\";\n\n/**\n * The editor kind a leaf resolves to.\n *\n * Named separately from `StyleLeaf[\"kind\"]` rather than reused, because the two\n * answer different questions and will not stay parallel: `dimension` and\n * `number` are distinct storage shapes that both draw a numeric field with a\n * scrub affordance, and a future leaf kind may reuse an existing control\n * outright. Collapsing them onto one name would make that a breaking rename.\n */\nexport type StyleControlKind =\n  | \"select\"\n  | \"length\"\n  | \"number\"\n  | \"color\"\n  | \"css\"\n  | \"url\";\n\n/**\n * The control each leaf kind draws with.\n *\n * A MAPPED TYPE over the engine's own union, so a leaf kind added there fails\n * to compile here until it is given a control. The alternative — a `switch` with\n * a `default` — accepts the new kind silently and draws nothing, which presents\n * an incomplete property as a complete one.\n */\nconst CONTROL_KIND_BY_LEAF: {\n  readonly [K in StyleLeaf[\"kind\"]]: StyleControlKind;\n} = {\n  keyword: \"select\",\n  dimension: \"length\",\n  number: \"number\",\n  color: \"color\",\n  cssValue: \"css\",\n  url: \"url\",\n};\n\n/**\n * The leaf kinds this build can draw.\n *\n * DERIVED from the mapping rather than listed beside it. A second list agrees\n * with the mapping on the day it is written: adding a leaf kind and its\n * required map entry while forgetting the list still compiles, and\n * `controlForLeaf` then reports a kind it can perfectly well draw as\n * unsupported.\n *\n * Membership is still checked at runtime rather than trusted from the type,\n * because a catalog written by a NEWER engine can carry a kind absent from\n * both — and indexing a mapped type with it returns `undefined` while the type\n * says otherwise. Such a kind resolves to an unsupported descriptor rather\n * than to `undefined` flowing into a renderer, the same policy as\n * `inspector.ts`'s `SUPPORTED_PROP_TYPES`: the author is told the property\n * exists and is not editable here, because omitting it entirely would present\n * an incomplete property as a complete one.\n */\nexport const SUPPORTED_LEAF_KINDS = Object.keys(\n  CONTROL_KIND_BY_LEAF\n) as readonly StyleLeaf[\"kind\"][];\n\n/**\n * One editable position inside a property's value, with everything a control\n * needs to draw itself and nothing about how it is drawn.\n */\nexport interface StyleControl {\n  /** The catalog key this belongs to, as stored in a `StyleValues` record. */\n  readonly property: string;\n  /**\n   * Where inside the property's value this control writes, outermost first.\n   *\n   * Empty for a property stored as a scalar. `[\"blockEnd\"]` for the bottom\n   * margin, `[\"startStart\"]` for the top-left corner radius. A control writes\n   * by handing this path back to `style-values.ts`, which is what keeps the\n   * addressing in one place rather than in every control.\n   */\n  readonly path: readonly string[];\n  /** The leaf the catalog declares at this path, carrying units, bounds and token kinds. */\n  readonly leaf: StyleLeaf;\n  /**\n   * The control to draw, or `undefined` when this build has no control for the\n   * leaf's kind.\n   *\n   * Carried rather than recomputed by the panel, for the reason `EditableProp`\n   * carries `supported`: the panel would have to repeat the membership test, and\n   * the two would disagree the first time the set gained a member.\n   */\n  readonly kind: StyleControlKind | undefined;\n  /** Whether {@link kind} is present. */\n  readonly supported: boolean;\n  /**\n   * Whether the value stored here is one the Baseline gate withholds: a value\n   * of a withheld property, or a withheld keyword. Such a value is still on\n   * the page, so it is shown and may be cleared, and nothing new is offered.\n   */\n  readonly withheld: boolean;\n}\n\n/**\n * A union's variants, when the shape at a path accepts more than one form.\n *\n * `borderRadius` stores either one measurement or four corners, and an editor\n * offers a way to move between them. Recorded here so that affordance reads the\n * catalog's own list instead of re-deriving which forms exist.\n */\nexport interface StyleControlVariants {\n  /**\n   * Where in the property's value the choice sits, empty at the root.\n   *\n   * Carried because a union is not only a top-level shape: `position.zIndex` is\n   * a number OR the `auto` keyword, nested a level down. Reporting choices only\n   * at the root would leave a renderer no way to offer `auto` at all.\n   */\n  readonly path: readonly string[];\n  /** Which variant the returned controls describe, as an index into the union. */\n  readonly active: number;\n  /** How many variants the catalog declares at this position. */\n  readonly count: number;\n  /**\n   * Each arm's own shape kind, in the catalog's order.\n   *\n   * Carried so an affordance offering the choice can NAME the forms from the\n   * catalog rather than numbering them: `borderRadius` is a length or four\n   * corners, and \"Form 1 / Form 2\" tells an author nothing about which is\n   * which. The arms have no names of their own, so their shape kind is the\n   * most specific thing the catalog actually says about them.\n   */\n  readonly kinds: readonly StyleShape[\"kind\"][];\n  /**\n   * Each arm in plain words, in the catalog's order: what the toggle offering\n   * the choice says. Derived from the arms here, once, so nothing else names\n   * a form its own way. Optional, so a variant built to the earlier shape\n   * stays valid; read it through {@link formNamesOf}.\n   */\n  readonly names?: readonly string[];\n}\n\n/**\n * What a caller can tell the resolver about the site.\n *\n * DERIVED from the engine's own option type rather than restated beside it.\n * Both this and `StylePolicy` in `style-values.ts` are the same contract — what\n * this site allows — read at two moments, and three structural copies of it\n * would all keep compiling while the next field was added to one: arm selection\n * and write validation would then disagree about a value, which is the failure\n * the module docblock above describes from the other direction.\n *\n * Kept as a NAME rather than making callers import the engine's, because it is\n * this package's public surface and a rename there should not be one here.\n */\nexport type StyleControlOptions = StyleUnionVariantOptions;\n\n/**\n * Everything {@link styleControlsFor} accepts.\n *\n * The site policy, plus the one thing the engine has no opinion about: which\n * form an AUTHOR has chosen to write a value in. A union's arm is decided by\n * the stored value wherever there is one, so this is consulted only where the\n * position is unset — which is exactly when the engine has nothing to read and\n * answers with the catalog's first arm for every caller alike.\n */\nexport interface StyleControlInput extends StyleControlOptions {\n  /**\n   * The arm an author picked at one position inside the value, if any.\n   *\n   * Addressed by the same path a control carries, so a union nested below the\n   * property root is answerable too — `position.zIndex` is a number OR `auto`,\n   * and a caller that could only speak about the root could never offer it.\n   */\n  readonly variantAt?: (path: readonly string[]) => number | undefined;\n}\n\n/** A property's controls, and every choice of form its shape offers. */\nexport interface StyleControlSet {\n  readonly property: string;\n  readonly controls: readonly StyleControl[];\n  /** Empty when the property's shape holds no union at any depth. */\n  readonly variants: readonly StyleControlVariants[];\n}\n\n/** A stored value holding named sub-values, as a composite shape addresses. */\ntype CompositeValue = { readonly [key: string]: StyleValue };\n\n/**\n * Whether a stored value is a record of sub-values rather than a scalar.\n *\n * A token reference is a RECORD and is nonetheless a scalar: `{ $token }` is one\n * value that happens to be spelled as an object, so a shape test that went by\n * `typeof` alone would show a token-valued radius in the four-corner control\n * with the token in none of them.\n *\n * A type predicate rather than a boolean, so the narrowing it establishes is\n * the one the caller reads the value through. Returning a plain boolean would\n * leave every read behind it needing an assertion to say what this already\n * decided.\n */\nfunction isCompositeValue(value: StyleValue): value is CompositeValue {\n  if (typeof value !== \"object\" || value === null) return false;\n  // Asked of the engine rather than by looking for the marker key, so a change\n  // to what counts as a reference cannot leave this reading the old spelling.\n  return !isTokenRef(value);\n}\n\n/** One descriptor for a leaf, resolving the control it draws with. */\nfunction controlForLeaf(\n  property: string,\n  path: readonly string[],\n  leaf: StyleLeaf,\n  value: StyleValue | undefined\n): StyleControl {\n  // Read through the runtime set rather than off the mapping directly. A\n  // catalog from a newer engine can carry a kind absent from both, and indexing\n  // a mapped type with it returns `undefined` while the type says otherwise.\n  const known = SUPPORTED_LEAF_KINDS.includes(leaf.kind);\n  const kind = known ? CONTROL_KIND_BY_LEAF[leaf.kind] : undefined;\n  return {\n    property,\n    path,\n    leaf: offeredLeaf(leaf),\n    kind,\n    supported: kind !== undefined,\n    withheld: storedValueWithheld(leaf.cssProperty, value),\n  };\n}\n\n/**\n * The leaf as the gate offers it: the catalog's own object where the gate\n * withholds none of its keywords, and a copy without them where it does.\n *\n * The same object when nothing is taken out, so a control still reads the\n * catalog's leaf itself in the common case.\n */\nfunction offeredLeaf(leaf: StyleLeaf): StyleLeaf {\n  const offered = (keywords: readonly string[]) =>\n    keywords.filter(keyword => !keywordWithheld(leaf.cssProperty, keyword));\n  if (leaf.kind === \"keyword\") {\n    const values = offered(leaf.values);\n    return values.length === leaf.values.length ? leaf : { ...leaf, values };\n  }\n  if (\n    (leaf.kind === \"dimension\" || leaf.kind === \"url\") &&\n    leaf.keywords !== undefined\n  ) {\n    const keywords = offered(leaf.keywords);\n    return keywords.length === leaf.keywords.length\n      ? leaf\n      : { ...leaf, keywords };\n  }\n  return leaf;\n}\n\n/**\n * Whether a stored value is one the gate withholds.\n *\n * A string is judged as a keyword in the case and spacing the validator\n * accepts, so a stored `Contents` reads as `contents`. Anything stored under a\n * withheld property is withheld, whatever it is.\n */\nfunction storedValueWithheld(\n  cssProperty: string,\n  value: StyleValue | undefined\n): boolean {\n  if (value === undefined) return false;\n  if (propertyWithheld(cssProperty)) return true;\n  if (typeof value !== \"string\") return false;\n  const keyword = value.trim().toLowerCase().replace(/\\s+/g, \" \");\n  return keyword !== \"\" && keywordWithheld(cssProperty, keyword);\n}\n\n/**\n * Every editable position inside a shape, depth-first, carrying its path.\n *\n * Parallel to the engine's `shapeLeaves` but path-aware and union-aware:\n * `shapeLeaves` flattens every arm of a union because a documentation generator\n * wants all of them, and a control layer that did the same would draw two\n * controls for one stored value.\n */\nfunction walk(\n  property: string,\n  path: readonly string[],\n  shape: StyleShape,\n  value: StyleValue | undefined,\n  options: StyleControlInput | undefined,\n  // Collected as the walk descends rather than returned alongside, so a union\n  // at ANY depth is recorded by the same line that resolves it.\n  variants: StyleControlVariants[]\n): StyleControl[] {\n  const down = (step: string, child: StyleShape): StyleControl[] =>\n    walk(\n      property,\n      [...path, step],\n      child,\n      childValue(value, step),\n      options,\n      variants\n    );\n  if (isStyleLeaf(shape)) {\n    // A withheld property is not offered: no control, until a value is stored\n    // there that the author needs to see and be able to clear.\n    if (value === undefined && propertyWithheld(shape.cssProperty)) return [];\n    return [controlForLeaf(property, path, shape, value)];\n  }\n  switch (shape.kind) {\n    case \"logicalSides\":\n      return entriesOf(shape.sides).flatMap(([side, leaf]) => down(side, leaf));\n    case \"logicalCorners\":\n      return entriesOf(shape.corners).flatMap(([corner, leaf]) =>\n        down(corner, leaf)\n      );\n    case \"object\":\n      return entriesOf(shape.fields).flatMap(([field, child]) =>\n        down(field, child)\n      );\n    case \"union\": {\n      // ASKED of the engine rather than decided here. Which arm a stored value\n      // belongs to is the same question validation answers when it picks the\n      // arm to judge that value against, so reading its answer makes the\n      // control and the error message beside it describe one arm by\n      // construction. The module docblock lists what predicting it would cost.\n      const active = activeVariant(shape, path, value, options);\n      // A union declaring no arms offers no choice and has nothing to draw. The\n      // catalog ships none; the matcher this replaced answered 0 regardless and\n      // handed `undefined` down as though it were a shape.\n      if (active === undefined) return [];\n      variants.push({\n        path,\n        active,\n        count: shape.of.length,\n        kinds: shape.of.map(arm => arm.kind),\n        names: shape.of.map(arm => formName(arm, shape.of)),\n      });\n      return walk(property, path, shape.of[active], value, options, variants);\n    }\n  }\n}\n\n/**\n * Which arm of a union to draw at one position.\n *\n * A STORED value settles it, and the engine settles that — so a caller's\n * preference cannot make the panel show one arm while validation judges the\n * value under another. Where nothing is stored there is no such value to\n * disagree with: the engine answers with the catalog's first arm for everyone,\n * and an author who wants to write the four-corner radius rather than the\n * single one has no other way to say so.\n *\n * A preference outside the union's own arms is ignored rather than clamped.\n * Clamping would silently draw arm 0 for a caller asking for arm 7, which reads\n * as the choice having been honoured.\n */\nfunction activeVariant(\n  shape: Extract<StyleShape, { kind: \"union\" }>,\n  path: readonly string[],\n  value: StyleValue | undefined,\n  options: StyleControlInput | undefined\n): number | undefined {\n  if (value === undefined) {\n    const preferred = options?.variantAt?.(path);\n    if (\n      preferred !== undefined &&\n      Number.isInteger(preferred) &&\n      preferred >= 0 &&\n      preferred < shape.of.length\n    ) {\n      return preferred;\n    }\n  }\n  return styleUnionVariant(shape, value, options);\n}\n\n/**\n * A shape's named children, typed.\n *\n * `Object.entries` widens the key to `string`, and the widened key then flows\n * into a control's `path` where it is the address a write is applied at. The\n * narrowing is local because the shapes' key sets are declared, not open.\n */\nfunction entriesOf<T>(record: Readonly<Record<string, T>>): [string, T][] {\n  return Object.entries(record);\n}\n\n/** The stored sub-value at a name, when the parent holds a record. */\nfunction childValue(\n  value: StyleValue | undefined,\n  name: string\n): StyleValue | undefined {\n  if (value === undefined || !isCompositeValue(value)) return undefined;\n  // OWN keys only, as `validateStyleValues` and the declaration walk both read\n  // them. A nested field reached through a prototype is one the compiler will\n  // not emit, so deriving a control from it shows an active variant the stored\n  // document does not have — and an inherited accessor would RUN during a read\n  // taken only to draw a panel.\n  return Object.hasOwn(value, name) ? value[name] : undefined;\n}\n\n/**\n * The controls one catalog property offers.\n *\n * `value` is optional and affects exactly one thing: which arm of a union the\n * controls describe. Every other answer is a property of the catalog alone,\n * which is what lets a caller derive a panel before any value is loaded.\n */\nexport function styleControlsFor(\n  property: StyleProperty,\n  value?: StyleValue,\n  options?: StyleControlInput\n): StyleControlSet {\n  const variants: StyleControlVariants[] = [];\n  const controls = walk(\n    property.property,\n    [],\n    property.shape,\n    value,\n    options,\n    variants\n  );\n  return { property: property.property, controls, variants };\n}\n\n/**\n * What each form is called, from the arm's own shape kind.\n *\n * The catalog gives arms no names, so their shape kind is the most specific\n * thing it says about them, and \"Form 1 / Form 2\" tells an author nothing.\n * Partial so a kind this build has not learned about gets the kind itself.\n */\nconst FORM_NAME: Partial<Record<StyleShape[\"kind\"], string>> = {\n  dimension: \"Length\",\n  number: \"Number\",\n  keyword: \"Keyword\",\n  color: \"Colour\",\n  cssValue: \"Custom\",\n  url: \"URL\",\n  logicalSides: \"Sides\",\n  logicalCorners: \"Corners\",\n  object: \"Fields\",\n  union: \"Mixed\",\n};\n\n/**\n * One arm's name beside the others. A keyword arm of one word is that word\n * (\"Auto\"), and a length beside a per-corner or per-side arm is the value for\n * all of them (\"All | Corners\").\n */\nfunction formName(arm: StyleShape, arms: readonly StyleShape[]): string {\n  if (arm.kind === \"keyword\" && arm.values.length === 1) {\n    const word = arm.values[0] ?? \"\";\n    return word.charAt(0).toUpperCase() + word.slice(1);\n  }\n  return kindName(\n    arm.kind,\n    arms.map(other => other.kind)\n  );\n}\n\n/** A form's name from its kind and its siblings' kinds alone. */\nfunction kindName(\n  kind: StyleShape[\"kind\"],\n  kinds: readonly StyleShape[\"kind\"][]\n): string {\n  if (\n    kind === \"dimension\" &&\n    kinds.some(other => other === \"logicalCorners\" || other === \"logicalSides\")\n  ) {\n    return \"All\";\n  }\n  return FORM_NAME[kind] ?? kind;\n}\n\n/**\n * Each form of a variant in plain words: its own names, or, for a variant\n * built without them, names read from the forms' kinds.\n */\nexport function formNamesOf(variant: StyleControlVariants): readonly string[] {\n  return (\n    variant.names ?? variant.kinds.map(kind => kindName(kind, variant.kinds))\n  );\n}\n","/**\n * Whether a control's value was authored here, inherited, or never set.\n *\n * This is the question the has-value dot beside every control exists to answer,\n * and the answer is READ rather than re-derived. `styleOrigin` already decides\n * which recorded declaration a node is showing, having settled tier order, both\n * breakpoint axes, states joining the base rules, refused values, descendant\n * selectors and specificity. Walking the cascade again here would be a second\n * implementation of that, and the two would disagree on exactly the cases that\n * made the first one hard.\n *\n * **Three states, following the affordance Webflow established.** A property\n * nothing set is empty; one set on this node at the breakpoint and state being\n * edited is authored here; anything else is inherited — from a named class, a\n * block type's defaults, the page, or this same node at a wider breakpoint. The\n * distinction is what stops an author editing a class through a control that\n * looks like it belongs to one node.\n *\n * **The inherited answer carries its ORIGIN, not just a colour.** A class origin\n * holds both the id and the slug, so a panel can name the class it came from and\n * offer to open it without looking anything up.\n *\n * @module style-provenance\n */\n\nimport {\n  shapeLeaves,\n  SITE_TEXT_ROOT,\n  STYLE_CATALOG,\n  styleOrigin,\n  BASE_BREAKPOINT,\n  breakpointContexts,\n  statePropagatesToAncestors,\n  outranksEntry,\n  type BreakpointAxis,\n  type BreakpointId,\n  type BreakpointSet,\n  type StyleOrigin,\n  type StyleState,\n  type StyleSubject,\n  type StyleTraceEntry,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { offeredTiers } from \"../canvas/canvas-width\";\n\nimport { BASE_DEVICE_LABEL, isUsableWidth } from \"./breakpoints\";\n\n/** What a control's dot reports. */\nexport type StyleProvenance =\n  /**\n   * Nothing in this document's own cascade wrote this property for this node.\n   *\n   * NOT the same as \"the browser's default applies\". `styleOrigin` considers an\n   * ancestor's declaration only when it carries a descendant selector, so an\n   * inheritable property — `color`, the font properties — set on an ancestor is\n   * visibly active on this node and reported here as unset. Modelling CSS\n   * inheritance needs to know which properties inherit, which the catalog does\n   * not declare, so it belongs to the engine that owns the cascade rather than\n   * to a reading of its output.\n   */\n  | { readonly kind: \"unset\" }\n  /** This node's own value, at the state and breakpoint being edited. */\n  | { readonly kind: \"authored\"; readonly entry: StyleTraceEntry }\n  /**\n   * A value from somewhere else — another tier, or this node at another\n   * breakpoint or state. Editing the control writes HERE and takes over.\n   */\n  | {\n      readonly kind: \"inherited\";\n      readonly entry: StyleTraceEntry;\n      readonly from: StyleOrigin;\n    }\n  /**\n   * A declaration reached this control, and which control wrote it cannot be\n   * told from what the trace records.\n   *\n   * The trace identifies a declaration by its CSS property and the selector it\n   * attached to, and that pair does not always identify a CONTROL: the catalog\n   * writes `background-image` from both `background.url` and\n   * `backgroundGradient`, on the node itself, with nothing to separate them.\n   * With one of the two stored, both controls would otherwise be classified\n   * from the same winning entry and the unset one would report as authored.\n   *\n   * Reported rather than guessed, because a dot that claims a value the control\n   * does not hold is worse than one that says it cannot tell. Resolving it needs\n   * the catalog property carried in the trace, which is the engine's to record.\n   */\n  | {\n      readonly kind: \"ambiguous\";\n      readonly entry: StyleTraceEntry;\n      /** Every catalog property that writes this declaration, this one included. */\n      readonly sharedWith: readonly string[];\n    };\n\n/** Everything needed to place one control's dot. */\nexport interface StyleProvenanceQuery {\n  /** The declarations the compiler wrote, in emission order. */\n  readonly trace: readonly StyleTraceEntry[];\n  /** The node the control belongs to, and the ancestors whose rules reach it. */\n  readonly subject: StyleSubject;\n  /**\n   * The CSS property, as the trace records it.\n   *\n   * Taken from the control's own leaf (`StyleLeaf.cssProperty`) rather than from\n   * the catalog key: two catalog keys can write one CSS property, and the trace\n   * records what was written.\n   */\n  readonly cssProperty: string;\n  /**\n   * The selector inside the block this control's declaration attaches to, from\n   * the control's own leaf (`StyleLeaf.descendant`), and `undefined` for the\n   * ordinary case of styling the block itself.\n   *\n   * Load-bearing, because a CSS property does not identify a control on its\n   * own. The catalog writes `color` from THREE properties: `color` on the block,\n   * `linkColor` on ` a`, and `linkColorHover` on ` a:hover`. `styleOrigin` reads\n   * the descendant for SPECIFICITY and does not filter on it, so a query\n   * carrying only the property lets a link rule win the plain text-colour\n   * control — reporting an unset control as authored, and all three controls as\n   * showing the same value.\n   */\n  readonly descendant?: string;\n  /** The state being edited. */\n  readonly state: StyleState;\n  /** The breakpoint being edited, which is what \"authored here\" is measured against. */\n  readonly breakpoint: BreakpointId;\n  /**\n   * Every breakpoint live at the width being viewed.\n   *\n   * Distinct from {@link breakpoint}, and both are needed: the live set decides\n   * which declarations are in play at all, while the edited one decides whether\n   * the winner among them belongs to this control. An editor simulating a narrow\n   * viewport inside a wide window is the ordinary case, so neither can be\n   * derived from the other.\n   */\n  readonly liveBreakpoints: readonly BreakpointId[];\n  /**\n   * Every state whose rules are matching right now.\n   *\n   * A fact about the viewer, exactly as {@link liveBreakpoints} is: an element\n   * under a pressed pointer matches `:active` AND `:hover`, and a focused one\n   * being hovered matches two more. All of their rules apply at once, and\n   * because each is wrapped in `:where()` none outranks another — so emission\n   * order alone decides, and a winner can come from a state other than the one\n   * being edited.\n   *\n   * Omitted means the state being edited plus base, which is right when the\n   * canvas simulates exactly the state under the cursor. A canvas that\n   * simulates several should say so, or a control will report a value the\n   * browser is not showing.\n   */\n  readonly liveStates?: readonly StyleState[];\n}\n\n/**\n * A descendant selector in the one spelling both sides can be compared in.\n *\n * The trace stores the selector as the compiler GROUPED it — `\" a\"`, with the\n * leading combinator — while `StyleLeaf.descendant` declares `\"a\"`. Measured:\n * compiling a node with `linkColor` and `linkColorHover` produces trace entries\n * carrying `\" a\"` and `\" a:hover\"`. Comparing the two spellings directly\n * matches nothing, so every link-colour control would report unset.\n *\n * Trimmed rather than re-joined with a space, so this does not depend on which\n * separator the compiler happens to use — only that the two differ by\n * surrounding whitespace, which is what a descendant combinator is.\n */\nfunction normalizeDescendant(value: string | undefined): string {\n  return value === undefined ? \"\" : value.trim();\n}\n\n/**\n * Whether a PAGE declaration lands on this block at all.\n *\n * `styleOrigin` treats every page-origin entry as reaching every subject, which\n * is right for the question it answers and wrong for this one. The page's own\n * settings compile onto the page ROOT, so a non-inherited property written there\n * — padding, width, a background colour — styles that root element and nothing\n * inside it. Reported unfiltered, a block control shows \"Inherited from the\n * page\" for a value the browser is not applying to it.\n *\n * A page entry carrying a DESCENDANT selector is the case that genuinely\n * reaches: `.page a` styles the links inside, this block's included, which is\n * the same rule `reachesThroughAncestor` applies to an ancestor's declarations.\n *\n * **What this deliberately gives up.** A property that truly inherits — `color`,\n * the font properties — set on the page IS visibly active on this block, and\n * that case is now reported as unset rather than as coming from the page.\n * Separating it needs to know which properties inherit, which the catalog does\n * not declare; this module's own `unset` docblock already states that limit for\n * an ancestor's declarations and says the knowledge belongs to the engine that\n * owns the cascade. Answering the two cases differently here would be a second,\n * partial model of CSS inheritance in the layer that reads the output.\n *\n * Quiet where it cannot tell, rather than confidently wrong, which is the same\n * judgement `ambiguous` makes one level up.\n */\nfunction landsOnTheBlock(entry: StyleTraceEntry): boolean {\n  if (onThePageRoot(entry)) return false;\n  if (entry.origin.kind !== \"page\") return true;\n  return normalizeDescendant(entry.descendant) !== \"\";\n}\n\n/**\n * Whether a declaration is written on the page root itself, which a block\n * reads only by inheritance: the page's own values, and the element tier's\n * root, where Site text's Body row is written.\n */\nfunction onThePageRoot(entry: StyleTraceEntry): boolean {\n  const { origin } = entry;\n  if (origin.kind === \"element\") return origin.tag === SITE_TEXT_ROOT;\n  return origin.kind === \"page\" && normalizeDescendant(entry.descendant) === \"\";\n}\n\n/*\n * The typographic baseline is deliberately NOT part of the case above. It does\n * land on the block — `:where(h1)` styles the heading itself rather than the\n * page root — so it needs no descendant to reach one, and `styleOrigin` has\n * already refused it for any subject whose element does not match.\n *\n * The subject learns its tag from the CANVAS — `renderedTagOf` reads the\n * element carrying the node's id — so a heading reports its size as coming from\n * the baseline while `core/rich-text` does not: that block's own root is a\n * `div` with its headings inside, and the baseline genuinely does not style its\n * box. A host that supplies no canvas states no tag and gets the refusal, which\n * is the quiet answer rather than a guessed one.\n */\n\n/**\n * Whether a recorded declaration reaches the element this control addresses.\n *\n * Exact equality is too narrow, because a descendant selector carries the\n * pseudo-classes with it: link hover is `a:hover` in the CATALOG rather than a\n * `StyleState`, so a hovered anchor matches both `a:hover` and the plain `a`\n * beside it. A control on `a:hover` with only `a` stored is displaying the `a`\n * rule, and filtering it out reported the browser's default instead.\n *\n * Less-specific only, and never the reverse: an anchor that is NOT hovered does\n * not match `a:hover`, so a plain-link control must not see a hover rule.\n * Which of the two wins is left to `styleOrigin`, whose ranking already counts\n * pseudo-classes as specificity.\n */\nfunction reachesControl(entry: string, query: string): boolean {\n  if (entry === query) return true;\n  if (entry === \"\" || query === \"\") return false;\n  const [entryBase] = entry.split(\":\");\n  const [queryBase] = query.split(\":\");\n  return entryBase === queryBase && !entry.includes(\":\") && query.includes(\":\");\n}\n\n/**\n * Every catalog property that writes one CSS property at one descendant.\n *\n * Derived from the catalog rather than listed, so a property added there is\n * covered without an edit here.\n */\nexport function propertiesWriting(\n  cssProperty: string,\n  descendant: string | undefined\n): string[] {\n  const names: string[] = [];\n  for (const entry of STYLE_CATALOG) {\n    for (const leaf of shapeLeaves(entry.shape)) {\n      if (leaf.cssProperty !== cssProperty) continue;\n      if (\n        normalizeDescendant(leaf.descendant) !== normalizeDescendant(descendant)\n      ) {\n        continue;\n      }\n      if (!names.includes(entry.property)) names.push(entry.property);\n    }\n  }\n  return names;\n}\n\n/**\n * Whichever of several winning entries the browser is actually showing.\n *\n * They all reach the node at the same specificity, so the one written last\n * wins. The trace records declarations in emission order, so its index IS that\n * ordering and nothing here re-derives it.\n */\nfunction lastWritten(\n  trace: readonly StyleTraceEntry[],\n  winners: readonly (StyleTraceEntry | undefined)[]\n): StyleTraceEntry | undefined {\n  let best: StyleTraceEntry | undefined;\n  let bestIndex = -1;\n  for (const winner of winners) {\n    if (winner === undefined) continue;\n    const index = trace.indexOf(winner);\n    /*\n     * WEIGHT before source order, which is the order the cascade itself applies\n     * them in — and `styleOrigin` already ranks this way WITHIN a state. Across\n     * states it cannot, because it is asked once per state and each answer is a\n     * separate winner, so the comparison lands here.\n     *\n     * Position alone is wrong wherever the states disagree on weight. A state's\n     * rules are wrapped in `:where()`, which contributes NOTHING, so an earlier\n     * `.card a:hover` outranks a later `:where(:hover) a` however far apart they\n     * were emitted — and picking the later one names a declaration the browser\n     * is not showing.\n     *\n     * Ranked THROUGH the engine's comparator rather than by counting\n     * pseudo-classes here. That count was the same answer only while every tier\n     * carried one class-worth of prefix. A default is now anchored to a single\n     * page-root class with its descendant inside `:where()`, so its ` a:hover`\n     * weighs `0-1-0` against a node's ` a` at `0-3-1` — counting names the\n     * default while the browser shows the node. One weighting, owned beside the\n     * compiler that emits the selectors it describes.\n     */\n    if (best !== undefined) {\n      // The standing answer weighs more, so nothing here can displace it.\n      if (outranksEntry(best, winner)) continue;\n      // Equal weight, and this one was written first. Source order decides.\n      if (!outranksEntry(winner, best) && index < bestIndex) continue;\n    }\n    best = winner;\n    bestIndex = index;\n  }\n  return best;\n}\n\n/** Whether an entry is this node's own value at the position being edited. */\nfunction isAuthoredHere(\n  entry: StyleTraceEntry,\n  query: StyleProvenanceQuery\n): boolean {\n  return (\n    entry.origin.kind === \"node\" &&\n    entry.origin.id === query.subject.nodeId &&\n    entry.breakpoint === query.breakpoint &&\n    entry.state === query.state &&\n    // The DESCENDANT too, because a candidate can reach this control without\n    // belonging to it: a plain `a` rule is what a hovered link displays, and it\n    // is this node's own value at this breakpoint and state — but the control\n    // that wrote it is the plain-link one. Calling that authored would offer to\n    // reset a value this control never set.\n    normalizeDescendant(entry.descendant) ===\n      normalizeDescendant(query.descendant)\n  );\n}\n\n/**\n * Where the value a control is showing came from.\n *\n * Undefined from `styleOrigin` is a real answer rather than a failure — a\n * property no tier set is one the browser takes from its own defaults, and a\n * control over it is genuinely empty.\n */\nexport function styleProvenance(query: StyleProvenanceQuery): StyleProvenance {\n  // NARROWED before the question is asked, rather than re-ranked afterwards.\n  // `styleOrigin` still decides which of the candidates a node is showing —\n  // this only removes the declarations that belong to a different control, so\n  // nothing here re-implements tier order, breakpoint axes or specificity.\n  const wanted = normalizeDescendant(query.descendant);\n  const candidates = query.trace.filter(\n    entry =>\n      reachesControl(normalizeDescendant(entry.descendant), wanted) &&\n      landsOnTheBlock(entry)\n  );\n  const ask = (state: StyleState): StyleTraceEntry | undefined =>\n    styleOrigin(candidates, query.subject, {\n      property: query.cssProperty,\n      state,\n      breakpoints: query.liveBreakpoints,\n    });\n  // An interaction state and the base state are asked SEPARATELY, because\n  // `styleOrigin` ranks within one state — and then ranked against each other\n  // here, because the browser does not keep them apart. A state selector is\n  // wrapped in `:where()`, which adds NO specificity, so a base rule emitted\n  // later beats an earlier interaction rule: measured, a class's hover colour\n  // followed by the node's base colour leaves the node's base colour showing\n  // while hovered. Preferring any interaction winner would report a value the\n  // browser is not displaying.\n  //\n  // Ranked by position in the trace, which is emission order — the same thing\n  // the cascade is settling — rather than by a second idea of tier order.\n  // Every state matching right now, base included: base always matches, and the\n  // state being edited is the one the canvas is simulating.\n  /*\n   * A SUPPLIED set is authoritative. The field's own contract says omitting it\n   * means the edited state plus base — so adding the edited state back when a\n   * caller did state one contradicts the answer they gave: a canvas simulating\n   * only `base` while the panel edits `hover` would have a hover declaration\n   * reported as the visible winner, which is exactly the case the field exists\n   * to let a host rule out.\n   *\n   * `base` is added either way because base rules are not state-gated and match\n   * whatever else is.\n   */\n  const live = new Set<StyleState>([\n    ...(query.liveStates ?? [query.state]),\n    \"base\",\n  ]);\n  const winner = lastWritten(\n    candidates,\n    [...live].map(state => ask(state))\n  );\n  if (winner === undefined) return { kind: \"unset\" };\n  // Asked only once a declaration has won: nothing wrote this position is an\n  // unambiguous answer whatever else could have written it.\n  const sharedWith = propertiesWriting(query.cssProperty, query.descendant);\n  if (sharedWith.length > 1) {\n    return { kind: \"ambiguous\", entry: winner, sharedWith };\n  }\n  if (isAuthoredHere(winner, query)) return { kind: \"authored\", entry: winner };\n  return { kind: \"inherited\", entry: winner, from: winner.origin };\n}\n\n/**\n * What a control would show without the node's own value at the position\n * being edited: the same ranking, over the trace with that one declaration\n * taken away.\n *\n * The question \"does this value cover a shared style's?\" asks, at the tier\n * being edited and not only at its exact address: a value the node sets at\n * a narrow breakpoint, or in an interaction state, over the style's wider or\n * base-state value covers it all the same. Answered by `styleProvenance`\n * rather than by looking the style's own value up, so the tier order, both\n * breakpoint axes and the state ranking are settled in one place.\n *\n * Pass the breakpoints that match AT the edited tier (`liveBreakpointsFor`),\n * since the answer is about the position the control writes, not the width\n * the canvas happens to show.\n */\nexport function provenanceBeneath(\n  query: StyleProvenanceQuery\n): StyleProvenance {\n  return styleProvenance({\n    ...query,\n    trace: query.trace.filter(entry => !isAuthoredHere(entry, query)),\n  });\n}\n\n/**\n * The CSS properties an element takes from its parent when nothing sets them\n * on it — those CSS defines as inherited, whether or not the catalog writes\n * each today, so a property added to the catalog is answered the day it lands.\n */\nconst INHERITED_PROPERTIES: ReadonlySet<string> = new Set([\n  \"border-collapse\",\n  \"caption-side\",\n  \"caret-color\",\n  \"color\",\n  \"color-scheme\",\n  \"accent-color\",\n  \"cursor\",\n  \"direction\",\n  \"empty-cells\",\n  \"font-family\",\n  \"font-size\",\n  \"font-stretch\",\n  \"font-style\",\n  \"font-variant\",\n  \"font-weight\",\n  \"hyphens\",\n  \"letter-spacing\",\n  \"line-height\",\n  \"list-style-position\",\n  \"list-style-type\",\n  \"overflow-wrap\",\n  \"quotes\",\n  \"tab-size\",\n  \"text-align\",\n  \"text-indent\",\n  \"text-shadow\",\n  \"text-transform\",\n  \"visibility\",\n  \"white-space\",\n  \"word-break\",\n  \"word-spacing\",\n  \"writing-mode\",\n]);\n\n/**\n * {@link styleProvenance}, with CSS inheritance: an inheritable property\n * nothing sets on this element is answered by the nearest enclosing block\n * whose own value shows, asked through the same ranking at that block's\n * address in its normal state.\n *\n * The ranking answers for rules that REACH an element, and a section's own\n * colour reaches only the section, so without this a heading inside it read\n * as unset while the canvas drew the section's colour on it. Asked of the\n * trace rather than of the canvas's computed style, so the answer names where\n * the value was written, which a computed value cannot say.\n *\n * Only for the element's own box: a control with a descendant selector styles\n * something inside it, whose parent is not the enclosing block. An ambiguous\n * answer on the way up stops the walk, since the next block's value would be\n * named over one whose source is unknown.\n */\nexport function inheritedProvenance(\n  query: StyleProvenanceQuery\n): StyleProvenance {\n  const own = styleProvenance(query);\n  const descendant = query.descendant?.trim() ?? \"\";\n  if (\n    own.kind !== \"unset\" ||\n    descendant !== \"\" ||\n    !INHERITED_PROPERTIES.has(query.cssProperty)\n  ) {\n    return own;\n  }\n  // Outermost first, as the engine reads them; walked from the nearest.\n  const chain = query.subject.ancestors ?? [];\n  for (let at = chain.length - 1; at >= 0; at -= 1) {\n    const ancestor = chain[at];\n    if (ancestor === undefined) continue;\n    const found = styleProvenance({\n      ...query,\n      subject: { ...ancestor, ancestors: chain.slice(0, at) },\n      // The enclosing block in the state the canvas holds it in: a state the\n      // engine forces up the chain (hover, pressed) is the ancestor's too, and\n      // any other leaves it in its normal state.\n      ...ancestorState(query.state),\n    });\n    if (found.kind === \"authored\") {\n      return {\n        kind: \"inherited\",\n        entry: found.entry,\n        from: found.entry.origin,\n      };\n    }\n    if (found.kind !== \"unset\") return found;\n  }\n  return pagePassesDown(query) ?? own;\n}\n\n/**\n * The state an enclosing block is in while this element is edited in\n * `state`, by the engine's own decision about which states the canvas forces\n * up the chain, so the walk and the canvas cannot disagree.\n */\nfunction ancestorState(\n  state: StyleState\n): Pick<StyleProvenanceQuery, \"state\" | \"liveStates\"> {\n  return statePropagatesToAncestors(state)\n    ? { state }\n    : { state: \"base\", liveStates: [\"base\"] };\n}\n\n/**\n * The page's own value for an inheritable property, which every block takes\n * when nothing nearer sets it. A page declaration on the root lands on no\n * block of its own, so the ranking above never meets it; ranked here, among\n * the page's root declarations alone, as the last place a value comes from.\n */\nfunction pagePassesDown(\n  query: StyleProvenanceQuery\n): StyleProvenance | undefined {\n  // The page's own values and Body's, ranked by the engine as the cascade\n  // ranks them: the page's, on the doubled root class, outrank Body's.\n  const candidates = query.trace.filter(onThePageRoot);\n  const entry = styleOrigin(candidates, query.subject, {\n    property: query.cssProperty,\n    state: \"base\",\n    breakpoints: query.liveBreakpoints,\n  });\n  return entry === undefined\n    ? undefined\n    : { kind: \"inherited\", entry, from: entry.origin };\n}\n\n/** Where a value a control is showing was authored, in breakpoint terms. */\nexport interface BreakpointSource {\n  /** The breakpoint's own id, as the trace records it. */\n  readonly breakpoint: BreakpointId;\n  /**\n   * What to call it in front of an author.\n   *\n   * The stored definition's label, never the id: an id is an addressing detail\n   * a site is free to spell `bp_2`, and putting it in front of an author at the\n   * one moment the control is explaining itself is the storage layer leaking.\n   * Falls back to the id only when no definition carries that bound, where\n   * there is no honest name to use instead.\n   */\n  readonly label: string;\n  /**\n   * Which axis it belongs to.\n   *\n   * Carried because a breakpoint NAMED without its axis is ambiguous whenever a\n   * site defines both: `breakpointContexts` emits over viewport and container\n   * separately, a container context emits a query even at its widest, and\n   * container is the axis an author is least likely to be holding in mind. A\n   * badge saying \"Tablet\" when two different tiers could be meant is a label\n   * that reads as precise and is not.\n   */\n  readonly axis: BreakpointAxis;\n  /**\n   * Whether a canvas can actually be taken to this tier.\n   *\n   * Two ids can carry one bound, and only the tier that WINS is offered as a\n   * choice — but a declaration stored under the loser can still be what a\n   * control is showing, and would otherwise earn a \"go to\" that cannot be\n   * honoured: the width lookup answers `undefined` for it, which a host reads\n   * as the unconditional tier and releases the canvas instead. Naming the tier\n   * is still right; offering to travel to it is not.\n   *\n   * The unconditional tier IS selectable: releasing the canvas is how it is\n   * shown, so `undefined` means something there.\n   */\n  readonly selectable: boolean;\n}\n\n/**\n * What a control's breakpoint badge reports, beside the origin dot.\n *\n * The dot answers WHICH TIER a value came from — this node, a class, the block\n * type, the page. This answers the breakpoint DIMENSION of the same question,\n * which the dot cannot: `StyleOrigin` records only the tier, so \"from a class\"\n * and \"from this node at desktop\" arrive as the same `node`/`class` answer with\n * nothing to separate them, and they are the two an author most needs told\n * apart because the next action differs. One is \"go and change it there\", the\n * other is \"override it here\".\n */\nexport type BreakpointBadge =\n  /**\n   * Nothing to say about breakpoints.\n   *\n   * The control is unset, or its value came from another TIER rather than\n   * another breakpoint, or the declaration cannot be attributed to one control\n   * at all. Ambiguous is deliberately included: a badge offering to reset a\n   * declaration two controls could have written would clear one the author was\n   * not looking at.\n   */\n  | { readonly kind: \"none\" }\n  /**\n   * Authored at the breakpoint being edited, so clearing it here is meaningful.\n   *\n   * `revealed` is what would then show through — the value the cascade falls\n   * back to once this one is gone. Absent when nothing would: the control\n   * becomes unset.\n   *\n   * Named rather than assumed to be the base tier. In a desktop-first model\n   * values flow from wider to narrower, and a chain can hold values at several\n   * breakpoints, so what a reset reveals is whatever the next one holding a\n   * value is.\n   */\n  | {\n      readonly kind: \"authored\";\n      readonly revealed?: BreakpointSource;\n      /**\n       * Set when nothing on the block would show once this value is gone,\n       * but an enclosing block or the page passes one down: the control is\n       * not left unset, and no breakpoint names where the value comes from.\n       */\n      readonly passedDown?: true;\n    }\n  /**\n   * The value on screen was authored by THIS NODE at another breakpoint.\n   *\n   * The case the badge exists for, and the one the origin dot reports as a bare\n   * `node` origin indistinguishable from a value set right here. Editing the\n   * control writes at the edited breakpoint and takes over from this one.\n   */\n  | { readonly kind: \"inherited\"; readonly source: BreakpointSource };\n\n/**\n * Resolve a breakpoint id to something an author can be shown.\n *\n * Exported because it is the ONE answer to \"what is this breakpoint called\" —\n * the panel's own label helper reads it rather than repeating the lookup, which\n * would be two matchers for a rule that has a subtlety in it (the survivor is\n * matched on the BOUND as well as the id) and two places to lose it.\n *\n * The AXIS and the bound come from `breakpointContexts`, which is the reader\n * that decides what a site's breakpoints are for the sheet; the label is then\n * matched on the bound as well as the id, because among definitions sharing an\n * id the compiler keeps one and a lookup by id alone can name the survivor\n * after a row the sheet discarded.\n */\nexport function breakpointSource(\n  breakpoint: BreakpointId,\n  breakpoints: BreakpointSet | undefined\n): BreakpointSource | undefined {\n  const context = breakpointContexts(breakpoints).find(\n    candidate => candidate.id === breakpoint\n  );\n  /*\n   * No context, or one that does not say which axis it belongs to, yields no\n   * badge at all.\n   *\n   * `BreakpointContext.axis` is optional, and a badge is a claim about which\n   * axis a value came from — the one thing the research says a breakpoint name\n   * cannot be shown without. Defaulting it to the viewport would put a\n   * confident label on the axis an author is least likely to be holding in\n   * mind, which is the case the axis is carried for.\n   */\n  if (context?.axis === undefined) return undefined;\n  const defs =\n    context.axis === \"container\"\n      ? breakpoints?.container\n      : breakpoints?.viewport;\n  const named = (defs ?? []).find(\n    def => def?.id === breakpoint && def?.maxWidth === context.maxWidth\n  );\n  return {\n    breakpoint,\n    // The base viewport tier by the device switcher's name for it.\n    label:\n      context.axis === \"viewport\" && breakpoint === BASE_BREAKPOINT\n        ? BASE_DEVICE_LABEL\n        : (named?.label ?? breakpoint),\n    axis: context.axis,\n    /*\n     * Unbounded is the unconditional tier and always reachable. A bounded tier\n     * is reachable only if it is the one `offeredTiers` kept for that width —\n     * the same list the switcher builds its options from, so \"a tier a canvas\n     * can be taken to\" has one definition rather than two.\n     */\n    /*\n     * The unconditional VIEWPORT tier is reachable — releasing the canvas is\n     * how it is shown. An unbounded CONTAINER definition is not: it has no\n     * `maxWidth` either, but `offeredTiers` and `widthForBreakpoint` exclude\n     * the container axis entirely, so a jump would hand the host `undefined`\n     * and release the canvas as though base had been chosen. Sizing a canvas\n     * cannot put an element's own query container at a width, whatever the\n     * definition looks like.\n     */\n    selectable:\n      context.axis !== \"container\" &&\n      (!isUsableWidth(context.maxWidth) ||\n        offeredTiers(breakpoints).some(tier => tier.id === breakpoint)),\n  };\n}\n\n/**\n * The badge for a value that won from somewhere other than the edited address.\n *\n * Its own function because the question is one word — is this THIS control at\n * another breakpoint? — and the answer needs the whole address checked.\n * `styleOrigin` deliberately returns declarations from an enclosing node, from\n * another state, and from a less specific sibling control, so a bare `node`\n * origin proves none of what the action promises.\n */\nfunction inheritedBadge(\n  query: StyleProvenanceQuery,\n  provenance: Extract<StyleProvenance, { kind: \"inherited\" }>,\n  breakpoints: BreakpointSet | undefined\n): BreakpointBadge {\n  const { from, entry } = provenance;\n  const sameAddress =\n    from.kind === \"node\" &&\n    from.id === query.subject.nodeId &&\n    entry.state === query.state &&\n    normalizeDescendant(entry.descendant) ===\n      normalizeDescendant(query.descendant);\n  if (!sameAddress) return { kind: \"none\" };\n  if (entry.breakpoint === query.breakpoint) return { kind: \"none\" };\n  const source = breakpointSource(entry.breakpoint, breakpoints);\n  return source === undefined\n    ? { kind: \"none\" }\n    : { kind: \"inherited\", source };\n}\n\n/**\n * The breakpoint badge for one control.\n *\n * Derived from {@link styleProvenance} rather than beside it, so there is one\n * answer to \"what is this control showing\" and this adds only the breakpoint\n * reading of it. A second ranking here would be a second cascade, and the two\n * would disagree first at exactly the boundaries the trace exists to settle.\n *\n * What a reset REVEALS is computed by asking the same question again with the\n * edited breakpoint removed from the live set — the engine's own ranking, run\n * once more over an already-filtered trace, rather than a hand-rolled \"next\n * wider\" that would have to re-derive tier order, both axes and specificity.\n * Only reached for a control that is authored here, which is the small minority\n * of them, so the cost is bounded by what an author has actually set.\n */\nexport function breakpointBadge(\n  query: StyleProvenanceQuery,\n  /**\n   * What {@link styleProvenance} already answered for this control.\n   *\n   * Taken rather than recomputed, because the badge is the breakpoint READING\n   * of a provenance and not a second opinion about it. A caller placing a dot\n   * has one in hand, and computing another here would be a second ranking of\n   * the same trace — the two would first disagree at exactly the boundaries the\n   * trace exists to settle.\n   */\n  provenance: StyleProvenance,\n  breakpoints: BreakpointSet | undefined\n): BreakpointBadge {\n  if (provenance.kind === \"unset\" || provenance.kind === \"ambiguous\") {\n    return { kind: \"none\" };\n  }\n  if (provenance.kind === \"inherited\") {\n    return inheritedBadge(query, provenance, breakpoints);\n  }\n  /*\n   * Authored here. What a reset would reveal is whatever wins once the\n   * declarations the reset ACTUALLY CLEARS are gone.\n   *\n   * Simulated by removing those declarations from the trace, not by removing\n   * the breakpoint from the live set. A reset clears one address — this node,\n   * this state, this breakpoint, this control's property and path — and leaves\n   * every other origin at that breakpoint standing. Dropping the whole\n   * breakpoint discards a class, block-type or page declaration that would\n   * survive, so a node value overriding a class value at Mobile was described\n   * as \"leaving it unset\" while the class value is what actually appears.\n   *\n   * The descendant is matched too: a rule on a more specific selector reaches\n   * this control without being written BY it, so this control's reset does not\n   * remove it.\n   */\n  const cleared = query.trace.filter(\n    entry =>\n      !(\n        entry.origin.kind === \"node\" &&\n        entry.origin.id === query.subject.nodeId &&\n        entry.state === query.state &&\n        entry.breakpoint === query.breakpoint &&\n        entry.property === query.cssProperty &&\n        normalizeDescendant(entry.descendant) ===\n          normalizeDescendant(query.descendant)\n      )\n  );\n  const revealedBy = styleProvenance({ ...query, trace: cleared });\n  if (revealedBy.kind === \"unset\") {\n    // What CSS inheritance would show instead, asked the same way the\n    // control is described once the value is gone.\n    const inherited = inheritedProvenance({ ...query, trace: cleared });\n    return inherited.kind === \"unset\"\n      ? { kind: \"authored\" }\n      : { kind: \"authored\", passedDown: true };\n  }\n  if (revealedBy.kind === \"ambiguous\") return { kind: \"authored\" };\n  const source = breakpointSource(revealedBy.entry.breakpoint, breakpoints);\n  return source === undefined\n    ? { kind: \"authored\" }\n    : { kind: \"authored\", revealed: source };\n}\n","/**\n * Previewing a value while the pointer is still down, and committing once.\n *\n * A scrub is two different operations wearing one gesture. Dragging must show\n * the result immediately and cost nothing per frame; releasing must produce a\n * single undoable edit. Doing both through the document would recompile a\n * stylesheet on every pointer move and push an undo entry for each — so the\n * drag writes CSS and only the release writes the document.\n *\n * **The preview is compiled, not formatted.** `compileStyleValues` is the same\n * function the published stylesheet is emitted through, so a token reference\n * becomes the same `var()`, a composite expands to the same logical properties,\n * and a value the compiler refuses produces no declarations here either. Writing\n * `${property}: ${value}` by hand would be a second emission path, and the two\n * would disagree exactly where emission is interesting.\n *\n * **A refused value never reaches the screen.** The compiler validates before it\n * writes, so the preview and the commit accept exactly the same values — by\n * construction rather than by both remembering to check.\n *\n * **The rule sits at the compiler's own specificity and wins on ORDER.** It is\n * anchored to the same root the compiled sheet uses — `PAGE_ROOT_SELECTOR`,\n * plus the document's scope class when it has one — because that is where the\n * override contract lives. Spelling a stronger selector would quietly raise\n * that contract for the duration of a drag, so the preview would land where the\n * committed value will not; spelling a weaker one loses to the rule being\n * previewed over, and the drag shows nothing move. The consequence for the host\n * is that the element holding this text must come after the compiled sheet's\n * rules for the SAME state — later of two equals wins — and removing it on\n * commit reveals the real rule underneath with no visible change.\n *\n * **Mounting it after the WHOLE sheet is wrong for a base-state preview**, and\n * this module cannot prevent that on its own. The compiler emits interaction\n * states after base at equal specificity, so a base rule placed last also\n * outranks an existing hover, focus or active declaration: the element shows\n * the scrubbed base value while hovered, and reverts on release. Placing the\n * preview beside the rules for its own state is the host's part of this\n * contract; which states carry a declaration for the property is in the trace\n * the provenance query already reads.\n *\n * @module style-scrub\n */\n\nimport {\n  compilePageCss,\n  compileStyleValues,\n  escapeIdentifier,\n  MAX_SCOPE_LENGTH,\n  nodeClassName,\n  PAGE_ROOT_SELECTOR,\n  previewContainerName,\n  STYLE_STATES,\n  type BlockDocument,\n  type BreakpointDef,\n  type BreakpointSet,\n  type Declaration,\n  type NodeStyles,\n  type StyleState,\n  type StyleValue,\n  type ValidationIssue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { BASE_BREAKPOINT } from \"./breakpoints\";\nimport type {\n  StyleAddress,\n  StylePolicy,\n  StyleWrite,\n  StyleWriteRequest,\n} from \"./style-values\";\nimport {\n  readStyleValue,\n  styleValueAtPath,\n  styleWriteOp,\n  styleWriteOps,\n} from \"./style-values\";\n\n/** The node a scrub is previewing against. */\nexport interface ScrubTarget {\n  readonly nodeId: string;\n  /**\n   * The class the compiler emitted for this node.\n   *\n   * Supplied rather than derived from the id. `nodeClassName` cannot see a hash\n   * collision — only `nodeClassNames`, which reads the whole document, can — so\n   * a target that hashed the id itself would preview against the wrong node on\n   * exactly the documents where the compiler had already disambiguated.\n   */\n  readonly nodeClass: string;\n  /**\n   * The container a preview surface compiled this page's breakpoints against.\n   *\n   * Carried because the override must be wrapped in the SAME at-rule the rule\n   * it outranks was emitted under. Compiled without it while the page was\n   * compiled with it, a non-base override sits in `@media` while its target sits\n   * in a container query — so in a narrow canvas inside a wide window the\n   * override matches nothing, the drag looks frozen, and the value jumps into\n   * place on commit.\n   */\n  readonly previewContainer?: string;\n  /**\n   * The document's compile scope, when it has one.\n   *\n   * `compilePageCss` anchors every rule to `${PAGE_ROOT_SELECTOR}.${scope}`, so\n   * a preview that spelled the unscoped root would sit one class BELOW the rule\n   * it is previewing over — the stored value would win and the drag would show\n   * nothing move. It would also reach a same-class node in another document\n   * rendered beside this one.\n   *\n   * Escaped through the engine's own `escapeIdentifier`, so the preview and the\n   * compiled sheet cannot disagree about a scope needing escapes.\n   */\n  readonly scope?: string;\n  /**\n   * The site's breakpoint definitions, as the canvas compiles with.\n   *\n   * `compilePageCss` wraps a non-base breakpoint's rules in `@media` or\n   * `@container` — measured, a `mobile` value comes out inside\n   * `@media (max-width: 640px)`. A preview that ignored the address's\n   * breakpoint would show the value at every width and lose it on release, and\n   * for a breakpoint id this site does not define the compiler writes no rule\n   * at all while an unconditional preview still showed one.\n   *\n   * Omitted means every value previews unconditionally, which is right only for\n   * a site whose breakpoints are all unconditional.\n   */\n  readonly breakpoints?: BreakpointSet;\n  readonly address: StyleAddress;\n  /**\n   * The custom-property prefix this site emits tokens under.\n   *\n   * `compilePageCss` takes it from `StyleCompileContext.tokenPrefix`, so a site\n   * that configured `--acme-` would have its published sheet read\n   * `var(--acme-brand)` while a preview compiled with the default read\n   * `var(--site-brand)` — a token that resolves to nothing, or to a different\n   * value, for exactly as long as the drag lasts. Omitted means the engine's\n   * own default, which is what the compiler falls back to.\n   */\n  readonly tokenPrefix?: string;\n  /** The site policy, forwarded to the compile so a refused URL never previews. */\n  readonly policy?: StylePolicy;\n  /**\n   * The node's own styles, so the preview can decline to outrank a state it\n   * does not belong to.\n   *\n   * The compiler emits one rule per state at EQUAL specificity, in\n   * `STYLE_STATES` order — measured: base, then hover, then focus, then active,\n   * each constrained by a zero-specificity `:where()`. Later therefore beats\n   * earlier on document ORDER alone, and a preview mounted after the whole\n   * sheet is later than all of them. So a base-state preview silently outranks\n   * an existing hover declaration: the block shows the scrubbed base value\n   * while the pointer is over it, and reverts to hover on release.\n   *\n   * Given the styles, the rule excludes exactly the states that are emitted\n   * AFTER this one and declare THIS address. The exclusion is written with\n   * `:not(:where(...))`, whose specificity is that of its most specific\n   * argument — and `:where()` is always zero — so the rule still ranks exactly\n   * where the compiler put the one it is previewing over. Raising specificity\n   * instead would win the hover case and lose the contract: the preview would\n   * land somewhere the committed value cannot.\n   *\n   * Omitted, the preview outranks every later state, which is the behaviour\n   * this field exists to correct. Supply it whenever a node may carry\n   * interaction states — which is any node an editor can style.\n   */\n  readonly styles?: NodeStyles;\n}\n\n/**\n * The fragment the compiler constrains one state's rules with, per state.\n *\n * READ from the compiler rather than restated here. `compilePageCss` appends\n * `:where(:hover)` and its siblings from a table it does not export, so a copy\n * would be a second statement of which pseudo-class each state means — and the\n * two would agree until the engine moved, at which point a hover preview would\n * land somewhere the committed rule does not. Compiling one probe per state and\n * taking the fragment out of the selector it produced cannot drift.\n *\n * Without it a preview matches the node in EVERY state: dragging a hover value\n * would repaint the resting appearance too, and releasing would reveal\n * behaviour the drag never showed.\n *\n * Four states, computed once.\n */\nconst STATE_FRAGMENTS = new Map<StyleState, string>();\n\n/** The probe node's id, used only to derive the fragments above. */\nconst PROBE_ID = \"scrub-state-probe\";\n\n/** Compile one probe document and return the selector it wrote. */\nfunction probeSelector(state: StyleState): string {\n  const document: BlockDocument = {\n    formatVersion: 1,\n    kind: \"page\",\n    nodes: [\n      {\n        id: PROBE_ID,\n        type: \"core/box\",\n        version: 1,\n        props: {},\n        // A property with no descendant, so the selector carries the state\n        // fragment and nothing else after the node class.\n        styles: { [state]: { base: { height: \"1px\" } } },\n      },\n    ],\n  };\n  const compiled = compilePageCss(document, {\n    breakpoints: { viewport: [{ id: \"base\", label: \"Base\" }], container: [] },\n    /*\n     * Compiled the way the EDITOR compiles, which is the only way this fragment\n     * is useful. An editor showing a state the pointer is not really in adds\n     * `previewStateClass` to the node and relies on the sheet carrying an arm\n     * for it — the compiler writes `:where(:hover, .nx-pb-state-hover)` for\n     * both at once. Probed without this the fragment is the bare pseudo-class,\n     * so a preview of a FORCED state matches nothing: the drag shows no\n     * movement and the value jumps into place on release.\n     *\n     * Harmless where no state is forced. `:where()` has zero specificity, so\n     * the selector ranks exactly as it did, and the extra arm matches only an\n     * element carrying a marker class — which a surface that never forces a\n     * state does not have.\n     */\n    previewStates: true,\n  });\n  return compiled.css.split(\"{\")[0].trim();\n}\n\n/**\n * What a state adds to a node's selector.\n *\n * Falls back to constraining nothing only for `base`, which genuinely adds\n * nothing. For any other state a fragment that could not be derived would mean\n * previewing in the wrong place, so this throws rather than emitting a rule\n * that silently repaints the resting appearance.\n */\nfunction stateFragment(state: StyleState): string {\n  const cached = STATE_FRAGMENTS.get(state);\n  if (cached !== undefined) return cached;\n  const prefix = `${PAGE_ROOT_SELECTOR} .${nodeClassName(PROBE_ID)}`;\n  const selector = probeSelector(state);\n  if (!selector.startsWith(prefix)) {\n    throw new Error(\n      `the compiler's selector for the ${state} state no longer starts with ` +\n        `the node's own selector, so a preview cannot be placed beside it`\n    );\n  }\n  const fragment = selector.slice(prefix.length);\n  STATE_FRAGMENTS.set(state, fragment);\n  return fragment;\n}\n\n/** Every state's fragment, for a caller that wants them warmed or asserted. */\nexport function scrubStateFragments(): ReadonlyMap<StyleState, string> {\n  for (const state of STYLE_STATES) stateFragment(state);\n  return STATE_FRAGMENTS;\n}\n\n/**\n * At-rules already derived, per breakpoint set and id.\n *\n * Held against the set OBJECT, and checked against its CONTENT. Identity alone\n * is not enough: a host that edits a definition in place keeps the same object,\n * so a cache keyed on identity keeps answering with the old query — measured, a\n * `mobile` breakpoint previewed at 640px still emitted `@media (max-width:\n * 640px)` after its `maxWidth` became 320, while the next compile used 320.\n * The preview would then sit at a width where the committed value is absent.\n *\n * The content key is recomputed per lookup and the entries dropped when it\n * moves, which keeps this bounded by the number of live sets rather than by how\n * often one is edited. Serializing a handful of definitions costs far less than\n * the probe compile it saves.\n */\ninterface AtRuleCache {\n  content: string;\n  perId: Map<string, string | null>;\n}\n\nconst AT_RULES = new WeakMap<BreakpointSet, AtRuleCache>();\n\n/**\n * The at-rule the compiler wraps one breakpoint's declarations in.\n *\n * `null` means the compiler writes NO rule for this id — which is what it does\n * for an id the site does not define, and is a refusal rather than an\n * unconditional rule. `\"\"` means it writes one with no wrapper, as base does.\n *\n * READ from a probe compile rather than rebuilt from the definitions. Turning a\n * breakpoint into a media query is the compiler's own arithmetic — which axis,\n * which bound, how a container query differs — and it does not export it, so a\n * copy here would drift from the sheet the preview is meant to sit beside.\n */\nfunction breakpointAtRule(\n  breakpoints: BreakpointSet,\n  preview: string | undefined,\n  id: string\n): string | null {\n  /*\n   * NORMALISED before it reaches the cache identity, not merely before the\n   * compile.\n   *\n   * The compiler refuses an empty, reserved, malformed or oversized name and\n   * emits published rules instead, so the raw string is not what decides the\n   * at-rule — the normalised one is, and serialising the raw form keys the\n   * cache on a distinction the output does not have.\n   *\n   * The cost is paid on a hot path rather than once. `scrubPreviewCss`\n   * recomputes this identity on every pointer update during a drag, so a\n   * refused name that is megabytes long is stringified per frame even though\n   * the at-rule it maps to was cached on the first move — the editor stalls\n   * while dragging, with nothing about the drag to explain it.\n   */\n  const effective = previewContainerName(preview);\n  // The preview name joins the cache identity, because it changes the derived\n  // at-rule for the same breakpoint set — cached without it, the first caller's\n  // mode would be served to the other.\n  const content = JSON.stringify([breakpoints, effective]);\n  let entry = AT_RULES.get(breakpoints);\n  if (entry === undefined || entry.content !== content) {\n    entry = { content, perId: new Map() };\n    AT_RULES.set(breakpoints, entry);\n  }\n  const cached = entry.perId.get(id);\n  if (cached !== undefined) return cached;\n  const document: BlockDocument = {\n    formatVersion: 1,\n    kind: \"page\",\n    nodes: [\n      {\n        id: PROBE_ID,\n        type: \"core/box\",\n        version: 1,\n        props: {},\n        styles: { base: { [id]: { height: \"1px\" } } },\n      },\n    ],\n  };\n  const css = compilePageCss(document, {\n    breakpoints,\n    // The SAME emission the page rule was compiled under. A scrub override\n    // wrapped in `@media` while the rule it must outrank sits in a container\n    // query matches nothing in a narrow canvas, so the drag looks frozen and\n    // then jumps on commit.\n    ...(effective === undefined ? {} : { previewContainer: effective }),\n  }).css.trim();\n  const wrapper = /^@[a-z-]+[^{]*/.exec(css);\n  const derived = css === \"\" ? null : wrapper === null ? \"\" : wrapper[0].trim();\n  entry.perId.set(id, derived);\n  return derived;\n}\n\n/**\n * The at-rule this target's declarations belong inside, or `null` to refuse.\n *\n * Omitting the breakpoint set is only safe for the BASE breakpoint, which the\n * compiler writes unconditionally. For any other id the committed value is\n * wrapped in a query — or dropped entirely, when the site does not define it —\n * and an unconditional preview would show the value at every width and lose it\n * on release. Refusing says the preview cannot be placed, which is the honest\n * answer when the caller has not said where it goes.\n */\nfunction atRuleFor(target: ScrubTarget): string | null {\n  if (target.breakpoints !== undefined) {\n    return breakpointAtRule(\n      target.breakpoints,\n      target.previewContainer,\n      target.address.breakpoint\n    );\n  }\n  return target.address.breakpoint === BASE_BREAKPOINT ? \"\" : null;\n}\n\n/**\n * The root every rule for this document is anchored to.\n *\n * A scope the compiler REFUSES falls back to the unscoped root here too. It\n * refuses an empty scope and one carrying ASCII whitespace, because `a b` in a\n * class attribute is two classes and no escaping makes it the single class the\n * renderer attached — so it warns and emits unscoped rules. Escaping the\n * whitespace instead would produce a selector requiring a class the DOM cannot\n * hold, and the preview would show nothing while the commit produced working\n * CSS.\n *\n * The whitespace set is ASCII only, matching what HTML splits a class attribute\n * on: `\\s` in JavaScript also matches NBSP and the Unicode spaces, and those do\n * NOT split a class, so rejecting them would drop a scope the compiler kept.\n */\nfunction rootSelector(scope: string | undefined): string {\n  if (\n    scope === undefined ||\n    scope === \"\" ||\n    /[ \\t\\n\\f\\r]/.test(scope) ||\n    /*\n     * The compiler's OWN cap, imported rather than restated. A scope prefixes\n     * every rule the page emits, so it refuses an oversized one and writes the\n     * sheet unscoped — and a preview that scoped itself anyway would sit one\n     * class below a rule anchored at the bare root, matching nothing. The drag\n     * would look frozen and the value would appear on release.\n     */\n    scope.length > MAX_SCOPE_LENGTH\n  ) {\n    return PAGE_ROOT_SELECTOR;\n  }\n  return `${PAGE_ROOT_SELECTOR}.${escapeIdentifier(scope)}`;\n}\n\n/** CSS for the value under the pointer, or the reasons it was refused. */\nexport type ScrubPreview =\n  | {\n      readonly ok: true;\n      readonly css: string;\n      /**\n       * What the compiler remarked on while writing this declaration.\n       *\n       * Emitting and objecting are not the same outcome. A site whose\n       * `tokenPrefix` is invalid gets its declarations written under the\n       * engine's default prefix WITH a warning saying so — measured: a plain\n       * `24px` compiles to one declaration and one `severity: \"warning\"`\n       * issue. Treating that as a refusal would blank every preview on that\n       * site, including values with no token in them, while the commit\n       * succeeded and the published page rendered normally.\n       */\n      readonly warnings: readonly ValidationIssue[];\n    }\n  | { readonly ok: false; readonly issues: readonly ValidationIssue[] };\n\n/**\n * The rule text for one node's declarations, one rule per declaration.\n *\n * Deliberately NOT grouped by descendant. The compiler groups because it\n * serializes a whole document and a stable, compact sheet matters there; a\n * preview carries the declarations of a single leaf, which share one selector\n * anyway, and separate rules at equal specificity cascade identically to one\n * merged rule. Repeating the grouping here would be a second copy of a function\n * the engine already has, kept in step by nothing.\n */\n/**\n * The states that would beat this preview, as selector exclusions.\n *\n * Only the states emitted AFTER this one — earlier states lose to it already —\n * and only those declaring the SAME address. Granularity matters both ways: a\n * hover that sets `margin.blockStart` compiles to `margin-block-start` alone and\n * does not touch a `blockEnd` preview, so excluding on the property would blank\n * the preview wherever the author had styled any other side of the same box.\n *\n * Empty when the caller supplied no styles, which leaves the previous behaviour\n * rather than guessing at one.\n */\n/** The definition one breakpoint id has on this site, with its axis. */\nfunction breakpointDef(\n  breakpoints: BreakpointSet | undefined,\n  id: string\n):\n  | { readonly def: BreakpointDef; readonly axis: \"viewport\" | \"container\" }\n  | undefined {\n  if (breakpoints === undefined) return undefined;\n  const viewport = breakpoints.viewport.find(one => one.id === id);\n  if (viewport !== undefined) return { def: viewport, axis: \"viewport\" };\n  const container = breakpoints.container.find(one => one.id === id);\n  return container === undefined\n    ? undefined\n    : { def: container, axis: \"container\" };\n}\n\n/**\n * Whether a rule at `other` still applies everywhere a rule at `edited` does.\n *\n * Only such a rule can compete with the preview, which is wrapped in the edited\n * breakpoint's own at-rule and shows up nowhere else. A bound is always an UPPER\n * one — `BreakpointDef` carries `maxWidth`, and the unconditional tier omits it\n * — so the question reduces to whether one range contains the other, which the\n * site's own definitions answer without parsing any CSS.\n *\n * A breakpoint this site does not define competes with nothing: `compilePageCss`\n * writes no rule for it at all.\n *\n * Two CONDITIONAL breakpoints on different axes are read as not covering, and\n * that is the honest answer rather than a cautious one: a `@media` width and a\n * `@container` width are measured against different boxes, so neither contains\n * the other by anything these numbers say. Excluding on a guess would freeze the\n * preview wherever the guess was wrong, which is the worse of the two failures.\n */\nfunction coversTier(\n  breakpoints: BreakpointSet | undefined,\n  edited: string,\n  other: string\n): boolean {\n  if (other === edited) return true;\n  const there = breakpointDef(breakpoints, other);\n  // Undefined here, so the compiler emits nothing for it.\n  if (there === undefined) return false;\n  // Unconditional: it applies at every width, so it covers any tier.\n  if (there.def.maxWidth === undefined) return true;\n  const here = breakpointDef(breakpoints, edited);\n  if (here === undefined || here.def.maxWidth === undefined) return false;\n  if (here.axis !== there.axis) return false;\n  // Both upper bounds on one axis: the wider range contains the narrower.\n  return there.def.maxWidth >= here.def.maxWidth;\n}\n\n/** The breakpoint map a state holds, read by own keys only. */\nfunction ownBreakpoints(\n  styles: NodeStyles,\n  state: StyleState\n): readonly string[] {\n  const part = Object.getOwnPropertyDescriptor(styles, state);\n  const value = part !== undefined && \"value\" in part ? part.value : undefined;\n  return typeof value === \"object\" && value !== null\n    ? Object.keys(value as Record<string, unknown>)\n    : [];\n}\n\nfunction laterStateExclusions(target: ScrubTarget): string {\n  const { address, styles } = target;\n  if (styles === undefined) return \"\";\n  const from = STYLE_STATES.indexOf(address.state);\n  /* c8 ignore next -- the address's state comes from the same union */\n  if (from < 0) return \"\";\n  /*\n   * Every breakpoint the node stores, not only the edited one.\n   *\n   * A later state's rules are emitted after EVERY base-state breakpoint —\n   * measured: `hover` at the unconditional tier comes out after `base` inside\n   * `@media (max-width: 640px)`. So a hover declared one tier out still beats a\n   * narrow base rule, and a lookup keyed on the edited breakpoint alone missed\n   * it: the drag appeared to work while hovered and snapped back on release,\n   * which is this function's own defect one dimension over.\n   */\n  const declaredWhereItCompetes = (state: StyleState): boolean =>\n    ownBreakpoints(styles, state).some(\n      breakpoint =>\n        coversTier(target.breakpoints, address.breakpoint, breakpoint) &&\n        readStyleValue(styles, { ...address, state, breakpoint }) !== undefined\n    );\n  return STYLE_STATES.slice(from + 1)\n    .filter(declaredWhereItCompetes)\n    .map(later => `:not(${stateFragment(later)})`)\n    .join(\"\");\n}\n\nfunction ruleText(\n  target: ScrubTarget,\n  declarations: readonly Declaration[],\n  atRule: string\n): string {\n  const root = rootSelector(target.scope);\n  const state =\n    stateFragment(target.address.state) + laterStateExclusions(target);\n  return declarations\n    .map(declaration => {\n      const descendant =\n        declaration.descendant === undefined\n          ? \"\"\n          : ` ${declaration.descendant}`;\n      const rule =\n        `${root} .${target.nodeClass}${state}${descendant} ` +\n        `{ ${declaration.property}: ${declaration.value} }`;\n      return atRule === \"\" ? rule : `${atRule} {\\n  ${rule}\\n}`;\n    })\n    .join(\"\\n\");\n}\n\n/**\n * The stylesheet text that shows `value` without touching the document.\n *\n * Only the scrubbed property is compiled. Everything else the node carries\n * still comes from the sheet underneath, so a preview of one side of a margin\n * does not restate — and cannot accidentally drop — the other three.\n */\nexport function scrubPreviewCss(\n  target: ScrubTarget,\n  value: StyleValue\n): ScrubPreview {\n  const { property, path } = target.address;\n  // Resolved BEFORE compiling the value: a breakpoint the site does not define\n  // is one the published sheet carries no rule for, so previewing it would show\n  // an author a result the page will never have.\n  const atRule = atRuleFor(target);\n  if (atRule === null) return { ok: false, issues: [] };\n  const compiled = compileStyleValues(\n    { [property]: styleValueAtPath(path, value) },\n    \"\",\n    target.tokenPrefix,\n    undefined,\n    undefined,\n    // The WHOLE policy, not just the host half. The token table decides which\n    // arm of a union a stored reference belongs to, so forwarding half of it\n    // would let this preview compile through one arm while the control beside\n    // it draws another.\n    target.policy\n  );\n  // Two different outcomes wear one field. An ERROR means the compiler refused\n  // the value, and nothing was written; a warning can accompany a declaration\n  // it wrote anyway. Reading the field's length alone conflates them, so a\n  // setting the compiler recovered from would blank the preview while the\n  // published page rendered fine.\n  const errors = compiled.warnings.filter(issue => issue.severity === \"error\");\n  if (errors.length > 0) return { ok: false, issues: errors };\n  // Nothing written is a refusal however it was reported: previewing a value\n  // the page will not carry shows the author a result they cannot keep.\n  if (compiled.declarations.length === 0) {\n    return { ok: false, issues: compiled.warnings };\n  }\n  return {\n    ok: true,\n    css: ruleText(target, compiled.declarations, atRule),\n    warnings: compiled.warnings,\n  };\n}\n\n/**\n * The single op that ends a scrub.\n *\n * Separate from the preview and deliberately not derived from it: the preview\n * is CSS the canvas throws away, and the commit is a document edit. Passing one\n * through the other would make the stored value a function of a string that was\n * built for display.\n */\nexport function scrubCommitOp(\n  target: ScrubTarget,\n  styles: Parameters<typeof styleWriteOp>[1],\n  value: StyleValue\n): StyleWrite {\n  // The SAME breakpoint decision the preview makes. A breakpoint removed while\n  // a drag was in flight makes `scrubPreviewCss` refuse, and a commit that\n  // ignored the set would persist a value `compilePageCss` never emits — the\n  // drag would end by storing something the page cannot show.\n  if (atRuleFor(target) === null) {\n    return { ok: false, issues: [] };\n  }\n  return styleWriteOp(\n    target.nodeId,\n    styles,\n    target.address,\n    value,\n    target.policy\n  );\n}\n\n/**\n * The single op that ends a scrub touching SEVERAL addresses at once.\n *\n * A gesture that moves more than one side — every side of a margin, or a pair\n * across from each other — is still ONE thing the author did, so it has to cost\n * one entry in the history. `styleWriteOps` is what makes that true at the\n * value layer rather than at each caller: it folds the writes so the envelope\n * carries all of them, where repeated `scrubCommitOp` calls would each build a\n * complete envelope from the same starting styles and the last would silently\n * drop the rest.\n *\n * The breakpoint is decided ONCE, from the target, and every write is required\n * to share it. They come from one gesture at one tier by construction — the\n * addresses differ only in their side — so a mixed list is a caller mistake\n * rather than a case to serve, and committing a value at a tier the compiler\n * writes no rule for is the failure this refusal exists to prevent.\n *\n * @param target - the node and tier being scrubbed\n * @param styles - that node's styles before the gesture\n * @param writes - the addresses and values the gesture settled on\n * @returns one op for all of them, or the reasons the first refusal gives\n */\nexport function scrubCommitOps(\n  target: ScrubTarget,\n  styles: Parameters<typeof styleWriteOps>[1],\n  writes: readonly StyleWriteRequest[]\n): StyleWrite {\n  if (atRuleFor(target) === null) {\n    return { ok: false, issues: [] };\n  }\n  /*\n   * ENFORCED, not assumed.\n   *\n   * The breakpoint is judged once, from the target, and this used to say that a\n   * mixed list was a caller mistake rather than a case to serve — while doing\n   * nothing to stop one. A write naming another tier would then be persisted\n   * under a breakpoint this function never checked, including one the site does\n   * not define, which `compilePageCss` emits no rule for at all: the value is\n   * stored, the page never shows it, and nothing reports either.\n   *\n   * An invariant a function documents and does not check is one its callers are\n   * free to break, and the caller here is a gesture whose addresses change under\n   * a modifier. Refusing costs one comparison per write.\n   */\n  const { state, breakpoint } = target.address;\n  const strayed = writes.some(\n    write =>\n      write.address.state !== state || write.address.breakpoint !== breakpoint\n  );\n  if (strayed) return { ok: false, issues: [] };\n  return styleWriteOps(target.nodeId, styles, writes, target.policy);\n}\n","/**\n * Where a control's custom behaviour lives, when the generic mapping is not\n * enough.\n *\n * Most controls need nothing here: a leaf's kind decides the control, and the\n * leaf's own fields carry the units, bounds and keywords it draws with. A few\n * will want something the catalog cannot express — a spoken value that reads\n * \"24 pixels, medium\" rather than \"24\", a bespoke keyboard step.\n *\n * **That behaviour is referenced by NAME and never embedded in the catalog.**\n * `catalog.ts` says of itself that it is data, not code, and four consumers\n * depend on it: validation, the compiler, the inspector, and the generated\n * reference documentation. A function stored in a catalog entry cannot be\n * serialized for the first, cannot be reasoned about by the second, and cannot\n * be documented at all by the fourth — so the catalog keeps its identity and\n * this holds the behaviour under a key derived from it.\n *\n * The alternative was measured in the field rather than reasoned about: a\n * Visual Page Builder that allows functions inside its input config has to stringify\n * and re-evaluate them, and documents the consequence — such a function may not\n * reference anything outside its own body, which typechecks and fails at\n * runtime.\n *\n * **This registry is EMPTY, deliberately.** The shape is fixed so the contract\n * is settled and a control needing behaviour has somewhere to put it; inventing\n * entries before a control asks for one would be building against a guess.\n *\n * **A plain map rather than a mutable module global.** A registry a module\n * mutates on import is one that differs between a test, a server render and a\n * browser, and cannot be varied per editor instance. Passing the map keeps the\n * lookup pure and makes \"no behaviour registered\" the default that needs no\n * setup.\n *\n * @module style-control-behaviour\n */\n\nimport type { StyleValue } from \"@nextlyhq/blocks-engine\";\n\n/** Behaviour a control cannot derive from its leaf. */\nexport interface StyleControlBehaviour {\n  /**\n   * What a screen reader announces in place of the raw value.\n   *\n   * A slider's thumb reports its number, and a number is the wrong unit of\n   * meaning for some properties. `aria-valuetext` is where a spoken form\n   * belongs, and it is read from the THUMB rather than inherited from anything.\n   */\n  readonly ariaValueText?: (value: StyleValue) => string;\n}\n\n/** Behaviour by key, as an editor is configured with it. */\nexport type StyleControlBehaviours = ReadonlyMap<string, StyleControlBehaviour>;\n\n/**\n * The default: nothing registered.\n *\n * Exported as a value so a caller has something to pass rather than reaching\n * for `new Map()` and creating one per render.\n */\nexport const NO_STYLE_CONTROL_BEHAVIOUR: StyleControlBehaviours = new Map();\n\n/**\n * The key a control's behaviour is registered under.\n *\n * Derived from the catalog's own identity — the property key and the path\n * inside its value — so nothing has to be added to `catalog.ts` for a control\n * to be addressable. A dot separates the segments because a catalog key is a\n * JavaScript identifier and a path segment is a declared field name, so neither\n * can contain one and the join is unambiguous.\n */\nexport function styleControlBehaviourKey(\n  property: string,\n  path: readonly string[]\n): string {\n  return [property, ...path].join(\".\");\n}\n\n/** The behaviour registered for a control, when there is one. */\nexport function styleControlBehaviour(\n  behaviours: StyleControlBehaviours,\n  property: string,\n  path: readonly string[]\n): StyleControlBehaviour | undefined {\n  return behaviours.get(styleControlBehaviourKey(property, path));\n}\n","/**\n * What the selected block offers on the Style tab.\n *\n * Pure, for the reason `inspector.ts` is: which sections a block offers, which\n * properties sit in each, and which control each property draws is derivation —\n * and a component test in jsdom cannot separate a correct answer from a\n * plausible wrong one, because both render a column of inputs.\n *\n * **Nothing here holds a list of properties, groups or capabilities.** A\n * block's `supports` decides which properties it may set and the engine answers\n * that; the catalog decides which group each property belongs to and the order\n * the groups appear in; a property's shape decides which controls it draws.\n * Adding a property or a group to the engine gives every block that supports it\n * an editor with no edit here — which is the property worth protecting, because\n * a list written here would be a second answer to a question the engine already\n * holds and the two would agree only on the day they were written.\n *\n * **The sections are the builder's, not the engine's.** The engine's groups\n * are the `supports` vocabulary block authors declare, so they decide WHICH\n * properties a block has; `inspector-sections.ts` decides where an author\n * finds each one — eight sections, Layout to Effects, every property placed\n * once. A property the table has not met yet still appears, as one the author\n * adds from \"Add CSS property\".\n *\n * **Every supported property is offered; the common ones show at once.** Each\n * property carries whether it has an effect on the block in hand (`applies`,\n * the engine's answer, judged by the block's own arrangement, its parent's and\n * what it renders) and whether it shows without being asked for (`common`):\n * its tier is common and it applies. The rest are the author's to add from\n * \"Add CSS property\", which is the panel's to draw. A property holding a value\n * here always shows, whether or not it still has an effect.\n *\n * @module style-inspector\n */\n\nimport {\n  applies,\n  asciiLower,\n  BASE_BREAKPOINT,\n  breakpointContexts,\n  decodeIdentifier,\n  DISCLOSURE_ICON_PROPERTY,\n  getBlock,\n  getStyleProperty,\n  locateNode,\n  statePropagatesToAncestors,\n  STYLE_CATALOG,\n  stylePropertiesForSupports,\n  trimCssWhitespace,\n  type AppliesContext,\n  type BlockDocument,\n  type BlockNode,\n  type BreakpointId,\n  type BreakpointSet,\n  type NodeStyles,\n  type StyleState,\n  type StyleSubject,\n  type StyleTraceEntry,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { liveBreakpointsFor } from \"../../styles/breakpoints\";\nimport type { ParentArrangement } from \"../../styles/plain-layout\";\nimport {\n  styleControlsFor,\n  type StyleControl,\n  type StyleControlOptions,\n  type StyleControlVariants,\n} from \"../../styles/style-controls\";\nimport { styleProvenance } from \"../../styles/style-provenance\";\nimport { readStyleValue } from \"../../styles/style-values\";\nimport { fieldLabel, selectedNode } from \"../inspector\";\nimport {\n  INSPECTOR_SECTIONS,\n  placementOf,\n  tierShows,\n  type InspectorSectionKey,\n  type TierContext,\n} from \"../inspector-sections\";\n\n/** Which state × breakpoint the panel reads and writes, and what the site is. */\nexport interface StyleInspectionOptions extends StyleControlOptions {\n  /**\n   * The form an author picked for one union position, if any.\n   *\n   * Addressed by property AND path, because a union can sit below the property\n   * root — `position.zIndex` is a number or `auto`. Consulted only where\n   * nothing is stored: a stored value decides its own arm, and the engine\n   * decides that.\n   */\n  readonly variantAt?: (\n    property: string,\n    path: readonly string[]\n  ) => number | undefined;\n  /**\n   * The interaction state being edited.\n   *\n   * `base` unless a caller says otherwise. The switcher that changes it does\n   * not exist yet, and defaulting to anything else would write hover styles\n   * from a panel with no way to say so.\n   */\n  readonly state?: StyleState;\n  /**\n   * The breakpoint being edited.\n   *\n   * The engine's unconditional context unless a caller says otherwise, for the\n   * same reason: a panel with no breakpoint switcher must write the rules that\n   * apply at every width, not a narrow band an author never chose.\n   */\n  readonly breakpoint?: BreakpointId;\n  /**\n   * Whether the block renders a replaced element (an image, a video, an\n   * embed), which is where the media fit properties have an effect. The canvas\n   * knows what a block renders as; the document does not. `false` counts as\n   * known only where the canvas has been read (the cascade's subject names the\n   * element drawn); before that, every property is treated as applying.\n   */\n  readonly media?: boolean;\n  /**\n   * The styles the controls read, when they are not the node's own: a shared\n   * style the block wears, chosen as the target. The node's own otherwise.\n   */\n  readonly styles?: NodeStyles;\n  /**\n   * The site's breakpoints, so the display a tier is judged by can be read\n   * through the wider tiers that also apply at this one. Without them only\n   * this tier and the unconditional one are read.\n   */\n  readonly breakpoints?: BreakpointSet;\n  /**\n   * The page's compiled cascade and the node in it, so the display a tier is\n   * judged by includes what a class or the block's own defaults set, not just\n   * the node's stored styles. Without it only the node's own values are read.\n   */\n  readonly cascade?: {\n    readonly trace: readonly StyleTraceEntry[];\n    readonly subject: StyleSubject;\n  };\n}\n\n/** One catalog property as the Style tab offers it. */\nexport interface InspectedStyleProperty {\n  /** The catalog key, as stored in a `StyleValues` record. */\n  readonly property: string;\n  /** The property's name as a human reads it. */\n  readonly label: string;\n  /** The catalog's own one-line description, for a tooltip or a hint. */\n  readonly summary: string;\n  /** One descriptor per editable position inside the property's value. */\n  readonly controls: readonly StyleControl[];\n  /** Every choice of form the property's shape offers, empty when it holds no union. */\n  readonly variants: readonly StyleControlVariants[];\n  /** What this node stores for the property at this address, if anything. */\n  readonly value: StyleValue | undefined;\n  /**\n   * Whether this node sets the property HERE.\n   *\n   * At this state and breakpoint only, and deliberately: a value inherited from\n   * the base breakpoint is not one this panel would clear, so reporting it as\n   * set would put a reset affordance on a control that has nothing to reset.\n   * Where the value visibly comes from is `styleProvenance`'s question, and it\n   * needs the compiler's trace rather than the document.\n   */\n  readonly set: boolean;\n  /**\n   * Whether the block's `supports` still declares this property.\n   *\n   * False only for a property this node STORES and the block no longer offers —\n   * a capability removed by a block update, or a value written through the API,\n   * which never consults `supports` at all. Carried rather than dropped so the\n   * panel can say why a control is there: the value is live on the page, and an\n   * author looking at styling they cannot explain needs the control that clears\n   * it more than they need it hidden.\n   */\n  readonly offered: boolean;\n  /**\n   * Whether it has an effect on this block, as the engine answers it: true\n   * wherever what the block is could not be read.\n   */\n  readonly applies: boolean;\n  /**\n   * Whether its tier shows it without being asked for while the block is\n   * edited this way, whether or not it applies. False makes it a property the\n   * author adds from \"Add CSS property\", drawn in \"CSS properties\" once added\n   * or holding a value.\n   */\n  readonly tierShows: boolean;\n  /**\n   * The engine's answer for each field of an object property that answers\n   * per field (`position`'s `zIndex`), where one does.\n   */\n  readonly fieldApplies?: Readonly<Record<string, boolean>>;\n  /**\n   * Whether it shows without being asked for: its tier holds for this block\n   * and it applies, or it holds a value here.\n   */\n  readonly common: boolean;\n}\n\n/** One section of the Style tab, and the properties this block has in it. */\nexport interface StyleSection {\n  readonly key: InspectorSectionKey;\n  readonly label: string;\n  /**\n   * In the placement table's order. Never empty — a section this block has\n   * nothing in is not drawn.\n   */\n  readonly properties: readonly InspectedStyleProperty[];\n}\n\n/** The selected block, as something to style. */\nexport interface StyleInspection {\n  readonly nodeId: string;\n  readonly state: StyleState;\n  readonly breakpoint: BreakpointId;\n  /**\n   * Sections in the builder's order, Layout to Effects, each holding at least\n   * one property.\n   *\n   * Empty for a block that opts into no style groups at all, which is a real\n   * answer rather than a failure: the panel says the block offers none, exactly\n   * as the content tab says when a block declares no props.\n   */\n  readonly sections: readonly StyleSection[];\n  /**\n   * How the block's parent arranges it at the edited device, which decides\n   * what \"Inside its parent\" offers; absent where the parent isn't known.\n   */\n  readonly parent?: ParentArrangement;\n  /** The parent's way of laying the block out, beside its arrangement. */\n  readonly parentLayout?: ParentLayout;\n  /**\n   * The `object-fit` keyword in force here, lowercased, or `undefined` when\n   * nothing sets one: what decides what the focal point says it does.\n   */\n  readonly objectFit?: string | undefined;\n}\n\n/**\n * Describe the selected block's style surface, or `null` when there is none.\n *\n * `null` for no selection and for an id the document no longer holds — but NOT\n * for a block the registry does not know, which is where this parts company\n * with the content tab. A node whose plugin was disabled, or whose type was\n * renamed, still has its styles emitted: `compile-page.ts` walks every node and\n * hands `node.styles` to `envelopeRules` without asking the registry anything.\n * So the panel that could clear them is the one surface that must not go away\n * when the definition does. With no definition nothing is OFFERED, every stored\n * property is retained, and the whole section set is clear-only.\n */\nexport function inspectStyle(\n  document: BlockDocument,\n  selectedId: string | null,\n  options?: StyleInspectionOptions\n): StyleInspection | null {\n  const node = selectedNode(document, selectedId);\n  if (node === null) return null;\n  const definition = getBlock(node.type);\n  // The envelope every control below reads: the target's, which is the\n  // node's own unless a shared style is being edited.\n  const styles = options?.styles ?? node.styles;\n\n  const state = options?.state ?? \"base\";\n  const breakpoint = options?.breakpoint ?? BASE_BREAKPOINT;\n  // ASKED of the engine. `supports` is a capability declaration whose meaning —\n  // `true` for a whole group, an object naming sub-flags — is the registry's,\n  // and a second reading of it here would withhold a property the block really\n  // has, or offer one it does not.\n  //\n  // Empty where the registry has no definition, which is not the same as a\n  // block that supports nothing: the retaining pass below still finds every\n  // stored property, so the panel offers exactly the properties that ARE on the\n  // page and offers each of them clear-only.\n  const offered = new Set(\n    definition === undefined\n      ? []\n      : stylePropertiesForSupports(definition.supports).map(\n          entry => entry.property\n        )\n  );\n  // Plus anything this node ALREADY stores here, whether the block still\n  // supports it or not. Measured: neither `validation.ts` nor `compile-page.ts`\n  // consults `supports`, so a value written before a block update removed the\n  // capability — or written by the API, which never had one — stays valid and\n  // is still emitted on the page. Filtering on `supports` alone would show the\n  // author styling that is visibly active with no control able to clear it.\n  const allowed = new Set(offered);\n  for (const entry of STYLE_CATALOG) {\n    if (allowed.has(entry.property)) continue;\n    const stored = readStyleValue(styles, {\n      state,\n      breakpoint,\n      property: entry.property,\n      path: [],\n    });\n    if (stored !== undefined) allowed.add(entry.property);\n  }\n\n  const at = {\n    state,\n    breakpoint,\n    breakpoints: options?.breakpoints,\n    cascade: options?.cascade,\n  };\n  const objectFit = cascadedKeyword(styles, at, \"object-fit\", \"objectFit\");\n  const context = appliesContextOf(document, node, styles, at, options);\n  const tiers: TierContext = {\n    replaced: context.replaced,\n    // Read as the engine reads the keyword, escapes and all, so the icon a\n    // page draws is the one the tier judges.\n    disclosureIcon: keywordIdentity(\n      cascadedKeyword(styles, at, DISCLOSURE_ICON_PROPERTY, \"disclosureIcon\")\n    ),\n    state,\n  };\n  const inspected = [...allowed].flatMap(property => {\n    const entry = getStyleProperty(property);\n    const placement = placementOf(property, entry?.group ?? \"effects\");\n    const row = inspectProperty(property, styles, offered.has(property), {\n      ...options,\n      state,\n      breakpoint,\n    });\n    // Chosen in the Content tab, at the block's base values, so neither drawn\n    // nor added here, but for a value held at another device or state, which\n    // only this tab reaches: drawn so it can be seen and cleared. A shared\n    // style keeps it here at every address, since Content writes only the\n    // block's own styles.\n    if (\n      placement.tier === \"content\" &&\n      options?.styles === undefined &&\n      !heldAwayFromBase(row.set, at)\n    ) {\n      return [];\n    }\n    const has = applies(property, context);\n    const shows = tierShows(placement.tier, tiers);\n    const fields = fieldAnswers(property, context);\n    return [\n      {\n        placement,\n        row: {\n          ...row,\n          applies: has,\n          tierShows: shows,\n          ...(fields === undefined ? {} : { fieldApplies: fields }),\n          common: row.set || (has && shows),\n        },\n      },\n    ];\n  });\n  const sections: StyleSection[] = [];\n  for (const section of INSPECTOR_SECTIONS) {\n    const properties = inspected\n      .filter(each => each.placement.section === section.key)\n      .sort((a, b) => a.placement.order - b.placement.order)\n      .map(each => each.row);\n    // A section the block has nothing in is not drawn. Rendering an empty one\n    // would offer an author somewhere to click that opens onto nothing.\n    if (properties.length > 0) {\n      sections.push({ key: section.key, label: section.label, properties });\n    }\n  }\n\n  const parentLayout = laidOutBy(document, node, at, options, {\n    position: context.position,\n    sized: offered.has(\"width\"),\n  });\n  return {\n    nodeId: node.id,\n    state,\n    breakpoint,\n    sections,\n    ...(objectFit === undefined ? {} : { objectFit }),\n    ...parentFields(parentLayout),\n  };\n}\n\n/**\n * The engine's answer for each field a catalog property answers for on its\n * own, or `undefined` where it answers only as a whole.\n */\nfunction fieldAnswers(\n  property: string,\n  context: AppliesContext\n): Readonly<Record<string, boolean>> | undefined {\n  const fields = getStyleProperty(property)?.fieldAppliesWhen;\n  if (fields === undefined) return undefined;\n  return Object.fromEntries(\n    Object.keys(fields).map(field => [field, applies(property, context, field)])\n  );\n}\n\n/** Where a property is read: the edited address, and how to read it. */\ninterface ReadAt {\n  readonly state: StyleState;\n  readonly breakpoint: BreakpointId;\n  readonly breakpoints: BreakpointSet | undefined;\n  readonly cascade: StyleInspectionOptions[\"cascade\"];\n}\n\n/**\n * What the block is, for the engine's `applies`: its own display, wrap and\n * position, its parent's display, and whether it renders a replaced element.\n *\n * Through the compiled cascade a keyword nothing sets is known: the CSS\n * initial value, since nothing else reaches the box. Without one only what\n * the document stores is known, and a keyword it does not store is left\n * `undefined`, which the engine reads as \"applies\": a class or the block's\n * defaults may set it, and hiding a property wrongly is the worse mistake.\n */\nfunction appliesContextOf(\n  document: BlockDocument,\n  node: BlockNode,\n  styles: NodeStyles | undefined,\n  at: ReadAt,\n  options: StyleInspectionOptions | undefined\n): AppliesContext {\n  const known = at.cascade !== undefined;\n  const own = (\n    cssProperty: string,\n    property: string,\n    initial: string,\n    path: readonly string[] = []\n  ) =>\n    cascadedKeyword(styles, at, cssProperty, property, path) ??\n    (known ? initial : undefined);\n  return {\n    display: own(\"display\", \"display\", IN_FLOW),\n    flexWrap: own(\"flex-wrap\", \"flexWrap\", \"nowrap\"),\n    // A position is stored as an object; its type is the keyword in force.\n    position: own(\"position\", \"position\", \"static\", [\"type\"]),\n    parentDisplay: parentDisplayOf(document, node, at, options),\n    // Known not to be media only once the canvas has said what it draws.\n    replaced:\n      options?.media === true\n        ? true\n        : at.cascade?.subject.tag === undefined\n          ? undefined\n          : false,\n  };\n}\n\n/**\n * How the block's parent lays it out, for a block with a size of its own to\n * set and in its parent's flow. One that no longer offers a size keeps what\n * it stores as clear-only rows; one its position takes out of the flow isn't\n * laid out by its parent at all.\n */\nfunction laidOutBy(\n  document: BlockDocument,\n  node: BlockNode,\n  at: ReadAt,\n  options: StyleInspectionOptions | undefined,\n  block: { readonly position: string | undefined; readonly sized: boolean }\n): ParentLayout | undefined {\n  if (!block.sized || OUT_OF_FLOW.has(block.position ?? \"\")) return undefined;\n  return parentLayoutOf(document, node, at, options);\n}\n\n/** How the parent lays the block out, as the inspection says it. */\nfunction parentFields(\n  layout: ParentLayout | undefined\n): Pick<StyleInspection, \"parent\" | \"parentLayout\"> {\n  return layout === undefined\n    ? {}\n    : { parent: layout.arrangement, parentLayout: layout };\n}\n\n/** The positions that take a block out of its parent's layout. */\nconst OUT_OF_FLOW: ReadonlySet<string> = new Set([\"absolute\", \"fixed\"]);\n\n/** A display that lays children out in flow, for a box nothing gives one. */\nconst IN_FLOW = \"block\";\n\n/** The document kinds whose top-level blocks sit in the page's own flow. */\nconst PAGE_ROOTED: ReadonlySet<string> = new Set([\"page\", \"template\"]);\n\n/**\n * The box that lays this block out: its parent, or past a `display:\n * contents` parent, the nearest ancestor that draws a box; read as the\n * keywords in force on it. `inFlow` says a keyword it doesn't set is known to\n * be the initial one (the cascade reached it), rather than unknown.\n */\ninterface ParentBox {\n  readonly read: (cssProperty: string, property: string) => string | undefined;\n  readonly inFlow: boolean;\n}\n\n/**\n * The block's parent box, read in the state the canvas puts the parent in:\n * the edited one for a state that reaches ancestors (hover, active), the base\n * state otherwise. A top-level block of a page or a template sits in the page\n * root, laid out as the page's settings say; one of a component or a pattern\n * goes wherever it is placed, so its parent is not known. Nor is it for a\n * shared style or a look, which many blocks wear wherever each one sits.\n */\nfunction parentBoxOf(\n  document: BlockDocument,\n  node: BlockNode,\n  at: ReadAt,\n  options: StyleInspectionOptions | undefined\n): ParentBox | undefined {\n  // The state the canvas forces up the chain while the child is edited in\n  // one: hover and active reach every ancestor, the others only the block.\n  const base: ReadAt = statePropagatesToAncestors(at.state)\n    ? at\n    : { ...at, state: \"base\" };\n  // A shared style or a look is worn by many blocks, wherever each one sits:\n  // the selected block's parent says nothing about the others.\n  if (options?.styles !== undefined) return undefined;\n  // The page root lays out its top-level blocks as the page's own settings\n  // say, which is in flow unless they give it a display.\n  const atRoot: ParentBox | undefined = PAGE_ROOTED.has(document.kind)\n    ? {\n        read: (cssProperty, property) =>\n          cascadedKeyword(\n            document.settings?.styles,\n            { ...base, cascade: undefined },\n            cssProperty,\n            property\n          ),\n        inFlow: true,\n      }\n    : undefined;\n  return at.cascade === undefined\n    ? storedParentBox(document.nodes, node.id, base, atRoot)\n    : cascadedParentBox(at.cascade, base, atRoot);\n}\n\n/** The display of the box that lays this block out, as {@link parentBoxOf}. */\nfunction parentDisplayOf(\n  document: BlockDocument,\n  node: BlockNode,\n  at: ReadAt,\n  options: StyleInspectionOptions | undefined\n): string | undefined {\n  const box = parentBoxOf(document, node, at, options);\n  if (box === undefined) return undefined;\n  return box.read(\"display\", \"display\") ?? (box.inFlow ? IN_FLOW : undefined);\n}\n\n/**\n * How the block's parent arranges it at the edited device, by the display and\n * direction in force on the parent there: a Row stacked here is a column.\n * `undefined` where the parent isn't known (a shared style, a component's\n * top level) or arranges another way (a table).\n */\nfunction parentLayoutOf(\n  document: BlockDocument,\n  node: BlockNode,\n  at: ReadAt,\n  options: StyleInspectionOptions | undefined\n): ParentLayout | undefined {\n  const box = parentBoxOf(document, node, at, options);\n  if (box === undefined) return undefined;\n  const arrangement = arrangementOf(\n    keywordIdentity(box.read(\"display\", \"display\")) ?? IN_FLOW,\n    keywordIdentity(box.read(\"flex-direction\", \"flexDirection\"))\n  );\n  if (arrangement === undefined) return undefined;\n  const keyword = (cssProperty: string, property: string) =>\n    keywordIdentity(box.read(cssProperty, property));\n  return {\n    arrangement,\n    alignItems: keyword(\"align-items\", \"alignItems\"),\n    justifyItems: keyword(\"justify-items\", \"justifyItems\"),\n  };\n}\n\n/**\n * How the block's parent lays it out: its arrangement, and the alignment it\n * gives its items, which a child's automatic self-alignment defers to.\n */\nexport interface ParentLayout {\n  readonly arrangement: ParentArrangement;\n  readonly alignItems: string | undefined;\n  readonly justifyItems: string | undefined;\n}\n\n/** The arrangement a display and a direction lay a box's children out in. */\nfunction arrangementOf(\n  display: string,\n  direction: string | undefined\n): ParentArrangement | undefined {\n  if (display === \"grid\" || display === \"inline-grid\") return \"grid\";\n  if (display === \"flex\" || display === \"inline-flex\") {\n    return direction?.startsWith(\"column\") === true ? \"column\" : \"row\";\n  }\n  return display === \"block\" || display === \"flow-root\" ? \"flow\" : undefined;\n}\n\n/**\n * The parent box through the cascade. The subject already names its\n * ancestors, outermost first; one that does not say is not taken for a\n * top-level block.\n */\nfunction cascadedParentBox(\n  cascade: NonNullable<StyleInspectionOptions[\"cascade\"]>,\n  base: ReadAt,\n  atRoot: ParentBox | undefined\n): ParentBox | undefined {\n  const ancestors = cascade.subject.ancestors;\n  if (ancestors === undefined) return undefined;\n  for (let index = ancestors.length - 1; index >= 0; index -= 1) {\n    const subject = {\n      ...ancestors[index],\n      ancestors: ancestors.slice(0, index),\n    };\n    const at = { ...base, cascade: { trace: cascade.trace, subject } };\n    const read = (cssProperty: string, property: string) =>\n      cascadedKeyword(undefined, at, cssProperty, property);\n    const display = read(\"display\", \"display\") ?? IN_FLOW;\n    if (keywordIdentity(display) !== \"contents\") return { read, inFlow: true };\n  }\n  return atRoot;\n}\n\n/** The parent box as the document stores it, guarded against a cycle. */\nfunction storedParentBox(\n  nodes: BlockDocument[\"nodes\"],\n  nodeId: string,\n  base: ReadAt,\n  atRoot: ParentBox | undefined\n): ParentBox | undefined {\n  const seen = new Set<string>([nodeId]);\n  let parent = locateNode(nodes, nodeId)?.parent;\n  while (parent !== undefined && !seen.has(parent.id)) {\n    seen.add(parent.id);\n    const styles = parent.styles;\n    const read = (cssProperty: string, property: string) =>\n      cascadedKeyword(styles, base, cssProperty, property);\n    if (keywordIdentity(read(\"display\", \"display\")) !== \"contents\") {\n      return { read, inFlow: false };\n    }\n    parent = locateNode(nodes, parent.id)?.parent;\n  }\n  // Out of parents: the page's own flow, unless the walk met a node twice.\n  return parent === undefined ? atRoot : undefined;\n}\n\n/** A keyword as the engine identifies it: trimmed, unescaped, lowercased. */\nfunction keywordIdentity(value: string | undefined): string | undefined {\n  return value === undefined\n    ? undefined\n    : asciiLower(decodeIdentifier(trimCssWhitespace(value)));\n}\n\n/**\n * The keyword a property takes at this address, lowercased: the display, wrap\n * and position that decide what applies, the fit the focal point describes.\n *\n * Asked of the compiled cascade when there is one, through the same ranking\n * the provenance dots use: a class or the block's defaults can make a block a\n * flex container, or give an image its fit, without the node storing it. The live tiers are\n * the ones that apply at the edited tier, and the live state is the edited one\n * (base always matches as well).\n *\n * Without a cascade it reads what the node stores, the way the cascade would:\n * this state at this tier, then at each wider tier, then the base state the\n * same way. A state rule outranks a breakpoint rule (its pseudo-class is more\n * specific), so the whole state comes first.\n */\nfunction cascadedKeyword(\n  styles: NodeStyles | undefined,\n  at: ReadAt,\n  cssProperty: string,\n  property: string,\n  path: readonly string[] = []\n): string | undefined {\n  const tiers = tiersFrom(at.breakpoint, at.breakpoints);\n  if (at.cascade !== undefined) {\n    const shown = styleProvenance({\n      trace: at.cascade.trace,\n      subject: at.cascade.subject,\n      cssProperty,\n      state: at.state,\n      breakpoint: at.breakpoint,\n      liveBreakpoints: tiers,\n      liveStates: [at.state],\n    });\n    return shown.kind === \"unset\"\n      ? undefined\n      : shown.entry.value.trim().toLowerCase();\n  }\n  const states: StyleState[] =\n    at.state === \"base\" ? [\"base\"] : [at.state, \"base\"];\n  for (const atState of states) {\n    for (const atBreakpoint of tiers) {\n      const value = readStyleValue(styles, {\n        state: atState,\n        breakpoint: atBreakpoint,\n        property,\n        path,\n      });\n      if (typeof value === \"string\") return value.trim().toLowerCase();\n    }\n  }\n  return undefined;\n}\n\n/**\n * The tiers whose rules apply at the edited one, the one that wins first.\n *\n * WHICH tiers is the shared resolver's answer (`liveBreakpointsFor`), the one\n * the provenance dots use, so an axis's unbounded container tier is included\n * exactly where the compiler applies it. The ORDER is the compiler's own\n * emission order, reversed: `breakpointContexts` lists the contexts in cascade\n * order, where a later rule wins over an earlier one of the same specificity,\n * so the walk over a node's own values meets the winner first. Two tiers with\n * no upper bound (the unconditional one and a container axis's unbounded one)\n * are then ordered as the stylesheet orders them, not as equals.\n */\nfunction tiersFrom(\n  breakpoint: BreakpointId,\n  breakpoints: BreakpointSet | undefined\n): BreakpointId[] {\n  const emitted = new Map(\n    breakpointContexts(breakpoints).map((context, index) => [context.id, index])\n  );\n  // An id the compiler does not emit sorts last: nothing it holds applies.\n  const positionOf = (id: BreakpointId) => emitted.get(id) ?? -1;\n  return liveBreakpointsFor(breakpoints, breakpoint).sort(\n    (a, b) => positionOf(b) - positionOf(a)\n  );\n}\n\n/**\n * Labels other than the property's name: shorter, where the name is cut short\n * in the Style tab's 7rem label column (\"Justify content\" read \"Justify\n * cont…\"), Webflow's and Figma's words for the same two controls; or plainer,\n * where the name says how CSS does it rather than what it is.\n */\nconst SHORT_LABELS: Readonly<Record<string, string>> = {\n  justifyContent: \"Justify\",\n  alignItems: \"Align\",\n  textTransform: \"Letter case\",\n  objectFit: \"Fit\",\n  // Which part of the picture stays in view: what an author is choosing.\n  objectPosition: \"Focal point\",\n  // In an Accordion's own Icon section, where \"Disclosure\" says nothing an\n  // author does not already see.\n  disclosureIcon: \"Icon\",\n  disclosurePosition: \"Icon position\",\n  // In the Background section, where \"Background\" already says whose it is;\n  // the whole name was cut to \"Background gradi…\".\n  backgroundGradient: \"Gradient\",\n  // What the value says: the size of each column or row (\"1fr 2fr\"). Not\n  // \"Columns\" alone, which on a Columns block reads as how many there are.\n  // Rows is shortened with Columns so the pair reads as one in Layout.\n  gridTemplateColumns: \"Column sizes\",\n  gridTemplateRows: \"Row sizes\",\n  // A child's share of a Row or a Grid, in the words of what each one does:\n  // \"Flex grow\" says how CSS spells it, \"Grow\" what the block does.\n  flexGrow: \"Grow\",\n  flexShrink: \"Shrink\",\n  flexBasis: \"Starting size\",\n  // The room between a container's blocks, as an author asks for it; rows\n  // and columns apart where a Grid sets them separately.\n  gap: \"Space between\",\n  rowGap: \"Between rows\",\n  columnGap: \"Between columns\",\n  // What it is in an author's words: an entrance animation.\n  appear: \"Animation when it appears\",\n};\n\n/**\n * What a property's label says on hover, where the inspector edits it on\n * another scale than the catalog describes: opacity is a percent here.\n */\nconst SUMMARIES: Readonly<Record<string, string>> = {\n  opacity: \"How solid the element is, from 0 (clear) to 100 percent.\",\n};\n\n/**\n * Whether a value is held at a device or state other than the base values,\n * where the Content tab's controls, which write the base values, cannot\n * reach it.\n */\nfunction heldAwayFromBase(\n  set: boolean,\n  at: { readonly state: StyleState; readonly breakpoint: BreakpointId }\n): boolean {\n  return set && (at.state !== \"base\" || at.breakpoint !== BASE_BREAKPOINT);\n}\n\n/** One property's controls and the value they are showing. */\nfunction inspectProperty(\n  property: string,\n  styles: Parameters<typeof readStyleValue>[0],\n  offered: boolean,\n  options: StyleInspectionOptions & {\n    state: StyleState;\n    breakpoint: BreakpointId;\n  }\n): Omit<\n  InspectedStyleProperty,\n  \"common\" | \"applies\" | \"tierShows\" | \"fieldApplies\"\n> {\n  // Present by construction: the name came out of `stylePropertiesForSupports`,\n  // which reads the same catalog. Asked again rather than threaded through so\n  // this function takes a name, which is what makes it callable from a test\n  // without assembling a catalog row.\n  const entry = getStyleProperty(property);\n  if (entry === undefined) {\n    throw new Error(`${property} is not a style property`);\n  }\n  const value = readStyleValue(styles, {\n    state: options.state,\n    breakpoint: options.breakpoint,\n    property,\n    path: [],\n  });\n  const set = styleControlsFor(entry, value, {\n    ...options,\n    // Bound to THIS property before it reaches the walk, which speaks only in\n    // paths: two properties can both hold a union at the root, and a resolver\n    // told only the path would answer for whichever asked first.\n    variantAt: path => options.variantAt?.(property, path),\n  });\n  const short = SHORT_LABELS[property];\n  return {\n    property,\n    label: short ?? fieldLabel(property),\n    // A shortened label keeps the property's CSS name in its tooltip.\n    summary:\n      short === undefined\n        ? (SUMMARIES[property] ?? entry.summary)\n        : `${fieldLabel(property)}: ${SUMMARIES[property] ?? entry.summary}`,\n    controls: set.controls,\n    variants: set.variants,\n    value,\n    set: value !== undefined,\n    offered,\n  };\n}\n","/**\n * What a SELECTION of blocks shares at one style address, and what it takes to\n * change it.\n *\n * ## A different surface, not a wider one\n *\n * `StyleInspectorPanel` refuses a multi-selection and says why: `selectedId` is\n * the primary, so inspecting it would draw writable controls that change one\n * block while the canvas outlines six. Editing one property across a whole\n * selection is a different question — it has to say what a shared value even\n * MEANS before it can offer to change one — and this module answers that half\n * without knowing anything about how it is drawn.\n *\n * ## One group, one undo\n *\n * Every write here produces a GROUP of ops for `applyAll`, never a sequence of\n * `apply` calls. The store folds a group onto a working document and commits\n * nothing until all of them succeed, then pushes one history entry. That is the\n * whole point of batching: six blocks aligned in one gesture must come back in\n * one undo, and a half-applied batch must not exist at all.\n *\n * ## The nodes are passed in, not looked up\n *\n * A caller holds the selection and the document; resolving ids here would mean\n * walking the tree once per address, and a panel asks about many addresses per\n * render. The same reason `style-subject` gives for building a subject once.\n *\n * @module batch-style\n */\n\nimport {\n  getBlock,\n  isLook,\n  isTextStyle,\n  stylePropertiesForSupports,\n  supportedStylesOf,\n  TEXT_STYLE_PROPERTIES,\n  type AnyBlockDefinition,\n  type BlockNode,\n  type NamedClass,\n  type NodeStyles,\n  type StyleValue,\n  type TokenKind,\n  type ValidationIssue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { sameStyleValue, type BuilderOp } from \"../op-vocabulary\";\n\nimport {\n  readStyleValue,\n  styleClearOp,\n  styleWriteOp,\n  styleWriteOps,\n  type StyleWriteRequest,\n  type StyleAddress,\n  type StylePolicy,\n} from \"./style-values\";\n\n/**\n * What a selection holds at one address.\n *\n * `mixed` is a THIRD answer rather than an absence, and keeping it distinct is\n * the whole reason this type exists. A control showing nothing means every\n * selected block has nothing there and typing sets them all; a control showing\n * \"Mixed\" means typing REPLACES values that differ, and an author is entitled\n * to know which of those they are about to do.\n */\nexport type SharedValue =\n  | { readonly kind: \"same\"; readonly value: StyleValue | undefined }\n  | { readonly kind: \"mixed\" };\n\n/**\n * What the selection shares at one address, or that it shares nothing.\n *\n * An EMPTY selection answers `same` with no value rather than `mixed`: nothing\n * disagrees when there is nothing to disagree, and reporting a conflict for an\n * empty set would put \"Mixed\" on a panel describing no blocks.\n *\n * Compared with `sameStyleValue`, which is the predicate `styleWriteOp` uses to\n * decide a write changes nothing. Sharing it is what keeps this reader and that\n * writer from disagreeing: a comparison of this module's own could call two\n * values equal that the writer treats as different, and a control committing\n * the value they \"share\" would then emit an op per node and an undo entry for a\n * gesture that changed nothing.\n *\n * The STYLE comparison rather than the general stored one, because the compiler\n * sorts a composite's keys before emitting it — so two blocks holding one value\n * in different key order render identically and do agree.\n *\n * What it brings: structural rather than serialised, so a value carrying its\n * own `toJSON` cannot decide its comparison; iterative, so a deep value cannot\n * exhaust the stack; bounded, and answering \"different\" when the budget runs\n * out. That direction is the safe one — MIXED makes the control say so and\n * makes typing a replacement, while a wrong \"same\" shows one block's value\n * while another holds a different one and the next edit overwrites it silently.\n */\nexport function sharedValueAt(\n  nodes: readonly BlockNode[],\n  address: StyleAddress\n): SharedValue {\n  let first: { value: StyleValue | undefined } | undefined;\n  for (const node of nodes) {\n    const value = readStyleValue(node.styles, address);\n    if (first === undefined) {\n      first = { value };\n      continue;\n    }\n    if (!sameStyleValue(first.value, value)) return { kind: \"mixed\" };\n  }\n  return { kind: \"same\", value: first?.value };\n}\n\n/** What a batch edit would do, before anything is applied. */\nexport interface BatchStyleWrite {\n  /**\n   * The ops to apply as ONE group, in selection order.\n   *\n   * Pair an op with the node it NAMES rather than with the position it\n   * arrived in: there is one op per block that needs writing, so a selection\n   * where some blocks already hold the value yields fewer ops than nodes.\n   *\n   * Deliberately NOT ordered by what each op costs the document, though there\n   * is a reason to want that. The editor folds a group and judges every step\n   * against the byte cap, so a selection sitting at that cap — where one block\n   * grows to the shared value and another shrinks by more — is refused when\n   * the growing block comes first and accepted when it comes second, for the\n   * same resulting document. Writing the reductions first would fix it.\n   *\n   * Knowing which block shrinks means measuring what each one currently holds,\n   * and `measureBytes` invokes a value's own `toJSON` — measured, once per\n   * call — on data no guard has accepted yet. Ordering is an optimisation of\n   * the peak, never a gate, and running author code to obtain one is not a\n   * trade worth making; a measurement that avoided it would be a second\n   * implementation of a walk the engine already owns. Left to the surface\n   * that can reach a multi-selection, which does not exist yet.\n   *\n   * Empty when every selected block already holds the value. That is not a\n   * failure and must not be reported as one — it is the ordinary result of\n   * setting a value half the selection already had, and applying an empty group\n   * would ask the store for a history entry that undoes nothing.\n   */\n  readonly ops: readonly BuilderOp[];\n  /**\n   * Why the value cannot be written, or `undefined` when it can.\n   *\n   * ONE answer for the whole selection rather than one per block, because that\n   * is what the value layer actually decides: `styleWriteOp` refuses on the\n   * VALUE and the POLICY, and a batch passes the same two to every node — so a\n   * refusal is a property of what is being written, never of which block is\n   * receiving it. Measured rather than assumed: a node carrying an unrelated\n   * invalid stored value is still accepted, so even a malformed document does\n   * not split the answer.\n   *\n   * A per-block list was the first shape here and it was machinery for a case\n   * that cannot arise. If a policy ever varies by block type — which is the\n   * reason one would — this becomes a list again, as a change with its own\n   * evidence rather than a shape kept in advance.\n   */\n  readonly refused: string | undefined;\n  /**\n   * Findings the catalog reported that do NOT refuse the write.\n   *\n   * Carried rather than dropped, for the reason `style-values` gives beside\n   * its own `warnings`: a warning is the validator explaining something about\n   * a value it ACCEPTED — a token reference no supplied token table defines,\n   * for instance, which renders as nothing — and a surface that discarded them\n   * would present an accepted-with-reservations value as an unremarkable one.\n   * The single-block panel already shows them; a batch that swallowed them\n   * would be the same edit explaining less about itself the more blocks it\n   * touched.\n   *\n   * DEDUPLICATED across the selection rather than repeated per block. Every\n   * node is asked about the same value under the same policy, so an issue\n   * arising from the value appears once per node and saying it six times is\n   * noise. Deduplicated by CONTENT rather than assumed identical, because that\n   * every node produces the same set is a property of today's value layer\n   * rather than something this module is entitled to rely on.\n   */\n  readonly warnings: readonly ValidationIssue[];\n}\n\n/**\n * The ops that set one address across a selection.\n *\n * Built per node from that node's OWN styles, never from the primary's, and the\n * reason is the OTHER values each block holds. A style op patches the whole\n * `styles` envelope, so an op built from the primary and repeated carries the\n * primary's unrelated declarations with it: measured, writing `fontSize` to a\n * block from a primary that also set `color` produces a patch containing both,\n * so the batch silently gives every block the primary's colour.\n *\n * Not, as first written here, because the inverse would be wrong. `applyOp`\n * derives the inverse from the document it is applied to rather than from the\n * op, so undo is correct either way — which is exactly why this had to be\n * measured instead of reasoned about.\n */\nexport function batchStyleWriteOps(\n  nodes: readonly BlockNode[],\n  address: StyleAddress,\n  value: StyleValue,\n  policy?: StylePolicy\n): BatchStyleWrite {\n  const shared = batchPolicy(policy);\n  return collect(nodes, node =>\n    styleWriteOp(node.id, node.styles, address, value, shared)\n  );\n}\n\n/**\n * The ops that set several addresses, each to its own value, across a\n * selection: the sides of a margin set together, or two parts of one value.\n * One op per block, the writes folded into it, so the gesture is one entry in\n * the history.\n */\nexport function batchStyleWritesOps(\n  nodes: readonly BlockNode[],\n  writes: readonly StyleWriteRequest[],\n  policy?: StylePolicy\n): BatchStyleWrite {\n  const shared = batchPolicy(policy);\n  return collect(nodes, node =>\n    styleWriteOps(node.id, node.styles, writes, shared)\n  );\n}\n\n/**\n * The ops that clear one address across a selection.\n *\n * Clearing is not writing an empty value, and the distinction survives the\n * batch: a block with nothing there produces no op rather than an op that\n * writes nothing.\n */\nexport function batchStyleClearOps(\n  nodes: readonly BlockNode[],\n  address: StyleAddress,\n  policy?: StylePolicy\n): BatchStyleWrite {\n  const shared = batchPolicy(policy);\n  return collect(nodes, node =>\n    styleClearOp(node.id, node.styles, address, shared)\n  );\n}\n\n/**\n * The caller's policy with its lookups answered once per BATCH.\n *\n * `tokens.kindOf` and `mayFetchUrl` are supplied by the site, and the value\n * layer memoizes them for the span of ONE validation — so a ten-node selection\n * asked the site ten times for the same answer. Measured: ten nodes, ten\n * `kindOf` calls, for a token whose kind cannot vary by node.\n *\n * Sound because the question does not depend on the node. `kindOf` maps a token\n * NAME to its kind and `mayFetchUrl` judges a URL; neither is handed anything\n * about the block receiving the value, so an answer that differed between two\n * nodes of one batch would be a site policy contradicting itself mid-gesture.\n *\n * Scoped to the batch and thrown away with it, rather than cached across calls:\n * a site that adds a token between two gestures must be seen by the second one.\n *\n * Deliberately NOT solved by validating once and reusing the result. That needs\n * the value layer to split validation from op-building — a second entry point\n * into the code deciding what a valid write is, and two of those drift. The\n * per-node validation that remains is a pure function of a small value and\n * costs nothing measurable; what costs something is calling the SITE.\n */\nfunction batchPolicy(policy: StylePolicy | undefined): StylePolicy | undefined {\n  if (policy === undefined) return policy;\n  const lookup = policy.tokens;\n  const mayFetch = policy.mayFetchUrl;\n  if (lookup === undefined && mayFetch === undefined) return policy;\n\n  const kinds = new Map<string, TokenKind | undefined>();\n  const urls = new Map<string, boolean>();\n  return {\n    ...policy,\n    ...(lookup === undefined\n      ? {}\n      : {\n          tokens: {\n            kindOf(name: string) {\n              // `has` rather than a truthy check: `undefined` is the answer for\n              // a token the site does not define, and it is the answer most\n              // worth not asking twice.\n              if (kinds.has(name)) return kinds.get(name);\n              const kind = lookup.kindOf(name);\n              kinds.set(name, kind);\n              return kind;\n            },\n          },\n        }),\n    ...(mayFetch === undefined\n      ? {}\n      : {\n          mayFetchUrl(url: string) {\n            const cached = urls.get(url);\n            if (cached !== undefined) return cached;\n            const allowed = mayFetch(url);\n            urls.set(url, allowed);\n            return allowed;\n          },\n        }),\n  };\n}\n\n/** The shared walk, so writing and clearing cannot come to differ. */\nfunction collect(\n  nodes: readonly BlockNode[],\n  build: (node: BlockNode) => ReturnType<typeof styleWriteOp>\n): BatchStyleWrite {\n  const ops: BuilderOp[] = [];\n  // Keyed on every field an issue carries, so two findings that differ only in\n  // `path` or `suggestion` both survive. `code` and `message` alone would merge\n  // the same complaint about two different sub-values into one.\n  const warnings = new Map<string, ValidationIssue>();\n  for (const node of nodes) {\n    const result = build(node);\n    if (!result.ok) {\n      // The FIRST refusal ends it, and nothing partial is returned. Every node\n      // is being asked the same question, so a second answer would repeat the\n      // first — and writing the blocks that agreed while the rest did not would\n      // leave a selection half-styled from one gesture.\n      return {\n        ops: [],\n        refused: result.issues[0]?.message ?? \"This value cannot be used here.\",\n        // Nothing is being written, so there is nothing an accepted value\n        // needs explaining about. A refusal and a warning are different\n        // answers and reporting both would leave a surface saying the value\n        // was rejected AND that it was accepted with reservations.\n        warnings: [],\n      };\n    }\n    for (const warning of result.warnings) {\n      warnings.set(\n        `${warning.code}\\u0000${warning.severity}\\u0000${warning.path}\\u0000${warning.message}\\u0000${warning.suggestion ?? \"\"}`,\n        warning\n      );\n    }\n    // `null` is the value already being there, which is not a refusal and not\n    // an op. Six blocks where two already match produce four ops, and the two\n    // are as successful as the four.\n    if (result.op !== null) ops.push(result.op);\n  }\n  return { ops, refused: undefined, warnings: [...warnings.values()] };\n}\n\n/**\n * One block's look as \"Copy style\" takes it: its own values, every state and\n * device, and the classes it wears (its block style, its text style and its\n * shared styles), as the class list holds them.\n */\nexport interface StyleSource {\n  readonly styles: NodeStyles | undefined;\n  readonly classes: readonly string[];\n}\n\n/** What a paste reads besides the blocks. */\nexport interface StylePasteOptions {\n  /**\n   * The site's styles, to tell a block style and a text style from a shared\n   * style. Unread, every class is pasted as it is.\n   */\n  readonly library?: readonly NamedClass[] | undefined;\n  /** Where block definitions are read: the registry, unless told. */\n  readonly definitions?: (type: string) => AnyBlockDefinition | undefined;\n}\n\n/** How many of the source's settings one target had no place for. */\nexport interface SkippedSettings {\n  readonly nodeId: string;\n  readonly type: string;\n  readonly count: number;\n}\n\n/** What a paste would do: the ops as one group, and what each target skips. */\nexport interface BatchStylePaste {\n  /** One op per target that changes, in selection order; empty when none does. */\n  readonly ops: readonly BuilderOp[];\n  /** The targets that skip something, in selection order. */\n  readonly skipped: readonly SkippedSettings[];\n}\n\n/**\n * The ops that give each block the source's look: the source's own values in\n * place of the block's, and the source's classes in place of the ones it\n * wears. The block's words, images and links are not touched.\n *\n * Each op updates a block's own `styles` and `classes` and nothing else, so a\n * paste never writes into a shared style, whatever the editing bar targets.\n *\n * A block keeps only what it can show: a value its type does not support\n * (read by `supportedStylesOf`, as \"Turn into\" reads it), a block style of\n * another type, and a text style on a block with no text settings are\n * skipped and counted, one per value at each state and device, so the\n * author can be told how many.\n */\nexport function batchStylePasteOps(\n  nodes: readonly BlockNode[],\n  source: StyleSource,\n  options: StylePasteOptions = {}\n): BatchStylePaste {\n  const definitionOf = options.definitions ?? getBlock;\n  const ops: BuilderOp[] = [];\n  const skipped: SkippedSettings[] = [];\n  for (const node of nodes) {\n    const supports = definitionOf(node.type)?.supports;\n    const supported = new Set(\n      stylePropertiesForSupports(supports).map(entry => entry.property)\n    );\n    const styles = supportedStylesOf(source.styles, supports);\n    const classes = keptClasses(\n      source.classes,\n      node.type,\n      supported,\n      options.library\n    );\n    const count = styles.skipped + classes.skipped;\n    if (count > 0) skipped.push({ nodeId: node.id, type: node.type, count });\n    const op = pasteOp(node, styles.styles, classes.kept);\n    if (op !== null) ops.push(op);\n  }\n  return { ops, skipped };\n}\n\n/**\n * The source's classes a block can wear, and how many it can't: a block\n * style belongs to one block type, and a text style is offered only on a\n * block with text settings. A shared style, and a class the site doesn't\n * name, are worn as they are.\n */\nfunction keptClasses(\n  classes: readonly string[],\n  type: string,\n  supported: ReadonlySet<string>,\n  library: readonly NamedClass[] | undefined\n): { kept: string[]; skipped: number } {\n  const takesText = [...TEXT_STYLE_PROPERTIES].some(property =>\n    supported.has(property)\n  );\n  const kept: string[] = [];\n  let skipped = 0;\n  for (const id of classes) {\n    const entry = library?.find(each => each.id === id);\n    const fits =\n      entry === undefined ||\n      (isLook(entry)\n        ? entry.blockType === type\n        : !isTextStyle(entry) || takesText);\n    if (fits) kept.push(id);\n    else skipped += 1;\n  }\n  return { kept, skipped };\n}\n\n/**\n * The one op that leaves a block with these values and classes, or `null`\n * when it already has them. A field left empty is removed by name, as every\n * style op removes one.\n */\nfunction pasteOp(\n  node: BlockNode,\n  styles: NodeStyles | undefined,\n  classes: readonly string[]\n): BuilderOp | null {\n  const patch: { styles?: NodeStyles; classes?: string[] } = {};\n  const unset: (\"styles\" | \"classes\")[] = [];\n  if (!sameStyleValue(node.styles ?? {}, styles ?? {})) {\n    if (styles === undefined) unset.push(\"styles\");\n    else patch.styles = styles;\n  }\n  if (!sameIds(node.classes ?? [], classes)) {\n    if (classes.length === 0) unset.push(\"classes\");\n    else patch.classes = [...classes];\n  }\n  if (Object.keys(patch).length === 0 && unset.length === 0) return null;\n  return {\n    kind: \"update\",\n    id: node.id,\n    patch,\n    ...(unset.length === 0 ? {} : { unset }),\n  };\n}\n\n/** Two class lists by value, in order: the order is what a block stores. */\nfunction sameIds(a: readonly string[], b: readonly string[]): boolean {\n  return a.length === b.length && a.every((id, index) => id === b[index]);\n}\n","/**\n * Page checks: what on the open page needs the author's attention before it\n * goes out, as one list grouped Accessibility, Content and data, Publishing,\n * and Search where a check offers it.\n *\n * The model only: the check contract, the finding each check reports with\n * where its fix is, the groups, and the runner over a document. No React and\n * no DOM, so a script, a route or an agent asking about a stored page gets\n * the findings the editor lists for the draft on screen.\n *\n * A finding never blocks anything. The editor counts them beside Publish and\n * lists them; Save and Publish read none of this.\n *\n * @module page-checks/page-checks\n * @experimental The checks and the provider point grow with later checks.\n */\nimport {\n  blockDefaultsOf,\n  getBlock,\n  resolveComponentInstances,\n  walkNodes,\n  type AnyBlockDefinition,\n  type BlockDocument,\n  type BlockNode,\n  type DefinitionsById,\n  type RegionArea,\n  type ResolvedBlockNode,\n  type NamedClass,\n  type NodeStyles,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  revealedDefinitions,\n  revealedForCanvas,\n} from \"../conditions/applied-conditions\";\nimport type { AskedSetting } from \"../editor-asks\";\nimport { layerLabel } from \"../panels/layers/layers\";\n\nimport type { PageFacts } from \"./page-facts\";\n\n/** The groups a finding is listed under. */\nexport type PageCheckGroup =\n  | \"accessibility\"\n  | \"content\"\n  | \"publishing\"\n  | \"search\";\n\n/** Each group's name, in the list's order. */\nconst GROUP_LABELS: Readonly<Record<PageCheckGroup, string>> = {\n  accessibility: \"Accessibility\",\n  content: \"Content and data\",\n  publishing: \"Publishing\",\n  search: \"Search\",\n};\n\n/** The groups listed on every page, whatever checks are offered. */\nconst CORE_GROUPS: readonly PageCheckGroup[] = [\n  \"accessibility\",\n  \"content\",\n  \"publishing\",\n];\n\n/** The groups in the list's order. */\nconst GROUP_ORDER = Object.keys(GROUP_LABELS) as PageCheckGroup[];\n\n/**\n * A header or footer drawn around the page, as its site's set places it: a\n * check that judges the page as a visitor reads it, top to bottom, reads\n * the header's blocks before the page's and the footer's after.\n */\nexport interface PageRegionDocument {\n  readonly area: RegionArea;\n  readonly document: BlockDocument;\n  /**\n   * The definitions its component placements are drawn from, where it is\n   * placed as a component, as a set's header is: the checks then read the\n   * blocks the component draws, not the one placement.\n   */\n  readonly definitions?: DefinitionsById;\n  /** What the editor calls it, such as \"Site header · Main\", where known. */\n  readonly label?: string;\n  /** Where it is changed, where the caller can say: its editor's address. */\n  readonly edit?: PageCheckLink;\n}\n\n/** A link out of the editor, as a finding offers one: its address and words. */\nexport interface PageCheckLink {\n  readonly href: string;\n  /** What the link says. */\n  readonly text: string;\n  /** Its accessible name, saying where it goes. */\n  readonly name: string;\n}\n\n/** A region as the checks read it, and as it is stored. */\nexport interface ResolvedRegion extends PageRegionDocument {\n  /**\n   * The region as stored, its placements unresolved: what a read names, a\n   * component placement among them, where `document` draws its blocks.\n   */\n  readonly stored: BlockDocument;\n}\n\n/** A region as the checks read it: its placements drawn as their blocks. */\nfunction composedRegion(region: PageRegionDocument): ResolvedRegion {\n  if (region.definitions === undefined) {\n    return { ...region, stored: region.document };\n  }\n  const { definitions, ...rest } = region;\n  return {\n    ...rest,\n    document: resolveComponentInstances(region.document, definitions).document,\n    stored: region.document,\n  };\n}\n\n/** The page a check reads. */\nexport interface CheckedPage {\n  /** The draft as it stands, unsaved changes included, or a stored page. */\n  readonly document: BlockDocument;\n  /**\n   * The definitions the page is drawn with, by block type: the registry this\n   * process holds unless the caller resolves blocks its own way.\n   */\n  readonly blocks?: (type: string) => AnyBlockDefinition | undefined;\n  /** The header and footer drawn around it, where the caller knows them. */\n  readonly regions?: readonly PageRegionDocument[];\n  /**\n   * The definitions the page's own component placements are drawn from, so\n   * a check that reads what the page draws can read inside them.\n   */\n  readonly definitions?: DefinitionsById;\n  /**\n   * The site's variables, light and dark, which a colour written as one is\n   * read through; absent where the caller has none, and a colour that needs\n   * them is then not judged.\n   */\n  readonly tokens?: SiteTokenSet;\n  /**\n   * The site's shared styles, among them its edits to a block type's own\n   * look, which a block is drawn with under its own values.\n   */\n  readonly namedClasses?: readonly NamedClass[];\n  /**\n   * What the caller knows of the page beyond its document: its bindings\n   * that no longer fit, its count of data, the parts it uses that aren't\n   * live, a header or footer it shows twice. A check of a fact the caller\n   * leaves out finds nothing.\n   */\n  readonly facts?: PageFacts;\n}\n\n/** The page as every check is handed it, its definitions resolved. */\nexport interface ResolvedPage {\n  readonly document: BlockDocument;\n  /**\n   * The page's blocks as it draws them: its component placements drawn as\n   * their components' blocks, under the page's own limits, where the caller\n   * gave the definitions; the stored blocks otherwise. A check reads these,\n   * and a finding on a block a component drew is moved to its placement.\n   */\n  readonly drawn: readonly BlockNode[];\n  readonly blocks: (type: string) => AnyBlockDefinition | undefined;\n  /** The header and footer drawn around it; none where none is known. */\n  readonly regions: readonly ResolvedRegion[];\n  /** The page's component definitions, where the caller knows them. */\n  readonly definitions?: DefinitionsById;\n  /** The site's variables, where the caller knows them. */\n  readonly tokens?: SiteTokenSet;\n  /** The site's edits to each block type's own look, by type. */\n  readonly siteLooks: Readonly<Record<string, NodeStyles>>;\n  /** What the caller knows of the page beyond its document; none given, none. */\n  readonly facts: PageFacts;\n}\n\n/** What one check reports about one problem. */\nexport interface PageCheckResult {\n  /** The block it is about; absent for the page as a whole. */\n  readonly nodeId?: string;\n  /** Which of several problems a check finds on one block this is. */\n  readonly part?: string;\n  /** What is wrong, as a short line. */\n  readonly what: string;\n  /** Why it matters, and to whom. */\n  readonly why: string;\n  /** What to do about it. */\n  readonly todo: string;\n  /**\n   * The block's setting that fixes it, as the settings index names it;\n   * absent where no one setting does, and the block alone is selected.\n   */\n  readonly fix?: AskedSetting;\n  /**\n   * The tab of the document's own settings that fixes it, by its id, where\n   * the fix is there rather than on a block (a plugin's tab of Page settings).\n   */\n  readonly settingsTab?: string;\n  /**\n   * Where the fix is outside this editor, as a link the item is instead,\n   * for a block it cannot select (a header's, changed in its own editor).\n   */\n  readonly opens?: PageCheckLink;\n}\n\n/** One check: an id, the group it reports in, and what it finds. */\nexport interface PageCheck {\n  /** Stable and unique among the checks run together. */\n  readonly id: string;\n  readonly group: PageCheckGroup;\n  /** The problems on the page, in page order. Pure: no DOM, no writes. */\n  readonly run: (page: ResolvedPage) => readonly PageCheckResult[];\n  /**\n   * A line the list shows under the group's name whatever is found, such as\n   * how much data the page reads; never counted as an item. Pure, as `run`.\n   */\n  readonly note?: (page: ResolvedPage) => string | undefined;\n}\n\n/** A check's line under its group's name. */\nexport interface PageCheckNote {\n  readonly check: string;\n  readonly group: PageCheckGroup;\n  readonly text: string;\n}\n\n/** One problem as the list shows it. */\nexport interface PageFinding extends PageCheckResult {\n  /** Which check found it. */\n  readonly check: string;\n  readonly group: PageCheckGroup;\n  /** The same problem keeps its key from one run to the next. */\n  readonly key: string;\n  /** The block's name as Layers shows it, where the finding is on one. */\n  readonly block?: string;\n}\n\n/** What a run found, and which checks could not run. */\nexport interface PageCheckReport {\n  /** In the list's order: by group, then by where the block is on the page. */\n  readonly findings: readonly PageFinding[];\n  /** The ids of checks that threw, so the list can say they didn't run. */\n  readonly notRun: readonly string[];\n  /** The checks' lines under their groups' names, in the checks' order. */\n  readonly notes: readonly PageCheckNote[];\n}\n\n/** One group of the list, with its findings. */\nexport interface PageCheckGroupView {\n  readonly group: PageCheckGroup;\n  readonly label: string;\n  readonly findings: readonly PageFinding[];\n  /** The lines under its name, which are not items. */\n  readonly notes: readonly string[];\n}\n\n/**\n * Each drawn block a component drew, by id, to the page's placement of it:\n * the resolver marks every one (`instanceOf`), and leaves the page's own\n * blocks unmarked, slot content a placement holds among them.\n */\nfunction placementsOf(\n  drawn: readonly BlockNode[]\n): ReadonlyMap<string, string> {\n  const placements = new Map<string, string>();\n  walkNodes(drawn as BlockNode[], node => {\n    const placement = (node as ResolvedBlockNode).instanceOf;\n    if (placement !== undefined) placements.set(node.id, placement);\n  });\n  return placements;\n}\n\n/**\n * A finding as the page knows it: one on a block a component drew points at\n * the placement, which is what the author can select, and opens no setting,\n * which is the component's to change.\n */\nfunction onThePage(\n  result: PageCheckResult,\n  placementOf: ReadonlyMap<string, string>\n): PageCheckResult {\n  const placement =\n    result.nodeId === undefined ? undefined : placementOf.get(result.nodeId);\n  if (placement === undefined) return result;\n  return {\n    nodeId: placement,\n    ...(result.part === undefined ? {} : { part: result.part }),\n    what: result.what,\n    why: result.why,\n    todo: result.todo,\n  };\n}\n\n/** Each block's place on the page, by id, and the node itself. */\nfunction pageOrder(document: BlockDocument): Map<string, [number, BlockNode]> {\n  const order = new Map<string, [number, BlockNode]>();\n  walkNodes(document.nodes, node => {\n    if (!order.has(node.id)) order.set(node.id, [order.size, node]);\n  });\n  return order;\n}\n\n/** A key for the result, unique among those already given. */\nfunction keyOf(check: string, result: PageCheckResult, taken: Set<string>) {\n  const base = `${check}:${result.nodeId ?? \"\"}:${result.part ?? \"\"}`;\n  let key = base;\n  // A check naming one problem twice still lists it twice, each its own row.\n  for (let repeat = 2; taken.has(key); repeat += 1) {\n    key = `${base}#${String(repeat)}`;\n  }\n  taken.add(key);\n  return key;\n}\n\n/**\n * The page's blocks as the editing canvas draws them: every conditioned\n * block drawn with its conditions lifted, on the page and in the components\n * it places (`revealedForCanvas`, `revealedDefinitions`), so a block the\n * author sees on the canvas is judged, whatever its conditions decide.\n */\nfunction drawnNodesOf(page: CheckedPage): readonly BlockNode[] {\n  const revealed = revealedForCanvas(page.document, undefined);\n  if (page.definitions === undefined) return revealed.nodes;\n  return resolveComponentInstances(\n    revealed,\n    revealedDefinitions(revealed, page.definitions, undefined)\n  ).document.nodes;\n}\n\n/**\n * The page as every check is handed it: drawn once, its component\n * placements as their blocks where the definitions are given, its header and\n * footer read as their components draw them.\n */\nfunction resolvedPageOf(page: CheckedPage): ResolvedPage {\n  return {\n    document: page.document,\n    drawn: drawnNodesOf(page),\n    blocks: page.blocks ?? getBlock,\n    regions: (page.regions ?? []).map(composedRegion),\n    ...(page.definitions === undefined\n      ? {}\n      : { definitions: page.definitions }),\n    ...(page.tokens === undefined ? {} : { tokens: page.tokens }),\n    siteLooks: blockDefaultsOf(page.namedClasses ?? []),\n    facts: page.facts ?? {},\n  };\n}\n\n/**\n * Run the checks over a page. A check that throws is named in `notRun` and\n * the rest still run, so one broken check never hides the others' findings.\n */\nexport function runPageChecks(\n  page: CheckedPage,\n  checks: readonly PageCheck[]\n): PageCheckReport {\n  const resolved = resolvedPageOf(page);\n  const { drawn } = resolved;\n  const order = pageOrder(page.document);\n  const placementOf = placementsOf(drawn);\n  const taken = new Set<string>();\n  const found: PageFinding[] = [];\n  const notRun: string[] = [];\n  const notes: PageCheckNote[] = [];\n  for (const check of checks) {\n    let results: readonly PageCheckResult[];\n    let note: string | undefined;\n    try {\n      results = check.run(resolved);\n      note = check.note?.(resolved);\n    } catch {\n      notRun.push(check.id);\n      continue;\n    }\n    if (note !== undefined) {\n      notes.push({ check: check.id, group: check.group, text: note });\n    }\n    for (const drawnResult of results) {\n      const result = onThePage(drawnResult, placementOf);\n      const node =\n        result.nodeId === undefined ? undefined : order.get(result.nodeId)?.[1];\n      found.push({\n        ...result,\n        check: check.id,\n        group: check.group,\n        key: keyOf(check.id, result, taken),\n        ...(node === undefined\n          ? {}\n          : { block: layerLabel(node, resolved.blocks) }),\n      });\n    }\n  }\n  // Page-wide findings first in their group, then the page's blocks in order.\n  const place = (finding: PageFinding): number =>\n    finding.nodeId === undefined ? -1 : (order.get(finding.nodeId)?.[0] ?? -1);\n  const findings = found\n    .map((finding, index) => ({ finding, index }))\n    .sort(\n      (a, b) =>\n        GROUP_ORDER.indexOf(a.finding.group) -\n          GROUP_ORDER.indexOf(b.finding.group) ||\n        place(a.finding) - place(b.finding) ||\n        a.index - b.index\n    )\n    .map(each => each.finding);\n  return { findings, notRun, notes };\n}\n\n/**\n * The list's groups: Accessibility, Content and data and Publishing always,\n * and Search only where one of the checks offered reports in it, each with\n * its findings in order. Derived from the findings, never counted apart.\n */\nexport function pageCheckGroups(\n  findings: readonly PageFinding[],\n  checks: readonly Pick<PageCheck, \"group\">[],\n  notes: readonly PageCheckNote[] = []\n): PageCheckGroupView[] {\n  const offered = new Set(checks.map(check => check.group));\n  return GROUP_ORDER.filter(\n    group => CORE_GROUPS.includes(group) || offered.has(group)\n  ).map(group => ({\n    group,\n    label: GROUP_LABELS[group],\n    findings: findings.filter(finding => finding.group === group),\n    notes: notes.filter(note => note.group === group).map(note => note.text),\n  }));\n}\n","/**\n * The rich text a block holds, as the page checks read it: every prop whose\n * value is a stored rich text value, walked node by node in reading order.\n *\n * Shared by the checks that look inside rich text (its headings, its links),\n * so they agree on what a block's rich text is and walk it one way.\n *\n * @module page-checks/rich-text-parts\n */\nimport {\n  isRichTextNode,\n  isRichTextValue,\n  MAX_NODES,\n  type BlockNode,\n  type RichTextNode,\n} from \"@nextlyhq/blocks-engine\";\n\n/** An image's alternative text, as the rich text renderer reads it. */\nfunction imageAlt(image: RichTextNode): string {\n  const alt = image.altText ?? image.alt;\n  return typeof alt === \"string\" ? alt : \"\";\n}\n\n/**\n * Visit each node from `roots` down, in reading order. Iterative and bounded\n * by the document's node limit, since stored rich text reaches here\n * unvalidated; entries that are not nodes are skipped.\n */\nfunction walkRichText(\n  roots: readonly unknown[],\n  visit: (part: RichTextNode) => void\n): void {\n  const stack: unknown[] = [...roots].reverse();\n  let read = 0;\n  while (stack.length > 0 && read < MAX_NODES) {\n    const entry = stack.pop();\n    read += 1;\n    if (!isRichTextNode(entry)) continue;\n    visit(entry);\n    const children = Array.isArray(entry.children) ? entry.children : [];\n    for (let index = children.length - 1; index >= 0; index -= 1) {\n      stack.push(children[index]);\n    }\n  }\n}\n\n/** Visit every node of every rich text value the block's props hold. */\nexport function eachRichTextNode(\n  node: BlockNode,\n  visit: (part: RichTextNode) => void\n): void {\n  // A table of contents reads its passage's headings and draws its own list,\n  // never the passage, so nothing in it is on the page.\n  if (node.type === TABLE_OF_CONTENTS) return;\n  for (const [prop, value] of Object.entries(node.props)) {\n    // A passage bound to a field is drawn from the entry, not as stored.\n    if (node.bindings?.[prop] !== undefined) continue;\n    if (isRichTextValue(value)) walkRichText(value.root.children, visit);\n  }\n}\n\n/** The block that lists a passage's headings rather than drawing it. */\nconst TABLE_OF_CONTENTS = \"core/table-of-contents\";\n\n/**\n * The words a rich text node holds, its children's joined in order, an\n * image's alternative text among them, which names a link holding it.\n */\nexport function richTextWords(part: RichTextNode): string {\n  const words: string[] = [];\n  walkRichText([part], entry => {\n    if (typeof entry.text === \"string\") words.push(entry.text);\n    // A line break draws as a break between words, so it reads as a space.\n    if (entry.type === \"linebreak\") words.push(\" \");\n    if (entry.type === \"image\") words.push(imageAlt(entry));\n  });\n  return words.join(\"\");\n}\n","/**\n * The contrast check: text whose colour against its background falls below\n * WCAG AA, 4.5:1, or 3:1 for a heading, which is large text.\n *\n * Judged only where both colours are known, and only where the author chose\n * one of them on the block or a container around it: the site's own text on\n * its own background is the site's design, not one block's. A colour a\n * block takes from a shared style or a block style isn't known here, so that\n * block isn't judged. Text over an image or a gradient, or under opacity, a\n * filter or a blend, has no colour to measure, so it is skipped and the list\n * says so, never guessed.\n *\n * Measured with the editor's own reading of colours (`contrastOf`), in light\n * mode and again in dark mode where the site's variables give either colour\n * a different value there.\n *\n * @module page-checks/contrast-check\n */\nimport type {\n  BlockNode,\n  ContrastResult,\n  NodeStyles,\n  SiteTokenSet,\n  StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  contrastObscuringIn,\n  contrastOf,\n  contrastRatioText,\n} from \"../styles/style-colour\";\n\nimport type { PageCheck, PageCheckResult, ResolvedPage } from \"./page-checks\";\nimport { eachRichTextNode } from \"./rich-text-parts\";\n\n/** The blocks that draw text, each judged against its background. */\nconst TEXT_BLOCKS: ReadonlySet<string> = new Set([\n  \"core/text\",\n  \"core/heading\",\n  \"core/rich-text\",\n  \"core/button\",\n  \"core/quote\",\n  \"core/list\",\n]);\n\n/** The block drawn as large text, held to 3:1. */\nconst LARGE_TEXT = \"core/heading\";\n\n/** The site's text and background, where nothing on the page sets them. */\nconst SITE_TEXT: StyleValue = { $token: \"color.text\" };\nconst SITE_BACKGROUND: StyleValue = {\n  $token: \"color.background\",\n};\n\n/** What a block's text is drawn with, read down from the page. */\ninterface Painted {\n  readonly color?: StyleValue;\n  readonly background?: StyleValue;\n  /** Whether the author set either colour here or on a container. */\n  readonly chosen: boolean;\n  /**\n   * Whether an image, gradient or shadow is painted behind the text, which\n   * an opaque background in front of it covers.\n   */\n  readonly backdrop: boolean;\n  /** Whether opacity, a filter or a blend alters everything inside. */\n  readonly subtree: boolean;\n  /** Whether a colour comes from somewhere this check can't read. */\n  readonly unknown: boolean;\n}\n\n/** A node's text colour and background at its base state and width. */\ninterface Colours {\n  readonly color?: StyleValue;\n  readonly background?: StyleValue;\n}\n\n/** The colours set in one node's styles, at its base state and width. */\nfunction coloursIn(styles: NodeStyles | undefined): Colours {\n  const values = styles?.base?.base as\n    | Readonly<Record<string, StyleValue | undefined>>\n    | undefined;\n  return {\n    ...(values?.color === undefined ? {} : { color: values.color }),\n    ...(values?.backgroundColor === undefined\n      ? {}\n      : { background: values.backgroundColor }),\n  };\n}\n\n/** The block type's own look (a Button's blue), as the site has edited it. */\nfunction typeColours(\n  type: string,\n  { blocks, siteLooks }: Pick<ResolvedPage, \"blocks\" | \"siteLooks\">\n): Colours {\n  const site = coloursIn(siteLooks[type]);\n  const base = coloursIn(blocks(type)?.baseStyles);\n  const color = site.color ?? base.color;\n  const background = site.background ?? base.background;\n  return {\n    ...(color === undefined ? {} : { color }),\n    ...(background === undefined ? {} : { background }),\n  };\n}\n\n/**\n * What stands over the block's colours, from every tier it is drawn with:\n * its own styles, the site's edit of its type's look and the type's own.\n */\nfunction obscuringOf(\n  node: BlockNode,\n  { blocks, siteLooks }: Pick<ResolvedPage, \"blocks\" | \"siteLooks\">\n): { readonly local?: string; readonly subtree?: string } {\n  const tiers = [\n    node.styles,\n    siteLooks[node.type],\n    blocks(node.type)?.baseStyles,\n  ].map(contrastObscuringIn);\n  const local = tiers.find(tier => tier.local !== undefined)?.local;\n  const subtree = tiers.find(tier => tier.subtree !== undefined)?.subtree;\n  return {\n    ...(local === undefined ? {} : { local }),\n    ...(subtree === undefined ? {} : { subtree }),\n  };\n}\n\n/**\n * Whether the block draws any words: text it stores, words in its rich text,\n * or text bound to a field, which the entry gives. One with none has no\n * text to read, so nothing to judge.\n */\nfunction drawsWords(node: BlockNode): boolean {\n  if (Object.keys(node.bindings ?? {}).length > 0) return true;\n  if (WORD_PROPS.some(prop => hasText(node.props[prop]))) return true;\n  // A List's items, each its own words.\n  const items = node.props.items;\n  if (Array.isArray(items) && items.some(hasText)) return true;\n  let words = false;\n  eachRichTextNode(node, part => {\n    if (hasText(part.text)) words = true;\n  });\n  return words;\n}\n\n/** Whether a value is text with something in it. */\nfunction hasText(value: unknown): boolean {\n  return typeof value === \"string\" && value.trim() !== \"\";\n}\n\n/** The props a text block keeps its plain words in: a Heading's, a Button's. */\nconst WORD_PROPS: readonly string[] = [\"text\", \"label\"];\n\n/** Whether a block's colours come from somewhere this check can't read. */\nfunction unreadable(node: BlockNode): boolean {\n  const look = node.props.look;\n  if ((node.classes?.length ?? 0) > 0) return true;\n  // Classes the site's own CSS styles, which this check can't read.\n  if (typeof node.cssClasses === \"string\" && node.cssClasses.trim() !== \"\") {\n    return true;\n  }\n  if (typeof look === \"string\" && look !== \"\") return true;\n  return colouredInline(node);\n}\n\n/** The first colour set, nearest first. */\nfunction nearest(\n  ...colours: readonly (StyleValue | undefined)[]\n): StyleValue | undefined {\n  return colours.find(colour => colour !== undefined);\n}\n\n/** What the node's text is drawn with: its own, its type's, its container's. */\nfunction paintedBy(\n  node: BlockNode,\n  around: Painted,\n  page: Pick<ResolvedPage, \"blocks\" | \"siteLooks\">\n): Painted {\n  const own = coloursIn(node.styles);\n  const type = typeColours(node.type, page);\n  const color = nearest(own.color, type.color, around.color);\n  const background = nearest(\n    own.background,\n    type.background,\n    around.background\n  );\n  const obscuring = obscuringOf(node, page);\n  // A background of its own covers what its container paints behind it.\n  const covered = nearest(own.background, type.background) !== undefined;\n  return {\n    ...(color === undefined ? {} : { color }),\n    ...(background === undefined ? {} : { background }),\n    chosen:\n      around.chosen || own.color !== undefined || own.background !== undefined,\n    backdrop: obscuring.local !== undefined || (!covered && around.backdrop),\n    subtree: around.subtree || obscuring.subtree !== undefined,\n    unknown: around.unknown || unreadable(node),\n  };\n}\n\n/** Inline styles that change what colour a run of text is drawn in. */\nconst INLINE_COLOUR = /(^|;)\\s*(color|background(-color)?|opacity)\\s*:/i;\n\n/**\n * Whether the block's rich text gives some of its runs a colour, background\n * or opacity of their own: its text is then not one pair, so it isn't judged\n * as one.\n */\nfunction colouredInline(node: BlockNode): boolean {\n  let coloured = false;\n  eachRichTextNode(node, part => {\n    if (typeof part.style === \"string\" && INLINE_COLOUR.test(part.style)) {\n      coloured = true;\n    }\n  });\n  return coloured;\n}\n\n/** Text this many px or more is large, as WCAG counts it (18pt). */\nconst LARGE_PX = 24;\n\n/** A font size in px, where the stored value says it plainly. */\nfunction fontSizePx(value: unknown): number | undefined {\n  if (typeof value === \"string\") {\n    const match = /^(\\d+(?:\\.\\d+)?)(px|rem)$/.exec(value.trim());\n    if (match === null) return undefined;\n    return Number(match[1]) * (match[2] === \"rem\" ? 16 : 1);\n  }\n  if (typeof value === \"object\" && value !== null) {\n    const { value: size, unit } = value as { value?: unknown; unit?: unknown };\n    if (typeof size !== \"number\") return undefined;\n    if (unit === \"px\") return size;\n    return unit === \"rem\" ? size * 16 : undefined;\n  }\n  return undefined;\n}\n\n/**\n * Whether the block's text is large, held to 3:1: a size of its own that\n * reaches 24px, or, with none, a Heading at level 1 or 2, which the site's\n * type sizes draw large. A size it sets that can't be read isn't large.\n */\nfunction isLargeText(node: BlockNode): boolean {\n  const values = node.styles?.base?.base as\n    | Readonly<Record<string, unknown>>\n    | undefined;\n  if (values?.fontSize !== undefined) {\n    const px = fontSizePx(values.fontSize);\n    return px !== undefined && px >= LARGE_PX;\n  }\n  const level = node.props.level;\n  return node.type === LARGE_TEXT && (level === \"h1\" || level === \"h2\");\n}\n\n/** The ratio a block's text needs. */\nfunction threshold(node: BlockNode): number {\n  return isLargeText(node) ? 3 : 4.5;\n}\n\nconst WHY =\n  \"People with low vision, or reading in bright light, may not be able to read it.\";\n\n/** The block's finding, or none where its text reads or can't be judged. */\nfunction contrastFinding(\n  node: BlockNode,\n  painted: Painted,\n  tokens: SiteTokenSet | undefined\n): PageCheckResult | undefined {\n  if (painted.unknown) return undefined;\n  if (painted.backdrop || painted.subtree) {\n    return {\n      nodeId: node.id,\n      part: \"skipped\",\n      what: \"Contrast not checked: text over an image or gradient\",\n      why: \"The colours behind the text can change across the picture, so no one ratio can be measured.\",\n      todo: \"Check the text reads well over the whole picture, or give it a solid background.\",\n    };\n  }\n  if (!painted.chosen) return undefined;\n  const color = painted.color ?? SITE_TEXT;\n  const background = painted.background ?? SITE_BACKGROUND;\n  const needs = threshold(node);\n  const what = tooLowWords(\n    contrastOf(color, background, tokens, \"light\"),\n    contrastOf(color, background, tokens, \"dark\"),\n    needs\n  );\n  if (what === undefined) return undefined;\n  return {\n    nodeId: node.id,\n    what,\n    why: WHY,\n    todo: `Use a darker text colour or a lighter background, for at least ${String(needs)}:1.`,\n    fix: { tab: \"style\", id: \"color\" },\n  };\n}\n\n/**\n * What a failing pair says, in light mode and in dark, or nothing where it\n * reads. Each mode is its own answer where it can be measured, so a pair\n * only dark mode resolves is still judged there; dark mode is reported only\n * where its colours differ from light's.\n */\nfunction tooLowWords(\n  light: ContrastResult | undefined,\n  dark: ContrastResult | undefined,\n  needs: number\n): string | undefined {\n  const darkOwn = dark !== undefined && dark.ratio !== light?.ratio;\n  const darkFails = darkOwn && dark.ratio < needs;\n  if (light !== undefined && light.ratio < needs) {\n    const inDark = darkFails\n      ? ` (${contrastRatioText(dark)} in dark mode)`\n      : \"\";\n    return `Text contrast is too low: ${contrastRatioText(light)}${inDark}`;\n  }\n  return darkFails\n    ? `Text contrast is too low in dark mode: ${contrastRatioText(dark)}`\n    : undefined;\n}\n\n/** A stored entry read as a block, or none where it can't be. */\nfunction asBlock(entry: unknown): BlockNode | undefined {\n  if (typeof entry !== \"object\" || entry === null) return undefined;\n  const block = entry as BlockNode;\n  return typeof block.type === \"string\" && typeof block.props === \"object\"\n    ? block\n    : undefined;\n}\n\n/** A block's children in drawing order, across its slots. */\nfunction childrenOf(block: BlockNode): unknown[] {\n  return Object.values(block.slots ?? {}).flatMap(slot =>\n    Array.isArray(slot) ? slot : []\n  );\n}\n\n/** The block's finding, where it is a text block that draws words. */\nfunction judged(\n  block: BlockNode,\n  painted: Painted,\n  page: ResolvedPage\n): PageCheckResult | undefined {\n  if (!TEXT_BLOCKS.has(block.type) || !drawsWords(block)) return undefined;\n  return contrastFinding(block, painted, page.tokens);\n}\n\n/** Every text block whose contrast is too low, or which couldn't be judged. */\nfunction contrastFindings(page: ResolvedPage): PageCheckResult[] {\n  const found: PageCheckResult[] = [];\n  const start: Painted = {\n    chosen: false,\n    backdrop: false,\n    subtree: false,\n    unknown: false,\n  };\n  const stack: { node: unknown; around: Painted }[] = [...page.drawn]\n    .reverse()\n    .map(node => ({ node, around: start }));\n  const seen = new Set<unknown>();\n  for (let next = stack.pop(); next !== undefined; next = stack.pop()) {\n    const block = seen.has(next.node) ? undefined : asBlock(next.node);\n    if (block === undefined) continue;\n    seen.add(block);\n    const painted = paintedBy(block, next.around, page);\n    const finding = judged(block, painted, page);\n    if (finding !== undefined) found.push(finding);\n    const children = childrenOf(block);\n    for (let index = children.length - 1; index >= 0; index -= 1) {\n      stack.push({ node: children[index], around: painted });\n    }\n  }\n  return found;\n}\n\n/** Text that is hard to read against its background, in light and dark. */\nexport const CONTRAST_CHECK: PageCheck = {\n  id: \"contrast\",\n  group: \"accessibility\",\n  run: contrastFindings,\n};\n","/**\n * An image's source and its alt text as the inspector edits them: which props\n * make each up, what the stored values mean, and what each choice writes.\n *\n * Each is one question to an author and two props to the block. Where the\n * picture comes from is `mediaId` (a library file) or `src` (an address), and\n * the block draws the library file first and the address only as its\n * fallback. What a screen reader hears is `alt` and `decorative`, which the\n * block reads in that order: decorative wins outright, an alt the page stores\n * (even an empty one) comes next, and the library's alt text applies only\n * when the page stores none. Drawn one row per prop, the panel showed two\n * sources competing and three alt states spread over two controls.\n *\n * Found by prop NAME and type, as the link group is: an embed's `src` is a\n * `url` prop too, and is no image's source without a `mediaId` beside it.\n *\n * Every rule reads what is STORED, never a default: the block's defaults are\n * written when it is placed, not applied when it draws, so a default here\n * would describe a value the page does not hold.\n *\n * Pure, so each rule is tested without a panel.\n *\n * @module image-group\n */\nimport { isAuthoredText } from \"@nextlyhq/blocks-engine\";\n\nimport type { EditableProp } from \"../inspector\";\n\n/** Several props written as one edit: a value each, `undefined` to remove it. */\nexport type ImageChanges = Readonly<Record<string, unknown>>;\n\n/** The two props an image's picture comes from. */\nexport interface ImageSourceGroup {\n  /** The library file's id: drawn first. */\n  readonly media: string;\n  /** The address: drawn when there is no library file. */\n  readonly address: string;\n  readonly drawn: ReadonlySet<string>;\n}\n\n/** The two props an image's alt text comes from. */\nexport interface ImageAltGroup {\n  readonly alt: string;\n  readonly decorative: string;\n  /** The library file whose alt text applies when the page stores none. */\n  readonly media?: string;\n  readonly drawn: ReadonlySet<string>;\n}\n\n/** A block's image groups: either, both, or neither. */\nexport interface ImageGroup {\n  readonly source?: ImageSourceGroup;\n  readonly alt?: ImageAltGroup;\n}\n\n/**\n * The image groups of a block's props, or `undefined` when it declares\n * neither. The source needs `mediaId` as a media prop and `src` as a URL;\n * the alt text needs `alt` as text and `decorative` as a checkbox. A prop\n * that does not join keeps its own row.\n */\nexport function imageGroupOf(\n  props: ReadonlyArray<Pick<EditableProp, \"name\" | \"schema\">>\n): ImageGroup | undefined {\n  const types = new Map(props.map(prop => [prop.name, prop.schema.type]));\n  const media = types.get(\"mediaId\") === \"media\" ? \"mediaId\" : undefined;\n  const source =\n    media !== undefined && types.get(\"src\") === \"url\"\n      ? { media, address: \"src\", drawn: new Set([media, \"src\"]) }\n      : undefined;\n  const alt =\n    types.get(\"alt\") === \"text\" && types.get(\"decorative\") === \"checkbox\"\n      ? {\n          alt: \"alt\",\n          decorative: \"decorative\",\n          ...(media === undefined ? {} : { media }),\n          drawn: new Set([\"alt\", \"decorative\"]),\n        }\n      : undefined;\n  if (source === undefined && alt === undefined) return undefined;\n  return {\n    ...(source === undefined ? {} : { source }),\n    ...(alt === undefined ? {} : { alt }),\n  };\n}\n\n/** A stored string, trimmed, or `undefined` for anything else or nothing. */\nfunction storedString(value: unknown): string | undefined {\n  if (typeof value !== \"string\") return undefined;\n  const trimmed = value.trim();\n  return trimmed === \"\" ? undefined : trimmed;\n}\n\n/** Where an image's picture comes from. */\nexport type SourceMode = \"library\" | \"url\";\n\n/**\n * What the source holds now: a library file (also when an address is stored\n * beside it, which the block draws only as the file's fallback), else an\n * address, else nothing, which is offered as the library.\n */\nexport function sourceModeOf(\n  group: ImageSourceGroup,\n  values: Readonly<Record<string, unknown>>\n): SourceMode {\n  if (storedString(values[group.media]) !== undefined) return \"library\";\n  return storedString(values[group.address]) === undefined ? \"library\" : \"url\";\n}\n\n/**\n * What an address typed in URL mode writes. A cleared field removes the\n * address. An address clears a stored library file, because the block draws\n * the file first and the address would otherwise do nothing; both go in one\n * edit, so one undo puts the file back.\n */\nexport function addressChanges(\n  group: ImageSourceGroup,\n  typed: string,\n  values: Readonly<Record<string, unknown>>\n): ImageChanges {\n  const address = typed.trim();\n  if (address === \"\") return { [group.address]: undefined };\n  return {\n    [group.address]: address,\n    ...(values[group.media] === undefined ? {} : { [group.media]: undefined }),\n  };\n}\n\n/**\n * What picking a library file writes. A stored address is kept as the file's\n * fallback, since an author may have typed it, unless it is still one the\n * block was placed with (`placedWith`: its example's placeholder, not\n * anyone's address): that one is removed in the same edit, so a fresh image\n * holds the picked file alone.\n */\nexport function mediaPickChanges(\n  group: ImageSourceGroup,\n  mediaId: string,\n  values: Readonly<Record<string, unknown>>,\n  placedWith: ReadonlyArray<Readonly<Record<string, unknown>>>\n): ImageChanges {\n  const address = values[group.address];\n  const placeholder =\n    typeof address === \"string\" &&\n    placedWith.some(props => props[group.address] === address);\n  return {\n    [group.media]: mediaId,\n    ...(placeholder ? { [group.address]: undefined } : {}),\n  };\n}\n\n/** What a screen reader is given for the image. */\nexport type AltMode = \"library\" | \"custom\" | \"decorative\";\n\n/**\n * Which mode the stored props are in, read as the block reads them:\n * decorative first, then an alt the page stores (an empty one included,\n * which the block draws as no alt text at all), then the library's.\n */\nexport function altModeOf(\n  group: ImageAltGroup,\n  values: Readonly<Record<string, unknown>>\n): AltMode {\n  if (values[group.decorative] === true) return \"decorative\";\n  return isAuthoredText(values[group.alt]) ? \"custom\" : \"library\";\n}\n\n/** The page's own alt text as the field shows it, or `\"\"` for none. */\nexport function storedAlt(\n  group: ImageAltGroup,\n  values: Readonly<Record<string, unknown>>\n): string {\n  const alt = values[group.alt];\n  return isAuthoredText(alt) ? String(alt) : \"\";\n}\n\n/**\n * What committing the alt field's words writes. The field shows the words in\n * use: the page's own, else the library's. So:\n *\n * - words other than those in use are stored as the page's own;\n * - the words in use, committed unchanged, write nothing, so an image showing\n *   the library's words keeps following the library;\n * - an emptied field removes the page's own words, so the library's apply\n *   again; \"Decorative, no alt text\" is how an author says \"none\".\n */\nexport function altTextChanges(\n  group: ImageAltGroup,\n  typed: string,\n  values: Readonly<Record<string, unknown>>,\n  libraryAlt: string | undefined\n): ImageChanges {\n  const words = typed.trim();\n  const own = values[group.alt];\n  if (words === \"\") {\n    return own === undefined ? {} : { [group.alt]: undefined };\n  }\n  const inUse = isAuthoredText(own) ? String(own).trim() : libraryAlt;\n  return words === inUse ? {} : { [group.alt]: words };\n}\n\n/**\n * What ticking or clearing \"Decorative, no alt text\" writes: the mark alone,\n * so the alt text is kept for when it is cleared; the block ignores it while\n * the image is decorative. Only `true` marks an image decorative, as the\n * block reads it, so clearing a mark that is not set names nothing, and a\n * lock on it does not refuse the change.\n */\nexport function decorativeChanges(\n  group: ImageAltGroup,\n  on: boolean,\n  values: Readonly<Record<string, unknown>>\n): ImageChanges {\n  if (on) return { [group.decorative]: true };\n  return values[group.decorative] === true\n    ? { [group.decorative]: undefined }\n    : {};\n}\n","/**\n * How the checks read a block's stored value: whether it holds anything,\n * and whether a field supplies it instead. One reading, so the alt text and\n * the empty-block checks agree on what \"left empty\" means.\n *\n * @module page-checks/stored-values\n */\nimport type { BlockNode } from \"@nextlyhq/blocks-engine\";\n\n/** A stored value with something in it: a cleared text field holds nothing. */\nexport function holds(value: unknown): boolean {\n  if (typeof value === \"string\") return value.trim() !== \"\";\n  return value !== undefined && value !== null;\n}\n\n/** Whether a prop is bound to a field, which then supplies its value. */\nexport function bound(node: BlockNode, prop: string): boolean {\n  return node.bindings?.[prop] !== undefined;\n}\n","/**\n * Blocks left empty, which draw nothing useful on the live page: an Image\n * with no picture, a Button with no link, and a Collection list with no\n * source. Each is found where nothing supplies the missing part, neither a\n * stored value nor a field it is bound to, and opens the setting that does.\n *\n * Read over the blocks the page draws, so a component's own empty block is\n * found too and pointed at its placement, as every check's is.\n *\n * @module page-checks/empty-blocks-check\n */\nimport {\n  COLLECTION_LIST_TYPE,\n  isLinkableUrl,\n  readListQuery,\n  walkNodes,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport { fetchableUrl } from \"@nextlyhq/blocks-react\";\n\nimport { imageGroupOf } from \"../inspector/content/image-group\";\n\nimport type { PageCheck, PageCheckResult, ResolvedPage } from \"./page-checks\";\nimport { bound, holds } from \"./stored-values\";\n\n/** The button block, whose link is its `LINK_PROPS`. */\nconst BUTTON_TYPE = \"core/button\";\n\n/** An image block with neither a library file nor an address for its picture. */\nfunction emptyImage(\n  node: BlockNode,\n  page: ResolvedPage\n): PageCheckResult | undefined {\n  const declared = page.blocks(node.type)?.props;\n  if (declared === undefined) return undefined;\n  const source = imageGroupOf(\n    Object.entries(declared).flatMap(([name, schema]) =>\n      schema === undefined ? [] : [{ name, schema }]\n    )\n  )?.source;\n  if (source === undefined) return undefined;\n  // A library file or a field supplies the picture; a stored address does\n  // only where the renderer would fetch it (`fetchableUrl`), so a\n  // `javascript:` or `blob:` address draws nothing here as on the page. The\n  // site's own allowed hosts aren't known to the check, so any host passes.\n  const supplied =\n    holds(node.props[source.media]) ||\n    bound(node, source.media) ||\n    fetchableUrl(node.props[source.address], undefined) !== undefined ||\n    bound(node, source.address);\n  if (supplied) return undefined;\n  return {\n    nodeId: node.id,\n    what: \"Image has no picture\",\n    why: \"Visitors see an empty space where the picture should be.\",\n    todo: \"Choose a picture, or remove the image.\",\n    fix: { tab: \"content\", id: source.media },\n  };\n}\n\n/**\n * A button that goes nowhere: no address the page would link to, no entry\n * and no field supplying either, and no form job (sending or clearing a\n * form) of its own. An address is judged by the format's own rule\n * (`isLinkableUrl`), which the renderer draws a link by, so a stored\n * `javascript:` address is no link here as it is none on the page.\n */\nfunction emptyButton(node: BlockNode): PageCheckResult | undefined {\n  if (node.type !== BUTTON_TYPE) return undefined;\n  const linked =\n    isLinkableUrl(node.props.href) ||\n    bound(node, \"href\") ||\n    (holds(node.props.entryCollection) && holds(node.props.entryId)) ||\n    bound(node, \"entryId\");\n  const formJob = node.props.type === \"submit\" || node.props.type === \"reset\";\n  if (linked || formJob) return undefined;\n  return {\n    nodeId: node.id,\n    what: \"Button has no link\",\n    why: \"Pressing it does nothing for visitors.\",\n    todo: \"Add a link, or remove the button.\",\n    fix: { tab: \"content\", id: \"href\" },\n  };\n}\n\n/** A collection list that names nothing to show: no collection, related entries or custom source. */\nfunction emptyList(node: BlockNode): PageCheckResult | undefined {\n  if (node.type !== COLLECTION_LIST_TYPE) return undefined;\n  const { query } = readListQuery(node.props);\n  if (\n    query.collection !== undefined ||\n    query.relation !== undefined ||\n    query.namedQuery !== undefined\n  ) {\n    return undefined;\n  }\n  return {\n    nodeId: node.id,\n    what: \"Collection list has no source\",\n    why: \"It shows no entries, so visitors see nothing there.\",\n    todo: \"Choose what it shows in “Show entries from”.\",\n    fix: { tab: \"content\", id: \"collection\" },\n  };\n}\n\n/** Every empty Image, Button and Collection list, in page order. */\nexport const EMPTY_BLOCKS_CHECK: PageCheck = {\n  id: \"empty-blocks\",\n  group: \"content\",\n  run: page => {\n    const found: PageCheckResult[] = [];\n    walkNodes(page.drawn as BlockNode[], node => {\n      const result =\n        emptyImage(node, page) ?? emptyButton(node) ?? emptyList(node);\n      if (result !== undefined) found.push(result);\n    });\n    return found;\n  },\n};\n","/**\n * What a page costs to read, as the editor tells an author.\n *\n * A published page makes every read it needs (a list's entries, an image, a\n * link to an entry, a related entry, the page's own data) under one allowance\n * per visit, 500 unless the site's code says otherwise. Past it, reads stop and\n * each block that needed one is drawn as it is when its data is missing. An\n * author cannot see that happening on the page itself, so the editor counts\n * the reads its own draw makes, by the same rules, and says how close the page\n * is to the limit: the top bar only from 80% of it, Page settings always.\n *\n * This module is the model: the report a count produces and the one reading\n * of it every surface shares, so the bar's colour, the trigger's words and the\n * panel's sentence cannot disagree about whether a page is near its limit.\n *\n * @module read-budget\n * @experimental Settles with the canvas's read count.\n */\n\nimport {\n  READ_KINDS,\n  type PageReadReport,\n  type ReadKind,\n  type UnreadBlock,\n} from \"@nextlyhq/blocks-react\";\n\n// The report and its kinds are the renderer's own, so the meter reads\n// exactly what the page's budget counted, by the same names.\nexport { READ_KINDS };\nexport type { PageReadReport, ReadKind, UnreadBlock };\n\n/**\n * Where a page stands against its allowance:\n * - `counting`: the canvas is still drawing, so there is no count yet;\n * - `within`: under 80% of it;\n * - `near`: from 80%, with room left;\n * - `over`: the whole allowance is spent, so the next read is refused, or it\n *   needed more than it may make, so some blocks went unread.\n */\nexport type ReadBudgetStanding = \"counting\" | \"within\" | \"near\" | \"over\";\n\n/** The share of the allowance from which the editor warns. */\nexport const READ_WARNING_SHARE = 0.8;\n\n/** Where a report puts the page. `undefined` is a draw still counting. */\nexport function readBudgetStanding(\n  report: PageReadReport | undefined\n): ReadBudgetStanding {\n  if (report === undefined) return \"counting\";\n  if (report.refused > 0 || report.unread.length > 0) return \"over\";\n  // An unlimited route (`maxQueries: Infinity`) is never near its limit.\n  if (!Number.isFinite(report.cap)) return \"within\";\n  // A page that spent its whole allowance has no room for one more list or\n  // image: the next block that needs data comes up empty.\n  if (report.cap > 0 && report.used >= report.cap) return \"over\";\n  return report.used >= warningAt(report.cap) ? \"near\" : \"within\";\n}\n\n/**\n * Whether the top bar shows the meter: only once the page nears its limit,\n * since a page far from it has nothing to warn of, and never while counting.\n * A count that could not be made is shown too (the meter says so), because a\n * hidden failure could hide a page over its limit.\n */\nexport function shownInTopBar(standing: ReadBudgetStanding): boolean {\n  return standing === \"near\" || standing === \"over\";\n}\n\n/** The read from which a page of `cap` is warned about. */\nexport function warningAt(cap: number): number {\n  return Math.ceil(cap * READ_WARNING_SHARE);\n}\n\n/** How full the allowance is, from 0 to 1, for a bar. */\nexport function readShare(report: PageReadReport): number {\n  if (!Number.isFinite(report.cap) || report.cap <= 0) {\n    return report.cap === 0 && report.refused > 0 ? 1 : 0;\n  }\n  return Math.min(1, Math.max(0, report.used / report.cap));\n}\n\n/**\n * What each kind is called in the explanation's rows, and what a block that\n * went without it shows on the live site.\n */\nexport const READ_KIND_WORDS: Readonly<\n  Record<ReadKind, { readonly label: string; readonly unread: string }>\n> = {\n  entries: { label: \"List entries\", unread: \"Its entries don't load\" },\n  related: {\n    label: \"Related entries\",\n    unread: \"Its related entries don't load\",\n  },\n  image: { label: \"Images\", unread: \"Its image doesn't load\" },\n  link: { label: \"Links to entries\", unread: \"Its link doesn't load\" },\n  page: { label: \"The page itself\", unread: \"Its data doesn't load\" },\n  component: { label: \"Components\", unread: \"Its component doesn't load\" },\n};\n\n/** A count as the editor writes it: grouped digits, `∞` for no limit. */\nexport function readCount(value: number): string {\n  return Number.isFinite(value) ? value.toLocaleString(\"en-US\") : \"∞\";\n}\n\n/**\n * The count as the meter writes it: \"Page data: 430 of 500\", or for a site\n * with no limit, \"Page data: 12 (no limit)\".\n */\nexport function pageDataCount(report: PageReadReport): string {\n  return Number.isFinite(report.cap)\n    ? `Page data: ${readCount(report.used)} of ${readCount(report.cap)}`\n    : `Page data: ${readCount(report.used)} (no limit)`;\n}\n\n/** Where a page stands, as the meter's accessible name says it. */\nconst STANDING_NAME: Record<Exclude<ReadBudgetStanding, \"counting\">, string> = {\n  within: \"within the limit\",\n  near: \"near the limit\",\n  over: \"over the limit\",\n};\n\n/**\n * The meter's accessible name: the count, where it stands, and that pressing\n * it explains (\"Page data: 430 of 500, near the limit. What's this?\").\n */\nexport function readBudgetName(report: PageReadReport | undefined): string {\n  const standing = readBudgetStanding(report);\n  if (report === undefined || standing === \"counting\") {\n    return \"Page data: counting. What's this?\";\n  }\n  if (!Number.isFinite(report.cap)) {\n    return `Page data: ${readCount(report.used)}, no limit. What's this?`;\n  }\n  return `${pageDataCount(report)}, ${STANDING_NAME[standing]}. What's this?`;\n}\n\n/** The meter's words and name when the count could not be made. */\nexport const COUNT_FAILED_NAME = \"Page data: couldn't count. Retry\";\n\n/** One block drawn without its data, with every read it went without. */\nexport interface UnreadRow {\n  readonly nodeId: string;\n  readonly what: readonly ReadKind[];\n}\n\n/**\n * The blocks a report names as unread, each once in the order it first\n * asked, with every kind of read it missed: what the panel lists and every\n * count of unread blocks says, so a block that missed its image and its link\n * is one block, not two.\n */\nexport function unreadBlocks(report: PageReadReport): readonly UnreadRow[] {\n  const rows = new Map<string, ReadKind[]>();\n  for (const { nodeId, what } of report.unread) {\n    const missed = rows.get(nodeId) ?? [];\n    if (!missed.includes(what)) missed.push(what);\n    rows.set(nodeId, missed);\n  }\n  return [...rows].map(([nodeId, what]) => ({ nodeId, what }));\n}\n","/**\n * Where a block the page's data ran out before is: on the page, or in a\n * header or footer drawn around it, which the page's editor cannot select.\n * One answer for the top bar's meter and Page checks, so both name the same\n * block and offer the same way to it.\n *\n * @module shell/unread-places\n */\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\n\nimport { blockNameOf, type ComponentTitleOf } from \"../panels/layers/layers\";\n\n/**\n * The region whose stored document holds the block `nodeId`, with the\n * block's name there, when one does. A read names the stored blocks, a\n * component placement among them, so the stored document is what is asked.\n */\nexport function regionHolding<R>(\n  regions: readonly R[],\n  nodeId: string,\n  storedOf: (region: R) => BlockDocument,\n  componentTitle?: ComponentTitleOf\n): { readonly region: R; readonly name: string } | undefined {\n  for (const region of regions) {\n    const name = blockNameOf(storedOf(region), nodeId, componentTitle);\n    if (name !== undefined) return { region, name };\n  }\n  return undefined;\n}\n","/**\n * The checks over what the caller knows of a page beyond its document\n * (`page-facts`): bindings that no longer fit, how much data the page reads\n * against its limit, parts it uses that aren't published, and a header or\n * footer it shows twice. Each reads its fact as handed in and finds nothing\n * where it is left out, so the words are the only thing decided here.\n *\n * @module page-checks/fact-checks\n */\nimport {\n  COMPONENT_INSTANCE_TYPE,\n  walkNodes,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { blockNameOf } from \"../panels/layers/layers\";\nimport {\n  pageDataCount,\n  readBudgetStanding,\n  READ_KIND_WORDS,\n  unreadBlocks,\n  type PageReadReport,\n  type ReadKind,\n} from \"../shell/read-budget\";\nimport { regionHolding } from \"../shell/unread-places\";\n\nimport type { PageCheck, PageCheckResult, ResolvedPage } from \"./page-checks\";\nimport type { UnpublishedPart } from \"./page-facts\";\n\n/** The page's bindings that no longer fit, as \"Bindings to fix\" lists them. */\nexport const BINDINGS_TO_FIX_CHECK: PageCheck = {\n  id: \"bindings-to-fix\",\n  group: \"content\",\n  run: page =>\n    (page.facts.bindingsToFix ?? []).map(binding => ({\n      nodeId: binding.nodeId,\n      part: binding.prop,\n      what: `Binding no longer fits: ${binding.where}`,\n      why: binding.change,\n      todo: \"Bind it to a field again, or unbind it.\",\n    })),\n};\n\n/** The line under Content and data: the page's data against its limit. */\nfunction pageDataNote(page: ResolvedPage): string | undefined {\n  const fact = page.facts.pageData;\n  if (fact === undefined) return undefined;\n  if (fact.state === \"counting\") return \"Page data: counting…\";\n  if (fact.state === \"failed\") return \"Page data: couldn’t count\";\n  return pageDataCount(fact.report);\n}\n\n/** What a block over the limit misses, in the meter's words, as one line. */\nfunction missedWords(what: readonly ReadKind[]): string {\n  return what.map(kind => READ_KIND_WORDS[kind].unread).join(\". \");\n}\n\n/**\n * One block the page's data ran out before, as the meter places it: a\n * page's block is selected; a header's or footer's, which this editor\n * cannot select, is named with its region and links to where it is\n * changed; one on neither (undone since the count) is the page's item.\n */\nfunction overLimitItem(\n  page: ResolvedPage,\n  row: { readonly nodeId: string; readonly what: readonly ReadKind[] },\n  words: { readonly why: string; readonly todo: string }\n): PageCheckResult {\n  const missed = missedWords(row.what);\n  if (blockNameOf(page.document, row.nodeId) !== undefined) {\n    return {\n      nodeId: row.nodeId,\n      what: `Over the page data limit: ${missed}`,\n      ...words,\n    };\n  }\n  const held = regionHolding(page.regions, row.nodeId, region => region.stored);\n  if (held === undefined) {\n    return {\n      part: row.nodeId,\n      what: `Over the page data limit: ${missed}`,\n      ...words,\n    };\n  }\n  const { region, name } = held;\n  const where = region.label ?? `the site ${region.area}`;\n  return {\n    part: row.nodeId,\n    what: `Over the page data limit in ${where}: ${name}`,\n    why: `${missed}. ${words.why}`,\n    todo: `Show fewer entries in ${where}, or move some blocks to another page.`,\n    ...(region.edit === undefined ? {} : { opens: region.edit }),\n  };\n}\n\n/** The blocks the page's data runs out before, each named. */\nfunction overLimit(\n  page: ResolvedPage,\n  report: PageReadReport\n): PageCheckResult[] {\n  const why = `The page reads more data than the site allows (${pageDataCount(report)}), so on the live page this block shows empty.`;\n  const todo =\n    \"Show fewer entries in a list, or move some blocks to another page.\";\n  const rows = unreadBlocks(report);\n  // Refused reads with no block to name: the page as a whole is over.\n  if (rows.length === 0) {\n    return [{ what: \"Page data over the limit\", why, todo }];\n  }\n  return rows.map(row => overLimitItem(page, row, { why, todo }));\n}\n\n/**\n * How much data the page reads against its limit, always as the group's\n * line, and over the limit an item for each block that then shows empty:\n * the same count and standing as the top bar's meter, never a second one.\n * A page that used exactly its allowance stands \"over\" for the meter, since\n * its next read would be refused, but missed nothing: an item needs a read\n * that was refused.\n */\nexport const PAGE_DATA_CHECK: PageCheck = {\n  id: \"page-data\",\n  group: \"content\",\n  note: pageDataNote,\n  run: page => {\n    const fact = page.facts.pageData;\n    if (fact?.state !== \"counted\") return [];\n    const { report } = fact;\n    const missed = report.refused > 0 || report.unread.length > 0;\n    return missed && readBudgetStanding(report) === \"over\"\n      ? overLimit(page, report)\n      : [];\n  },\n};\n\n/** The page's first placement of the component `id`, where it places one. */\nfunction placementOf(\n  nodes: readonly BlockNode[],\n  id: string\n): string | undefined {\n  let found: string | undefined;\n  walkNodes(nodes as BlockNode[], node => {\n    if (\n      found === undefined &&\n      node.type === COMPONENT_INSTANCE_TYPE &&\n      node.props.componentId === id\n    ) {\n      found = node.id;\n    }\n  });\n  return found;\n}\n\n/** What to do about a part that isn't live, for who may and may not publish it. */\nfunction publishWords(part: UnpublishedPart): string {\n  return part.mayPublish\n    ? \"Publish it: when you publish the page, you're offered to publish it too.\"\n    : \"Ask someone who can publish it to do so.\";\n}\n\n/** One part the page uses that isn't published. */\nfunction unpublishedResult(\n  part: UnpublishedPart,\n  page: ResolvedPage\n): PageCheckResult {\n  const title = part.title ?? \"Untitled\";\n  if (part.kind === \"layout\") {\n    return {\n      part: `layout:${part.id}`,\n      what: `Header & footer not published: ${title}`,\n      // Until it is live the published page falls back to the site's default\n      // set where there is one, which this check doesn't know: said so.\n      why: \"Until it's live, visitors don't see it: the page shows the site's default header and footer instead, or none if the site has no default.\",\n      todo: publishWords(part),\n    };\n  }\n  const nodeId = placementOf(page.document.nodes, part.id);\n  return {\n    ...(nodeId === undefined ? {} : { nodeId }),\n    part: `component:${part.id}`,\n    what: `Component not published: ${title}`,\n    why: \"Visitors don't see it on the live page until it's published.\",\n    todo: publishWords(part),\n  };\n}\n\n/** The components and header & footer set the page uses that aren't live. */\nexport const UNPUBLISHED_PARTS_CHECK: PageCheck = {\n  id: \"unpublished-parts\",\n  group: \"publishing\",\n  run: page =>\n    (page.facts.unpublished ?? []).map(part => unpublishedResult(part, page)),\n};\n\n/** A header or footer the page shows twice: the set's and its own. */\nexport const DOUBLED_REGIONS_CHECK: PageCheck = {\n  id: \"doubled-regions\",\n  group: \"content\",\n  run: page =>\n    (page.facts.doubledRegions ?? []).map(region => {\n      // Selects the page's own block, which is the one the author can remove.\n      const nodeId = region.nodeIds[0];\n      return {\n        ...(nodeId === undefined ? {} : { nodeId }),\n        part: region.area,\n        what: `Two ${region.area}s on this page`,\n        why: `${region.said} Visitors see both.`,\n        todo: `Remove the page's own ${region.area} block, or change the header & footer in Page settings.`,\n      };\n    }),\n};\n","/**\n * A Form block's picked form: the provider and the provider's own reference,\n * as the block stores them in `form`, and the words the panel and the canvas\n * say about one.\n *\n * @module form-picked\n */\nimport { pickedForm } from \"@nextlyhq/blocks-react\";\n\n/** The Form block, whose `form` this is. */\nexport const FORM_BLOCK = \"core/form\";\n\n/** A form a block picked from a provider. */\nexport interface PickedForm {\n  readonly provider: string;\n  readonly ref: string;\n}\n\n/**\n * The picked form `value` names, or `undefined` for a simple form: the\n * renderer's own rule (`pickedForm`), so the panel, the canvas and the page\n * the visitor gets can never read one Form two ways.\n */\nexport const pickedFormOf: (value: unknown) => PickedForm | undefined =\n  pickedForm;\n\n/**\n * Whether a Form's answers have nowhere to go: a simple form (no form picked\n * from a provider) whose \"Send to\" is empty. The one rule the canvas notice\n * and the page's checks both read.\n */\nexport function answersGoNowhere(\n  props: Readonly<Record<string, unknown>>\n): boolean {\n  if (pickedFormOf(props.form) !== undefined) return false;\n  const { action } = props;\n  return typeof action !== \"string\" || action.trim() === \"\";\n}\n\n/** What the Form block's panel and canvas say, in one place. */\nexport const FORM_WORDS = {\n  pickLabel: \"Form\",\n  pickPlaceholder: \"Pick a form\",\n  edit: \"Edit this form ↗\",\n  comesFrom: (label: string): string =>\n    `Fields, emails, spam protection and saved responses come from ${label}.`,\n  useSimple: \"or use a simple form\",\n  installHint:\n    \"Want saved responses, emails and spam protection? Install the Forms plugin. This block will then let you pick a form.\",\n  listFailed: \"Your forms couldn't be listed. Reopen the form to try again.\",\n  draft: \"Draft form: visitors can't send it until it's published\",\n  closed: \"This form is closed. Visitors see its closed message.\",\n  deleted: \"This form was deleted.\",\n  pickAnother: \"Pick another form\",\n  nowhere:\n    \"Answers have nowhere to go yet: add an address, or install the Forms plugin to save them\",\n  /** How a listed form's state is marked in the picker. */\n  stateMark: { draft: \"Draft\", closed: \"Closed\" } as Readonly<\n    Record<string, string>\n  >,\n} as const;\n","/**\n * A content check: a simple form whose answers have nowhere to go, with no\n * \"Send to\" address and no form picked from a provider, so what visitors\n * send reaches no one. The canvas says so over the block too, by the same\n * rule (`answersGoNowhere`).\n *\n * @module page-checks/form-nowhere-check\n */\nimport { walkNodes, type BlockNode } from \"@nextlyhq/blocks-engine\";\n\nimport { answersGoNowhere, FORM_BLOCK } from \"../inspector/content/form-picked\";\n\nimport type { PageCheck, PageCheckResult } from \"./page-checks\";\n\n/** Every Form on the page whose answers have nowhere to go, in page order. */\nexport const FORM_NOWHERE_CHECK: PageCheck = {\n  id: \"form-nowhere\",\n  group: \"content\",\n  run: page => {\n    const found: PageCheckResult[] = [];\n    // The page as it draws, so a Form inside a placed component is read too;\n    // the runner moves its finding to the placement the author can select.\n    walkNodes(page.drawn as BlockNode[], node => {\n      if (node.type !== FORM_BLOCK || !answersGoNowhere(node.props)) return;\n      found.push({\n        nodeId: node.id,\n        what: \"Form answers have nowhere to go\",\n        why: \"Visitors can send the form, but their answers aren’t sent or saved anywhere.\",\n        todo: \"Add an address in Send to, or install the Forms plugin to save them.\",\n        fix: { tab: \"content\", id: \"action\" },\n      });\n    });\n    return found;\n  },\n};\n","/**\n * The headings check: a page with no main heading (H1), with more than one,\n * or with a heading that skips a level, judged in the order a visitor reads\n * the page, the site's header before it and its footer after.\n *\n * Screen reader users move through a page by its headings, and the main\n * heading says what the page is. Which headings a page draws, and at what\n * level, is the renderer's page outline (`pageOutline`), the one reading of\n * it the page's anchors and its table of contents use too, so the check and\n * the page cannot disagree. The page's own component placements are drawn as\n * their blocks, each heading inside one pointing back to the placement.\n *\n * @module page-checks/heading-check\n */\nimport {\n  COLLECTION_LIST_TYPE,\n  MAX_DEPTH,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  pageOutline,\n  type OutlineHeading,\n  type OutlinePart,\n} from \"@nextlyhq/blocks-react\";\n\nimport type { PageCheck, PageCheckResult, ResolvedPage } from \"./page-checks\";\n\n/** The Heading block's type, whose Level setting holds its level. */\nconst HEADING_TYPE = \"core/heading\";\n\n/** What a heading whose words come from a field is read with here. */\nconst BOUND_WORDS = \"Bound heading\";\n\n/**\n * A Heading whose words are bound to a field, read as having words: the page\n * draws the entry's, and the outline lists only a heading with words.\n */\nfunction withBoundWords(node: BlockNode): BlockNode {\n  const { text } = node.props;\n  const empty = typeof text !== \"string\" || text.trim() === \"\";\n  if (\n    node.type !== HEADING_TYPE ||\n    node.bindings?.text === undefined ||\n    !empty\n  ) {\n    return node;\n  }\n  return { ...node, props: { ...node.props, text: BOUND_WORDS } };\n}\n\n/** The drawn blocks, each bound Heading read with words, down the tree. */\nfunction withBoundHeadings(list: readonly BlockNode[], depth = 0): BlockNode[] {\n  return list.map(stored => {\n    const node = withBoundWords(stored);\n    if (node.slots === undefined || depth >= MAX_DEPTH) return node;\n    const slots = Object.fromEntries(\n      Object.entries(node.slots)\n        // A Collection list draws its entries or its empty state, never both:\n        // its entries are read, so the two can't count as one page.\n        .filter(\n          ([slot]) => node.type !== COLLECTION_LIST_TYPE || slot !== \"empty\"\n        )\n        .map(([slot, children]) => [\n          slot,\n          Array.isArray(children)\n            ? withBoundHeadings(children, depth + 1)\n            : children,\n        ])\n    );\n    return { ...node, slots };\n  });\n}\n\n/** Where a heading is, as a finding names it and points to it. */\nfunction placeOf(heading: OutlineHeading): {\n  readonly where: string;\n  readonly at: Pick<PageCheckResult, \"nodeId\" | \"fix\">;\n} {\n  if (heading.area !== \"content\") {\n    return { where: ` in the site ${heading.area}`, at: {} };\n  }\n  // One a component drew is moved to its placement by the runner.\n  return {\n    where: \"\",\n    at: {\n      nodeId: heading.node.id,\n      // A Heading's level is its Level setting; one in rich text has none.\n      ...(heading.node.type === HEADING_TYPE\n        ? { fix: { tab: \"content\", id: \"level\" } }\n        : {}),\n    },\n  };\n}\n\n/** The finding for an H1 after the first one. */\nfunction secondMain(place: ReturnType<typeof placeOf>): PageCheckResult {\n  return {\n    ...place.at,\n    part: \"second-h1\",\n    what: `More than one main heading (H1)${place.where}`,\n    why: \"A page has one main topic. Two main headings leave screen reader users unsure which one is the page’s title.\",\n    todo: \"Keep one Heading 1 and set the others to Heading 2.\",\n  };\n}\n\n/** The finding for a heading more than one level below the one before. */\nfunction skipped(\n  place: ReturnType<typeof placeOf>,\n  before: number,\n  level: number\n): PageCheckResult {\n  return {\n    ...place.at,\n    part: \"skipped\",\n    what: `Heading skips a level${place.where}: H${String(before)}, then H${String(level)}`,\n    why: \"People who move through the page by its headings may think they missed a section.\",\n    todo: `Set this heading to Heading ${String(before + 1)}, or add the level in between.`,\n  };\n}\n\n/** The page's heading problems, page-wide first, then in reading order. */\nfunction headingFindings(page: ResolvedPage): PageCheckResult[] {\n  const drawn = withBoundHeadings(page.drawn);\n  const part = (area: \"header\" | \"footer\"): OutlinePart[] =>\n    page.regions\n      .filter(region => region.area === area)\n      .map(region => ({\n        area,\n        nodes: withBoundHeadings(region.document.nodes),\n      }));\n  const { headings } = pageOutline([\n    ...part(\"header\"),\n    { area: \"content\", nodes: drawn },\n    ...part(\"footer\"),\n  ]);\n  const found: PageCheckResult[] = [];\n  if (!headings.some(heading => heading.level === 1)) {\n    found.push({\n      part: \"no-h1\",\n      what: \"Page has no main heading (H1)\",\n      why: \"Screen reader users look for the main heading to learn what the page is about.\",\n      todo: \"Set the page’s main title to Heading 1.\",\n    });\n  }\n  let mainSeen = false;\n  headings.forEach((heading, index) => {\n    const place = placeOf(heading);\n    if (heading.level === 1) {\n      if (mainSeen) found.push(secondMain(place));\n      mainSeen = true;\n    }\n    const before = headings[index - 1]?.level;\n    if (before !== undefined && heading.level > before + 1) {\n      found.push(skipped(place, before, heading.level));\n    }\n  });\n  return found;\n}\n\n/** No H1, a second H1, or a skipped level, across header, page and footer. */\nexport const HEADING_CHECK: PageCheck = {\n  id: \"headings\",\n  group: \"accessibility\",\n  run: headingFindings,\n};\n","/**\n * The first accessibility check: an image a visitor sees, with no alt text\n * and not marked decorative, which a screen reader then announces by its\n * file name or not at all.\n *\n * It judges only what the page itself decides, read the way the block reads\n * it (`image-group`): decorative first, then an alt the page stores (an empty\n * one included, the block's own way to say \"decorative\"), then the library's.\n * So it leaves alone an image whose picture comes from the media library,\n * whose words come from there, an alt text bound to a field, and an image\n * with no picture yet, which draws nothing to describe. An image whose\n * picture is bound to a field is listed more softly, as \"may be missing\":\n * each entry brings its own picture, and some may have no words.\n *\n * Which props are an image's alt text is the inspector's answer\n * (`imageGroupOf`), so the check finds every block the panel draws an alt\n * field for, and its fix opens that field.\n *\n * @module page-checks/image-alt-check\n */\nimport { walkNodes, type BlockNode } from \"@nextlyhq/blocks-engine\";\n\nimport {\n  altModeOf,\n  imageGroupOf,\n  type ImageGroup,\n} from \"../inspector/content/image-group\";\n\nimport type { PageCheck, PageCheckResult, ResolvedPage } from \"./page-checks\";\nimport { bound, holds } from \"./stored-values\";\n\n/** The props a block's image is drawn from, where it has an alt text. */\nfunction imageOf(\n  node: BlockNode,\n  page: ResolvedPage\n): Required<ImageGroup> | undefined {\n  const declared = page.blocks(node.type)?.props;\n  if (declared === undefined) return undefined;\n  const group = imageGroupOf(\n    Object.entries(declared).flatMap(([name, schema]) =>\n      schema === undefined ? [] : [{ name, schema }]\n    )\n  );\n  return group?.alt === undefined || group.source === undefined\n    ? undefined\n    : { alt: group.alt, source: group.source };\n}\n\n/**\n * What the page says of an image's words: described (an alt of its own or\n * decorative, a bound alt, a picture from the library, which brings the\n * library's, or no picture at all), missing, or possibly missing, where the\n * picture is bound to a field and each entry's may come with none.\n */\nfunction altState(\n  node: BlockNode,\n  { alt, source }: Required<ImageGroup>\n): \"described\" | \"missing\" | \"may-be-missing\" {\n  if (altModeOf(alt, node.props) !== \"library\" || bound(node, alt.alt)) {\n    return \"described\";\n  }\n  if (bound(node, source.media) || bound(node, source.address)) {\n    return \"may-be-missing\";\n  }\n  if (holds(node.props[source.media])) return \"described\";\n  return holds(node.props[source.address]) ? \"missing\" : \"described\";\n}\n\n/** The finding for one image, or nothing when it is described or exempt. */\nfunction missingAlt(\n  node: BlockNode,\n  page: ResolvedPage\n): PageCheckResult | undefined {\n  const image = imageOf(node, page);\n  const state = image === undefined ? \"described\" : altState(node, image);\n  if (image === undefined || state === \"described\") return undefined;\n  const fix = { tab: \"content\", id: image.alt.alt } as const;\n  if (state === \"may-be-missing\") {\n    return {\n      nodeId: node.id,\n      part: \"may-be-missing\",\n      what: \"Image may be missing alt text\",\n      why: \"Its picture comes from a field, and a picture there may have no alt text, so screen readers can’t describe it.\",\n      todo: \"Write alt text here, bind Alt text to a field, or tick “Decorative, no alt text” if it only decorates.\",\n      fix,\n    };\n  }\n  return {\n    nodeId: node.id,\n    what: \"Image has no alt text\",\n    why: \"Screen readers can’t describe the picture to people who can’t see it.\",\n    todo: \"Describe the picture in Alt text, or tick “Decorative, no alt text” if it only decorates.\",\n    fix,\n  };\n}\n\n/** Every image on the page with no alt text, in page order. */\nexport const IMAGE_ALT_CHECK: PageCheck = {\n  id: \"image-alt\",\n  group: \"accessibility\",\n  run: page => {\n    const found: PageCheckResult[] = [];\n    walkNodes(page.drawn as BlockNode[], node => {\n      const finding = missingAlt(node, page);\n      if (finding !== undefined) found.push(finding);\n    });\n    return found;\n  },\n};\n","/**\n * The labels check: a form field with no label, and an embed with no title.\n *\n * A screen reader reads a field's label when the field is reached, and an\n * embed's title to say what the frame holds; without either, people hear\n * only \"edit text\" or \"frame\". A form field with no label is sent under its\n * name, which is a worse label than one an author writes. A bound title is\n * the entry's to give, and an embed with no address draws nothing yet.\n *\n * @module page-checks/labels-check\n */\nimport { walkNodes, type BlockNode } from \"@nextlyhq/blocks-engine\";\n\nimport type { PageCheck, PageCheckResult } from \"./page-checks\";\n\n/** A value's text, trimmed; anything that is not text reads as none. */\nfunction textOf(value: unknown): string {\n  return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/**\n * Whether the Form draws its own fields: not while it names another\n * provider's form, which draws that form's fields instead. `simple` is the\n * page builder's own provider, the block's own fields, as the renderer reads\n * the setting.\n */\nfunction drawsOwnFields(form: unknown): boolean {\n  if (typeof form !== \"object\" || form === null) return true;\n  const { provider } = form as { provider?: unknown };\n  return (\n    typeof provider !== \"string\" || provider === \"\" || provider === \"simple\"\n  );\n}\n\n/** Each of the Form's fields with no label of its own. */\nfunction formFindings(node: BlockNode): PageCheckResult[] {\n  if (!drawsOwnFields(node.props.form)) return [];\n  const fields = node.props.fields;\n  if (!Array.isArray(fields)) return [];\n  return fields.flatMap((field: unknown, index): PageCheckResult[] => {\n    const label =\n      typeof field === \"object\" && field !== null\n        ? textOf((field as { label?: unknown }).label)\n        : \"\";\n    if (label !== \"\") return [];\n    return [\n      {\n        nodeId: node.id,\n        part: `field-${String(index)}`,\n        what: `Form field ${String(index + 1)} has no label`,\n        why: \"Screen readers announce only the kind of field, so people can’t tell what to enter.\",\n        todo: \"Give the field a Label, like “Your email”.\",\n        fix: { tab: \"content\", id: \"fields\" },\n      },\n    ];\n  });\n}\n\n/** An Embed that shows something with no title to say what. */\nfunction embedFindings(node: BlockNode): PageCheckResult[] {\n  const shows =\n    textOf(node.props.src) !== \"\" || node.bindings?.src !== undefined;\n  if (\n    !shows ||\n    textOf(node.props.title) !== \"\" ||\n    node.bindings?.title !== undefined\n  ) {\n    return [];\n  }\n  return [\n    {\n      nodeId: node.id,\n      what: \"Embed has no title\",\n      why: \"Screen readers announce it as just “frame”, so people can’t tell what’s in it.\",\n      todo: \"Say what the embed shows in Screen reader label, like “Product demo video”.\",\n      fix: { tab: \"content\", id: \"title\" },\n    },\n  ];\n}\n\n/** Every unlabelled form field and untitled embed on the page. */\nexport const LABELS_CHECK: PageCheck = {\n  id: \"labels\",\n  group: \"accessibility\",\n  run: page => {\n    const found: PageCheckResult[] = [];\n    walkNodes(page.drawn as BlockNode[], node => {\n      if (node.type === \"core/form\") found.push(...formFindings(node));\n      else if (node.type === \"core/embed\") found.push(...embedFindings(node));\n    });\n    return found;\n  },\n};\n","/**\n * The link text check: a link or button with no words, or with only vague\n * ones (\"click here\", \"read more\"), and a linked icon with no label.\n *\n * Screen reader users often list a page's links and buttons on their own, so\n * each one's words must say where it goes or what it does without the text\n * around it. A screen reader label stands in for a button's words, and words\n * bound to a field are the entry's to give. The vague-text list is English,\n * the language the builder edits.\n *\n * @module page-checks/link-text-check\n */\nimport { walkNodes, type BlockNode } from \"@nextlyhq/blocks-engine\";\n\nimport type { PageCheck, PageCheckResult } from \"./page-checks\";\nimport { eachRichTextNode, richTextWords } from \"./rich-text-parts\";\n\n/** Words that say nothing of where a link goes, compared as normalized. */\nconst VAGUE_WORDS: ReadonlySet<string> = new Set([\n  \"click here\",\n  \"click\",\n  \"here\",\n  \"read more\",\n  \"more\",\n  \"learn more\",\n  \"more info\",\n  \"more information\",\n  \"find out more\",\n  \"details\",\n  \"link\",\n  \"this link\",\n  \"this\",\n  \"go\",\n  \"continue\",\n]);\n\n/** Words as compared: lower case, spaces collapsed, edge punctuation gone. */\nfunction normalized(words: string): string {\n  return words\n    .toLowerCase()\n    .replace(/\\s+/g, \" \")\n    .replace(/^[\\s\\p{P}]+|[\\s\\p{P}]+$/gu, \"\");\n}\n\n/** Whether the words only say \"click here\" or the like. */\nfunction isVague(words: string): boolean {\n  return VAGUE_WORDS.has(normalized(words));\n}\n\n/** A prop's text, trimmed; anything that is not text reads as none. */\nfunction textOf(value: unknown): string {\n  return typeof value === \"string\" ? value.trim() : \"\";\n}\n\n/** Whether a stored address has somewhere to go, as a link is drawn. */\nfunction goesSomewhere(address: unknown): boolean {\n  return textOf(address) !== \"\";\n}\n\n/** Whether a prop is bound to a field. */\nfunction bound(node: BlockNode, prop: string): boolean {\n  return node.bindings?.[prop] !== undefined;\n}\n\n/** Whether a block links somewhere: an address, an entry, or a bound one. */\nfunction links(node: BlockNode): boolean {\n  const { href, entryCollection, entryId } = node.props;\n  return (\n    textOf(href) !== \"\" ||\n    bound(node, \"href\") ||\n    (textOf(entryCollection) !== \"\" && textOf(entryId) !== \"\")\n  );\n}\n\nconst WHY_EMPTY =\n  \"Screen readers announce it as just “link” or “button”, so people can’t tell what it does.\";\nconst WHY_VAGUE =\n  \"People who list a page’s links hear only these words, out of context, so they can’t tell where it goes.\";\n\n/** A Button with no words, or only vague ones. */\nfunction buttonFindings(node: BlockNode): PageCheckResult[] {\n  if (bound(node, \"ariaLabel\")) return [];\n  // A Screen reader label is what screen readers say in place of the words,\n  // so it is the one judged where it is set.\n  const ariaLabel = textOf(node.props.ariaLabel);\n  if (ariaLabel !== \"\") {\n    return isVague(ariaLabel)\n      ? [\n          {\n            nodeId: node.id,\n            what: \"Screen reader label doesn’t say where it goes\",\n            why: WHY_VAGUE,\n            todo: \"Say where it goes in Screen reader label, like “See pricing”.\",\n            fix: { tab: \"content\", id: \"ariaLabel\" },\n          },\n        ]\n      : [];\n  }\n  if (bound(node, \"label\")) return [];\n  const label = textOf(node.props.label);\n  const fix = { tab: \"content\", id: \"label\" } as const;\n  if (label === \"\") {\n    return [\n      {\n        nodeId: node.id,\n        what: \"Button has no text\",\n        why: WHY_EMPTY,\n        todo: \"Write what the button does in Label.\",\n        fix,\n      },\n    ];\n  }\n  if (!isVague(label)) return [];\n  return [\n    {\n      nodeId: node.id,\n      what: \"Button text doesn’t say where it goes\",\n      why: WHY_VAGUE,\n      todo: \"Say where it goes in Label, like “See pricing”, or add a Screen reader label.\",\n      fix,\n    },\n  ];\n}\n\n/** An Icon that links somewhere with no label to read in its place. */\nfunction iconFindings(node: BlockNode): PageCheckResult[] {\n  if (!links(node) || textOf(node.props.label) !== \"\" || bound(node, \"label\")) {\n    return [];\n  }\n  return [\n    {\n      nodeId: node.id,\n      what: \"Icon button has no label\",\n      why: \"Screen readers can’t read a picture of an icon, so people can’t tell what it does.\",\n      todo: \"Say what it does in Screen reader label, like “Open the menu”.\",\n      fix: { tab: \"content\", id: \"label\" },\n    },\n  ];\n}\n\n/** A link's words judged: none, vague, or fine. */\nfunction linkWordsFinding(\n  node: BlockNode,\n  words: string,\n  part: string,\n  fix?: PageCheckResult[\"fix\"]\n): PageCheckResult | undefined {\n  const at = { nodeId: node.id, part, ...(fix === undefined ? {} : { fix }) };\n  if (words.trim() === \"\") {\n    return {\n      ...at,\n      what: \"Link has no text\",\n      why: WHY_EMPTY,\n      todo: \"Give the link words that say where it goes.\",\n    };\n  }\n  if (!isVague(words)) return undefined;\n  return {\n    ...at,\n    what: `Link text doesn’t say where it goes: “${words.trim()}”`,\n    why: WHY_VAGUE,\n    todo: \"Use words that say where it goes, like “Read our pricing”.\",\n  };\n}\n\n/** The buttons a rich text button node draws: one, or each of a group's. */\nfunction richButtons(part: {\n  readonly type: string;\n  readonly buttons?: unknown;\n}): Record<string, unknown>[] {\n  if (part.type === \"button-link\") return [part];\n  if (part.type !== \"button-group\" || !Array.isArray(part.buttons)) return [];\n  return part.buttons.filter(\n    (entry): entry is Record<string, unknown> =>\n      typeof entry === \"object\" && entry !== null\n  );\n}\n\n/** A rich text button with only vague words; one with none isn't drawn. */\nfunction richButtonFinding(\n  node: BlockNode,\n  button: Record<string, unknown>,\n  part: string\n): PageCheckResult | undefined {\n  const words = textOf(button.text);\n  // Drawn only with somewhere to go: one with none isn't on the page.\n  if (!goesSomewhere(button.url) || words === \"\" || !isVague(words)) {\n    return undefined;\n  }\n  return {\n    nodeId: node.id,\n    part,\n    what: `Button text doesn’t say where it goes: “${words}”`,\n    why: WHY_VAGUE,\n    todo: \"Use words that say where it goes, like “See pricing”.\",\n  };\n}\n\n/** A Heading that links, judged by its words; the links in rich text. */\nfunction linkFindings(node: BlockNode): PageCheckResult[] {\n  const found: PageCheckResult[] = [];\n  if (node.type === \"core/heading\" && links(node) && !bound(node, \"text\")) {\n    const finding = linkWordsFinding(node, textOf(node.props.text), \"heading\", {\n      tab: \"content\",\n      id: \"text\",\n    });\n    if (finding !== undefined) found.push(finding);\n  }\n  let index = 0;\n  eachRichTextNode(node, part => {\n    if (part.type === \"link\") {\n      // A link with nowhere to go is drawn as its plain words.\n      if (!goesSomewhere(part.url)) return;\n      const finding = linkWordsFinding(\n        node,\n        richTextWords(part),\n        `link-${String(index)}`\n      );\n      index += 1;\n      if (finding !== undefined) found.push(finding);\n      return;\n    }\n    for (const button of richButtons(part)) {\n      const finding = richButtonFinding(\n        node,\n        button,\n        `button-${String(index)}`\n      );\n      index += 1;\n      if (finding !== undefined) found.push(finding);\n    }\n  });\n  return found;\n}\n\n/** Every link and button on the page with no words, or only vague ones. */\nexport const LINK_TEXT_CHECK: PageCheck = {\n  id: \"link-text\",\n  group: \"accessibility\",\n  run: page => {\n    const found: PageCheckResult[] = [];\n    walkNodes(page.drawn as BlockNode[], node => {\n      if (node.type === \"core/button\") found.push(...buttonFindings(node));\n      else if (node.type === \"core/icon\") found.push(...iconFindings(node));\n      else found.push(...linkFindings(node));\n    });\n    return found;\n  },\n};\n","/**\n * The checks the builder itself runs on every page. A plugin's checks are\n * offered beside them, never in place of them.\n *\n * @module page-checks/core-checks\n * @experimental Grows as the builder's own checks are written.\n */\nimport { CONTRAST_CHECK } from \"./contrast-check\";\nimport { EMPTY_BLOCKS_CHECK } from \"./empty-blocks-check\";\nimport {\n  BINDINGS_TO_FIX_CHECK,\n  DOUBLED_REGIONS_CHECK,\n  PAGE_DATA_CHECK,\n  UNPUBLISHED_PARTS_CHECK,\n} from \"./fact-checks\";\nimport { FORM_NOWHERE_CHECK } from \"./form-nowhere-check\";\nimport { HEADING_CHECK } from \"./heading-check\";\nimport { IMAGE_ALT_CHECK } from \"./image-alt-check\";\nimport { LABELS_CHECK } from \"./labels-check\";\nimport { LINK_TEXT_CHECK } from \"./link-text-check\";\nimport type { PageCheck } from \"./page-checks\";\n\n/** The builder's own checks, in the order they are run. */\nexport const CORE_PAGE_CHECKS: readonly PageCheck[] = [\n  IMAGE_ALT_CHECK,\n  HEADING_CHECK,\n  LINK_TEXT_CHECK,\n  LABELS_CHECK,\n  CONTRAST_CHECK,\n  // Content and data: the page as stored and as the editor reads and counts it.\n  BINDINGS_TO_FIX_CHECK,\n  PAGE_DATA_CHECK,\n  DOUBLED_REGIONS_CHECK,\n  EMPTY_BLOCKS_CHECK,\n  FORM_NOWHERE_CHECK,\n  // Publishing: the parts it uses that are not live.\n  UNPUBLISHED_PARTS_CHECK,\n];\n","/**\n * `@nextlyhq/builder` — the visual page-builder editor.\n *\n * The editor half of the page builder: the shell, the canvas, and the op store\n * that everything in it either produces or reads. It is deliberately NOT a\n * renderer.\n *\n * **The invariant this package is built around**: the canvas renders documents\n * through `@nextlyhq/blocks-react` — the same renderer that serves published\n * pages — and re-implements nothing downstream of the document model. Read-path\n * preparation, condition gating and slot pruning are consumed from the engine's\n * own entry points, never reproduced here.\n *\n * No test enforces it. Reimplementing rendering on React and the engine\n * imports exactly the same packages as delegating to the renderer, so the\n * layering guard cannot tell the two apart; it narrows what may be imported,\n * which makes the shortcut inconvenient rather than impossible.\n *\n * That rule is not stylistic. `plugin-page-builder` carries a second renderer of\n * its own, and the two disagree about condition gating in OPPOSITE directions —\n * one failing closed, the other not evaluating conditions at all. Sharing a\n * predicate would not have prevented that, because sharing a predicate does not\n * share the decision to call it; only sharing the entry point does.\n *\n * **Public surface**, all of it `@experimental` while the editor is being built\n * out:\n *\n * - {@link BUILDER_PACKAGE_NAME}, for diagnostics that report what a host loaded.\n * - The frame geometry — {@link pointToCanvas}, {@link pointToHost},\n *   {@link rectToHost}, {@link frameContentOrigin}, {@link frameInsetOf} — also\n *   published at `@nextlyhq/builder/geometry`, which carries no `\"use client\"`\n *   banner and so is reachable from a server component.\n * - The shell's declared bounds and preference port, also published at\n *   `@nextlyhq/builder/shell-state`.\n * - `BuilderShell` itself at `@nextlyhq/builder/shell`, which is the ONLY entry\n *   carrying `\"use client\"`. This one does not, so everything above is callable\n *   from a Server Component.\n * - `@nextlyhq/builder/styles.css`, the chrome's stylesheet. It SUPPLEMENTS the\n *   design system's rather than restating it, so a host loads\n *   `@nextlyhq/ui/styles.css` — or the admin's, which contains it — alongside.\n *   The shell says so in the console, in development, when it is missing.\n *\n * - {@link deepActiveElement} and {@link isHTMLElement}, which read focus and\n *   node kinds without a realm's constructors.\n *\n * - The op store — {@link applyOp}, {@link OpError} and the op vocabulary —\n *   which every edit is expressed in and which derives each edit's inverse.\n *\n * The package was created ahead of any of this so its name could be claimed on\n * npm, because trusted publishing cannot perform a package's first publish and\n * the bootstrap script will not claim a name that is not already a workspace\n * package.\n *\n * @module @nextlyhq/builder\n */\n\n/**\n * This package's npm name, for diagnostics that report which packages a host\n * has loaded.\n *\n * The name and not the version. A version literal in source would be stale one\n * release after it was written, because every release bumps this package in\n * lockstep with its siblings; reporting a version means injecting the manifest's\n * value at build time, which belongs with the surface that displays it rather\n * than with a constant nothing reads yet.\n */\nexport const BUILDER_PACKAGE_NAME = \"@nextlyhq/builder\" as const;\n\n/**\n * The one mapping between the canvas frame and the host page.\n *\n * Exported because the acceptance harness measures against the SAME arithmetic\n * the editor positions with. A browser test carrying its own copy certifies its\n * own stale copy, and would keep passing through exactly the correction it\n * exists to catch.\n */\nexport {\n  FrameGeometryError,\n  frameContentOrigin,\n  pointToCanvas,\n  pointToHost,\n  rectToHost,\n  type FrameGeometry,\n  type FrameInset,\n  type Point,\n  type Rect,\n} from \"./geometry\";\n\n/**\n * The DOM read the mapping cannot do for itself.\n *\n * Exported beside the geometry because the inset is the one input every caller\n * has to measure, and the one they get wrong: documenting the recipe as\n * `clientLeft`/`clientTop` left three call sites short by the padding.\n */\nexport { frameInsetOf } from \"./canvas/geometry-dom\";\n\n/**\n * @experimental Node kinds and focus, read the same way in every realm.\n *\n * Exported for the host that mounts the editor, which reads focus and checks\n * elements around a canvas that may live in a same-origin iframe: there an\n * `instanceof HTMLElement` check fails for the frame's nodes, and the host\n * document's `activeElement` names the iframe rather than what is focused in it.\n */\nexport { deepActiveElement, isHTMLElement } from \"./canvas/dom-kind\";\n\n/**\n * @experimental The op store: the vocabulary every edit is expressed in, and\n * how one applies.\n *\n * Exported from the package entry because the entry is what `tsdown` builds. A\n * module the entry does not reference is absent from `dist` however thoroughly\n * it is tested — the tests import it by relative path and pass, while a consumer\n * installing the package finds nothing.\n *\n * `OpPosition` travels with the vocabulary because `BuilderOp` is written in\n * terms of it: a consumer that can name an op but not the position inside one\n * cannot construct an insert or a move.\n */\nexport {\n  applyOp,\n  OpError,\n  type AppliedOp,\n  type BuilderOp,\n  type NodePatch,\n  type OpPosition,\n} from \"./op-vocabulary\";\n\n/**\n * @experimental The editor shell's props.\n *\n * The TYPE only. `BuilderShell` itself lives at `@nextlyhq/builder/shell`, and\n * this entry deliberately does not re-export it: a value re-export would pull\n * the component into this bundle, which would then need the `\"use client\"`\n * banner, which would make every export above it a client reference — including\n * the geometry, which a Server Component is supposed to be able to call.\n *\n * A type costs nothing at runtime, so it can be described from here.\n */\nexport type { BuilderShellProps, PanelView } from \"./shell/builder-shell\";\n\n/**\n * @experimental What a host lends the inspector for a block's own custom CSS\n * (`InspectorPanelProps.customCss`): its checker, given only to a person who\n * may change the site's code. A type, so it costs this entry nothing.\n */\nexport type { BlockCustomCssAccess } from \"./inspector/custom-css\";\n\n/**\n * @experimental The shell's own decisions: which panels the rail offers, the\n * bounds handed to the panel library, and the preference port.\n *\n * `DEFAULT_PREFERENCES` travels with them for a host that mirrors a\n * preference outside the shell — the zoom and the editing breakpoint are\n * reported after the shell has read them, which is later than such a host's\n * own first render. Reading the default from here rather than restating it is\n * what keeps that first render honest, and keeps it that way if the default\n * here ever changes.\n */\nexport {\n  DEFAULT_PREFERENCES,\n  LEFT_PANELS,\n  MIN_CANVAS_WIDTH,\n  MIN_SHELL_WIDTH,\n  PANEL_BOUNDS,\n  RAIL_WIDTH,\n} from \"./shell-state\";\nexport type {\n  LeftPanel,\n  PreferenceStore,\n  ShellPreferences,\n} from \"./shell-state\";\n/**\n * @experimental A `localStorage` store under a key of the host's own, for\n * something the editor remembers beside the shell's chrome (a list of\n * recently opened pages, say). Outside a browser it remembers nothing.\n */\nexport { browserStore } from \"./shell-state\";\n\n/**\n * @experimental The command palette's TYPES only.\n *\n * The component itself carries `\"use client\"` and is reached through\n * `@nextlyhq/builder/shell` beside `BuilderShell`, for the same reason that\n * entry exists: this root is server-callable, and re-exporting a client\n * component from it would make importing the geometry pull React into a server\n * bundle.\n *\n * A type costs nothing at runtime, so a host can describe its command list\n * without reaching for the client entry.\n */\nexport type {\n  BuilderCommand,\n  CommandPaletteProps,\n} from \"./shell/command-palette\";\n\n/**\n * @experimental The drop rules: where a dragged block can land, and which of\n * those places a pointer means.\n *\n * From this entry rather than from `/shell`, because none of it touches React —\n * it is arithmetic over measured rectangles, and the split is what lets the\n * acceptance harness and a host reason about a drop without loading an editor.\n *\n * The same argument as the geometry above, and the same hazard: a harness\n * carrying its own copy of this ranking would certify its own copy, and would\n * keep passing through exactly the correction it exists to catch.\n *\n * `PlacementTarget` and `SlotSource` travel with them because the region types\n * are written in terms of both: a consumer that can name a region but not what\n * it accepts cannot ask the nesting rule about one.\n */\nexport {\n  axisOfRects,\n  collectRegions,\n  movingSubtree,\n  regionAt,\n  resolveDrop,\n  ROOT_REGION,\n  targetsInRegion,\n  type DropAxis,\n  type DropQuery,\n  type DropRefusal,\n  type DropRegion,\n  type DropResolution,\n  type DropTarget,\n  type RectSource,\n} from \"./canvas/drop-targets\";\nexport {\n  blockAllowedAt,\n  registryBlockSource,\n  registrySlotSource,\n  slotsShowingEmpty,\n  // The engine spells the placement destination, and this package re-exports\n  // that spelling rather than a second one: the drop and region types below are\n  // written in terms of it, and a consumer holding one has to be able to hand it\n  // straight to the nesting rule. `InsertTarget` is the name it used to carry,\n  // kept for one release so a host importing it still compiles.\n  type PlacementTarget,\n  /** @deprecated Import `PlacementTarget`; its discriminant is `kind`. */\n  type InsertTarget,\n  // The shape a host has to supply for the panel to offer saved patterns. The\n  // prop has existed since the tier landed and the type did not, so a host\n  // filling it had to infer the contract from the panel's props — including the\n  // two absences that are not interchangeable, `keywords` and `content`, each\n  // of which arrives as `null` from a stored row rather than missing.\n  type SavedPattern,\n  // The same contract for the component tier, published with it rather than\n  // after, so the host filling `components` never has to infer it.\n  type SavedComponent,\n  type SlotSource,\n} from \"./panels/add/inserter\";\n\n/**\n * @experimental When a drag is allowed to change the target it has committed\n * to.\n *\n * Separate from the drop rules above because it decides something different:\n * those say what the pointer is over NOW, this says when that answer may\n * replace the one being drawn. Keeping them apart is what lets a region\n * boundary be an ordinary candidate change rather than a case of its own.\n */\nexport {\n  nextTargetSwitchState,\n  NO_TARGET,\n  type PendingTarget,\n  type TargetId,\n  type TargetSwitchState,\n} from \"./canvas/target-switch\";\n\n/**\n * @experimental The document as a structure: the layers tree, the path to a\n * block, and what a search leaves standing.\n *\n * From this entry rather than from `/shell`, because none of it touches React.\n * A host that wants an outline of a stored document — a summary, an export, an\n * agent describing a page — needs the tree without needing an editor.\n */\nexport {\n  ancestorIds,\n  blockNameOf,\n  componentTitles,\n  filterLayers,\n  layerLabel,\n  layersOf,\n  pathTo,\n  type ComponentTitleOf,\n  type LayerNode,\n  type LayerSearch,\n} from \"./panels/layers/layers\";\nexport { blockLabel } from \"./panels/add/inserter\";\n\n/**\n * @experimental Bring one block into view by its id, inside the canvas root a\n * caller names. The one way the editor scrolls to a block it was asked to\n * show, whichever surface asked.\n */\nexport { revealNode } from \"./canvas/reveal-node\";\n/**\n * A binding as a person reads it on this platform (\"⌘K\" on a Mac, \"Ctrl+K\"\n * elsewhere), for a host drawing a shortcut hint beside its own control.\n *\n * @experimental\n */\nexport { keyHint } from \"./shell/key-hint\";\n\n/**\n * @experimental Whether the editor may move or delete a block the author has\n * locked.\n *\n * From this entry because it is plain functions over a document. A host or an\n * agent deciding whether an action is permitted has to ask the SAME question\n * the editor asks — a second reading of `node.locked` would miss that deleting\n * a container is refused by a lock anywhere inside it, while moving one is not.\n */\nexport { isLocked, lockBlockingDelete, lockBlockingMove } from \"./locking\";\n\n/**\n * @experimental How a lock reads across a whole selection.\n *\n * From this entry because it is a plain function over a document, and because\n * anything showing a lock for several blocks needs the same THREE answers the\n * inspector uses. A surface that collapsed \"some of these\" into on or off would\n * tell an author something false about half of what they selected.\n */\nexport { lockStateOf, type LockState } from \"./inspector/inspector\";\n\n/**\n * @experimental What a selected component instance exposes for editing, and\n * the ops that set, clear and reset one exposed property.\n *\n * From this entry because they are plain functions over a document and the\n * canvas's definition lookup. An agent asked to \"change the header's title on\n * this page\" needs the same rows the inspector draws — read back from the\n * resolver, so a row shows what the page shows — and the same override write,\n * which keeps every other override and omits the record when the last one\n * goes. A second implementation would drop `componentId` on its first edit.\n */\nexport {\n  EDITABLE_EXPOSED_TYPES,\n  inspectInstance,\n  overridesPatch,\n  partOfComponentSentence,\n  resetOverrideOp,\n  setOverrideOp,\n  type ExposedRow,\n  type InstanceInspection,\n  type OrphanedOverride,\n} from \"./inspector/instance-inspector\";\n\n/**\n * @experimental Duplicating a block: the copy, and where it goes.\n *\n * From this entry because it is a plain function over a document. An agent\n * asked to \"make three of these\" needs the same copy the editor makes — one\n * that re-ids the whole subtree and drops the DOM id — and a second\n * implementation would produce a document with two nodes sharing an id.\n */\nexport {\n  blockDuplication,\n  COPY_SUFFIX,\n  type BlockDuplication,\n} from \"./canvas/duplicate-block\";\n\n/**\n * @experimental Delete, duplicate and lock across a whole selection.\n *\n * From this entry because each is a plain function returning ops. An agent\n * asked to \"remove these six\" needs the same plan the editor makes — including\n * that one lock refuses the whole group, and that copies must be planned in\n * reverse so each lands beside its own original.\n */\nexport {\n  isRefusal,\n  selectionDeletion,\n  selectionDuplication,\n  selectionLock,\n  selectionMove,\n  type SelectionDuplication,\n  type SelectionEdit,\n  type SelectionMove,\n  type SelectionMovePlan,\n  type SelectionPlan,\n  type SelectionRefusal,\n} from \"./canvas/selection-ops\";\n\n/**\n * @experimental What \"the selection\" is once it can hold more than one block.\n *\n * From this entry because every part of it is a plain function over a document.\n * A host, an agent, or a surface answering \"what is selected\" needs the same\n * normalisation the editor uses — a second reading would let one of them act on\n * a container AND something inside it, which deletes the child twice.\n */\nexport {\n  EMPTY_SELECTION,\n  applySelection,\n  documentOrder,\n  normalizeSelection,\n  pruneSelection,\n  rangeBetween,\n  type BlockSelection,\n  type SelectionMode,\n} from \"./canvas/selection\";\n\n/**\n * @experimental The palette's command list, as a plain function over state.\n *\n * From this entry because a host assembling its own palette — or an agent\n * enumerating what the editor can do right now — needs the same list the editor\n * offers, and availability derived from a second reading of the lock and move\n * rules is how the two come to disagree.\n */\n/**\n * @experimental How large the canvas draws the page.\n *\n * Pure, so it stays on this entry: a host reads a stored preference and hands\n * the result to the canvas, and neither half needs a component to do it.\n */\nexport {\n  FIT_ZOOM,\n  MAX_ZOOM,\n  MIN_ZOOM,\n  ZOOM_STEPS,\n  readZoom,\n  steppedZoom,\n  writeZoom,\n  type CanvasZoom,\n} from \"./canvas/canvas-zoom\";\n\n/**\n * @experimental The device an author edits at once the device they chose is\n * removed from the site's breakpoints.\n *\n * Pure, so it is on this entry beside the zoom model: a host keeps the set it\n * last drew with and asks this when a new one arrives.\n */\nexport { fallbackBreakpoint } from \"./canvas/canvas-width\";\n\nexport {\n  BLOCK_GROUP,\n  EDITOR_GROUP,\n  HISTORY_GROUP,\n  blockActionRunners,\n  builderCommands,\n  type BuilderCommandsInput,\n  type CommandVerbs,\n} from \"./shell/builder-commands\";\n\n/**\n * @experimental Why a composition verb refused, in words an author can act on.\n *\n * From this entry because the surface that phrases a refusal is not always one\n * of the editor's own: the form that names a pattern is the host's, and it has\n * to say the same thing the toolbar said about the same selection. A second\n * phrasing of one cause is how an author is told two different things about one\n * refusal.\n */\nexport {\n  compositionRefusalReason,\n  isPlanProblem,\n} from \"./canvas/composition-refusal\";\n\n/**\n * @experimental Who owns Escape while the editor is on screen.\n *\n * From this entry because the rule is a plain function over the DOM and a\n * selection. A host embedding the editor beside its own Escape handling needs\n * the same answer the editor uses, and a second reading of it is how the two\n * end up both claiming the key or both releasing it.\n */\nexport {\n  CANVAS_ESCAPE_PRIORITY,\n  escapeOutcome,\n  isTextEntry,\n  modalIsOpen,\n  type EscapeOutcome,\n} from \"./canvas/canvas-escape\";\n\n/**\n * @experimental What the floating toolbar offers, and where it sits.\n *\n * From this entry because both halves are plain functions. The action list is\n * the same set of questions an agent asks before proposing a structural edit —\n * whether this block can move, whether a lock forbids removing it — answered by\n * the rules the editor itself uses rather than by a second reading of them.\n */\nexport {\n  TOOLBAR_GAP_PX,\n  toolbarActions,\n  toolbarPlacement,\n  unionRect,\n  type ComponentVerbsOffer,\n  type ToolbarAction,\n  type ToolbarActionId,\n  type ToolbarPlacement,\n  type ToolbarSize,\n} from \"./canvas/toolbar-actions\";\n\n/**\n * @experimental The style controls SDK: what a property offers, and how a\n * control reads, previews and writes it.\n *\n * From this entry because every piece is a plain function over a catalog entry\n * or a style envelope. The controls a property offers are DERIVED from\n * `catalog.ts` rather than listed, so a property added to the engine gains an\n * editor with no code here — and an agent asked to \"set the bottom margin\"\n * addresses the value through the same functions the panel does, rather than\n * reaching into `node.styles` with its own idea of where a side lives.\n *\n * No control renders yet. This is the contract they will be built on.\n */\nexport {\n  styleControlsFor,\n  SUPPORTED_LEAF_KINDS,\n  type StyleControl,\n  type StyleControlKind,\n  type StyleControlOptions,\n  type StyleControlSet,\n  type StyleControlVariants,\n} from \"./styles/style-controls\";\n\n/**\n * @experimental Addressing one control's value inside a node's style envelope.\n *\n * From this entry because the envelope is `state × breakpoint × property` and\n * a caller that spelled that path itself would be a second answer to where a\n * value lives. Validation is the catalog's, so a refused value comes back with\n * the catalog's own reasons rather than a control's guess at them.\n */\nexport {\n  readStyleValue,\n  styleClearOp,\n  styleValueAtPath,\n  styleWriteOp,\n  styleWriteOps,\n  type StyleAddress,\n  type StylePolicy,\n  type StyleWrite,\n  type StyleWriteRequest,\n} from \"./styles/style-values\";\n\n/**\n * @experimental Whether a control's value was authored here, inherited, or\n * never set.\n *\n * From this entry because it is a pure classification over the compiler's own\n * provenance record. Anything showing where a value came from — a dot beside a\n * control, an agent explaining why a page looks as it does — needs the answer\n * the compiler already wrote, not a second walk of the cascade.\n */\nexport {\n  styleProvenance,\n  type StyleProvenance,\n  type StyleProvenanceQuery,\n} from \"./styles/style-provenance\";\n\n/**\n * @experimental Previewing a value mid-drag, and committing it once.\n *\n * From this entry because the preview is compiled through the same function\n * that emits the published stylesheet, so what a drag shows is what a release\n * would store. The rule sits at the compiler's own specificity and wins on\n * document order, so the element carrying it belongs AFTER the compiled sheet.\n */\nexport {\n  scrubCommitOp,\n  scrubPreviewCss,\n  scrubStateFragments,\n  type ScrubPreview,\n  type ScrubTarget,\n} from \"./styles/style-scrub\";\n\n/**\n * @experimental Where a control's custom behaviour lives, referenced by name.\n *\n * From this entry because it is the seam a host configures. The catalog stays\n * data — it is read by validation, the compiler, the inspector and the\n * generated reference docs, and a function stored in it could not be\n * serialized, reasoned about, or documented — so behaviour is registered under\n * a key derived from the catalog's own identity instead. Ships empty.\n */\nexport {\n  NO_STYLE_CONTROL_BEHAVIOUR,\n  styleControlBehaviour,\n  styleControlBehaviourKey,\n  type StyleControlBehaviour,\n  type StyleControlBehaviours,\n} from \"./styles/style-control-behaviour\";\n\n/**\n * @experimental What the selected block offers on the Style tab.\n *\n * From this entry because it is a plain function over a document and the\n * registry. A host drawing its own style surface — or an agent asked \"what can\n * I set on this block\" — needs the same answer the panel draws from, which is\n * `supports` read through the engine rather than a second reading of it. The\n * panel itself is behind the client banner in `./shell`.\n */\nexport {\n  inspectStyle,\n  type InspectedStyleProperty,\n  type StyleInspection,\n  type StyleInspectionOptions,\n  type StyleSection,\n} from \"./inspector/style-inspector/style-inspector\";\n\n/**\n * What a SELECTION of blocks shares at one style address, and what changes it.\n *\n * The model half of batch editing, exported for the same reason the style\n * inspection above is: a host drawing its own multi-selection surface — or an\n * agent asked \"do these six blocks agree on this padding\" — needs the answer\n * this package already computes rather than a second implementation of it. The\n * shipped panel is behind the client banner in `./shell`.\n *\n * Headless by construction: it answers what a shared value MEANS and what ops\n * would change it, and knows nothing about how either is drawn.\n *\n * @experimental\n */\nexport {\n  sharedValueAt,\n  batchStyleWriteOps,\n  batchStyleClearOps,\n  type SharedValue,\n  type BatchStyleWrite,\n} from \"./styles/batch-style\";\n\n/**\n * Page checks: the check contract, the findings with the setting that fixes\n * each, the groups, and the builder's own checks, run over a document.\n *\n * From this entry because the checks are plain functions over a document and\n * the registry: a script, a route or an agent asking what a stored page needs\n * gets the findings the editor lists for its draft. The list itself is\n * behind the client banner in `./shell`.\n *\n * @experimental\n */\nexport {\n  pageCheckGroups,\n  runPageChecks,\n  type CheckedPage,\n  type PageCheck,\n  type PageCheckGroup,\n  type PageCheckGroupView,\n  type PageCheckNote,\n  type PageCheckReport,\n  type PageCheckResult,\n  type PageFinding,\n  type PageRegionDocument,\n  type ResolvedPage,\n} from \"./page-checks/page-checks\";\nexport { CORE_PAGE_CHECKS } from \"./page-checks/core-checks\";\n// What a caller knows of the page beyond its document, for the content,\n// data and publishing checks: a script hands in the same facts the editor does.\nexport type {\n  BindingToFix,\n  DoubledRegionFact,\n  PageDataFact,\n  PageFacts,\n  UnpublishedPart,\n} from \"./page-checks/page-facts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,eAAe;;AAGrB,MAAM,iBAAiB;;;;;;;;AASvB,SAAgB,UAAU,OAAkC;CAC1D,OACE,OAAO,UAAU,YACjB,UAAU,QACV,cAAc,SACd,MAAM,aAAa;AAEvB;;;;;;;;;AAUA,SAAgB,cAAc,OAAsC;CAClE,OAAO,UAAU,KAAK,KAAK,MAAM,iBAAiB;AACpD;;AAGA,SAAgB,WAAW,OAA8C;CACvE,OAAO,cAAc,KAAK,KAAK,MAAM,cAAc;AACrD;;AAGA,SAAgB,QAAQ,OAA2C;CACjE,OAAO,cAAc,KAAK,KAAK,MAAM,cAAc;AACrD;;AAkBA,SAAgB,SAAS,OAA4C;CACnE,OAAO,cAAc,KAAK,KAAK,MAAM,cAAc;AACrD;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,kBAAkB,KAA+B;CAC/D,IAAI,SAAS,IAAI;CACjB,OAAO,SAAS,MAAM,GAAG;EACvB,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,MAAM;EACpB,MAAM,UAAU,MAAM;EACtB,IACE,YAAY,QACZ,YAAY,MAAM,QAClB,YAAY,MAAM,iBAElB;EAEF,SAAS;CACX;CACA,OAAO;AACT;;;;;;;;;;;;AC9CA,SAAgB,aAAa,OAAsC;CACjE,MAAM,QAAQ,MAAM,cAAc,aAA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