{"version":3,"file":"shell.mjs","names":["filterEntries","TAB_WORDS","filterEntries","TAB_WORDS","CHOICES","laidOut","isComposite","judge","BASE_BREAKPOINT","storedAt","written","SIZES","sizeOf","regionAt","positionOf","roleOf","labelOf","placementTypesOf","registryBlockSource","blockNameOf","pathTo","lockedAncestorOf","lockedAncestorIn","ACCORDION_BLOCK","PROPERTY","placementOf","optionsOf","offered","sectionsOf","ACCORDION_BLOCK","lockedAncestorOf","compileTrace","fractionOf","PAGE_SCHEME_ATTRIBUTE","FOCUS_RING","deviceLabel","FOCUS_RING","shownLabel","NO_MARKS","deviceLabel","FOLD_HINT","drawnRows","DATE_LABELS","choicesFor","valueFor","settled","listeners","X_POINTS","Y_POINTS","SPREADS","readStack","planWrap","chosenWords","storedText","idsIn","watchers","watch","SEARCH_PAUSE_MS","EMPTY","editableNode","targetFor","keepFocus","movedTo","LinkForm","storedText","UnsupportedField","CONTROLS","ChoiceValue","inSentence","KIND_WORDS","valueFor","BoundField","countWords","hasNoSource","holds","OPPOSITE","NO_REGION","placeOf","toggled","COPIED_FOR_MS","ACCORDION_BLOCK","deviceLabel","giveBack","placeHandles","isColour","laidOut","placeOf","WEIGHTS","rowOf","DEFAULT_FLUID_RANGE","fluidValue","ZERO","written","counted","placesIn","rowsOf","labelOf","optionsOf","nextOrderIndex","sameLook","permittedLabel","permittedLabelWith","permittedLabel","asPermittedList","siblingsOf","copyName","positionOf","lockRefusal","placementRefusal","patternRefusal","pathTo","valueAt","exposedTarget","NO_IDS","NOTHING_MEASURED","deviceLabel","settle","ARROWS","planRepair","planDocumentRepair","toggled","positionOf","ICONS","Map","RenameField","heldWords","problemSentence","ImageIcon","RowActions","applied","ShownValue","TextValue","sourceOf","tabOf","storedString","chipWords","OptionRow","PRESETS","isRecord","refusalOf","groupOf","fits","choiceLabel","choiceLabel","noteFor","AddressField","movedTo","gridMove","EDIT_REFUSED","noteFor","NONE","storedString","storedValues","labelOf","UnsupportedField","hintFor","countOf","heldReason","DraftInput","listedOf","SharedItems","UsageLine","ImageIcon","styleCount","ancestorsOf","VariableRow","chipWords","GROUPS","choicesFor","normalised","storedText","sameIds","entriesOf","BLOCK_STYLE_WORDS","variableRead","placementTypesOf","useDraft","storedText","typedWrite","unsetWords","arrowStep","NONE","storedText","useDraft","storedText","NONE","ACROSS","storedText","variableRead","ShowMore","WhereUsed","ShowMore","StyleRow","LABEL","NONE","storedText","useDraft","settle","hintFor","ICONS","useDraft","OPPOSITE","GROUPS","flowOf","variableCss","colourOf","useDraft","storedText","arrowStep","flowOf","planWrap","CHOICES","NONE","placementOf","isRecord","NONE","SIZES","sizeOf","CHOICES","CONTAINED_PROP","writesOf","PREVIEW_PX","SAMPLE","NONE","NONE","nameOf","candidatesOf","CandidateRow","NONE","optionLabel","deviceLabel","cssNamesOf","NO_OFFERS","placeKey","refusalAt","placementRefusal","composing","BASE_BREAKPOINT","BASE_BREAKPOINT","pathTo","TRANSPARENT_WRAPPER","groupOf","movedTo","pathTo","SIDES","sameRect","BASE_BREAKPOINT","SIDES","isTokenRef","BASE_BREAKPOINT","placeOf","CONTROLS","WORDS","shownRectOf","shownRectOf","WORDS","shownRectOf","reserveRoom","release","gapKey","titleOf","gapKey","blockNameOf","positionOf","pathTo","placementRefusal","judged","markOf","RenameField","RowActions","deviceLabel","groupOf","DEFAULT_FLUID_RANGE","variableCss","DARK_KINDS","SAMPLE","plain","AddRow","RowMenu","VariableRow","shownName","rowKeys","menuActionsOf","RowEditor","RowMenu","rowLabel","nameHeld","nameRefusal","copyName","WORDS","WORDS","PAGE_SIZE","Unread","PanelNotes","Group","VariableRow","ShowMore","StyleRow","focusLater","opensMenu","Unread","PAGE_SIZE","Unread","ShowMore","pathTo","blockNameOf","ComponentMark","blockNameOf","bound","bound","blockNameOf","bound","textOf","entries","stored"],"sources":["../src/geometry.ts","../src/canvas/border-radii.ts","../src/canvas/dom-kind.ts","../src/canvas/geometry-transform.ts","../src/canvas/geometry-clip.ts","../src/canvas/geometry-dom.ts","../src/canvas/canvas-frame-context.tsx","../src/canvas/canvas-zoom.ts","../src/canvas/value-holder.ts","../src/canvas/hovered-block.tsx","../src/canvas/insertion-preview.tsx","../src/inspector/css-names-context.tsx","../src/inspector/panel-folds.ts","../src/inspector/settings-index.ts","../src/inspector/settings-filter.tsx","../src/inspector/panel-folds-context.tsx","../src/shell-state.ts","../src/shell/shell-active.ts","../src/shell/builder-notices.tsx","../src/shell/shell-preferences.ts","../src/chrome-tooltip.tsx","../src/editor-words.ts","../src/shell/editor-rail.tsx","../src/shell/docs-links.ts","../src/shell/key-hint.ts","../src/shell/help-shortcuts.ts","../src/shell/modal-keyboard-hold.ts","../src/shell/help-dialog.tsx","../src/shell/latest-callback.ts","../src/shell/shell-rail-dialogs.tsx","../src/canvas/canvas-zoom-control.tsx","../src/shell/shell-canvas-region.tsx","../src/shell/shell-region-cycling.ts","../src/shell/shell-side-panels.ts","../src/shell/dev-warn.ts","../src/shell/shell-stylesheet.ts","../src/shell/top-bar-room.ts","../src/shell/shell-top-bar.tsx","../src/shell/show-inspector.ts","../src/shell/shell-regions.tsx","../src/shell/builder-shell.tsx","../src/styles/style-values.ts","../src/styles/breakpoints.ts","../src/canvas/canvas-width.ts","../src/canvas/columns-layout.ts","../src/canvas/empty-slot.ts","../src/styles/block-shortcuts.ts","../src/panels/add/insertion-candidates.ts","../src/panels/add/inserter-types.ts","../src/panels/add/inserter-catalog.ts","../src/panels/add/inserter-palette.ts","../src/panels/add/inserter.ts","../src/conditions/condition-gate.ts","../src/inspector/custom-css.ts","../src/placement-props.ts","../src/panels/layers/layers.ts","../src/lock-refusal.ts","../src/locking.ts","../src/canvas/drag-refusal.ts","../src/canvas/drop-targets.ts","../src/move-refusal.ts","../src/inspector/content/accordion-icon.ts","../src/inspector/content/content-control-types.ts","../src/inspector/content/gallery-pictures.ts","../src/inspector/inspector-sections.ts","../src/prop-label.ts","../src/inspector/inspector.ts","../src/styles/style-trace.ts","../src/shell/command-palette.tsx","../src/canvas/rendered-nodes.ts","../src/canvas/canvas-addressing.ts","../src/canvas/canvas-chrome.ts","../src/canvas/canvas-region-placement.ts","../src/canvas/site-ground.ts","../src/canvas/canvas-regions.tsx","../src/canvas/previewed-entry.tsx","../src/canvas/canvas-block-marks.ts","../src/canvas/canvas-preview-width-field.tsx","../src/roving-radios.ts","../src/shell/breakpoint-switcher.tsx","../src/canvas/canvas-device-hidden.ts","../src/choice-list.tsx","../src/inspector/content/list-query-model.ts","../src/inspector/content/loop-sort.ts","../src/inspector/content/collection-loop-controls.tsx","../src/field-edit.ts","../src/stored-draft.ts","../src/typing-run.ts","../src/live-draft.ts","../src/inspector/style-inspector/style-keyword-labels.ts","../src/styles/style-numeric.ts","../src/styles/plain-layout.ts","../src/inspector/code-hints.ts","../src/inspector/commit-on-enter.ts","../src/inspector/css-hint.tsx","../src/inspector/content/entry-field-control.tsx","../src/inspector/content/lucide-icon-source.ts","../src/inspector/content/media-controls.tsx","../src/inspector/content/recent-icons.ts","../src/inspector/content/relation-control.tsx","../src/canvas/format-actions.tsx","../src/canvas/format-bar-state.ts","../src/canvas/inline-prop-kind.ts","../src/canvas/inline-target.ts","../src/canvas/inline-rich-text.ts","../src/inspector/content/rich-text-full-editor.tsx","../src/inspector/content/rich-text-control.tsx","../src/inspector/content/content-services.ts","../src/inspector/content/content-controls.tsx","../src/inspector/content/list-query-filter-values.tsx","../src/inspector/content/list-query-parts.tsx","../src/inspector/content/named-query-model.ts","../src/inspector/content/list-query-reading.ts","../src/inspector/content/sentence-row.tsx","../src/inspector/content/list-query-filters.tsx","../src/inspector/content/list-query-how-many.tsx","../src/inspector/content/named-query-controls.tsx","../src/inspector/content/list-query-source.tsx","../src/inspector/content/list-query-named-source.ts","../src/inspector/content/list-query-sort.tsx","../src/inspector/content/list-query-controls.tsx","../src/conditions/condition-checks.ts","../src/conditions/condition-model.ts","../src/conditions/applied-conditions.ts","../src/conditions/condition-hidden-block.tsx","../src/canvas/canvas-layout-parts.tsx","../src/canvas/page-placeholder.tsx","../src/canvas/canvas-drawn-page.tsx","../src/canvas/refusal-notice.tsx","../src/canvas/canvas-drop-refusal.tsx","../src/canvas/canvas-edited-region.ts","../src/canvas/canvas-link-guard.ts","../src/canvas/clicked-entry.ts","../src/canvas/selection.ts","../src/canvas/canvas-pointer.ts","../src/canvas/nearest-theme.ts","../src/canvas/canvas-site-surface.ts","../src/canvas/entry-content-canvas.ts","../src/canvas/canvas-entry-content-inert.ts","../src/canvas/rendered-tree.ts","../src/canvas/use-canvas-markers.ts","../src/canvas/canvas.tsx","../src/canvas/accordion-questions.ts","../src/canvas/reduced-motion.ts","../src/canvas/appear-replay.ts","../src/canvas/canvas-frame-sheet.ts","../src/canvas/canvas-preview-width.ts","../src/canvas/canvas-preview-width-edges.tsx","../src/canvas/site-chrome.ts","../src/canvas/site-chrome-cues.tsx","../src/canvas/canvas-frame.tsx","../src/styles/class-library.ts","../src/panels/design/colour-groups.ts","../src/styles/fluid-size.ts","../src/styles/style-folded.ts","../src/panels/design/tokens-studio.ts","../src/styles/style-colour.ts","../src/styles/shared-style-library.ts","../src/inspector/style-inspector/look-tiles.ts","../src/inspector/style-inspector/look-reach.ts","../src/canvas/canvas-escape.ts","../src/canvas/canvas-geometry-watch.ts","../src/canvas/canvas-tab-places.ts","../src/canvas/exposed-outline.ts","../src/canvas/component-holds.ts","../src/inspector/instance-inspector.ts","../src/inspector/style-inspector/state-switcher.tsx","../src/styles/shared-style-target.ts","../src/canvas/permitted-prose.ts","../src/canvas/composition-refusal.ts","../src/canvas/delete-block.ts","../src/canvas/entry-content-rules.ts","../src/canvas/keyboard-move.ts","../src/canvas/duplicate-block.ts","../src/canvas/selection-ops.ts","../src/canvas/selection-wrap.ts","../src/canvas/turn-into-verb.ts","../src/canvas/toolbar-actions.ts","../src/canvas/exposed-inline.ts","../src/canvas/inline-edit-outcome.ts","../src/canvas/inline-text.ts","../src/canvas/use-inline-text.ts","../src/canvas/canvas-marks.tsx","../src/canvas/canvas-drag-gesture.ts","../src/canvas/drop-indicator.tsx","../src/canvas/insertion-line-geometry.ts","../src/canvas/spacing-response.ts","../src/canvas/insertion-line.tsx","../src/canvas/region-selection.ts","../src/canvas/region-editing-scrim.tsx","../src/canvas/first-add.ts","../src/editor-history.ts","../src/editor-asks.ts","../src/kept-lock-answers.ts","../src/lock-sources.ts","../src/editor-state.ts","../src/shell/editing-target.ts","../src/shell/region-editing-bar.tsx","../src/canvas/canvas-passage.ts","../src/inspector/style-inspector/rendered-lengths.ts","../src/styles/style-subject.ts","../src/styles/side-orientation.ts","../src/canvas/use-canvas-reading.ts","../src/panels/design/block-look-rows.ts","../src/inspector/asked-setting.ts","../src/block-icon.tsx","../src/canvas/selection-offer.ts","../src/inspector/block-card.tsx","../src/panels/components/component-fields.ts","../src/inspector/component-fields-panel.tsx","../src/panels/components/component-variants.ts","../src/inspector/component-variants-panel.tsx","../src/inspector/held-by-lock.tsx","../src/inspector/custom-css-section.tsx","../src/panels/layers/layer-row-actions.ts","../src/inspector/hide-on.tsx","../src/conditions/condition-ops.ts","../src/conditions/condition-controls.tsx","../src/inspector/custom-attributes.ts","../src/inspector/advanced-panel.tsx","../src/inspector/content/link-group.ts","../src/inspector/content/link-control.tsx","../src/with-article.ts","../src/bindings/binding-format-field.tsx","../src/bindings/binding-ops.ts","../src/bindings/binding-picker-reads.ts","../src/bindings/binding-setting-source.tsx","../src/bindings/item-binding-source.ts","../src/bindings/binding-picker.tsx","../src/bindings/binding-bound-names.ts","../src/bindings/binding-notes.tsx","../src/bindings/image-binding-fallback.tsx","../src/bindings/binding-controls.tsx","../src/shell/visitor-unreadable-badges.tsx","../src/shell/visitor-unreadable-context.tsx","../src/inspector/content/list-marker-note.tsx","../src/inspector/content/image-group.ts","../src/inspector/content/image-controls.tsx","../src/inspector/content/when-clicked-control.tsx","../src/inspector/content/prop-groups.tsx","../src/inspector/content/toc-left-out-note.tsx","../src/inspector/inspector-content-fields.tsx","../src/inspector/kept-while-hidden.ts","../src/inspector/never-quote.tsx","../src/inspector/panel-section.tsx","../src/inspector/inspector-advanced-tab.tsx","../src/canvas/embed-states-model.ts","../src/styles/style-provenance.ts","../src/inspector/style-inspector/style-panel-reading.ts","../src/inspector/content/accordion-icon-field.tsx","../src/inspector/segment-choices.tsx","../src/inspector/content/columns-layout-field.tsx","../src/inspector/content/embed-sections.tsx","../src/inspector/content/form-picked.ts","../src/inspector/content/form-after-sending.tsx","../src/inspector/content/form-fields-control.tsx","../src/inspector/content/form-source-control.tsx","../src/inspector/content/form-sections.tsx","../src/inspector/content/gallery-columns.ts","../src/inspector/content/gallery-fields.tsx","../src/inspector/inspector-content-tab.tsx","../src/inspector/inspector-style-state.ts","../src/canvas/prefers-dark.ts","../src/inspector/style-inspector/editing-chips.tsx","../src/inspector/style-inspector/editing-bar.tsx","../src/inspector/style-inspector/focal-frame.ts","../src/inspector/style-inspector/look-tiles-view.tsx","../src/inspector/style-inspector/inherited-value.ts","../src/panels/design/font-library.ts","../src/styles/style-variables.ts","../src/panels/design/site-text-rows.ts","../src/panels/design/variable-choice.tsx","../src/panels/design/font-family-field.tsx","../src/inspector/style-inspector/style-field-surroundings.ts","../src/styles/batch-style.ts","../src/styles/style-baseline.ts","../src/styles/style-controls.ts","../src/styles/style-sides.ts","../src/inspector/style-inspector/style-field-target.ts","../src/inspector/style-inspector/appear-play.tsx","../src/inspector/style-inspector/block-style-words.ts","../src/inspector/style-inspector/site-default-source.ts","../src/inspector/style-inspector/spacing-box.tsx","../src/canvas/autoscroll.ts","../src/canvas/canvas-drag-types.ts","../src/canvas/target-switch.ts","../src/canvas/canvas-drag.tsx","../src/scrub-gesture.ts","../src/inspector/style-inspector/style-text-field.tsx","../src/inspector/style-inspector/spacing-presets.tsx","../src/live-gesture.ts","../src/inspector/style-inspector/label-scrub.tsx","../src/inspector/style-inspector/style-numeric-field.tsx","../src/inspector/style-inspector/spacing-side-popover.tsx","../src/inspector/style-inspector/spacing-side.tsx","../src/inspector/style-inspector/field-path-writes.ts","../src/panels/design/colour-usage.ts","../src/panels/design/variable-usage.ts","../src/panels/design/panel-actions.tsx","../src/panels/design/uses-read.ts","../src/panels/design/shared-style-details.tsx","../src/panels/design/usage-reads.tsx","../src/panels/design/variable-usage-view.tsx","../src/panels/design/built-in-colours.tsx","../src/panels/design/recent-colours.ts","../src/panels/design/variable-swatch.tsx","../src/inspector/style-inspector/style-colour-field.tsx","../src/inspector/style-inspector/aspect-ratio-field.tsx","../src/inspector/style-inspector/background-placement.ts","../src/inspector/style-inspector/raw-css.ts","../src/inspector/style-inspector/focal-point-field.tsx","../src/inspector/style-inspector/background-fields.tsx","../src/canvas/image-states-model.ts","../src/inspector/style-inspector/background-image-control.tsx","../src/inspector/style-inspector/icon-choice-field.tsx","../src/inspector/style-inspector/section-held.ts","../src/inspector/style-inspector/decoration-field.tsx","../src/inspector/style-inspector/style-alignment-icons.ts","../src/panels/design/variable-value-controls.tsx","../src/styles/shadow-css.ts","../src/inspector/style-inspector/shadow-control.tsx","../src/inspector/style-inspector/style-shadow-field.tsx","../src/inspector/style-inspector/style-value-fields.tsx","../src/inspector/style-inspector/style-control-value.tsx","../src/inspector/style-inspector/style-provenance-indicators.tsx","../src/inspector/style-inspector/type-size-pair.tsx","../src/inspector/style-inspector/style-field-shell.tsx","../src/inspector/style-inspector/spacing-box-fields.tsx","../src/inspector/style-inspector/style-property-fields.tsx","../src/inspector/style-inspector/plain-layout-controls.tsx","../src/inspector/style-inspector/plain-parent-controls.tsx","../src/inspector/style-inspector/style-inspector.ts","../src/inspector/style-inspector/css-properties.ts","../src/inspector/style-inspector/add-css-property.tsx","../src/inspector/style-inspector/block-shortcuts-field.tsx","../src/inspector/style-inspector/content-width-control.tsx","../src/inspector/style-inspector/content-width-fields.tsx","../src/inspector/style-inspector/section-padding.ts","../src/inspector/style-inspector/section-padding-fields.tsx","../src/inspector/style-inspector/style-block-shortcuts.tsx","../src/panels/design/text-style-choice.ts","../src/inspector/style-inspector/text-style-picker.tsx","../src/inspector/style-inspector/style-panel-sections.tsx","../src/inspector/style-inspector/style-inspector-panel.tsx","../src/styles/class-selector.tsx","../src/inspector/style-inspector/style-target.tsx","../src/inspector/inspector-style-tab.tsx","../src/make-component-setting.ts","../src/inspector/make-component-setting-section.tsx","../src/inspector/variant-picker.tsx","../src/inspector/instance-inspector-panel.tsx","../src/inspector/look-inspector.tsx","../src/inspector/many-blocks-panel.tsx","../src/inspector/panel-options.tsx","../src/inspector/settings-entries.ts","../src/inspector/inspector-panel.tsx","../src/shell/component-banner.tsx","../src/canvas/variant-preview.tsx","../src/canvas/canvas-preview-tags.tsx","../src/panels/add/insert-panel-notices.tsx","../src/panels/add/insert-lock.ts","../src/panels/add/insert-placement-words.tsx","../src/panels/add/insert-usage.ts","../src/panels/add/insert-panel-offers.ts","../src/panels/add/insert-panel-summon.ts","../src/panels/add/insert-panel-tiles.tsx","../src/panels/add/insert-panel.tsx","../src/panels/add/insert-picker-keys.ts","../src/panels/add/insert-picker-choices.tsx","../src/panels/add/insert-picker-body.tsx","../src/panels/add/insert-picker.tsx","../src/panels/add/insert-picker-anchor.ts","../src/panels/components/components-panel.tsx","../src/shared/miniature-surface.tsx","../src/shared/document-miniature.tsx","../src/shell/breakpoint-editor.tsx","../src/shell/breakpoint-manager.tsx","../src/shell/dark-preview-switch.tsx","../src/canvas/block-clipboard.ts","../src/canvas/block-clipboard-transport.ts","../src/canvas/block-clipboard-events.tsx","../src/shell/keyboard-announcements.ts","../src/canvas/block-clipboard-verbs.ts","../src/styles/style-clipboard.ts","../src/styles/style-clipboard-verbs.ts","../src/shell/block-actions-context.ts","../src/shell/builder-commands.ts","../src/shell/keyboard-actions-options.ts","../src/shell/keyboard-actions.tsx","../src/canvas/selection-actions.ts","../src/shell/editor-command-palette.tsx","../src/canvas/block-context-menu.tsx","../src/canvas/format-bar.tsx","../src/canvas/scroll-clearance.ts","../src/canvas/block-toolbar.tsx","../src/canvas/spacing-bands.ts","../src/canvas/spacing-gap.ts","../src/styles/style-scrub.ts","../src/canvas/spacing-drag.ts","../src/canvas/spacing-handles.tsx","../src/canvas/spacing-overlay.tsx","../src/shell/repair-ops.ts","../src/shell/repair-notice.tsx","../src/canvas/empty-container-appender.tsx","../src/canvas/gallery-states-model.ts","../src/canvas/image-states.tsx","../src/canvas/embed-states.tsx","../src/canvas/form-states-model.ts","../src/canvas/form-states.tsx","../src/canvas/collection-list-item.ts","../src/canvas/collection-list-picker.tsx","../src/canvas/columns-layout-picker.tsx","../src/canvas/reveal-node.ts","../src/canvas/first-add-choosers.tsx","../src/canvas/accordion-add-question.tsx","../src/conditions/use-applied-conditions.ts","../src/canvas/page-gaps.ts","../src/canvas/page-start-words.ts","../src/canvas/page-start-area.tsx","../src/canvas/page-inserters.tsx","../src/shell/starter-page.ts","../src/canvas/rich-passage.ts","../src/canvas/format-turn-into.ts","../src/canvas/use-inline-rich-text.ts","../src/canvas/use-inline-editing.ts","../src/canvas/open-passages.ts","../src/shell/onboarding.ts","../src/shell/onboarding-checklist.tsx","../src/panels/layers/entry-content-layers.tsx","../src/panels/layers/layer-row-menu.tsx","../src/panels/layers/layer-row-shortcuts.tsx","../src/panels/layers/layers-drop.ts","../src/panels/layers/layers-drag.tsx","../src/panels/layers/layers-regions.tsx","../src/panels/layers/layers-panel.tsx","../src/panels/design/design-group-toggle.tsx","../src/panels/design/colour-cleanup.tsx","../src/panels/design/in-place-field.ts","../src/panels/design/colour-group-ui.tsx","../src/panels/design/colour-usage-filter.tsx","../src/panels/design/colours-of-view.tsx","../src/panels/design/fluid-popover.tsx","../src/panels/design/editor-field-commit.ts","../src/panels/design/variable-contrast.ts","../src/panels/design/variable-popup-parts.tsx","../src/panels/design/variable-removal.ts","../src/panels/design/variable-shadow-value.tsx","../src/panels/design/variable-editor.tsx","../src/panels/design/site-text-panel.tsx","../src/panels/design/tokens-panel-open-variable.ts","../src/panels/design/variable-adds.tsx","../src/panels/design/colour-move-items.tsx","../src/panels/design/variable-row-menu.tsx","../src/panels/design/variable-row.tsx","../src/panels/design/variable-together-reads.ts","../src/styles/block-style-plans.ts","../src/panels/design/tokens-transfer-extras.ts","../src/panels/design/tokens-transfer-gaps.ts","../src/panels/design/tokens-transfer-reach.ts","../src/panels/design/tokens-transfer.ts","../src/panels/design/variables-transfer-fonts.tsx","../src/panels/design/variables-transfer.tsx","../src/panels/design/tokens-panel.tsx","../src/panels/design/styles-tab-matches.ts","../src/styles/block-style-actions.ts","../src/panels/design/block-style-row-menu.tsx","../src/panels/design/block-looks-group.tsx","../src/panels/design/shared-style-row.tsx","../src/panels/design/shared-styles-list.tsx","../src/panels/design/shared-styles-types.ts","../src/panels/design/shared-styles-remove-unused.tsx","../src/panels/design/shared-styles-usage.ts","../src/panels/design/shared-styles-panel.tsx","../src/panels/design/site-font-roles-model.ts","../src/panels/design/site-font-roles.tsx","../src/shell/breadcrumb.tsx","../src/shell/read-budget.ts","../src/shell/unread-places.ts","../src/shell/read-budget-meter.tsx","../src/panels/design/shared-style-save-dialog.tsx","../src/panels/design/text-style-parts.ts","../src/panels/design/text-style-editor.tsx","../src/panels/design/text-style-plans.ts","../src/panels/design/text-styles-section.tsx","../src/panels/design/font-choice-menu.tsx","../src/panels/design/font-preview.ts","../src/panels/design/font-catalogue-view.tsx","../src/panels/design/font-upload-editor.tsx","../src/panels/design/font-uses.ts","../src/panels/design/font-uses-view.tsx","../src/panels/design/fonts-panel.tsx","../src/shell/exposure-picker.tsx","../src/page-checks/rich-text-parts.ts","../src/page-checks/contrast-check.ts","../src/page-checks/stored-values.ts","../src/page-checks/empty-blocks-check.ts","../src/page-checks/fact-checks.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/page-checks/fix-walk.ts","../src/page-checks/page-checks.ts","../src/page-checks/page-checks-list.tsx","../src/page-checks/page-checks-chip.tsx"],"sourcesContent":["/**\n * The one place geometry crosses between the canvas frame and the host page.\n *\n * The canvas renders inside an iframe and the editor's chrome — the insertion\n * indicator, selection outlines, drag affordances — is drawn in the host\n * document above it. Every one of those has to answer the same question: where\n * is this canvas rectangle, in host coordinates?\n *\n * **Asked here and nowhere else.** Two modules computing that separately agree\n * on the day they are written and drift the first time anything changes — a\n * scroll offset one of them forgot, a zoom the other did not apply — and the\n * symptom is an indicator drawn a few pixels off the gap it names. That class of\n * bug is not caught by either module's own tests, because each is correct about\n * the question it asked.\n *\n * How much of that is ENFORCED, stated plainly because the difference matters —\n * and the honest answer is: none of it, by a boundary.\n *\n * A sibling test scans for a rectangle READ across the frame elsewhere in this\n * package, and it recognises a bounded set of spellings: a property access, a\n * string element access, a destructured binding. A name assembled at runtime, a\n * `Reflect.get` or a property descriptor all walk past it, and its own tests say\n * so. It narrows the easy paths; it is not a wall.\n *\n * Nothing checks the other half at all. A module handed an origin and a scale can\n * open-code the arithmetic without touching the DOM, and two numbers multiplied\n * and added look like any other code.\n *\n * What holds instead is narrower and true: the e2e helper adapts these\n * functions rather than restating them, and every caller needing a content\n * origin asks {@link frameContentOrigin} for one.\n *\n * The functions are pure and take plain numbers rather than DOM nodes, so the\n * mapping can be exercised without a browser and the DOM reads stay at the edge.\n *\n * @module geometry\n */\n\n/** A point in whichever coordinate space the caller is working in. */\nexport interface Point {\n  readonly x: number;\n  readonly y: number;\n}\n\n/** A rectangle, in the shape `getBoundingClientRect` reports. */\nexport interface Rect {\n  readonly x: number;\n  readonly y: number;\n  readonly width: number;\n  readonly height: number;\n}\n\n/** Four physical edge lengths, in unscaled CSS pixels. */\nexport interface EdgeLengths {\n  readonly top: number;\n  readonly right: number;\n  readonly bottom: number;\n  readonly left: number;\n}\n\n/**\n * How much bigger a measured rectangle is than the layout it came from.\n *\n * Per-axis because a transform scales the two independently. `{ x: 1, y: 1 }`\n * for an untransformed element, which is the ordinary case.\n */\nexport interface Scale {\n  readonly x: number;\n  readonly y: number;\n}\n\n/**\n * How the canvas frame sits inside the host page.\n *\n * `origin` is where the frame's CONTENT viewport lands in host coordinates, and\n * the word content is load-bearing. `getBoundingClientRect` on an iframe reports\n * its BORDER box, while every rectangle read inside the frame is relative to the\n * content viewport — so on a frame with any border or padding the two differ,\n * and an overlay built from the border box sits a couple of scaled pixels out\n * at every point. Measure that difference with {@link frameInsetOf}; the inset\n * is border PLUS padding, and `clientLeft`/`clientTop` alone are short by the\n * padding. A canvas that never sets\n * `border: none` gets the browser default and the fault is present from the\n * first render, which is exactly the sort of near-miss that reads as \"the\n * indicator feels slightly off\" rather than as a bug.\n *\n * Build one with {@link frameContentOrigin} rather than adding that correction\n * at the call site. Reading `clientLeft` needs a browser; turning it into an\n * origin is arithmetic over plain numbers, and splitting the two puts the sum\n * in every caller that measured a frame — where each writes it separately and\n * a correction reaches only the one being edited.\n *\n * `scale` is the visual scale the host applies to the frame: a zoomed-out canvas\n * at 50% has `scale: 0.5`.\n *\n * Scroll INSIDE the frame is deliberately not a field. A rectangle read from\n * inside the frame is already relative to the frame's viewport, so subtracting\n * its scroll would count it twice — the mistake that makes an overlay drift as\n * the canvas scrolls, rather than being wrong by a constant.\n */\nexport interface FrameGeometry {\n  readonly origin: Point;\n  readonly scale: number;\n}\n\n/**\n * A frame geometry that cannot describe a mapping.\n *\n * Thrown rather than defaulted, because every value that could stand in is\n * wrong in a way that looks right: a scale of zero maps the whole canvas onto a\n * point, a negative one mirrors it, and a non-finite one yields `NaN`\n * coordinates that place an overlay nowhere and report no error. An overlay\n * silently drawn at the wrong place is the exact failure this module exists to\n * prevent, so an unusable frame has to be loud.\n */\nexport class FrameGeometryError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"FrameGeometryError\";\n  }\n}\n\nfunction assertUsable(frame: FrameGeometry): void {\n  if (!Number.isFinite(frame.scale) || frame.scale <= 0) {\n    throw new FrameGeometryError(\n      `A frame scale of ${String(frame.scale)} describes no mapping. ` +\n        `Scale must be finite and greater than zero.`\n    );\n  }\n  if (!Number.isFinite(frame.origin.x) || !Number.isFinite(frame.origin.y)) {\n    throw new FrameGeometryError(\n      `A frame origin of (${String(frame.origin.x)}, ${String(frame.origin.y)}) ` +\n        `describes no mapping. Both coordinates must be finite.`\n    );\n  }\n}\n\n/**\n * How far the frame's content viewport sits inside its border box.\n *\n * The COMPLETE offset, border plus padding. A border alone is the tempting\n * reading, because `clientLeft`/`clientTop` report exactly that and are the\n * obvious things to reach for — but an iframe's nested viewport begins at the\n * content box, so padding displaces it too. Measured in Chromium: an 8px border\n * with 12px padding puts the content 20px in, while `clientLeft` reports 8.\n *\n * In CSS pixels of the FRAME's own untransformed space, which is the whole\n * reason this type exists rather than the caller passing two numbers. Every\n * other coordinate in this module is host space, and mixing the two is the\n * mistake {@link frameContentOrigin} exists to prevent.\n */\nexport interface FrameInset {\n  readonly left: number;\n  readonly top: number;\n}\n\n/**\n * Where the frame's content viewport starts, in host coordinates.\n *\n * `borderBox` is the corner `getBoundingClientRect` reports for the frame\n * element, and `inset` is its border-to-content offset. That offset is laid out in the\n * frame's own pixels, so a host that has scaled the frame scales the border with\n * everything else: at 50% a 2px border occupies 1 host pixel. Adding the inset\n * unscaled therefore misplaces the origin by `(1 - scale) * inset`, which is\n * zero at 100% and grows as the canvas zooms out — a fault that is invisible in\n * exactly the configuration people develop in.\n *\n * Both facts are needed together and neither is guessable from the other, which\n * is why this is a function rather than a note telling callers to add them up.\n */\nexport function frameContentOrigin(\n  borderBox: Point,\n  inset: FrameInset,\n  scale: number\n): Point {\n  assertUsable({ origin: borderBox, scale });\n  if (!Number.isFinite(inset.left) || !Number.isFinite(inset.top)) {\n    throw new FrameGeometryError(\n      `A frame inset of (${String(inset.left)}, ${String(inset.top)}) ` +\n        `describes no mapping. Both edges must be finite.`\n    );\n  }\n  return {\n    x: borderBox.x + inset.left * scale,\n    y: borderBox.y + inset.top * scale,\n  };\n}\n\n/** A point inside the canvas frame, in host coordinates. */\nexport function pointToHost(point: Point, frame: FrameGeometry): Point {\n  assertUsable(frame);\n  return {\n    x: frame.origin.x + point.x * frame.scale,\n    y: frame.origin.y + point.y * frame.scale,\n  };\n}\n\n/**\n * A point on the host page, in the canvas frame's coordinates.\n *\n * The exact inverse of {@link pointToHost}: a pointer event arrives in host\n * coordinates and has to be compared against rectangles read inside the frame,\n * which is the same mapping run backwards rather than a second one written to\n * match.\n */\nexport function pointToCanvas(point: Point, frame: FrameGeometry): Point {\n  assertUsable(frame);\n  return {\n    x: (point.x - frame.origin.x) / frame.scale,\n    y: (point.y - frame.origin.y) / frame.scale,\n  };\n}\n\n/**\n * A rectangle inside the canvas frame, in host coordinates.\n *\n * Its size scales with the frame. An overlay sized from the unscaled rectangle\n * would be correct only at 100%, and would look correct there, which is the\n * one configuration a canvas is usually looked at in.\n */\nexport function rectToHost(rect: Rect, frame: FrameGeometry): Rect {\n  const origin = pointToHost({ x: rect.x, y: rect.y }, frame);\n  return {\n    x: origin.x,\n    y: origin.y,\n    width: rect.width * frame.scale,\n    height: rect.height * frame.scale,\n  };\n}\n","/**\n * The used corner radii of a CSS box, as arithmetic over plain numbers.\n *\n * A rounded box is not the rectangle `getBoundingClientRect` reports for it, and\n * two things in this package care. The spacing overlay paints bands inside the\n * padding box, which on a rounded block curves away from the rectangle those\n * bands are cut from; and an ancestor that clips its overflow clips on that same\n * curve, so a child sitting inside all four of its padding edges can still be\n * visibly cut at a corner.\n *\n * Both need the USED radii, and reaching them from the computed value is three\n * steps that do not commute:\n *\n * 1. **Resolve.** A percentage stays a percentage in the computed value —\n *    `border-radius: 50%` computes as `\"50%\"` — and resolves against the border\n *    box, horizontally against its width and vertically against its height. A\n *    corner serializes as TWO values when it is elliptical (`\"10px 30px\"`) and\n *    one when it is not, and both forms occur.\n * 2. **Reduce.** CSS Backgrounds §5.5 shrinks every radius by a single factor\n *    when any side's two radii would overlap: `f = min(Lᵢ / Sᵢ)` over the four\n *    sides, where `Lᵢ` is the side's length and `Sᵢ` the sum of the two radii\n *    meeting it, applied to all eight radii when it comes out below one. The\n *    engine does not do this in the computed value — `border-radius: 200px` on a\n *    200×100 box still computes as `200px` while it renders as 50 — so a reader\n *    that trusts the computed value describes a corner four times the size of\n *    the one on screen. ONE factor for the whole box, not one per corner:\n *    measured, a 200×100 box with only `border-top-left-radius: 200px` draws\n *    that corner at 100, which is the box's own height constraining it through\n *    the shared factor.\n * 3. **Inset.** The padding box's radius is the border box's less that corner's\n *    two border widths, floored at zero — and NOT reduced a second time, even\n *    when the result no longer fits the padding box. Measured on a 200×100 box\n *    with `border-top-left-radius: 100px` and a 10px border: the inner curve is\n *    90, while the padding box is only 80 tall, and the engine draws the 90.\n *\n * Reducing after insetting gives different numbers than insetting after\n * reducing, and the order above is the one CSS specifies — the same box\n * separates them, since insetting first and then reducing against the 180×80\n * padding box would give 80 where the engine draws 90.\n *\n * Kept away from the DOM for the reason `spacing-bands.ts` gives about itself:\n * jsdom lays nothing out and reports every element as zero-sized, so a rule\n * written against live elements can only be exercised in a browser, while the\n * same rule written against numbers can be exercised anywhere.\n *\n * @module border-radii\n */\n\nimport type { EdgeLengths, Rect, Scale } from \"../geometry\";\n\n/**\n * One corner, as its two half-axes.\n *\n * Always a pair, never a single number: `border-radius: 10px / 30px` is one\n * declaration and an elliptical corner is what most `border-radius: 50%` boxes\n * actually have, since a non-square box resolves the two percentages against\n * different lengths.\n */\nexport interface CornerRadius {\n  /** The half-axis along the box's width. */\n  readonly x: number;\n  /** The half-axis along the box's height. */\n  readonly y: number;\n}\n\n/** The four corners, in the order the `border-radius` shorthand writes them. */\nexport interface CornerRadii {\n  readonly topLeft: CornerRadius;\n  readonly topRight: CornerRadius;\n  readonly bottomRight: CornerRadius;\n  readonly bottomLeft: CornerRadius;\n}\n\n/**\n * The four computed `border-*-radius` values, exactly as a computed style\n * reports them.\n *\n * Strings rather than numbers because that is the whole of what the DOM offers,\n * and resolving them needs the box they were declared on — which the reader has\n * and the parser would otherwise have to be told twice.\n */\nexport interface DeclaredRadii {\n  readonly topLeft: string;\n  readonly topRight: string;\n  readonly bottomRight: string;\n  readonly bottomLeft: string;\n}\n\n/** A corner with no curve at all. */\nconst SQUARE: CornerRadius = { x: 0, y: 0 };\n\n/** The radii of a box with no `border-radius`, which is nearly every box. */\nexport const SQUARE_CORNERS: CornerRadii = {\n  topLeft: SQUARE,\n  topRight: SQUARE,\n  bottomRight: SQUARE,\n  bottomLeft: SQUARE,\n};\n\n/** The four corners by name, in the order the shorthand writes them. */\nconst CORNERS = [\n  \"topLeft\",\n  \"topRight\",\n  \"bottomRight\",\n  \"bottomLeft\",\n] as const satisfies readonly (keyof CornerRadii)[];\n\n/**\n * Whether every corner is square, so no consumer needs to clip anything.\n *\n * A corner is square when EITHER half-axis is zero, not only when both are.\n * `border-radius: 40px / 0` is a legal declaration and draws a right angle: an\n * ellipse with a zero half-axis has no interior, so the corner it cuts away is\n * empty. Reading only one axis calls that corner curved and sends every consumer\n * on to divide by the other.\n */\nexport function isSquare(radii: CornerRadii): boolean {\n  return CORNERS.every(corner => radii[corner].x <= 0 || radii[corner].y <= 0);\n}\n\n/** The size of the box a radius is resolved against. */\ninterface BoxSize {\n  readonly width: number;\n  readonly height: number;\n}\n\n/**\n * One computed `<length-percentage>` against the length it is a fraction of.\n *\n * Answers UNDEFINED rather than zero for anything it cannot read, and the\n * difference is the whole point: zero means a square corner, and a value this\n * cannot resolve is a corner of UNKNOWN shape. Reading the second as the first\n * is what makes a rounded block draw square bands.\n *\n * It is reachable. A percentage inside a math function stays unresolved in the\n * computed value because it still depends on the box — measured, `border-radius:\n * calc(10% + 5px)` computes as `\"calc(10% + 5px)\"` while `calc(10px + 5px)`\n * computes as `\"15px\"` — and the catalog accepts a `calc()` length.\n *\n * An EMPTY value is the one unreadable case that is not unknown. A computed\n * style never reports a supported longhand as blank, so a blank one means the\n * engine has no such property — and an engine with no `border-radius` draws a\n * square corner, which is exactly what zero says. Treating it as unknown instead\n * would refuse every block in any renderer that does not implement the\n * property, jsdom included.\n */\nfunction lengthAgainst(token: string, basis: number): number | undefined {\n  if (token === \"\") return 0;\n  const parsed = Number.parseFloat(token);\n  if (!Number.isFinite(parsed)) return undefined;\n  const length = token.endsWith(\"%\") ? (parsed / 100) * basis : parsed;\n  // A negative radius is invalid CSS and never computes, but the floor costs\n  // nothing and keeps a hand-built input from producing an inverted corner.\n  return Math.max(0, length);\n}\n\n/**\n * One corner's computed value, which is one token or two.\n *\n * With a single token the SAME token resolves twice, once against each axis —\n * so `50%` is half the width horizontally and half the height vertically, and\n * only a length comes out equal on both.\n */\nfunction parseCorner(value: string, box: BoxSize): CornerRadius | undefined {\n  const tokens = value.trim().split(/\\s+/);\n  const horizontal = tokens[0] ?? \"0\";\n  const vertical = tokens[1] ?? horizontal;\n  const x = lengthAgainst(horizontal, box.width);\n  const y = lengthAgainst(vertical, box.height);\n  if (x === undefined || y === undefined) return undefined;\n  return { x, y };\n}\n\n/**\n * The factor CSS Backgrounds §5.5 shrinks every radius by when two meeting on\n * one side would together be longer than it.\n *\n * One factor for the whole box rather than one per side, which is what keeps the\n * corners consistent with each other: reducing only the offending side would\n * leave the two ends of an adjacent side scaled differently and the curve would\n * no longer meet the edge.\n *\n * A side with no curve on it contributes nothing — `Lᵢ / 0` is infinite, and a\n * box whose radii are all zero would otherwise reduce by `Infinity`.\n */\nfunction reductionFactor(radii: CornerRadii, box: BoxSize): number {\n  const sides = [\n    { length: box.width, sum: radii.topLeft.x + radii.topRight.x },\n    { length: box.height, sum: radii.topRight.y + radii.bottomRight.y },\n    { length: box.width, sum: radii.bottomRight.x + radii.bottomLeft.x },\n    { length: box.height, sum: radii.bottomLeft.y + radii.topLeft.y },\n  ];\n  let factor = 1;\n  for (const { length, sum } of sides) {\n    if (sum > 0) factor = Math.min(factor, length / sum);\n  }\n  return factor;\n}\n\n/** Every radius multiplied by one factor, per axis. */\nfunction mapCorners(\n  radii: CornerRadii,\n  by: (corner: CornerRadius) => CornerRadius\n): CornerRadii {\n  return {\n    topLeft: by(radii.topLeft),\n    topRight: by(radii.topRight),\n    bottomRight: by(radii.bottomRight),\n    bottomLeft: by(radii.bottomLeft),\n  };\n}\n\n/**\n * The border box's used radii: resolved against it, then reduced to fit it.\n *\n * `box` is the BORDER box, in the same units the declarations are in — unscaled\n * CSS pixels. Handing it a post-transform rectangle resolves every percentage\n * against the rendered size, which is right only while the scale is one.\n *\n * UNDEFINED when any corner cannot be resolved, which callers are expected to\n * treat as a shape they cannot describe rather than as a square one.\n */\nexport function usedCornerRadii(\n  declared: DeclaredRadii,\n  box: BoxSize\n): CornerRadii | undefined {\n  const topLeft = parseCorner(declared.topLeft, box);\n  const topRight = parseCorner(declared.topRight, box);\n  const bottomRight = parseCorner(declared.bottomRight, box);\n  const bottomLeft = parseCorner(declared.bottomLeft, box);\n  if (\n    topLeft === undefined ||\n    topRight === undefined ||\n    bottomRight === undefined ||\n    bottomLeft === undefined\n  ) {\n    return undefined;\n  }\n  const resolved: CornerRadii = { topLeft, topRight, bottomRight, bottomLeft };\n  const factor = reductionFactor(resolved, box);\n  if (factor >= 1) return resolved;\n  return mapCorners(resolved, corner => ({\n    x: corner.x * factor,\n    y: corner.y * factor,\n  }));\n}\n\n/**\n * The padding box's radii, given the border box's.\n *\n * Each half-axis loses the border width it runs alongside — the horizontal one\n * the left or right border, the vertical one the top or bottom — and a border\n * thicker than the curve squares the corner off rather than inverting it.\n */\nexport function insetCornerRadii(\n  radii: CornerRadii,\n  borders: EdgeLengths\n): CornerRadii {\n  const shrink = (value: number, by: number): number => Math.max(0, value - by);\n  return {\n    topLeft: {\n      x: shrink(radii.topLeft.x, borders.left),\n      y: shrink(radii.topLeft.y, borders.top),\n    },\n    topRight: {\n      x: shrink(radii.topRight.x, borders.right),\n      y: shrink(radii.topRight.y, borders.top),\n    },\n    bottomRight: {\n      x: shrink(radii.bottomRight.x, borders.right),\n      y: shrink(radii.bottomRight.y, borders.bottom),\n    },\n    bottomLeft: {\n      x: shrink(radii.bottomLeft.x, borders.left),\n      y: shrink(radii.bottomLeft.y, borders.bottom),\n    },\n  };\n}\n\n/**\n * The radii of a shape drawn `by` pixels outside one with these, so the two\n * stay concentric: each curve grows by the distance, and a square corner stays\n * square, as `outline-offset` draws one.\n */\nexport function outsetCornerRadii(radii: CornerRadii, by: number): CornerRadii {\n  return mapCorners(radii, corner => ({\n    x: corner.x > 0 ? corner.x + by : 0,\n    y: corner.y > 0 ? corner.y + by : 0,\n  }));\n}\n\n/**\n * Radii moved from layout pixels into the rendered pixels a transform draws\n * them at.\n *\n * Per-axis for the reason every other scale here is: `scale(2, 0.5)` is a single\n * legal value, and one factor would be right on one axis and wrong on the other.\n */\nexport function scaleCornerRadii(\n  radii: CornerRadii,\n  scale: Scale\n): CornerRadii {\n  return mapCorners(radii, corner => ({\n    x: corner.x * scale.x,\n    y: corner.y * scale.y,\n  }));\n}\n\n/** A rectangle given by its four edge COORDINATES rather than an origin and a size. */\nexport interface EdgeBounds {\n  readonly top: number;\n  readonly right: number;\n  readonly bottom: number;\n  readonly left: number;\n}\n\n/**\n * Whether a point reaching `dx` past a corner's horizontal centre and `dy` past\n * its vertical one is still inside that corner's arc.\n *\n * The two depths are measured from the arc's CENTRE — the point one radius in\n * along each axis — because that is where the ellipse is centred. A depth at or\n * below zero means the box never reaches into the corner's quarter at all on\n * that axis, which is the common case and the one that must not be mistaken for\n * a violation.\n */\nfunction insideArc(dx: number, dy: number, radius: CornerRadius): boolean {\n  if (radius.x <= 0 || radius.y <= 0) return true;\n  if (dx <= 0 || dy <= 0) return true;\n  const nx = dx / radius.x;\n  const ny = dy / radius.y;\n  return nx * nx + ny * ny <= 1;\n}\n\n/**\n * The most samples one corner arc is ever cut into.\n *\n * A rounded inner shape's extreme point in a corner is not its box corner — it\n * is a point on its own arc — so the two curves have to be compared along their\n * length rather than at one point, and the comparison is only as good as the\n * chord between samples.\n *\n * The count is DERIVED from the radius rather than fixed, because a fixed one is\n * wrong at both ends: it wastes several dozen evaluations on a four-pixel corner\n * and runs out of precision on a large one. A fixed sixty-four exceeds a\n * half-pixel allowance somewhere above a 6,600px rendered half-axis — reachable\n * on a large box, and more easily under an ancestor `scale`, where the allowance\n * would go NEGATIVE and refuse two identical flush rectangles.\n *\n * The cap bounds the cost. At this many samples the chord stays within a quarter\n * pixel of the arc out to a radius of some 210,000px, which no layout reaches;\n * past it, `roundedInsideRounded` refuses rather than answering to a precision it\n * cannot deliver.\n */\nconst MAX_ARC_SAMPLES = 512;\n\n/** The fewest, for a corner so small the chord is already the arc. */\nconst MIN_ARC_SAMPLES = 4;\n\n/**\n * How far a sampled chord can fall short of the arc it stands in for.\n *\n * The worst case sits half a step along, at `r * (1 - cos(theta / 2))` for a step\n * of `theta`. Taken off the caller's allowance rather than ignored, so the\n * approximation spends the slack instead of exceeding it.\n */\nfunction chordError(radius: number, samples: number): number {\n  return radius * (1 - Math.cos(Math.PI / (4 * samples)));\n}\n\n/**\n * The fewest samples that keep {@link chordError} within `target`.\n *\n * Inverting the expression above: a step of `2 * acos(1 - target / radius)`\n * lands exactly on the target, and a quarter turn needs that many of them.\n */\nfunction arcSamplesFor(radius: number, target: number): number {\n  if (!(radius > 0) || !(target > 0)) return MIN_ARC_SAMPLES;\n  const step = 2 * Math.acos(Math.max(-1, 1 - target / radius));\n  if (!(step > 0)) return MAX_ARC_SAMPLES;\n  const needed = Math.ceil(Math.PI / 2 / step);\n  return Math.min(MAX_ARC_SAMPLES, Math.max(MIN_ARC_SAMPLES, needed));\n}\n\n/** Which side of the box each corner sits on: -1 is left or top, 1 right or bottom. */\nconst CORNER_SIGNS = {\n  topLeft: { x: -1, y: -1 },\n  topRight: { x: 1, y: -1 },\n  bottomRight: { x: 1, y: 1 },\n  bottomLeft: { x: -1, y: 1 },\n} as const satisfies Record<keyof CornerRadii, { x: -1 | 1; y: -1 | 1 }>;\n\n/** The largest half-axis anywhere on a shape, which is what bounds the error. */\nfunction largestRadius(radii: CornerRadii): number {\n  let largest = 0;\n  for (const corner of CORNERS) {\n    largest = Math.max(largest, radii[corner].x, radii[corner].y);\n  }\n  return largest;\n}\n\n/**\n * Whether one corner of the inner shape stays inside the matching corner of the\n * outer one.\n *\n * A corner with a zero half-axis is square on BOTH axes — an ellipse with no\n * interior cuts nothing — so its radii are zeroed together before sampling\n * rather than one at a time, which would otherwise put the sampled point a\n * radius away from the box corner it should be at.\n */\nfunction cornerInside(\n  corner: keyof CornerRadii,\n  box: EdgeBounds,\n  boxRadius: CornerRadius,\n  clip: EdgeBounds,\n  clipRadius: CornerRadius,\n  slack: number,\n  samples: number\n): boolean {\n  // A square outer corner cuts nothing the straight-edge comparison has not\n  // already answered.\n  if (clipRadius.x <= 0 || clipRadius.y <= 0) return true;\n  const own = boxRadius.x > 0 && boxRadius.y > 0 ? boxRadius : SQUARE;\n  const sign = CORNER_SIGNS[corner];\n  const centre = arcCentre(sign, box, own);\n  const against = arcCentre(sign, clip, clipRadius);\n  const steps = own.x > 0 ? samples : 1;\n  for (let step = 0; step < steps; step += 1) {\n    const angle = (step / Math.max(1, steps - 1)) * (Math.PI / 2);\n    const px = centre.x + sign.x * own.x * Math.cos(angle);\n    const py = centre.y + sign.y * own.y * Math.sin(angle);\n    const dx = sign.x * (px - against.x) - slack;\n    const dy = sign.y * (py - against.y) - slack;\n    if (!insideArc(dx, dy, clipRadius)) return false;\n  }\n  return true;\n}\n\n/**\n * Where a corner's arc is centred: one radius in along each axis from it.\n *\n * The same arithmetic for the inner shape and the outer one, which is the point\n * — the two are compared in the same frame, and a sign written out twice is a\n * sign that can be written differently twice.\n */\nfunction arcCentre(\n  sign: { readonly x: -1 | 1; readonly y: -1 | 1 },\n  bounds: EdgeBounds,\n  radius: CornerRadius\n): { readonly x: number; readonly y: number } {\n  return {\n    x: sign.x < 0 ? bounds.left + radius.x : bounds.right - radius.x,\n    y: sign.y < 0 ? bounds.top + radius.y : bounds.bottom - radius.y,\n  };\n}\n\n/**\n * Whether one rounded rectangle lies inside another.\n *\n * The caller is expected to have compared the two rectangles first: this asks\n * only the question the rectangular comparison cannot, which is whether a shape\n * inside all four straight edges still pokes through one of the four arcs.\n *\n * The INNER shape's own curve is part of the question, not a detail. A rounded\n * block flush inside an equally rounded clipping container is not cut at all,\n * while its bounding rectangle's corners lie outside every one of that\n * container's arcs — so a test that reads only the rectangle refuses the\n * ordinary nested rounded card and takes the whole overlay with it.\n *\n * `slack` means the same thing here as it does for the straight edges: how far a\n * shape may overhang before the overhang is real rather than a rounding artefact\n * of two fractional measurements. The sampling bound comes off it, so the\n * approximation spends the allowance rather than exceeding it.\n */\nexport function roundedInsideRounded(\n  box: EdgeBounds,\n  boxRadii: CornerRadii,\n  clip: EdgeBounds,\n  clipRadii: CornerRadii,\n  slack: number\n): boolean {\n  const largest = largestRadius(boxRadii);\n  /*\n   * Half the allowance is spent on the approximation and half kept for the\n   * fractional measurements the slack exists for, so neither can consume the\n   * other.\n   */\n  const samples = arcSamplesFor(largest, slack / 2);\n  /*\n   * Past the cap the chords are further from the arcs than the whole allowance\n   * and this goes NEGATIVE, which is deliberate rather than a case to guard.\n   * A negative allowance makes every depth larger, so the comparison tightens\n   * instead of loosening: a shape sitting on the curve is refused while one\n   * comfortably inside is still accepted, which is exactly the right way to\n   * degrade. An explicit refusal here would throw away the second answer as\n   * well, and the arithmetic already delivers the first.\n   */\n  const allowance = slack - chordError(largest, samples);\n  return CORNERS.every(corner =>\n    cornerInside(\n      corner,\n      box,\n      boxRadii[corner],\n      clip,\n      clipRadii[corner],\n      allowance,\n      samples\n    )\n  );\n}\n\n/**\n * A rounded rectangle in the coordinate space of the element it clips.\n *\n * The shape a band must be cut to is the block's rounded box, which is a\n * different rectangle from the band — so it is stated relative to the band's own\n * origin, which is what a `clip-path` is resolved against.\n */\nexport interface RoundedShape {\n  readonly x: number;\n  readonly y: number;\n  readonly width: number;\n  readonly height: number;\n  readonly radii: CornerRadii;\n}\n\n/** Where `shape` sits inside `clipped`, in `clipped`'s own coordinates. */\nexport function roundedShapeIn(\n  clipped: Rect,\n  shape: Rect,\n  radii: CornerRadii\n): RoundedShape {\n  return {\n    x: shape.x - clipped.x,\n    y: shape.y - clipped.y,\n    width: shape.width,\n    height: shape.height,\n    radii,\n  };\n}\n\n/**\n * The shape as the `clip-path` value that cuts a band's fill to it.\n *\n * A PATH rather than `inset(... round ...)`, and that is not a style choice.\n * `inset()` resolves its radii the way `border-radius` does, which includes the\n * overlap reduction against the inset rectangle — so a padding-box curve that\n * legitimately exceeds its own box is silently shrunk by the browser and the\n * clip stops following the element's real edge.\n *\n * That case is exactly the one this module documents: an outer corner of 100\n * less a 10px border leaves an inner curve of 90 on a padding box only 80 tall,\n * and the engine draws the 90. Measured — a 180x80 element under\n * `inset(0 round 90px)` is cut at 80, so the two disagree wherever a border is\n * thick enough to matter. A path states the arcs outright and is not\n * renormalised.\n *\n * An arc with a zero radius is drawn as a straight line by the SVG path\n * grammar, so a square corner needs no special case and every shape is written\n * the same way.\n */\nexport function clipPathOf(shape: RoundedShape): string {\n  const n = (value: number): string => String(Math.round(value * 100) / 100);\n  const { radii } = shape;\n  const left = shape.x;\n  const top = shape.y;\n  const right = shape.x + shape.width;\n  const bottom = shape.y + shape.height;\n  const arc = (radius: CornerRadius, x: number, y: number): string =>\n    `A ${n(radius.x)} ${n(radius.y)} 0 0 1 ${n(x)} ${n(y)}`;\n  const steps = [\n    `M ${n(left + radii.topLeft.x)} ${n(top)}`,\n    `L ${n(right - radii.topRight.x)} ${n(top)}`,\n    arc(radii.topRight, right, top + radii.topRight.y),\n    `L ${n(right)} ${n(bottom - radii.bottomRight.y)}`,\n    arc(radii.bottomRight, right - radii.bottomRight.x, bottom),\n    `L ${n(left + radii.bottomLeft.x)} ${n(bottom)}`,\n    arc(radii.bottomLeft, left, bottom - radii.bottomLeft.y),\n    `L ${n(left)} ${n(top + radii.topLeft.y)}`,\n    arc(radii.topLeft, left + radii.topLeft.x, top),\n    \"Z\",\n  ];\n  return `path(\"${steps.join(\" \")}\")`;\n}\n","/**\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 * What an element's own transform does to its edges, worked out from numbers\n * `geometry-dom.ts` has already read.\n *\n * `renderedScale` there walks the transforms between an element and the canvas\n * root and measures the element. The arithmetic it then does on the matrices it\n * composed (which of the four edges render away from where they were laid out)\n * lives here, with the types it answers in. Nothing here reads a rectangle, so\n * a measurement still enters this package through `geometry-dom.ts` alone,\n * which `geometry-ownership.test.ts` holds.\n *\n * @module geometry-transform\n */\n\n/**\n * The cumulative transform between an element and the canvas root, reduced to\n * the two things axis-aligned chrome can use.\n *\n * `transform` is a catalog property taking a free-form CSS value, so an author\n * can scale, rotate, skew or MIRROR a block. Everything measured through\n * `getBoundingClientRect` is post-transform while every length from\n * `getComputedStyle` stays in unscaled CSS pixels, and anything combining the\n * two is wrong by whatever sits between them.\n *\n * ## Read from the matrix rather than inferred from a ratio\n *\n * Comparing the drawn box against `offsetWidth` looks equivalent and is not, in\n * three ways that all read as ordinary code:\n *\n * - `offsetWidth` is INTEGER-ROUNDED and a bounding rectangle is not, so an\n *   untransformed block of fractional width reports a scale it does not have —\n *   worst at exactly the small sizes where a band is hardest to judge by eye.\n * - A bounding rectangle is never negative, so `scaleX(-1)` divides out to an\n *   ordinary positive factor and the mirroring vanishes from the answer.\n * - A rotation or skew inflates the bounding box, so the ratio reports a scale\n *   that describes no axis at all.\n *\n * The matrix has none of those: it is exact, it is signed, and its off-diagonal\n * terms are what a rotation or skew shows up in.\n *\n * ## `describable` is a refusal, not a detail\n *\n * A band is an axis-aligned rectangle pinned to a physical side. That\n * representation has no meaning for a rotated, skewed or mirrored box — a left\n * margin on a mirrored element renders on the RIGHT — and no choice of scale\n * factor rescues it. So the answer carries whether the question is askable, and\n * chrome that cannot draw the truth draws nothing rather than something\n * confident and wrong.\n *\n * Composed up to the ROOT rather than read off the element, because a scaled\n * ancestor moves and resizes its descendants while their own transform stays\n * `none`.\n */\nexport interface RenderedScale {\n  readonly x: number;\n  readonly y: number;\n  /** False for a rotation, a skew, a reflection, or a collapse to zero. */\n  readonly describable: boolean;\n  /**\n   * The physical edges the element's OWN transform draws away from their layout\n   * position.\n   *\n   * Separated from the composed scale because the two do OPPOSITE things to a\n   * margin. **A transform does not affect layout.** An ancestor's transform\n   * scales the whole subtree it lays out, gaps included, so a margin inside one\n   * really does render smaller and `x`/`y` above are right to apply. The\n   * element's own transform moves only its rendering, while the space its margin\n   * reserves stays where the untransformed box left it — measured, a 100px block\n   * with `margin-bottom: 20px` under `scale(2)` leaves a gap of MINUS eighty\n   * pixels, drawn over the neighbour the margin is holding away.\n   *\n   * PER EDGE, and the question asked is the direct one: does this edge RENDER\n   * where it LAYS OUT. Coarser answers were tried and each was a different wrong\n   * one. Reading whether a transform is DECLARED blanks the margins of every\n   * resting hover state, since `scale(1)`, `translate(0)` and `rotate(360deg)`\n   * all compute to a non-`none` matrix that moves nothing. Reading it per AXIS\n   * blanks a valid band whenever one edge is pinned: measured,\n   * `translateY(-25px) scaleY(0.5)` on a 100px block computes to\n   * `matrix(1, 0, 0, 0.5, 0, -25)` and renders its top edge exactly where the\n   * layout put it while moving the bottom one, and `transform` is a catalog\n   * property so an author reaches that with no `transform-origin` at all.\n   *\n   * There is no finer grain below an edge, which is the point of asking the\n   * question this way rather than refining a proxy again.\n   */\n  readonly selfMoved: MovedEdges;\n  /**\n   * The composition ABOVE the element, excluding its own transform.\n   *\n   * Margins are measured with this and padding with the composed scale, because\n   * the two live in different spaces. Padding is inside the element's own\n   * transform and renders scaled with it; a margin is laid out in the PARENT's\n   * coordinates, and the element's own transform never touches the space it\n   * reserves.\n   *\n   * Measured: a 100px block with `margin-top: 28px` and a transform pinning its\n   * top edge leaves a real gap of 28 rendered pixels above it, not 14 — so a\n   * band drawn at the composed scale is half the size of the space it names.\n   */\n  readonly ancestor: { readonly x: number; readonly y: number };\n}\n\n/** Which physical edges are drawn away from where they were laid out. */\nexport interface MovedEdges {\n  readonly top: boolean;\n  readonly right: boolean;\n  readonly bottom: boolean;\n  readonly left: boolean;\n}\n\nexport const NO_EDGE_MOVED: MovedEdges = {\n  top: false,\n  right: false,\n  bottom: false,\n  left: false,\n};\n\n/**\n * How far an edge may be drawn from its layout position and still count as put.\n *\n * Half a rendered pixel: below that the band and the space it names are the same\n * pixels on screen, and refusing the band would cost an author information to\n * avoid an error nobody can see. Deliberately NOT the axis-aligned tolerance,\n * which guards serialization noise in a matrix term; this one is about what is\n * visible, and the two would drift apart if they shared a constant.\n */\nconst EDGE_STILL_PX = 0.5;\n\n/** Below this, an off-diagonal matrix term is serialization noise, not a rotation. */\nexport const AXIS_ALIGNED_TOLERANCE = 1e-9;\n\n/**\n * How far each of the box's four extremes is drawn from where it was laid out.\n *\n * A transform about an origin maps a local coordinate `v` to\n * `o + factor * (v - o) + shift`, so an extreme at `v` is displaced by\n * `(o - v) * (1 - factor) + shift`. The near extreme sits at `v = 0` and the far\n * one at `v = size`, which is the whole of the arithmetic.\n *\n * Compared in RENDERED pixels rather than local ones, because the tolerance is\n * about what an author can see: a tenth of a local pixel under a tenfold\n * ancestor scale is a visible pixel on screen, and the same displacement inside\n * a shrunken ancestor is not.\n *\n * Converted by the ANCESTOR scale, never the composed one. The displacement is\n * already expressed in the parent's coordinates — the element's own transform is\n * what produced it — so multiplying by that transform again counts it twice and\n * understates the movement by exactly the factor doing the moving. Measured, a\n * 100px block under `scaleY(0.01)` displaces each vertical extreme by 49.5\n * rendered pixels while the composed conversion answers 0.495, which is under\n * the threshold and would call a plainly moved extreme stationary.\n *\n * These are EXTREMES of the box rather than named sides, and the distinction is\n * load-bearing under a reflection: the image of `v = 0` is then the rendered\n * box's far side, so `leftX` names the displacement of the near extreme and not\n * of whatever ends up on the left. Callers that could meet a reflection refuse\n * it before reading these.\n */\nfunction endpointsMovedBy(\n  own: DOMMatrix,\n  origin: { x: number; y: number },\n  box: { width: number; height: number },\n  ancestor: { x: number; y: number }\n): { topY: boolean; bottomY: boolean; leftX: boolean; rightX: boolean } {\n  const moved = (\n    o: number,\n    v: number,\n    factor: number,\n    shift: number,\n    axisScale: number\n  ): boolean =>\n    Math.abs(((o - v) * (1 - factor) + shift) * axisScale) > EDGE_STILL_PX;\n\n  return {\n    topY: moved(origin.y, 0, own.d, own.f, ancestor.y),\n    bottomY: moved(origin.y, box.height, own.d, own.f, ancestor.y),\n    leftX: moved(origin.x, 0, own.a, own.e, ancestor.x),\n    rightX: moved(origin.x, box.width, own.a, own.e, ancestor.x),\n  };\n}\n\n/**\n * Which physical edges a single element's own transform draws away from layout.\n *\n * Asked of the MATRIX rather than of the declaration, because a declaration that\n * moves nothing is ordinary: `scale(1)`, `translate(0)`, `translateY(0)` and\n * `rotate(360deg)` all compute to a non-`none` transform and all serialize to\n * exactly `matrix(1, 0, 0, 1, 0, 0)`. They are the resting state of every hover\n * animation, so reading presence rather than effect blanks the margins of a\n * large share of real pages.\n *\n * Asked PER EDGE rather than per axis, because a transform is applied about\n * `transform-origin` and a translate composed with a scale pins one edge while\n * moving the other. Measured, `translateY(-25px) scaleY(0.5)` on a 100px block\n * renders its top edge exactly where layout put it and moves only the bottom —\n * and that needs `transform` alone, which IS a catalog property.\n *\n * An earlier version answered per axis and argued the pinned case could not\n * arise, on the grounds that `transform-origin` is not authorable here. That\n * trace was right and the conclusion drawn from it was too wide: proving one\n * MECHANISM unreachable is not proving the STATE unreachable, and composing two\n * functions of one property reaches it. The note is kept because the shape of\n * the error is worth more than the correction — the question to ask of an\n * unreachability argument is what ELSE produces the state.\n *\n * `a` and `d` are the per-axis scales and `e`/`f` the per-axis translations,\n * which is why each edge is decided by the two terms of its own axis. A rotation\n * or a skew mixes the axes and moves every edge; anything not flat in 2D is not\n * decidable by these terms at all, and all four are reported moved rather than\n * guessed at.\n *\n * There is no grain below an edge, which is the point of asking whether an edge\n * RENDERS WHERE IT LAYS OUT rather than refining a proxy for a fourth time.\n */\nexport function edgesMovedBy(\n  own: DOMMatrix | null,\n  origin: { x: number; y: number },\n  box: { width: number; height: number },\n  ancestor: { x: number; y: number }\n): MovedEdges {\n  const EVERY_EDGE: MovedEdges = {\n    top: true,\n    right: true,\n    bottom: true,\n    left: true,\n  };\n  if (own === null) return { ...NO_EDGE_MOVED };\n  /*\n   * A non-positive ancestor scale carries no margin that can be drawn, and it\n   * reaches here past the caller's own guard: that guard reads the COMPOSED\n   * matrix, and an ancestor reflection CANCELLED by the element's own reflection\n   * composes to a positive matrix. Measured, a parent at `scaleX(-1)` holding a\n   * child at `translateX(-200px) scaleX(-1)` composes to `a = 1` and passes\n   * describability while the ancestor's own `a` is still −1.\n   *\n   * Left unchecked that negative factor becomes the margin's scale, turning a\n   * positive margin into a negative extent — which the band code draws INWARD\n   * over the content while still labelling it as ordinary positive spacing. The\n   * mirrored space is real; a rectangle claiming to be it is not.\n   */\n  if (!(ancestor.x > 0) || !(ancestor.y > 0)) return EVERY_EDGE;\n  const skewed =\n    !own.is2D ||\n    Math.abs(own.b) > AXIS_ALIGNED_TOLERANCE ||\n    Math.abs(own.c) > AXIS_ALIGNED_TOLERANCE;\n  if (skewed) return EVERY_EDGE;\n\n  /*\n   * How far one edge is drawn from where it was laid out.\n   *\n   * A transform about an origin maps a local coordinate `v` to\n   * `o + factor * (v - o) + shift`, so an edge at `v` is displaced by\n   * `(o - v) * (1 - factor) + shift`. The near edge sits at `v = 0` and the far\n   * one at `v = size`, which is the whole of the arithmetic.\n   *\n   * Compared in RENDERED pixels rather than local ones, because the tolerance is\n   * about what an author can see: a tenth of a local pixel under a tenfold\n   * ancestor scale is a visible pixel on screen, and the same displacement\n   * inside a shrunken ancestor is not.\n   *\n   * Converted by the ANCESTOR scale, never the composed one. The displacement\n   * above is already expressed in the parent's coordinates — the element's own\n   * transform is what produced it — so multiplying by that transform again\n   * counts it twice and understates the movement by exactly the factor doing\n   * the moving. Measured, a 100px block under `scaleY(0.01)` displaces each\n   * vertical edge by 49.5 rendered pixels while the composed conversion answers\n   * 0.495, which is under the threshold and would call a plainly moved edge\n   * stationary.\n   */\n  const { topY, bottomY, leftX, rightX } = endpointsMovedBy(\n    own,\n    origin,\n    box,\n    ancestor\n  );\n\n  return edgesFromEndpoints({ topY, bottomY, leftX, rightX });\n}\n\n/**\n * Which edges are undrawable, given which of the box's extremes moved.\n *\n * An edge is a SEGMENT, so BOTH of its endpoints have to land where layout put\n * them. Its own coordinate is only half the question: measured,\n * `translate(30px, -25px) scaleY(0.5)` leaves the top edge's Y exactly where\n * layout had it and slides the whole edge thirty pixels sideways, so a band\n * anchored to it names pixels the margin never occupied, at exactly the right\n * height.\n *\n * The top and bottom edges therefore need the horizontal extent still, and the\n * left and right edges need the vertical extent still — which is why the four\n * answers are not independent even though the four displacements are.\n */\nfunction edgesFromEndpoints(moved: {\n  topY: boolean;\n  bottomY: boolean;\n  leftX: boolean;\n  rightX: boolean;\n}): MovedEdges {\n  const acrossStill = !moved.leftX && !moved.rightX;\n  const downStill = !moved.topY && !moved.bottomY;\n  return {\n    top: moved.topY || !acrossStill,\n    bottom: moved.bottomY || !acrossStill,\n    left: moved.leftX || !downStill,\n    right: moved.rightX || !downStill,\n  };\n}\n\n/** The resolved `transform-origin`, in local pixels from the border box's corner. */\nexport function transformOriginOf(style: CSSStyleDeclaration): {\n  x: number;\n  y: number;\n} {\n  // Two or three components, space separated, already resolved to pixels by the\n  // time computed style reports them — a keyword or a percentage never survives\n  // to here. The third is the Z origin, which an axis-aligned box ignores.\n  const parts = style.transformOrigin.split(\" \");\n  return { x: edgeWidth(parts[0] ?? \"\"), y: edgeWidth(parts[1] ?? \"\") };\n}\n\n/** A computed border width in pixels, or zero when the browser reports no number. */\nexport function edgeWidth(value: string): number {\n  const parsed = Number.parseFloat(value);\n  return Number.isFinite(parsed) ? parsed : 0;\n}\n","/**\n * Whether a clipping ancestor cuts a block, decided from what `geometry-dom.ts`\n * has already read.\n *\n * `clippedByAncestor`, `clippedByAncestorRect` and `visiblePartOf` there read\n * the block's rectangle and each ancestor's. The rest of the question lives\n * here: which computed displays clip at all, the walk over the ancestors, the\n * shape of one ancestor's clip, and the edge and corner comparisons against it.\n * Nothing here reads a rectangle, so a measurement still enters this package\n * through `geometry-dom.ts` alone, which `geometry-ownership.test.ts` holds.\n *\n * @module geometry-clip\n */\n\nimport type { Scale } from \"../geometry\";\n\nimport type { CornerRadii, EdgeBounds } from \"./border-radii\";\nimport {\n  insetCornerRadii,\n  isSquare,\n  roundedInsideRounded,\n  scaleCornerRadii,\n  usedCornerRadii,\n} from \"./border-radii\";\nimport { edgeWidth, type RenderedScale } from \"./geometry-transform\";\n\n/**\n * Computed `display` values whose generated box `overflow` does not clip.\n *\n * MEASURED across the catalog's display set in Chromium rather than read off a\n * spec table, by giving each value `overflow: hidden` and a child pulled outside\n * it, then reading the pixels. The list is wider than the inline box people\n * reach for first, and two of the entries are not guessable:\n *\n * - The internal TABLE boxes take no clip — a row, a row group, a header group\n *   and a footer group all paint a child straight through the edge — while\n *   `table`, `inline-table` and `table-cell` all clip normally.\n * - `contents` generates no box at all, so nothing clips AND\n *   `getBoundingClientRect` answers 0x0 on it. A caller that skipped this entry\n *   would compare a descendant against a zero-sized rectangle and conclude every\n *   block is outside it.\n *\n * `ruby-base`, `ruby-base-container` and `ruby-text-container` are deliberately\n * ABSENT: all three compute to plain `block` in Chromium, so they clip and an\n * entry for them would describe a value that never arrives.\n *\n * The measurement had to force overflow with a NEGATIVE MARGIN rather than an\n * oversized child, because table boxes size to their content: a wide child makes\n * them grow to fit, and \"not clipped\" then means \"never overflowed\" — which read\n * as six false entries on the first pass.\n */\nconst OVERFLOW_NEVER_CLIPS: ReadonlySet<string> = new Set([\n  \"inline\",\n  \"inline list-item\",\n  \"table-row\",\n  \"table-row-group\",\n  \"table-header-group\",\n  \"table-footer-group\",\n  \"ruby\",\n  \"ruby-text\",\n  \"contents\",\n]);\n\n/** Whether `overflow` establishes a clip on a box with this computed display. */\nexport function overflowApplies(display: string): boolean {\n  return !OVERFLOW_NEVER_CLIPS.has(display);\n}\n\n/** Cut `edges` to one ancestor's clip, on each axis the ancestor clips. */\nexport function narrowTo(\n  edges: { left: number; top: number; right: number; bottom: number },\n  context: { clipsX: boolean; clipsY: boolean; clip: EdgeBounds }\n): void {\n  if (context.clipsX) {\n    edges.left = Math.max(edges.left, context.clip.left);\n    edges.right = Math.min(edges.right, context.clip.right);\n  }\n  if (context.clipsY) {\n    edges.top = Math.max(edges.top, context.clip.top);\n    edges.bottom = Math.min(edges.bottom, context.clip.bottom);\n  }\n}\n\n/**\n * Walks the ancestors strictly between `element` and `root`, reporting\n * whether any one of them satisfies `cut`.\n *\n * Shared by {@link clippedByAncestor} and {@link clippedByAncestorRect}\n * rather than each climbing the chain on its own: the two answer different\n * questions about the same ancestor and must stop at the same first match for\n * the same reason `ancestorClipContext` is shared rather than re-derived —\n * two copies of \"which elements to ask\" agree on the day both are written and\n * are free to drift the moment either caller's walk changes.\n */\nexport function anyAncestorCuts(\n  element: Element,\n  root: Element,\n  cut: (node: Element) => boolean\n): boolean {\n  for (\n    let node: Element | null = element.parentElement;\n    node !== null && node !== root;\n    node = node.parentElement\n  ) {\n    if (cut(node)) return true;\n  }\n  return false;\n}\n\n/**\n * Whether an ancestor cuts the block's RECTANGLE — the whole of\n * {@link clippedByAncestorRect}'s verdict, and the first half of\n * {@link cutByAncestor}'s.\n *\n * ONE implementation rather than one per caller. The two questions differ by\n * the corner refinement below and by nothing else, so the straight-edge part\n * has to be the same reading in both — and it was not: written out twice, the\n * rect question guarded with `context.kind === \"clips\" && ...` while the\n * corner-aware one narrowed the union. A refusal reason added to\n * {@link AncestorClipContext} would have been gained by one caller and\n * silently skipped by the other.\n *\n * Exhaustive over the union deliberately: with no `default`, a fourth member\n * leaves this function able to return `undefined`, which its declared `boolean`\n * refuses. Both callers inherit that, which is the property the duplicate\n * version could not have.\n */\nexport function rectCut(context: AncestorClipContext, box: DOMRect): boolean {\n  switch (context.kind) {\n    case \"no-clip\":\n      return false;\n    case \"cut\":\n      return true;\n    case \"clips\":\n      return cutByEdges(box, context.clip, context.clipsX, context.clipsY);\n  }\n}\n\n/**\n * Whether a rounded clipping ancestor cuts the block at a CORNER — the\n * refinement {@link clippedByAncestor} adds and {@link clippedByAncestorRect}\n * deliberately does not.\n *\n * Only a `clips` ancestor has a curve to compare against: `no-clip` and `cut`\n * are already whole answers that {@link rectCut} gave, and asking a second\n * question about them would either re-refuse something or refuse something\n * nothing clips.\n */\nexport function cornerCut(\n  context: AncestorClipContext,\n  box: DOMRect,\n  radii: CornerRadii\n): boolean {\n  if (context.kind !== \"clips\") return false;\n  /*\n   * The BLOCK's radii are composed here too, and for the same reason the\n   * ancestor's geometry is.\n   *\n   * The caller scales them by the block's own composition, which stops below\n   * the root — so the outer curve below carries the canvas scale and the inner\n   * one does not. Compared across that difference, an oversized inner curve\n   * reads as fitting inside the outer one, and a block whose visible corner IS\n   * clipped keeps its bands and draws them over clipped pixels.\n   *\n   * Done at the comparison rather than at the call site: this is the only place\n   * that holds both curves, and asking the caller to pre-compose one of them\n   * puts half a decision somewhere that cannot see the other half.\n   */\n  const inner = scaleCornerRadii(radii, context.painted);\n  return cutByCorner(\n    box,\n    inner,\n    context.clip,\n    context.style,\n    context.scale,\n    context.clipsX && context.clipsY,\n    CLIP_SLACK_PX\n  );\n}\n\n/**\n * What one ancestor's clip means for a descendant, computed ONCE and shared\n * by {@link clippedByAncestor} (the corner-aware question) and\n * {@link clippedByAncestorRect} (the straight-edge one) — reading `overflow`,\n * composing the rendered scale and resolving the clip rectangle are the same\n * work either caller needs, and a second reading of any of them is a second\n * chance for the two to disagree about the same ancestor.\n *\n * Three outcomes rather than a boolean, because \"does not clip at all\" and\n * \"clips, but the geometry cannot be described\" are different answers a\n * caller must not conflate: the first lets the walk continue up to the next\n * ancestor, the second is itself a refusal.\n */\nexport type AncestorClipContext =\n  | { readonly kind: \"no-clip\" }\n  | { readonly kind: \"cut\" }\n  | {\n      readonly kind: \"clips\";\n      readonly clipsX: boolean;\n      readonly clipsY: boolean;\n      readonly style: CSSStyleDeclaration;\n      readonly clip: EdgeBounds;\n      readonly scale: RenderedScale;\n      readonly painted: Scale;\n    };\n\n/**\n * How far a block may sit outside a clip edge before the overhang is real.\n *\n * Half a pixel, because both rectangles are fractional and a block laid out\n * flush against its container's edge is not clipped by rounding.\n */\nconst CLIP_SLACK_PX = 0.5;\n\n/** The ancestor's PADDING edge, which is where overflow actually clips. */\nexport function clipEdges(\n  outer: DOMRect,\n  style: CSSStyleDeclaration,\n  scale: RenderedScale\n): EdgeBounds {\n  return {\n    top: outer.top + edgeWidth(style.borderTopWidth) * scale.y,\n    left: outer.left + edgeWidth(style.borderLeftWidth) * scale.x,\n    bottom: outer.bottom - edgeWidth(style.borderBottomWidth) * scale.y,\n    right: outer.right - edgeWidth(style.borderRightWidth) * scale.x,\n  };\n}\n\n/**\n * Whether the block falls outside the clip RECTANGLE, on an axis that clips.\n *\n * Each axis is asked only where it clips: a block overflowing the axis that is\n * still `visible` has its overflow rendered, and refusing it costs every band.\n */\nfunction cutByEdges(\n  box: DOMRect,\n  clip: EdgeBounds,\n  clipsX: boolean,\n  clipsY: boolean\n): boolean {\n  const cutVertically =\n    clipsY &&\n    (box.top < clip.top - CLIP_SLACK_PX ||\n      box.bottom > clip.bottom + CLIP_SLACK_PX);\n  const cutHorizontally =\n    clipsX &&\n    (box.left < clip.left - CLIP_SLACK_PX ||\n      box.right > clip.right + CLIP_SLACK_PX);\n  return cutVertically || cutHorizontally;\n}\n\n/**\n * Whether a rounded clipping ancestor cuts the block at one of its CORNERS.\n *\n * A container with `border-radius` and `overflow: hidden` clips on the curve,\n * not on the rectangle: a child inside all four padding edges can still have a\n * corner visibly removed, and the comparison above accepts it. That container is\n * the ordinary card, so declining every rounded ancestor outright would blank\n * the overlay for most blocks on a real page — the exact test is what keeps the\n * refusal to the blocks that are genuinely cut.\n *\n * Asked only when BOTH axes clip, which is measured rather than assumed. With\n * `overflow: clip visible` the clip region is unbounded on the visible axis, and\n * a corner needs two bounds to exist — probed in Chromium, a child at the corner\n * of a 60px-radius box under `overflow: clip visible` is painted in full, while\n * the same child under `overflow: hidden` is cut away. Applying the arc there\n * would refuse a block nothing removes.\n *\n * The radii come off the PADDING box, because that is where overflow clips and\n * `border-radius` states the border box's curve.\n */\nfunction cutByCorner(\n  box: DOMRect,\n  radii: CornerRadii,\n  clip: EdgeBounds,\n  style: CSSStyleDeclaration,\n  scale: RenderedScale,\n  bothAxesClip: boolean,\n  slack: number\n): boolean {\n  if (!bothAxesClip) return false;\n  const outer = usedCornerRadii(\n    {\n      topLeft: style.borderTopLeftRadius,\n      topRight: style.borderTopRightRadius,\n      bottomRight: style.borderBottomRightRadius,\n      bottomLeft: style.borderBottomLeftRadius,\n    },\n    /*\n     * The ancestor's LAYOUT size, so a percentage resolves against what the\n     * author declared it against. `clip` is post-transform and inset to the\n     * padding edge, so it is divided back out by the scale and re-widened by the\n     * borders that were taken off it.\n     */\n    {\n      width: (clip.right - clip.left) / scale.x + borderSpan(style, \"x\"),\n      height: (clip.bottom - clip.top) / scale.y + borderSpan(style, \"y\"),\n    }\n  );\n  /*\n   * A radius this cannot resolve is a clip of UNKNOWN shape, and the block is\n   * refused rather than treated as sitting inside a square one — the same answer\n   * this module gives for every other geometry it cannot describe.\n   */\n  if (outer === undefined) return true;\n  const inner = scaleCornerRadii(\n    insetCornerRadii(outer, {\n      top: edgeWidth(style.borderTopWidth),\n      right: edgeWidth(style.borderRightWidth),\n      bottom: edgeWidth(style.borderBottomWidth),\n      left: edgeWidth(style.borderLeftWidth),\n    }),\n    scale\n  );\n  if (isSquare(inner)) return false;\n  /*\n   * The block's OWN curve is part of the comparison. A rounded block flush\n   * inside an equally rounded container is not cut at all, while its bounding\n   * rectangle's corners lie outside every one of that container's arcs — so\n   * reading only the rectangle refuses the ordinary nested rounded card and\n   * takes the whole overlay with it.\n   */\n  return !roundedInsideRounded(box, radii, clip, inner, slack);\n}\n\n/** The two border widths an axis loses, in unscaled CSS pixels. */\nfunction borderSpan(style: CSSStyleDeclaration, axis: \"x\" | \"y\"): number {\n  return axis === \"x\"\n    ? edgeWidth(style.borderLeftWidth) + edgeWidth(style.borderRightWidth)\n    : edgeWidth(style.borderTopWidth) + edgeWidth(style.borderBottomWidth);\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","\"use client\";\n\n/**\n * Which document and window the canvas is rendered in.\n *\n * The canvas is meant to render inside a same-origin iframe the editor owns,\n * so that media queries, `vw` and `vh` answer for the previewed device rather\n * than for the admin window. Everything that listens, observes or asks a media\n * query on the canvas's behalf then has to do it in the FRAME's document and\n * window: a pointer moving over the frame is delivered to the frame's document\n * and never reaches the admin's, a key pressed with focus inside it is\n * dispatched there, and `matchMedia` in the admin window answers for the\n * admin's width, not the device's.\n *\n * Code that holds a canvas node asks the node: `node.ownerDocument` and its\n * `defaultView` are the canvas's document and window wherever the node lives,\n * and an observer built from that window is built in the realm of what it\n * observes. This context is for the code that holds no canvas node — a drag\n * begun from a palette row, the inspector's media queries, the keyboard — and\n * it answers the same question for them.\n *\n * With no provider, and with a provider given no frame, the answer is the\n * editor's own document and window: the canvas renders in the same document\n * as the editor, which is what a unit test or a harness mounting the canvas\n * directly is doing.\n *\n * @module canvas-frame-context\n */\n\nimport {\n  useIsomorphicLayoutEffect,\n  useShortcutManager,\n  type ShortcutManager,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { Point } from \"../geometry\";\n\nimport type { FrameSize } from \"./canvas-width\";\nimport { framePointInHost, hostPointInFrame } from \"./geometry-dom\";\n\n/**\n * The frame the canvas renders in and the document it holds now, or `null`\n * for the editor's own document.\n */\nconst CanvasFrameContext = React.createContext<CanvasFrame | null>(null);\n\n/**\n * Where the canvas is rendered, as the code around it needs to know.\n *\n * `document` and `window` are `null` only where there is no DOM at all, a\n * server render, and in a frame whose document is not readable. Every reader\n * here runs in an effect or an event, so a `null` there means there is nothing\n * to listen on rather than something to work around.\n *\n * @experimental\n */\nexport interface CanvasFrame {\n  /** The iframe the canvas renders in, or `null` while it shares the editor's document. */\n  readonly frame: HTMLIFrameElement | null;\n  /** The document the canvas's nodes belong to. */\n  readonly document: Document | null;\n  /** That document's window: the one whose media queries describe the canvas. */\n  readonly window: (Window & typeof globalThis) | null;\n  /**\n   * How much larger the editor paints the frame than it lays it out: `0.5` at\n   * 50%. `1` with no frame, where nothing is scaled.\n   *\n   * A value that changes whenever the zoom or the fit does, so chrome drawn\n   * over the frame can depend on it to be placed again: nothing inside the\n   * frame resizes when only its painted scale moves, so no observer there\n   * reports it.\n   */\n  readonly scale: number;\n  /**\n   * The part of the frame's page on screen, in the frame's own CSS pixels and\n   * without its scrollbars, or `null` with no frame. What chrome that has to\n   * stay visible, such as a toolbar flipping at the top edge, is kept inside.\n   */\n  readonly viewport: FrameSize | null;\n  /** A point in the canvas document's client coordinates, in the editor's. */\n  readonly toHost: (point: Point) => Point;\n  /** A point in the editor's client coordinates, in the canvas document's. */\n  readonly toCanvas: (point: Point) => Point;\n}\n\n/** What a mounted frame reports about how it is drawn. */\ninterface CanvasFrameLayout {\n  readonly scale: number;\n  readonly viewport: FrameSize | null;\n}\n\n/**\n * How a frame rendered beneath an uncontrolled provider hands its iframe and\n * its layout up to it.\n *\n * `null` under a provider told its frame directly, and with no provider at\n * all: the frame then provides for itself.\n */\ninterface FrameRegistration {\n  readonly register: (frame: HTMLIFrameElement | null) => void;\n  readonly report: (layout: CanvasFrameLayout) => void;\n}\n\nconst FrameRegistrationContext = React.createContext<FrameRegistration | null>(\n  null\n);\n\n/**\n * Where a frame registers itself, or `null` when nothing above will hear it.\n *\n * @internal\n */\nexport function useFrameRegistration(): FrameRegistration | null {\n  return React.useContext(FrameRegistrationContext);\n}\n\n/**\n * The answer, held where nothing walking an object's own keys can reach the\n * frame, its document or its window.\n *\n * The value is a context provider's prop, and React's development build\n * describes a changed prop by walking the object's own enumerable keys a few\n * levels down. A window's own keys include each frame inside it, and a page\n * with an Embed block holds one in an opaque origin, where reading anything\n * throws a `SecurityError` in the middle of React's commit. Private fields\n * behind getters are not own keys, so the walk finds nothing to enter.\n */\nclass CanvasFrameView implements CanvasFrame {\n  readonly #frame: HTMLIFrameElement | null;\n  readonly #document: Document | null;\n  readonly scale: number;\n  readonly viewport: FrameSize | null;\n\n  constructor(\n    frame: HTMLIFrameElement | null,\n    doc: Document | null,\n    layout: CanvasFrameLayout\n  ) {\n    this.#frame = frame;\n    this.#document = doc;\n    this.scale = layout.scale;\n    this.viewport = layout.viewport;\n  }\n\n  get frame(): HTMLIFrameElement | null {\n    return this.#frame;\n  }\n\n  get document(): Document | null {\n    return this.#document;\n  }\n\n  get window(): (Window & typeof globalThis) | null {\n    return this.#document?.defaultView ?? null;\n  }\n\n  // Read live at the call: where the frame sits on screen moves with every\n  // scroll of the editor, which no render reports.\n  toHost = (point: Point): Point => {\n    const frame = this.#frame;\n    return frame === null ? point : framePointInHost(frame, point);\n  };\n\n  toCanvas = (point: Point): Point => {\n    const frame = this.#frame;\n    return frame === null ? point : hostPointInFrame(frame, point);\n  };\n}\n\n/** A frame's layout before it has reported one. */\nconst UNREPORTED: CanvasFrameLayout = { scale: 1, viewport: null };\n\n/** A frame and the document it was last seen holding. */\ninterface SeenDocument {\n  readonly frame: HTMLIFrameElement | null;\n  readonly document: Document | null;\n}\n\n/**\n * Names the iframe the canvas renders in, for everything beneath it.\n *\n * `null`, like no provider at all, means the canvas is in the editor's own\n * document.\n *\n * The frame's document is HELD in state and re-read on the frame's `load`,\n * rather than read off `contentDocument` while rendering. A frame replaces its\n * document when it loads — its first `about:blank` gives way to its content,\n * and a reload builds another — and nothing in that renders. Read during\n * render, every listener and media query beneath would stay on the document\n * that was thrown away until some unrelated render happened to read again.\n * Held here, the replacement is itself the update: consumers depending on the\n * document or window re-run, detaching from the old one and attaching to the\n * new.\n *\n * @experimental\n */\nexport function CanvasFrameProvider({\n  frame: given,\n  children,\n}: {\n  /**\n   * The frame, when the caller holds it. Left out, the provider waits for a\n   * `CanvasFrame` beneath it to register its own, which is how an editor\n   * provides the frame to the panels and keys around the canvas as well as to\n   * the canvas itself.\n   */\n  frame?: HTMLIFrameElement | null;\n  children?: React.ReactNode;\n}): React.JSX.Element {\n  const [registered, setRegistered] = React.useState<HTMLIFrameElement | null>(\n    null\n  );\n  const [layout, setLayout] = React.useState<CanvasFrameLayout>(UNREPORTED);\n  const controlled = given !== undefined;\n  const frame = controlled ? given : registered;\n  // One object for the life of the provider, so a frame registering does not\n  // re-run on every render of what is above it.\n  const registration = React.useMemo<FrameRegistration | null>(\n    () =>\n      controlled\n        ? null\n        : {\n            register: next => {\n              setRegistered(next);\n              if (next === null) setLayout(UNREPORTED);\n            },\n            report: next =>\n              setLayout(current =>\n                current.scale === next.scale &&\n                sameSize(current.viewport, next.viewport)\n                  ? current\n                  : next\n              ),\n          },\n    [controlled]\n  );\n  const [seen, setSeen] = React.useState<SeenDocument>(() => ({\n    frame,\n    document: frame?.contentDocument ?? null,\n  }));\n  React.useEffect(() => {\n    if (frame === null) return;\n    const read = (): void => {\n      const current = frame.contentDocument;\n      // The same pair returns the same object, so a load that changed nothing\n      // renders nothing.\n      setSeen(previous =>\n        previous.frame === frame && previous.document === current\n          ? previous\n          : { frame, document: current }\n      );\n    };\n    // Once now as well: the frame may have loaded between the render that\n    // handed it here and this effect, and that load has already fired.\n    read();\n    frame.addEventListener(\"load\", read);\n    return () => frame.removeEventListener(\"load\", read);\n  }, [frame]);\n  /*\n   * A frame handed in that the state does not hold — a new frame, the frame\n   * cleared, or one handed back after being cleared — is read FRESH, here,\n   * and the state replaced before this render commits. Kept instead, a frame\n   * handed back would answer with the document it held when it was taken\n   * away, which it may have dropped since, unwatched; clearing the frame\n   * forgets it for the same reason. React re-runs this render with the new\n   * state before committing, so no committed render answers with a stale\n   * document.\n   */\n  let doc = seen.document;\n  if (seen.frame !== frame) {\n    doc = frame?.contentDocument ?? null;\n    setSeen({ frame, document: doc });\n  }\n  const value = React.useMemo<CanvasFrame | null>(\n    () => (frame === null ? null : new CanvasFrameView(frame, doc, layout)),\n    [frame, doc, layout]\n  );\n  return (\n    <FrameRegistrationContext.Provider value={registration}>\n      <CanvasFrameContext.Provider value={value}>\n        {children}\n      </CanvasFrameContext.Provider>\n    </FrameRegistrationContext.Provider>\n  );\n}\n\n/** Whether two sizes are the same, `null` included. */\nfunction sameSize(a: FrameSize | null, b: FrameSize | null): boolean {\n  if (a === null || b === null) return a === b;\n  return a.width === b.width && a.height === b.height;\n}\n\n/**\n * The document and window the canvas is rendered in.\n *\n * In a frame, the document its provider last saw it load, which changes when\n * the frame loads another: a dependency on `.document` or `.window` then\n * re-runs the effect that listened on the old one. With no frame, the\n * editor's own document and window, which do not change.\n *\n * @experimental\n */\nexport function useCanvasFrame(): CanvasFrame {\n  const framed = React.useContext(CanvasFrameContext);\n  const own = React.useMemo<CanvasFrame>(\n    () =>\n      new CanvasFrameView(\n        null,\n        typeof document === \"undefined\" ? null : document,\n        UNREPORTED\n      ),\n    []\n  );\n  return framed ?? own;\n}\n\n/**\n * Every document an input gesture on the canvas can be delivered to.\n *\n * Two while the canvas is in a frame: the editor's own, where the palette,\n * the panels and their search fields are, and the frame's, where the page is.\n * A pointer moving over the frame is delivered to the frame's document alone\n * and one moving over the panels to the editor's alone, so a gesture that\n * crosses between them is only heard whole by listening on both. A key goes to\n * whichever document holds focus, which is either.\n *\n * One while the canvas shares the editor's document, because the two are the\n * same document and listening on it twice would run every listener twice.\n *\n * The editor's document is the frame's OWNER document: the iframe element is\n * part of the editor's page, whichever window is asking.\n */\nexport function inputDocuments(canvas: CanvasFrame): readonly Document[] {\n  const host = canvas.frame?.ownerDocument ?? canvas.document;\n  const documents: Document[] = [];\n  for (const doc of [host, canvas.document]) {\n    if (doc !== null && !documents.includes(doc)) documents.push(doc);\n  }\n  return documents;\n}\n\n/** One manager's listener on one document, and how many asked for it. */\ninterface Attachment {\n  count: number;\n  readonly detach: () => void;\n}\n\n/**\n * The listeners this module has installed, per manager and per document.\n *\n * Counted rather than installed per caller, because two listeners from ONE\n * manager on one document run every binding twice for one key — a save\n * started twice, an undo that steps back two edits. Weakly keyed both ways, so\n * a frame's document that has been replaced, and everything it holds, is not\n * kept alive by having once been listened on.\n */\nconst attachments = new WeakMap<\n  ShortcutManager,\n  WeakMap<Document, Attachment>\n>();\n\nfunction attachOnce(manager: ShortcutManager, target: Document): () => void {\n  let byDocument = attachments.get(manager);\n  if (byDocument === undefined) {\n    byDocument = new WeakMap();\n    attachments.set(manager, byDocument);\n  }\n  const entry = byDocument.get(target) ?? {\n    count: 0,\n    detach: manager.attach(target),\n  };\n  byDocument.set(target, entry);\n  entry.count += 1;\n  const owner = byDocument;\n  let released = false;\n  return () => {\n    // Idempotent per caller, so a release that runs twice cannot take the\n    // listener from under another caller still counted.\n    if (released) return;\n    released = true;\n    entry.count -= 1;\n    if (entry.count > 0) return;\n    entry.detach();\n    owner.delete(target);\n  };\n}\n\n/**\n * Hears the editor's shortcuts in the canvas's document too.\n *\n * A key pressed with focus inside the frame is dispatched in the FRAME's\n * document, and the shell's shortcut manager listens on the editor's. Without\n * this, Mod+S, undo, Escape and every other binding would go dead the moment\n * the author clicked into the page.\n *\n * The SAME manager, attached to a second document, never a second manager. A\n * `ShortcutProvider` nested with the frame as its target would build one of its\n * own, and the bindings registered on the shell's — the admin's save among\n * them — would not be in it, so they would not fire inside the frame at all.\n *\n * Nothing while the canvas shares the editor's document: the manager already\n * listens there, and a second listener would run every binding twice.\n * Released when the frame's document goes, so a reloaded frame is listened on\n * once, in its new document. Counted per document by {@link attachOnce}, so a\n * Strict Mode replay or a second caller does not install a second listener.\n *\n * Rendered inside the shell's `ShortcutProvider`.\n *\n * @experimental\n */\nexport function CanvasFrameShortcuts(): null {\n  const manager = useShortcutManager();\n  const { document: canvasDocument } = useCanvasFrame();\n  // Layout timing, as the shell's own provider attaches: a passive effect\n  // listens only after paint, and a key pressed in the frame between the\n  // commit that shows it and that effect would reach no binding at all.\n  useIsomorphicLayoutEffect(() => {\n    if (canvasDocument === null) return;\n    if (canvasDocument === globalThis.document) return;\n    return attachOnce(manager, canvasDocument);\n  }, [manager, canvasDocument]);\n  return null;\n}\n","/**\n * How large the canvas draws the page it is previewing.\n *\n * The canvas has always had a scale, and it has never been the author's. It is\n * derived to make the requested width fit the region left over after the\n * panels, so opening a panel silently shrinks the page — measured at 89% with\n * the rail alone and 59.5% with a panel open. Nothing said which of those an\n * author was looking at, and nothing let them choose.\n *\n * ## Fit is a CHOICE, not the absence of one\n *\n * Modelled as a discriminated union rather than a nullable number, because\n * \"fit\" and \"a scale I picked\" are different intentions and a caller has to\n * tell them apart. `null` meaning fit would be the same overloaded absence\n * that a `number | null` scale invites: is it unset, is it fitting, or did\n * something fail to measure?\n *\n * Fit RE-DERIVES on every layout change, which is what makes it fit; a fixed\n * scale deliberately does not, so opening a panel narrows what is visible\n * rather than shrinking the page under the author.\n *\n * ## Why a percentage is absolute, and not a multiplier of the fit\n *\n * A multiplier is the obvious composition and it makes the number a lie: an\n * author choosing 100% is asking for actual size, and \"fit × 1\" is whatever\n * the panels happen to leave. Every editor that shows a zoom percentage means\n * the absolute one, so the number here means what it says and Fit is the mode\n * that computes one.\n *\n * @module canvas-zoom\n */\n\n/** What the canvas was asked to draw at. */\nexport type CanvasZoom =\n  | { readonly kind: \"fit\" }\n  | { readonly kind: \"fixed\"; readonly scale: number };\n\n/** The default, and what every canvas did before there was a choice. */\nexport const FIT_ZOOM: CanvasZoom = { kind: \"fit\" };\n\n/**\n * The steps the control offers, as fractions.\n *\n * Discrete rather than continuous. A slider or a free number invites values\n * whose arithmetic is exact and whose result is unreadable — 37% of a page is\n * not a view of anything — and every comparable editor offers steps for the\n * same reason. `1` is in the middle of the list because actual size is the\n * value an author returns to.\n */\nexport const ZOOM_STEPS: readonly number[] = [0.5, 0.75, 1, 1.5, 2];\n\n/**\n * The bounds a stored or typed scale is held to.\n *\n * Wider than the steps, because a value can arrive from storage written by a\n * later version, and clamping is what keeps that from painting the canvas\n * somewhere unreachable. Below the floor the page is illegible; above the\n * ceiling one block fills the region and the author has lost the page.\n */\nexport const MIN_ZOOM = 0.25;\nexport const MAX_ZOOM = 4;\n\n/**\n * A fixed scale the canvas can actually paint at, or `null` when it cannot.\n *\n * The bounds are not only about what STORAGE may hold. `CanvasZoom` is\n * exported, so a host can construct `{ kind: \"fixed\", scale }` directly with\n * any number the type admits — `NaN`, `Infinity`, zero, or something far\n * outside these bounds — and none of those reach `readZoom` on the way in.\n * Interpolated into a `zoom` declaration they produce an invalid rule or a\n * canvas nobody can see, so the check belongs wherever a scale is USED rather\n * than only where one is parsed.\n */\nexport function usableScale(scale: number): number | null {\n  if (!Number.isFinite(scale)) return null;\n  return scale < MIN_ZOOM || scale > MAX_ZOOM ? null : scale;\n}\n\n/**\n * A stored value read back as a zoom, or `null` when it is not one.\n *\n * `null` rather than a silent fall back to fit: a caller restoring preferences\n * needs to know it found nothing, and a fixed scale that quietly became fit\n * would look to an author like the editor forgetting what they chose.\n */\nexport function readZoom(value: unknown): CanvasZoom | null {\n  if (value === \"fit\") return FIT_ZOOM;\n  if (typeof value !== \"number\") return null;\n  const scale = usableScale(value);\n  return scale === null ? null : { kind: \"fixed\", scale };\n}\n\n/** A zoom as it is stored: the string `\"fit\"`, or the scale itself. */\nexport function writeZoom(zoom: CanvasZoom): \"fit\" | number {\n  return zoom.kind === \"fit\" ? \"fit\" : zoom.scale;\n}\n\n/**\n * The next step in a direction, or the same zoom when there is none.\n *\n * From FIT it steps off the scale the fit produced, so the first press moves\n * from what the author is looking at rather than jumping to an end of the\n * list. That needs the fit scale passed in, because only the canvas knows it.\n *\n * A scale the canvas cannot paint steps from the fit scale as well, for the\n * same reason and by the rule {@link usableScale} states: a host can construct\n * `{ kind: \"fixed\", scale }` with any number the type admits, and the canvas\n * already falls back to fit when it cannot use one. Stepping from the raw value\n * instead makes every comparison against `NaN` false, so both directions return\n * the zoom unchanged — leaving a stepper that cannot move off an unusable\n * scale, while the canvas is meanwhile painting the fit the steps would come\n * from.\n */\nexport function steppedZoom(\n  zoom: CanvasZoom,\n  fitScale: number,\n  direction: \"in\" | \"out\"\n): CanvasZoom {\n  const from =\n    zoom.kind === \"fit\" ? fitScale : (usableScale(zoom.scale) ?? fitScale);\n  const candidates =\n    direction === \"in\"\n      ? ZOOM_STEPS.filter(step => step > from + 1e-9)\n      : [...ZOOM_STEPS].reverse().filter(step => step < from - 1e-9);\n  const next = candidates[0];\n  return next === undefined ? zoom : { kind: \"fixed\", scale: next };\n}\n","/**\n * A value one surface of the editor sets and another reads, held outside\n * React state so a change re-renders only its readers.\n *\n * The editor keeps two: the block pointed at from Layers (`hovered-block`)\n * and the Add panel's highlighted place (`insertion-preview`). Both change\n * far more often than anything else in the editor, and a value in the\n * editor's state would draw the whole page again on every change.\n *\n * @module value-holder\n */\n\n/** A value, readable and writable by any surface under one editor. */\nexport interface ValueHolder<T> {\n  /** The value, or `null` for none. */\n  readonly get: () => T | null;\n  /** Set it, or clear it with `null`. A value equal to the one held changes nothing. */\n  readonly set: (value: T | null) => void;\n  /** Be told when it changes; answers the unsubscribe. */\n  readonly subscribe: (listener: () => void) => () => void;\n}\n\n/** A fresh holder, holding nothing, judging equal values by `same`. */\nexport function createValueHolder<T>(\n  same: (a: T, b: T) => boolean = Object.is\n): ValueHolder<T> {\n  let current: T | null = null;\n  const listeners = new Set<() => void>();\n  return {\n    get: () => current,\n    set: value => {\n      const unchanged =\n        value === null || current === null\n          ? value === current\n          : same(value, current);\n      if (unchanged) return;\n      current = value;\n      listeners.forEach(listener => listener());\n    },\n    subscribe: listener => {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n  };\n}\n\n/**\n * What a surface outside any editor reads: nothing held, and a set that goes\n * nowhere, so a panel or the canvas drawn alone in a test still work.\n */\nexport function nowhereHolder<T>(): ValueHolder<T> {\n  return {\n    get: () => null,\n    set: () => undefined,\n    subscribe: () => () => undefined,\n  };\n}\n","\"use client\";\n\n/**\n * Which block the author is pointing at from outside the canvas, so the canvas\n * can outline it.\n *\n * Layers sets it while the pointer is over a row, and the canvas marks read\n * it: hovering a row outlines its block on the page, which is how an author\n * finds which of five \"Text\" rows is the one they mean. One value for every\n * surface that points at a block, so a canvas hover style drawn later reads\n * the same answer rather than a second one.\n *\n * **Held outside React state on purpose.** The pointer crosses rows far more\n * often than anything else in the editor changes, and a value held in the\n * editor's state would re-render the whole editor, the canvas included, on\n * every row it crossed. Here only the two readers re-render: the row being\n * left and entered, and the marks.\n *\n * @module hovered-block\n */\nimport * as React from \"react\";\n\nimport {\n  createValueHolder,\n  nowhereHolder,\n  type ValueHolder,\n} from \"./value-holder\";\n\n/** The hovered block, readable and writable by any surface under one editor. */\nexport type HoveredBlock = ValueHolder<string>;\n\nconst HoveredBlockContext = React.createContext<HoveredBlock>(nowhereHolder());\n\n/**\n * Shares one hovered block with everything under it: the panels and the\n * canvas of one editor. A host with two editors gives each its own.\n */\nexport function HoveredBlockProvider({\n  children,\n}: {\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const [hovered] = React.useState(() => createValueHolder<string>());\n  return (\n    <HoveredBlockContext.Provider value={hovered}>\n      {children}\n    </HoveredBlockContext.Provider>\n  );\n}\n\n/** The holder, to point at a block. */\nexport function useHoveredBlockSetter(): HoveredBlock[\"set\"] {\n  return React.useContext(HoveredBlockContext).set;\n}\n\n/** The block pointed at, re-rendering when it changes. */\nexport function useHoveredBlock(): string | null {\n  const hovered = React.useContext(HoveredBlockContext);\n  return React.useSyncExternalStore(hovered.subscribe, hovered.get, () => null);\n}\n","\"use client\";\n\n/**\n * Where the tile highlighted in the Add panel would put its block, so the\n * canvas can draw it.\n *\n * The panel sets it while a tile is pointed at or has the keyboard's\n * highlight, and the canvas's insertion line reads it: the line on the page\n * at the very place a click would use, with the panel's own words.\n *\n * **Held outside React state on purpose**, as the hovered block is: the\n * pointer crosses tiles far more often than anything else in the editor\n * changes, and a value in the editor's state would re-render the editor, the\n * page included, on every tile it crossed. Here only the line re-renders.\n *\n * @module insertion-preview\n */\nimport * as React from \"react\";\n\nimport type { OpPosition } from \"../op-vocabulary\";\n\nimport {\n  createValueHolder,\n  nowhereHolder,\n  type ValueHolder,\n} from \"./value-holder\";\n\n/** A highlighted tile's place, as the canvas draws it. */\nexport interface InsertionPreview {\n  /** Where a click on the tile puts its block. */\n  readonly at: OpPosition;\n  /** The words for it, \"Heading goes inside Hero, at the end\". */\n  readonly words: string;\n}\n\n/** Whether two previews name the same place in the same words. */\nfunction samePreview(a: InsertionPreview, b: InsertionPreview): boolean {\n  return (\n    a.words === b.words &&\n    a.at.index === b.at.index &&\n    a.at.parentId === b.at.parentId &&\n    a.at.slot === b.at.slot\n  );\n}\n\nconst InsertionPreviewContext =\n  React.createContext<ValueHolder<InsertionPreview>>(nowhereHolder());\n\n/**\n * Shares one preview with everything under it: the Add panel and the canvas\n * of one editor. A host with two editors gives each its own.\n */\nexport function InsertionPreviewProvider({\n  children,\n}: {\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const [holder] = React.useState(() =>\n    createValueHolder<InsertionPreview>(samePreview)\n  );\n  return (\n    <InsertionPreviewContext.Provider value={holder}>\n      {children}\n    </InsertionPreviewContext.Provider>\n  );\n}\n\n/** The highlighted tile's place, re-rendering when it changes. */\nexport function useInsertionPreview(): InsertionPreview | null {\n  const holder = React.useContext(InsertionPreviewContext);\n  return React.useSyncExternalStore(holder.subscribe, holder.get, () => null);\n}\n\n/**\n * How long a preview outlasts the highlight that set it: the pointer crossing\n * from one tile to the next, or off the tiles and back, does not make the\n * line blink.\n */\nexport const PREVIEW_GRACE_MS = 150;\n\n/**\n * Hands `preview` to the canvas while it is set. A new one replaces the old\n * at once; going to nothing waits {@link PREVIEW_GRACE_MS} first, and a new\n * one inside that wait cancels it. Unmounting clears it at once: the panel\n * closing takes its line with it. A preview equal to the one held changes\n * nothing, so a caller may build it afresh on every render.\n */\nexport function usePublishInsertionPreview(\n  preview: InsertionPreview | null\n): void {\n  const holder = React.useContext(InsertionPreviewContext);\n  React.useEffect(() => {\n    if (preview !== null) {\n      holder.set(preview);\n      return undefined;\n    }\n    const wait = setTimeout(() => holder.set(null), PREVIEW_GRACE_MS);\n    return () => clearTimeout(wait);\n  }, [holder, preview]);\n  React.useEffect(() => () => holder.set(null), [holder]);\n}\n","\"use client\";\n\n/**\n * Whether the block panel prints each control's CSS names under its label,\n * the \"Show CSS names\" preference: the shell's, kept with its other\n * preferences, or the panel's own where it is mounted alone.\n *\n * The provider also supplies the tooltips' provider, so a panel mounted\n * without the shell still draws a control's \"what it writes\" tooltip.\n *\n * @module css-names-context\n */\nimport { TooltipProvider } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\n/** The preference and the way to change it. */\nexport interface CssNames {\n  readonly shown: boolean;\n  readonly set: (shown: boolean) => void;\n}\n\n/** The shell's preference, for a panel inside the shell. */\nexport const CssNamesContext: React.Context<CssNames | undefined> =\n  React.createContext<CssNames | undefined>(undefined);\n\nconst NOT_SHOWN: CssNames = { shown: false, set: () => {} };\n\n/** Whether CSS names are printed, and the way to change it. */\nexport function useCssNames(): CssNames {\n  return React.useContext(CssNamesContext) ?? NOT_SHOWN;\n}\n\n/**\n * Lends the preference to the panel inside it: the one lent from above, else\n * the panel's own, off at first; and a tooltip provider for the controls.\n */\nexport function CssNamesProvider({\n  children,\n}: {\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const above = React.useContext(CssNamesContext);\n  const [own, setOwn] = React.useState(false);\n  const value = React.useMemo<CssNames>(\n    () => above ?? { shown: own, set: setOwn },\n    [above, own]\n  );\n  return (\n    <CssNamesContext.Provider value={value}>\n      <TooltipProvider delayDuration={300}>{children}</TooltipProvider>\n    </CssNamesContext.Provider>\n  );\n}\n","/**\n * Which sections of the block panel are open: each tab's sections fold on\n * their own, and stay as the author left them across selections and visits.\n *\n * Kept per tab and section NAME (`style:Spacing`), not per block, because an\n * author working on spacing selects one block after another and means to keep\n * Spacing open on each. \"Expand all\" and \"Collapse all\" store one entry for\n * the tab (`style:*`) and drop the tab's own, so they reach sections the panel\n * has not drawn yet.\n *\n * Held with the shell's other preferences (`panel-folds-context` lends them\n * to the panel).\n *\n * @module panel-folds\n */\n/** The open or closed state of each section the author has folded. */\nexport type SectionFolds = Readonly<Record<string, boolean>>;\n\n/** The most sections remembered; the oldest are dropped past it. */\nexport const MAX_SECTION_FOLDS = 200;\n\n/** The longest key remembered: a tab, a colon and a section's name. */\nconst MAX_FOLD_KEY_LENGTH = 120;\n\n/** The key one section's fold is kept under. */\nfunction foldKey(tab: string, label: string): string {\n  return `${tab}:${label}`;\n}\n\n/** The key a whole tab's Expand all or Collapse all is kept under. */\nfunction allKey(tab: string): string {\n  return `${tab}:*`;\n}\n\n/** What a section's opening falls back to when nothing is remembered. */\nexport interface SectionDefault {\n  /** Whether it holds a value for what is being edited. */\n  readonly holdsValue: boolean;\n  /** Whether it is the tab's first section. */\n  readonly first: boolean;\n}\n\n/**\n * Whether a section is open: as the author last left it, else as they last\n * left the whole tab, else open when it holds a value or is the tab's first.\n */\nexport function sectionOpens(\n  folds: SectionFolds,\n  tab: string,\n  label: string,\n  fallback: SectionDefault\n): boolean {\n  return (\n    folds[foldKey(tab, label)] ??\n    folds[allKey(tab)] ??\n    (fallback.holdsValue || fallback.first)\n  );\n}\n\n/** The folds with the oldest dropped past {@link MAX_SECTION_FOLDS}. */\nfunction bounded(folds: Record<string, boolean>): SectionFolds {\n  const keys = Object.keys(folds);\n  if (keys.length <= MAX_SECTION_FOLDS) return folds;\n  return Object.fromEntries(\n    keys.slice(keys.length - MAX_SECTION_FOLDS).map(key => [key, folds[key]])\n  );\n}\n\n/** The folds with one section set open or closed, kept newest last. */\nexport function withSectionFold(\n  folds: SectionFolds,\n  tab: string,\n  label: string,\n  open: boolean\n): SectionFolds {\n  const key = foldKey(tab, label);\n  const { [key]: _previous, ...rest } = folds;\n  return bounded({ ...rest, [key]: open });\n}\n\n/** The folds with every section of a tab open or closed. */\nexport function withTabFold(\n  folds: SectionFolds,\n  tab: string,\n  open: boolean\n): SectionFolds {\n  const prefix = `${tab}:`;\n  const rest = Object.fromEntries(\n    Object.entries(folds).filter(([key]) => !key.startsWith(prefix))\n  );\n  return bounded({ ...rest, [allKey(tab)]: open });\n}\n\n/**\n * Stored folds as the panel may read them: a record of booleans under keys a\n * section could have, bounded, and nothing else.\n */\nexport function readSectionFolds(stored: unknown): SectionFolds {\n  if (typeof stored !== \"object\" || stored === null || Array.isArray(stored)) {\n    return {};\n  }\n  const kept: Record<string, boolean> = {};\n  for (const [key, open] of Object.entries(stored)) {\n    if (typeof open !== \"boolean\") continue;\n    if (key.length > MAX_FOLD_KEY_LENGTH || !key.includes(\":\")) continue;\n    kept[key] = open;\n  }\n  return bounded(kept);\n}\n","/**\n * Every setting the panel offers for the selected block, as one list an author\n * can search by name and filter to what they changed.\n *\n * Built from what the panel already reads for the selection (the block's\n * inspection, the Style tab's sections, the built-in Advanced rows), so a\n * setting is found under the words it is drawn with. Pure: no document, no\n * DOM, so a tool reaches the same answers the panel does.\n *\n * - **Matching** goes by a setting's plain label, its section, its options'\n *   labels, the CSS names it writes and a few other words for it\n *   ({@link SYNONYMS}), ignoring case, accents, hyphens, underscores and camel\n *   case: \"zindex\", \"z-index\" and \"zIndex\" are one word.\n * - **Order** stays the panel's: a match never moves a setting, so the panel\n *   does not rearrange itself while the author types.\n * - **Only changed** keeps the settings holding a value of their own for what\n *   is being edited.\n *\n * @module settings-index\n */\n\n/** The panel's three tabs. */\nexport type SettingTab = \"content\" | \"style\" | \"advanced\";\n\n/** The tabs in the panel's order. */\nexport const SETTING_TABS: readonly SettingTab[] = [\n  \"content\",\n  \"style\",\n  \"advanced\",\n];\n\n/** One setting, as the search and the filter read it. */\nexport interface SettingEntry {\n  readonly tab: SettingTab;\n  /** The section it is drawn in: its key in the tab's accordion. */\n  readonly section: string;\n  /** The section's plain label. */\n  readonly sectionLabel: string;\n  /** The prop name, catalog key or built-in id the row is drawn for. */\n  readonly id: string;\n  /** Its plain label. */\n  readonly label: string;\n  /** Its options' labels. */\n  readonly options: readonly string[];\n  /** The CSS properties or HTML attributes it writes. */\n  readonly css: readonly string[];\n  /** Whether it holds its own value for what is being edited. */\n  readonly set: boolean;\n  /**\n   * A CSS property this block can use but doesn't show yet: found, it is\n   * listed with \"Add\" in \"CSS properties\" rather than drawn as a row.\n   */\n  readonly addable?: true;\n}\n\n/** What the panel is filtered by. Empty and off: nothing is filtered. */\nexport interface SettingsFilter {\n  readonly query: string;\n  readonly onlyChanged: boolean;\n}\n\n/**\n * The other words authors use for a setting, each group read as one: typing\n * any word of a group finds what any other word of it would. Small and kept\n * by hand, so each pair is one an author would say.\n */\nconst SYNONYMS: readonly (readonly string[])[] = [\n  [\"colour\", \"color\"],\n  [\"corners\", \"radius\", \"rounded\"],\n  [\"z-index\", \"layer order\", \"stacking\"],\n  // Not \"rel\" alone: it is the start of \"Relative\", Position's choice.\n  [\"nofollow\", \"link relationship\"],\n  [\"hide\", \"hide on\", \"visible on\"],\n  [\"padding\", \"spacing\"],\n  [\"margin\", \"spacing\"],\n  [\"font\", \"typeface\"],\n  // A block's own CSS is the code an author writes for it.\n  [\"code\", \"custom css\"],\n];\n\n/**\n * Text as the matcher reads it: lower case, accents gone, camel case,\n * hyphens and underscores split into words, one space between words.\n */\nexport function normalise(text: string): string {\n  return text\n    .normalize(\"NFD\")\n    .replace(/[̀-ͯ]/g, \"\")\n    .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n    .toLowerCase()\n    .replace(/[-_/·.,:()&]+/g, \" \")\n    .replace(/\\s+/g, \" \")\n    .trim();\n}\n\n/** Normalised text without its spaces: \"z index\" and \"zindex\" meet. */\nfunction compact(text: string): string {\n  return normalise(text).replace(/ /g, \"\");\n}\n\n/** The query, and each other word for it, as the matcher looks for them. */\nfunction searchedFor(query: string): readonly string[] {\n  const asked = compact(query);\n  const words = new Set([asked]);\n  for (const group of SYNONYMS) {\n    if (group.some(word => compact(word) === asked)) {\n      for (const word of group) words.add(compact(word));\n    }\n  }\n  return [...words];\n}\n\n/** Everything an entry can be found by, each compacted. */\nfunction findableBy(entry: SettingEntry): readonly string[] {\n  return [entry.label, entry.sectionLabel, ...entry.options, ...entry.css].map(\n    compact\n  );\n}\n\n/** Whether an entry answers a query. An empty query answers every entry. */\nexport function entryMatches(entry: SettingEntry, query: string): boolean {\n  if (compact(query) === \"\") return true;\n  const wanted = searchedFor(query);\n  return findableBy(entry).some(text =>\n    wanted.some(word => text.includes(word))\n  );\n}\n\n/** Whether a filter narrows anything. */\nexport function filtering(filter: SettingsFilter): boolean {\n  return filter.onlyChanged || compact(filter.query) !== \"\";\n}\n\n/** The entries a filter keeps, in the panel's order. */\nexport function filterEntries(\n  entries: readonly SettingEntry[],\n  filter: SettingsFilter\n): SettingEntry[] {\n  return entries.filter(\n    entry =>\n      (!filter.onlyChanged || entry.set) && entryMatches(entry, filter.query)\n  );\n}\n\n/** How many entries each tab keeps. */\nexport function tabCounts(\n  kept: readonly SettingEntry[]\n): Readonly<Record<SettingTab, number>> {\n  const counts = { content: 0, style: 0, advanced: 0 };\n  for (const entry of kept) counts[entry.tab] += 1;\n  return counts;\n}\n\n/** The words for each tab, as its label reads. */\nexport const TAB_WORDS: Readonly<Record<SettingTab, string>> = {\n  content: \"Content\",\n  style: \"Style\",\n  advanced: \"Advanced\",\n};\n\n/**\n * What a screen reader is told once the author stops typing: \"5 settings\n * found: 3 in Style, 2 in Advanced\", or that none is.\n */\nexport function resultsAnnouncement(\n  counts: Readonly<Record<SettingTab, number>>\n): string {\n  const total = counts.content + counts.style + counts.advanced;\n  if (total === 0) return \"No setting matches. Try another word.\";\n  const where = SETTING_TABS.filter(tab => counts[tab] > 0)\n    .map(tab => `${String(counts[tab])} in ${TAB_WORDS[tab]}`)\n    .join(\", \");\n  const noun = total === 1 ? \"setting\" : \"settings\";\n  return `${String(total)} ${noun} found: ${where}`;\n}\n\n/** A row of a section, as the index reads it. */\nexport interface IndexedRow {\n  /** The prop name, catalog key or built-in id. */\n  readonly id: string;\n  readonly label: string;\n  readonly options?: readonly string[];\n  /** The CSS properties or HTML attributes it writes, where it says. */\n  readonly css?: readonly string[];\n  readonly set: boolean;\n  /** Whether it is offered to add rather than drawn. */\n  readonly addable?: boolean;\n}\n\n/** A section's rows as entries. */\nexport function sectionEntries(\n  tab: SettingTab,\n  section: { readonly key: string; readonly label: string },\n  rows: readonly IndexedRow[]\n): SettingEntry[] {\n  return rows.map(row => ({\n    tab,\n    section: section.key,\n    sectionLabel: section.label,\n    id: row.id,\n    label: row.label,\n    options: row.options ?? [],\n    css: row.css ?? [],\n    set: row.set,\n    ...(row.addable === true ? { addable: true as const } : {}),\n  }));\n}\n\n/** One device or state the edited target holds values at, and how many. */\nexport interface ElsewhereCount {\n  readonly id: string;\n  readonly label: string;\n  readonly count: number;\n}\n\n/**\n * Where else the edited target holds values: by device at the edited state,\n * and by state at the edited device, each in the order given.\n */\nexport interface ElsewhereCounts {\n  readonly devices: readonly ElsewhereCount[];\n  readonly states: readonly ElsewhereCount[];\n}\n\n/** Stored styles: state, then device, then property. */\nexport type StoredStyles = Readonly<\n  Record<string, Readonly<Record<string, Readonly<Record<string, unknown>>>>>\n>;\n\n/** How many properties a styles record holds at one state and device. */\nfunction heldAt(styles: StoredStyles, state: string, device: string): number {\n  return Object.keys(styles[state]?.[device] ?? {}).length;\n}\n\n/**\n * The values the edited target holds at the other devices and states, for\n * \"Also changed on Tablet (2) · Hover (1)\". Only those holding any are listed.\n */\nexport function changedElsewhere(\n  styles: StoredStyles | undefined,\n  at: { readonly state: string; readonly device: string },\n  names: {\n    readonly devices: readonly { id: string; label: string }[];\n    readonly states: readonly { id: string; label: string }[];\n  }\n): ElsewhereCounts {\n  if (styles === undefined) return { devices: [], states: [] };\n  return {\n    devices: names.devices\n      .filter(device => device.id !== at.device)\n      .map(device => ({\n        ...device,\n        count: heldAt(styles, at.state, device.id),\n      }))\n      .filter(device => device.count > 0),\n    states: names.states\n      .filter(state => state.id !== at.state)\n      .map(state => ({ ...state, count: heldAt(styles, state.id, at.device) }))\n      .filter(state => state.count > 0),\n  };\n}\n\n/** \"Also changed on Tablet (2) · Hover (1)\", or nothing where none is. */\nexport function elsewhereLine(counts: ElsewhereCounts): string | undefined {\n  const parts = [...counts.devices, ...counts.states].map(\n    each => `${each.label} (${String(each.count)})`\n  );\n  return parts.length === 0\n    ? undefined\n    : `Also changed on ${parts.join(\" · \")}`;\n}\n","\"use client\";\n\n/**\n * \"Find a setting\" and \"Only changed\" at the top of the block panel: the\n * search and filter state, the row they are typed in, and what every tab asks\n * of them to draw only the settings that match.\n *\n * The query and the toggle are panel state, kept while the author selects one\n * block after another, until cleared. What they keep is read from the\n * settings index (`settings-index`) once per selection; each tab then hides\n * the rows and sections with no match, and opens the ones with one, without\n * touching the folds the author left.\n *\n * @module settings-filter\n */\nimport { Search, X } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { isElement } from \"../canvas/dom-kind\";\nimport type { ParentArrangement } from \"../styles/plain-layout\";\n\nimport {\n  filterEntries,\n  filtering,\n  resultsAnnouncement,\n  SETTING_TABS,\n  tabCounts,\n  TAB_WORDS,\n  type SettingEntry,\n  type SettingsFilter,\n  type SettingTab,\n} from \"./settings-index\";\nimport type { StyleSection } from \"./style-inspector/style-inspector\";\n\n/** The search and the toggle, and their setters. */\ninterface FilterState extends SettingsFilter {\n  readonly setQuery: (query: string) => void;\n  readonly setOnlyChanged: (on: boolean) => void;\n}\n\nconst NO_FILTER: FilterState = {\n  query: \"\",\n  onlyChanged: false,\n  setQuery: () => {},\n  setOnlyChanged: () => {},\n};\n\nconst FilterStateContext = React.createContext<FilterState>(NO_FILTER);\n\n/**\n * Holds the search and the toggle for the panel, above the selection, so both\n * stay while the author selects other blocks.\n */\nexport function SettingsFilterProvider({\n  children,\n  initial,\n}: {\n  children: React.ReactNode;\n  /** What the panel opens filtered by; nothing unless said. */\n  initial?: Partial<SettingsFilter>;\n}): React.JSX.Element {\n  const [query, setQuery] = React.useState(initial?.query ?? \"\");\n  const [onlyChanged, setOnlyChanged] = React.useState(\n    initial?.onlyChanged ?? false\n  );\n  const value = React.useMemo(\n    () => ({ query, onlyChanged, setQuery, setOnlyChanged }),\n    [query, onlyChanged]\n  );\n  return (\n    <FilterStateContext.Provider value={value}>\n      <SearchFoldsProvider active={filtering(value)}>\n        {children}\n      </SearchFoldsProvider>\n    </FilterStateContext.Provider>\n  );\n}\n\n/** The panel's search and toggle. */\nexport function useFilterState(): FilterState {\n  return React.useContext(FilterStateContext);\n}\n\n/** What the filter keeps for the selected block. */\nexport interface SettingsMatch {\n  /** Whether anything is filtered: a query typed, or Only changed on. */\n  readonly active: boolean;\n  /** The query, as typed, so a tab's opened sections follow it. */\n  readonly query: string;\n  readonly onlyChanged: boolean;\n  /** Each tab's kept settings, by id. */\n  readonly kept: ReadonlyMap<SettingTab, ReadonlySet<string>>;\n  /** Each tab's sections holding a kept setting, by key. */\n  readonly sections: ReadonlyMap<SettingTab, ReadonlySet<string>>;\n  readonly counts: Readonly<Record<SettingTab, number>>;\n}\n\nconst NO_MATCH: SettingsMatch = {\n  active: false,\n  query: \"\",\n  onlyChanged: false,\n  kept: new Map(),\n  sections: new Map(),\n  counts: { content: 0, style: 0, advanced: 0 },\n};\n\nconst MatchContext = React.createContext<SettingsMatch>(NO_MATCH);\n\n/** What the filter keeps of a block's settings. */\nexport function settingsMatch(\n  entries: readonly SettingEntry[],\n  filter: SettingsFilter\n): SettingsMatch {\n  if (!filtering(filter)) return NO_MATCH;\n  const kept = filterEntries(entries, filter);\n  const byTab = (key: (entry: SettingEntry) => string) =>\n    new Map(\n      SETTING_TABS.map(tab => [\n        tab,\n        new Set(kept.filter(entry => entry.tab === tab).map(key)),\n      ])\n    );\n  return {\n    active: true,\n    query: filter.query,\n    onlyChanged: filter.onlyChanged,\n    kept: byTab(entry => entry.id),\n    sections: byTab(entry => entry.section),\n    counts: tabCounts(kept),\n  };\n}\n\n/** Lends a block's match to every tab. */\nexport const SettingsMatchProvider: React.Provider<SettingsMatch> =\n  MatchContext.Provider;\n\n/** The selected block's match. */\nexport function useSettingsMatch(): SettingsMatch {\n  return React.useContext(MatchContext);\n}\n\n/** The tab a row is drawn in, for rows drawn the same way on two tabs. */\nexport const SettingTabContext: React.Context<SettingTab | undefined> =\n  React.createContext<SettingTab | undefined>(undefined);\n\n/** Whether any of a row's settings is kept on its tab. */\nfunction useSettingShown(ids: readonly string[], tab?: SettingTab): boolean {\n  const match = useSettingsMatch();\n  const drawnOn = React.useContext(SettingTabContext);\n  const on = tab ?? drawnOn;\n  if (!match.active || on === undefined) return true;\n  const kept = match.kept.get(on);\n  return ids.some(id => kept?.has(id) === true);\n}\n\n/** Whether a section holds a kept setting. */\nexport function sectionShown(\n  match: SettingsMatch,\n  tab: string,\n  key: string\n): boolean {\n  if (!match.active) return true;\n  return match.sections.get(tab as SettingTab)?.has(key) === true;\n}\n\n/**\n * A row the filter may hide. Hidden rather than taken away, so a field's\n * unsaved text and its focus outlive a search typed and cleared. Marked with\n * its settings' ids, so a setting asked for from outside the panel (a page\n * check's fix) finds the row it is drawn in.\n */\nexport function SettingSlot({\n  ids,\n  tab,\n  children,\n}: {\n  ids: readonly string[];\n  tab?: SettingTab;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const shown = useSettingShown(ids, tab);\n  return (\n    <div className=\"nx-setting\" data-setting={ids.join(\" \")} hidden={!shown}>\n      {children}\n    </div>\n  );\n}\n\n/** Whether a key press is typed into a field rather than sent to the panel. */\nfunction typedIntoField(target: EventTarget | null): boolean {\n  if (!isElement(target)) return false;\n  if (\n    target.closest('[contenteditable=\"true\"], [contenteditable=\"\"]') !== null\n  ) {\n    return true;\n  }\n  return [\"INPUT\", \"TEXTAREA\", \"SELECT\"].includes(target.tagName);\n}\n\n/**\n * The panel's \"/\" shortcut: from anywhere in the panel outside a text field,\n * to \"Find a setting\".\n */\nexport function useFindShortcut(): {\n  readonly field: React.RefObject<HTMLInputElement | null>;\n  readonly onKeyDown: (event: React.KeyboardEvent) => void;\n} {\n  const field = React.useRef<HTMLInputElement | null>(null);\n  const onKeyDown = (event: React.KeyboardEvent) => {\n    if (event.key !== \"/\" || event.defaultPrevented) return;\n    if (event.metaKey || event.ctrlKey || event.altKey) return;\n    if (typedIntoField(event.target)) return;\n    event.preventDefault();\n    field.current?.focus();\n  };\n  return { field, onKeyDown };\n}\n\n/** How long typing pauses before the result is announced. */\nconst ANNOUNCE_AFTER_MS = 600;\n\n/** The announcement, once the author stops typing. */\nfunction useAnnouncement(match: SettingsMatch): string {\n  const [said, setSaid] = React.useState(\"\");\n  const text = match.active ? resultsAnnouncement(match.counts) : \"\";\n  React.useEffect(() => {\n    const timer = window.setTimeout(() => setSaid(text), ANNOUNCE_AFTER_MS);\n    return () => window.clearTimeout(timer);\n  }, [text]);\n  return said;\n}\n\n/**\n * The search row: \"Find a setting\", its clear button, and \"Only changed\".\n * Under the tabs, on every tab.\n */\nexport function SettingsSearchRow({\n  field,\n  end,\n}: {\n  field: React.RefObject<HTMLInputElement | null>;\n  /** What ends the row, after \"Only changed\": the panel's options menu. */\n  end?: React.ReactNode;\n}): React.JSX.Element {\n  const { query, onlyChanged, setQuery, setOnlyChanged } = useFilterState();\n  const match = useSettingsMatch();\n  const announcement = useAnnouncement(match);\n  return (\n    <div className=\"nx-settings-search\" role=\"search\">\n      <div className=\"nx-settings-search__field\">\n        <Search\n          size={14}\n          aria-hidden=\"true\"\n          className=\"nx-settings-search__icon\"\n        />\n        <input\n          ref={field}\n          type=\"search\"\n          className=\"nx-settings-search__input\"\n          aria-label=\"Find a setting\"\n          placeholder=\"Find a setting\"\n          autoComplete=\"off\"\n          spellCheck={false}\n          value={query}\n          onChange={event => setQuery(event.target.value)}\n          onKeyDown={event => {\n            if (event.key !== \"Escape\" || query === \"\") return;\n            // Cleared here, and kept from the canvas, which would take\n            // Escape as leaving the block.\n            event.preventDefault();\n            event.stopPropagation();\n            setQuery(\"\");\n          }}\n        />\n        {query === \"\" ? null : (\n          <button\n            type=\"button\"\n            className=\"nx-settings-search__clear\"\n            aria-label=\"Clear search\"\n            onClick={() => {\n              setQuery(\"\");\n              field.current?.focus();\n            }}\n          >\n            <X size={14} aria-hidden=\"true\" />\n          </button>\n        )}\n      </div>\n      <button\n        type=\"button\"\n        className=\"nx-settings-search__toggle\"\n        aria-pressed={onlyChanged}\n        onClick={() => setOnlyChanged(!onlyChanged)}\n      >\n        Only changed\n      </button>\n      {end}\n      {/* Polite, and a live region of its own rather than a status: the\n          panel's other status lines say what one control is doing. */}\n      <p className=\"nx-sr-only\" aria-live=\"polite\" aria-atomic=\"true\">\n        {announcement}\n      </p>\n    </div>\n  );\n}\n\n/**\n * What a tab says while the filter keeps nothing on it: where the matches\n * are, with a link to each tab holding some, or that nothing matches.\n */\nexport function FilterNote({\n  tab,\n  onChoose,\n}: {\n  tab: SettingTab;\n  onChoose: (tab: SettingTab) => void;\n}): React.JSX.Element | null {\n  const match = useSettingsMatch();\n  if (!match.active || match.counts[tab] > 0) return null;\n  const elsewhere = SETTING_TABS.filter(\n    each => each !== tab && match.counts[each] > 0\n  );\n  const searching = match.query.trim() !== \"\";\n  if (elsewhere.length === 0) {\n    return (\n      <p className=\"nx-settings-note\">\n        {searching\n          ? \"No setting matches. Try another word.\"\n          : \"Nothing changed on this block yet.\"}\n      </p>\n    );\n  }\n  return (\n    <p className=\"nx-settings-note\">\n      {searching ? \"No setting matches here.\" : \"Nothing changed here.\"}{\" \"}\n      {elsewhere.map((each, index) => (\n        <React.Fragment key={each}>\n          {index === 0 ? null : \" · \"}\n          <button\n            type=\"button\"\n            className=\"nx-settings-note__link\"\n            onClick={() => onChoose(each)}\n          >\n            {`${String(match.counts[each])} in ${TAB_WORDS[each]}`}\n          </button>\n        </React.Fragment>\n      ))}\n    </p>\n  );\n}\n\n/** A tab's match count, drawn on its label while the filter is on. */\nexport function TabCount({\n  tab,\n}: {\n  tab: SettingTab;\n}): React.JSX.Element | null {\n  const match = useSettingsMatch();\n  if (!match.active) return null;\n  const count = match.counts[tab];\n  return (\n    <span className=\"nx-inspector__tab-count\">\n      <span aria-hidden=\"true\">{count}</span>\n      <span className=\"nx-sr-only\">\n        {`, ${String(count)} ${count === 1 ? \"match\" : \"matches\"}`}\n      </span>\n    </span>\n  );\n}\n\n/** A device or state the edited target holds values at, with how many. */\ninterface ElsewhereLink {\n  readonly id: string;\n  readonly label: string;\n  readonly count: number;\n}\n\n/**\n * \"Also changed on Tablet (2) · Hover (1)\": while Only changed is on in\n * Style, where else the edited target holds values, each a link that shows\n * that device or state.\n */\nexport function ChangedElsewhere({\n  devices,\n  states,\n  onDevice,\n  onState,\n}: {\n  devices: readonly ElsewhereLink[];\n  states: readonly ElsewhereLink[];\n  onDevice: ((id: string) => void) | undefined;\n  onState: ((id: string) => void) | undefined;\n}): React.JSX.Element | null {\n  const { onlyChanged } = useFilterState();\n  if (!onlyChanged || devices.length + states.length === 0) return null;\n  const link = (\n    each: ElsewhereLink,\n    go: ((id: string) => void) | undefined\n  ) => {\n    const words = `${each.label} (${String(each.count)})`;\n    return go === undefined ? (\n      <span key={each.id}>{words}</span>\n    ) : (\n      <button\n        key={each.id}\n        type=\"button\"\n        className=\"nx-settings-note__link\"\n        onClick={() => go(each.id)}\n      >\n        {words}\n      </button>\n    );\n  };\n  const links = [\n    ...devices.map(each => link(each, onDevice)),\n    ...states.map(each => link(each, onState)),\n  ];\n  return (\n    <p className=\"nx-settings-note\">\n      Also changed on{\" \"}\n      {links.map((each, index) => (\n        <React.Fragment key={index}>\n          {index === 0 ? null : \" · \"}\n          {each}\n        </React.Fragment>\n      ))}\n    </p>\n  );\n}\n\n/** The Style tab's sections, as it draws them for the target it edits. */\nexport interface ReportedStyle {\n  readonly nodeId: string;\n  readonly sections: readonly StyleSection[];\n  /** Whether a shared style is the target, which draws no block shortcuts. */\n  readonly shared: boolean;\n  /**\n   * The target's own styles at every state and device: a shared style's\n   * while one is edited, the block's otherwise. What \"Also changed on\" reads.\n   */\n  readonly styles: unknown;\n  /** How the block's parent arranges it, which \"Inside its parent\" offers by. */\n  readonly parent?: ParentArrangement | undefined;\n  /**\n   * Whether Arrange reads the Layout in plain words (not Custom), so its\n   * Space between draws the space properties rather than CSS properties.\n   */\n  readonly arranges?: boolean | undefined;\n}\n\n/**\n * Where the Style tab says what it draws: the sections of the target it is\n * editing, a shared style's while one is chosen, so the filter keeps what\n * the controls show rather than what the block alone holds.\n */\nexport const StyleReportContext: React.Context<\n  ((reported: ReportedStyle | undefined) => void) | undefined\n> = React.createContext<\n  ((reported: ReportedStyle | undefined) => void) | undefined\n>(undefined);\n\n/** What a section set says to the filter: each property, and whether set. */\nfunction sectionsSignature(sections: readonly StyleSection[]): string {\n  return sections\n    .map(\n      section =>\n        `${section.key}:${section.properties\n          .map(property => `${property.property}${property.set ? \"+\" : \"-\"}`)\n          .join(\",\")}`\n    )\n    .join(\"|\");\n}\n\n/**\n * Tells the panel what the Style tab draws, each time that changes, and that\n * it no longer draws anything once it closes.\n */\nexport function useReportStyle(\n  nodeId: string | undefined,\n  sections: readonly StyleSection[] | undefined,\n  shared = false,\n  styles: unknown = undefined,\n  parent: ParentArrangement | undefined = undefined,\n  arranges: boolean | undefined = undefined\n): void {\n  const report = React.useContext(StyleReportContext);\n  // Told only while the panel is filtered: unfiltered, nothing reads it, and\n  // a report would draw the panel a second time for every selection.\n  const on = filtering(useFilterState());\n  const latest = React.useRef({ sections, styles });\n  latest.current = { sections, styles };\n  // The target's other states and devices count too: a value there changes\n  // \"Also changed on\" though no section shown here changes.\n  const signature =\n    sections === undefined || !on\n      ? \"\"\n      : `${sectionsSignature(sections)}\\u0000${JSON.stringify(styles ?? null)}`;\n  React.useEffect(() => {\n    if (report === undefined || nodeId === undefined) return;\n    const now = latest.current;\n    report(\n      on && now.sections !== undefined\n        ? {\n            nodeId,\n            sections: now.sections,\n            shared,\n            styles: now.styles,\n            parent,\n            arranges,\n          }\n        : undefined\n    );\n  }, [report, nodeId, signature, on, shared, parent, arranges]);\n  React.useEffect(() => () => report?.(undefined), [report]);\n}\n\n/**\n * What a tab's sections are while the panel is filtered, apart from the folds\n * the author left: those opened or closed during this search, or all opened\n * or all closed from the panel's menu. None at first: the matches open.\n */\nexport type SearchFold =\n  | {\n      readonly kind: \"chosen\";\n      readonly search: string;\n      readonly open: readonly string[];\n    }\n  | { readonly kind: \"all\"; readonly open: boolean };\n\n/** Each tab's folds while filtered, and how to change one. */\ninterface SearchFolds {\n  readonly folds: Readonly<Record<string, SearchFold | undefined>>;\n  readonly set: (tab: string, fold: SearchFold) => void;\n}\n\nconst NO_SEARCH_FOLDS: SearchFolds = { folds: {}, set: () => {} };\n\nconst SearchFoldsContext = React.createContext<SearchFolds>(NO_SEARCH_FOLDS);\n\n/**\n * Holds the filtered folds under the filter, so the panel's menu folds what\n * the filter shows, and drops them once the filter is off: the same search\n * typed again opens its matches afresh, and the author's folds are untouched.\n */\nfunction SearchFoldsProvider({\n  active,\n  children,\n}: {\n  active: boolean;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const [folds, setFolds] = React.useState<\n    Readonly<Record<string, SearchFold | undefined>>\n  >({});\n  React.useEffect(() => {\n    if (!active)\n      setFolds(current => (Object.keys(current).length === 0 ? current : {}));\n  }, [active]);\n  const value = React.useMemo<SearchFolds>(\n    () => ({\n      folds,\n      set: (tab, fold) => setFolds(current => ({ ...current, [tab]: fold })),\n    }),\n    [folds]\n  );\n  return (\n    <SearchFoldsContext.Provider value={value}>\n      {children}\n    </SearchFoldsContext.Provider>\n  );\n}\n\n/** The panel's filtered folds. */\nexport function useSearchFolds(): SearchFolds {\n  return React.useContext(SearchFoldsContext);\n}\n","\"use client\";\n\n/**\n * The block panel's section folds, lent to the panel: the shell's, held with\n * its other preferences, or the panel's own where it is mounted alone, which\n * then forgets on reload.\n *\n * @module panel-folds-context\n */\nimport * as React from \"react\";\n\nimport {\n  sectionOpens,\n  withSectionFold,\n  type SectionFolds,\n} from \"./panel-folds\";\nimport {\n  useSearchFolds,\n  useSettingsMatch,\n  type SearchFold,\n} from \"./settings-filter\";\nimport type { SettingTab } from \"./settings-index\";\n\n/** The folds and the way to change them. */\nexport interface PanelFolds {\n  readonly folds: SectionFolds;\n  readonly change: (next: (current: SectionFolds) => SectionFolds) => void;\n}\n\n/** The shell's folds, for a panel inside the shell. */\nexport const PanelFoldsContext: React.Context<PanelFolds | undefined> =\n  React.createContext<PanelFolds | undefined>(undefined);\n\n/** The folds lent from above, or none where nothing lends them. */\nconst NO_PANEL_FOLDS: PanelFolds = { folds: {}, change: () => {} };\n\n/** The folds the panel folds by: the shell's, or its own. */\nexport function usePanelFolds(): PanelFolds {\n  return React.useContext(PanelFoldsContext) ?? NO_PANEL_FOLDS;\n}\n\n/**\n * Lends folds to the panel inside it: the ones lent from above where there\n * are any (the shell's), else its own, held here at the panel's root so a\n * section list drawn again for another block or target keeps them.\n */\nexport function PanelFoldsProvider({\n  children,\n}: {\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const above = React.useContext(PanelFoldsContext);\n  const [own, setOwn] = React.useState<SectionFolds>({});\n  const change = React.useCallback(\n    (next: (current: SectionFolds) => SectionFolds) => setOwn(next),\n    []\n  );\n  const value = React.useMemo<PanelFolds>(\n    () => above ?? { folds: own, change },\n    [above, own, change]\n  );\n  return (\n    <PanelFoldsContext.Provider value={value}>\n      {children}\n    </PanelFoldsContext.Provider>\n  );\n}\n\n/**\n * Whether a section drawn above this list is the tab's first, as the Style\n * tab's Block style is above the editing bar: the list's own first section\n * then opens only when it holds a value, so the tab opens on one section.\n */\nexport const FirstSectionAbove: React.Context<boolean> =\n  React.createContext(false);\n\n/** One section of a tab, as its folding needs to know it. */\nexport interface FoldedSection {\n  /** What the accordion knows the section by. */\n  readonly key: string;\n  /** What it is called, which its fold is remembered by. */\n  readonly label: string;\n  readonly holdsValue: boolean;\n  /**\n   * `false` for a section that stays folded until the author opens it even\n   * while it holds a value, as Custom CSS does: its dot still shows, but its\n   * value is no reason to open it.\n   */\n  readonly opensWithValue?: false;\n}\n\n/**\n * A tab's open sections, as an accordion of independent sections reads them,\n * and the change that records which the author opened or closed.\n */\nexport function useTabFolds(\n  tab: string,\n  sections: readonly FoldedSection[]\n): {\n  readonly open: string[];\n  readonly onOpenChange: (open: string[]) => void;\n} {\n  const { folds, change } = usePanelFolds();\n  const match = useSettingsMatch();\n  const firstAbove = React.useContext(FirstSectionAbove);\n  const searchFolds = useSearchFolds();\n  if (match.active) return searchedFolds(tab, sections, match, searchFolds);\n  const open = sections\n    .filter((section, index) =>\n      sectionOpens(folds, tab, section.label, {\n        // A section that opts out opens only as the author leaves it; its\n        // heading's dot reads `holdsValue` on its own.\n        holdsValue: section.holdsValue && section.opensWithValue !== false,\n        first: index === 0 && !firstAbove,\n      })\n    )\n    .map(section => section.key);\n  const onOpenChange = (next: string[]) => {\n    const now = new Set(next);\n    const before = new Set(open);\n    change(current =>\n      sections.reduce(\n        (folded, section) =>\n          now.has(section.key) === before.has(section.key)\n            ? folded\n            : withSectionFold(folded, tab, section.label, now.has(section.key)),\n        current\n      )\n    );\n  };\n  return { open, onOpenChange };\n}\n\n/**\n * A list's folds while the panel is filtered. The sections holding a match\n * open on their own, and what the author opens or closes then is kept for\n * that search alone: the folds they left come back as they were once it is\n * cleared.\n *\n * One record per tab, which every list the tab draws shares (the Style tab\n * draws Block style above the editing bar and the rest under it): its\n * signature is the tab's matches, not one list's, and a list's change\n * replaces only its own sections in it, so folding one list leaves the\n * other's folds as they were.\n */\nfunction searchedFolds(\n  tab: string,\n  sections: readonly FoldedSection[],\n  match: ReturnType<typeof useSettingsMatch>,\n  searchFolds: ReturnType<typeof useSearchFolds>\n): {\n  readonly open: string[];\n  readonly onOpenChange: (open: string[]) => void;\n} {\n  const mine = new Set(sections.map(section => section.key));\n  const tabMatches = [...(match.sections.get(tab as SettingTab) ?? [])].sort();\n  // What a search's own folds belong to: the words and the toggle, and the\n  // sections the tab keeps, so a new device, state, block or search starts\n  // from its matches again.\n  const searching = [\n    match.query,\n    String(match.onlyChanged),\n    ...tabMatches,\n  ].join(\"\\u0000\");\n  const fold = searchFolds.folds[tab];\n  const tabOpen = filteredOpen(fold, searching, tabMatches);\n  return {\n    open: tabOpen.filter(key => mine.has(key)),\n    onOpenChange: next =>\n      searchFolds.set(tab, {\n        kind: \"chosen\",\n        search: searching,\n        open: [\n          ...tabOpen.filter(key => !mine.has(key)),\n          ...next.filter(key => mine.has(key)),\n        ],\n      }),\n  };\n}\n\n/**\n * The open sections while filtered: all or none from the panel's menu, those\n * the author chose during this search, else the matches.\n */\nfunction filteredOpen(\n  fold: SearchFold | undefined,\n  searching: string,\n  matched: string[]\n): string[] {\n  if (fold?.kind === \"all\") return fold.open ? matched : [];\n  if (fold?.kind === \"chosen\" && fold.search === searching) {\n    return [...fold.open];\n  }\n  return matched;\n}\n","/**\n * The editor shell's state, kept apart from the components that render it.\n *\n * Two reasons, and the second is why this file exists at all rather than the\n * state living in the shell component:\n *\n * - It is arithmetic and set membership — which panel is open, how wide it may\n *   be, whether the viewport can carry the full layout. None of it needs React.\n * - A layout cannot be checked by rendering it in jsdom, which reports every\n *   element as zero-sized. A component test of \"the panel is 320px\" measures\n *   nothing and passes whatever the CSS does. The decisions are made here,\n *   where they can be asserted, and the browser verifies the LAYOUT separately.\n *\n * @module shell-state\n */\n\nimport {\n  FIT_ZOOM,\n  readZoom,\n  writeZoom,\n  type CanvasZoom,\n} from \"./canvas/canvas-zoom\";\nimport { readSectionFolds, type SectionFolds } from \"./inspector/panel-folds\";\n\n/**\n * The panels the left rail switches between, in the order an author meets\n * them.\n *\n * One at a time, by decision (PB-D17 D10-1): fixed sides, no docking, no\n * floating. The rail selects; it never opens a second panel beside the first.\n * Settings and Help sit at the rail's foot as dialogs, never panels, so\n * neither is one of these.\n */\nexport const LEFT_PANELS = [\n  \"add\",\n  \"layers\",\n  \"pages\",\n  \"components\",\n  \"design\",\n] as const;\n\nexport type LeftPanel = (typeof LEFT_PANELS)[number];\n\n/**\n * The panel and view a stored preference names.\n *\n * A panel this shell no longer has, renamed or removed, opens the default\n * panel with no part chosen: no table of old names is kept, since no site\n * stored them for long, and the part chosen belonged to the old panel. With\n * no panel open, the part an author last chose is kept, so the panel reopens\n * on it, as it does when a panel is closed and opened again in one session.\n */\nfunction storedPanel(\n  panel: unknown,\n  view: unknown\n): { panel: LeftPanel | null; view: string | null } {\n  const shown = typeof view === \"string\" ? view : null;\n  if (isLeftPanel(panel)) return { panel, view: shown };\n  if (panel === null || panel === undefined)\n    return { panel: null, view: shown };\n  return {\n    panel: DEFAULT_PREFERENCES.leftPanel,\n    view: DEFAULT_PREFERENCES.leftPanelView,\n  };\n}\n\n/**\n * Whether a stored value still names a panel.\n *\n * Persisted preferences outlive the code that wrote them. A panel removed in a\n * later release leaves a string nothing answers to, and restoring it blindly\n * opens a panel that renders nothing — an empty region with no way back to a\n * real one.\n */\nexport function isLeftPanel(value: unknown): value is LeftPanel {\n  return (\n    typeof value === \"string\" &&\n    (LEFT_PANELS as readonly string[]).includes(value)\n  );\n}\n\n/**\n * Width bounds for the two resizable regions, in CSS pixels.\n *\n * DECLARED here and enforced by `react-resizable-panels`, which takes pixel\n * bounds directly (`minSize={240}`) and solves them — including which region\n * yields when a window resize leaves no room. This module deliberately does NOT\n * solve them a second time: a hand-rolled clamp beside a library that already\n * constrains the same drag is two answers to one question, and the two disagree\n * the first time the library changes how it distributes a shortfall.\n *\n * Lower bounds are the point below which a region stops being usable rather than\n * round numbers: a layers tree needs an indent plus a label, and the inspector\n * carries two-column controls.\n *\n * `MIN_CANVAS_WIDTH` is the reason bounds cannot be read per-panel. At the\n * minimum supported viewport, both panels at their individual maximums leave the\n * canvas at 232px — narrower than either panel, in an editor whose subject IS\n * the canvas — and no per-panel bound is violated, because the constraint was\n * never per-panel. Expressed as the canvas panel's OWN minimum, the library\n * enforces it jointly during a drag.\n */\nexport const PANEL_BOUNDS = {\n  left: { min: 240, max: 480, initial: 300 },\n  /*\n   * The inspector's minimum is the width its widest fixed control needs: the\n   * spacing box holds whole from a 264px field column (16.5rem), and the\n   * panel adds 24px of padding and up to 17px of classic scrollbar, which\n   * it keeps room for. Narrower, the box falls back to a list of rows.\n   */\n  inspector: { min: 308, max: 520, initial: 320 },\n} as const;\n\n/**\n * The rail's fixed width in CSS pixels: a 36px icon square with 6px either\n * side. The rail shows icons alone, each named by its tooltip, so it gives the\n * canvas back the width a labelled rail took.\n */\nexport const RAIL_WIDTH = 48;\n\n/**\n * The narrowest the canvas may become before a drag stops taking from it.\n *\n * The canvas is the thing being edited, so it is the region with a floor rather\n * than the one that absorbs whatever is left.\n *\n * This is the EDITING SURFACE, and {@link MIN_CANVAS_PANEL_WIDTH} is what a\n * bound is read from.\n */\nexport const MIN_CANVAS_WIDTH = 480;\n\n/**\n * The narrowest the canvas PANEL may become.\n *\n * The page meets the panel's edges with no gap around it, so the panel and the\n * editing surface it holds are one width, and the panel's floor is the\n * surface's own. Named apart from {@link MIN_CANVAS_WIDTH} because it is what\n * a resize bound is read from, and the surface is what the floor protects.\n */\nexport const MIN_CANVAS_PANEL_WIDTH: number = MIN_CANVAS_WIDTH;\n\n/**\n * The narrowest viewport the full shell is supported at (PB-D17 D10-5).\n *\n * Below this the rail, both panels and a usable canvas do not fit at their\n * minimum widths, so the shell does not try: it shows the canvas and says where\n * to edit instead. A builder that merely gets cramped is worse than one that\n * says it needs more width, because the author discovers the limit by failing\n * at a task.\n */\nexport const MIN_SHELL_WIDTH = 1280;\n\n/**\n * Whether a box of this width can carry the full shell.\n *\n * The parameter is the width of the space the shell was GIVEN, not the\n * window's. The shell sizes to its container, so the two differ whenever it is\n * embedded — a narrow column on a wide display being the case that matters.\n */\nexport function fitsFullShell(width: number): boolean {\n  return width >= MIN_SHELL_WIDTH;\n}\n\n/**\n * What the shell remembers between sessions.\n *\n * The layout is stored as the PROPORTIONAL map `react-resizable-panels` reports\n * from `onLayoutChanged` — panel id to a percentage — never as pixel widths. A\n * pixel layout is wrong on the next monitor; a proportional one survives a\n * window resize, and the pixel BOUNDS still hold because the library re-applies\n * them to whatever the proportions resolve to.\n *\n * Deliberately NOT stored: selection, scroll position, or anything describing\n * the document. Those belong to the document's own state, and a copy here is a\n * second source that goes stale the first time the document changes underneath\n * it.\n */\nexport interface ShellPreferences {\n  leftPanel: LeftPanel | null;\n  /**\n   * Which part of a panel is showing, for a panel with parts — the Design\n   * panel's tab. The host decides what the names mean; the shell only keeps\n   * the one the author last chose.\n   */\n  leftPanelView: string | null;\n  leftPinned: boolean;\n  /**\n   * Whether the author has hidden a side of the editor to give the canvas the\n   * room. Kept apart from which left panel is open, so hiding the left side\n   * and showing it again comes back to the same panel. The top bar's panel\n   * buttons and mod+backslash set them.\n   */\n  leftPanelHidden: boolean;\n  inspectorHidden: boolean;\n  /**\n   * How large the canvas draws the page, as the author last left it.\n   *\n   * Chrome rather than document state, like everything else here: it describes\n   * how one person is looking at the editor, not what the page IS, so it must\n   * not travel with the document to another author.\n   */\n  zoom: CanvasZoom;\n  /**\n   * The breakpoint the author is styling, as they last chose it: an id from the\n   * site's breakpoints, or null for the base one, which is named Desktop.\n   *\n   * A choice, never a reading. Taking it from the width the canvas measured\n   * made opening a panel, or a narrower window, move every edit to a narrower\n   * breakpoint the author never picked. Opening and closing panels changes\n   * only how far the canvas is zoomed to fit.\n   *\n   * Stored as the author left it even when the site no longer defines that\n   * breakpoint: the host resolves an unknown id to the base one, so removing a\n   * breakpoint and adding it back does not lose the choice.\n   */\n  editingBreakpoint: string | null;\n  /**\n   * Layouts, one per PANEL TOPOLOGY.\n   *\n   * Keyed rather than singular because a layout only means anything alongside\n   * the panel set it was measured for. The left panel is conditionally\n   * rendered, so the group has two shapes — with it and without — and their\n   * layouts have different keys and different arithmetic. Stored as one record\n   * they overwrote each other: resizing with a panel open and then closing it\n   * left a three-key layout that no two-panel group could accept, so the widths\n   * were dropped on the next load.\n   *\n   * This is the shape the panel library's own persistence helper uses, for the\n   * same reason — its `panelIds` prop exists so a group with conditionally\n   * rendered panels can \"save and restore multiple layouts\".\n   *\n   * Outer key: {@link topologyKey} over the mounted panel ids.\n   * Inner: panel id to percentage.\n   */\n  layouts: Record<string, Record<string, number>>;\n  /**\n   * Whether the rail's single-letter keys (A, L, P, C, D) open its panels.\n   *\n   * ON by default, and a preference because a key with no modifier can be\n   * set off by speech input or a stray press: WCAG 2.1.4 asks that such a\n   * shortcut can be turned off. Help holds the switch, beside the keys.\n   *\n   * Optional in this published type, so a host that builds preferences\n   * written before the switch still compiles; absent reads as on.\n   */\n  panelKeys?: boolean;\n  /**\n   * Which sections of the block panel the author left open or closed, by tab\n   * and section name (`panel-folds`).\n   *\n   * Optional in this published type, as `panelKeys` is; absent reads as none\n   * remembered.\n   */\n  sectionFolds?: SectionFolds;\n  /**\n   * Whether the block panel prints each control's CSS names under its label\n   * (\"Show CSS names\" in the panel's options menu). Off by default, and\n   * optional in this published type, as `panelKeys` is: absent reads as off.\n   */\n  showCssNames?: boolean;\n}\n\n/**\n * The class marking the editor shell's own root element.\n *\n * The scope every piece of editor chrome is drawn inside. Kept here and away\n * from the component because `builder-chrome.css` has to spell it out\n * literally, and a marker spelled out literally is one a rename can break\n * silently: so it has one exported spelling that the shell writing it, the\n * code asking about it and the test pinning the stylesheet all take from.\n */\nexport const BUILDER_CHROME_CLASS = \"nx-builder-chrome\";\n\n/**\n * A scope that resolves `--nx-builder-*` without claiming to be the chrome root.\n *\n * For a surface the shell mounts OUTSIDE {@link BUILDER_CHROME_CLASS} — custom\n * properties inherit down and never across, so such a surface needs the tokens\n * declared on an ancestor of its own. Giving it the chrome class instead would\n * put a second chrome root in the document, and every selector and query\n * meaning \"the editor\" would match whichever came first.\n */\nexport const BUILDER_TOKENS_CLASS = \"nx-builder-tokens\";\n\n/**\n * The class marking the canvas root, and the boundary the hit-test stops at.\n *\n * Here rather than in `canvas.tsx` for the reason above: it is the middle term\n * of the empty-container affordance's selector, which `empty-slot.ts` composes\n * — and reaching into the canvas COMPONENT for it would pull a React module\n * into every consumer of that constant, for one string. `canvas.tsx` re-exports\n * it, so callers reading it as the canvas's own marker are unaffected.\n *\n * The hit-test walk needs an upper bound (see `nodeIdFromEvent`), and that\n * bound has to be identifiable from a DOM node rather than from React state,\n * because the walk starts at an event target and climbs.\n */\nexport const CANVAS_ROOT_CLASS = \"nx-canvas\";\n\n/**\n * The identity of a panel arrangement, from the panels themselves.\n *\n * Sorted and joined rather than taken from `leftPanel`, so it is derived from\n * what is actually MOUNTED rather than from a second description of it that can\n * disagree. Sorting makes it independent of the order the ids arrive in, which\n * varies with how a host's JSON was serialised.\n */\nexport function topologyKey(panelIds: readonly string[]): string {\n  return [...panelIds].sort().join(\",\");\n}\n\nexport const DEFAULT_PREFERENCES: ShellPreferences = {\n  leftPanel: null,\n  leftPanelView: null,\n  leftPinned: true,\n  leftPanelHidden: false,\n  inspectorHidden: false,\n  zoom: FIT_ZOOM,\n  editingBreakpoint: null,\n  layouts: {},\n  panelKeys: true,\n  sectionFolds: {},\n  showCssNames: false,\n};\n\n/**\n * Where preferences are read and written.\n *\n * A PORT rather than a direct `localStorage` call, for two reasons that both\n * bite later. The ratified plan wants these durable per user on the server\n * eventually, and a component reaching for `localStorage` makes that a rewrite\n * instead of a different argument. And `localStorage` does not exist while the\n * shell renders on a server, so a direct call is a crash rather than a default.\n *\n * Both methods may fail and the shell must not care: storage is unavailable in\n * private browsing on some engines, and a quota error is possible on write.\n */\nexport interface PreferenceStore {\n  read: () => string | null;\n  write: (value: string) => void;\n}\n\n/** A store that remembers nothing, for a server render and for a browser that refuses storage. */\nexport const NO_STORAGE: PreferenceStore = {\n  read: () => null,\n  write: () => undefined,\n};\n\n/**\n * A `localStorage`-backed store under one key.\n *\n * Takes the key rather than owning one, so the shell's chrome preferences and\n * anything else the editor remembers share this port instead of each writing\n * their own `typeof window` check and their own swallow. Outside a browser it\n * degrades to {@link NO_STORAGE} rather than throwing, which is the whole\n * reason the port exists.\n *\n * @param key - where to store the value\n * @returns a store, or one that remembers nothing outside a browser\n *\n * @experimental\n */\nexport function browserStore(key: string): PreferenceStore {\n  if (typeof window === \"undefined\") return NO_STORAGE;\n  return {\n    read: () => window.localStorage.getItem(key),\n    write: value => window.localStorage.setItem(key, value),\n  };\n}\n\n/**\n * Where the shell keeps its preferences in a browser: under this key alone\n * for a host that names no user, and under this key and the user's id for\n * one that does.\n */\nexport const SHELL_PREFERENCES_KEY = \"nextly.builder.shell\";\n\n/**\n * The shell's preferences for one signed-in user, so two authors of one\n * browser each get their own panel, device and zoom.\n *\n * Preferences stored before they were kept per user sit under the shell's key\n * alone. The first user to load with no record of their own takes that one:\n * it is copied to theirs and removed, so it moves once and no second author\n * inherits it. With no user known (signed out, or not read yet), nothing is\n * remembered: a record kept for a guess would be read by the wrong author.\n *\n * A host whose browser storage follows rules of its own (a site that keeps\n * nothing on the device, a sign-out that forgets the person) passes `open`,\n * which opens the store under a key; both records, the user's and the one\n * from before, are then read, written and removed through it alone.\n *\n * @param userId - the signed-in user's id, or null when there is none\n * @param open - opens the store under a key; this browser's storage by default\n * @returns a store under that user's own key, or one that keeps nothing\n */\nexport function userPreferenceStore(\n  userId: string | null,\n  open: OpenPreferenceStore = browserStoreWithRemove\n): PreferenceStore {\n  if (userId === null || typeof window === \"undefined\") return NO_STORAGE;\n  // One store per user and opener, so a host may call this on every render:\n  // a new object would read as a different store, and the shell would reload.\n  let stores = userStores.get(open);\n  if (stores === undefined) {\n    stores = new Map();\n    userStores.set(open, stores);\n  }\n  const cached = stores.get(userId);\n  if (cached !== undefined) return cached;\n  const store = keyedStore(userId, open);\n  stores.set(userId, store);\n  return store;\n}\n\n/**\n * Opens the store under a key, one that can also remove what it holds: the\n * record from before is removed once moved, so no second author inherits it.\n *\n * @experimental\n */\nexport type OpenPreferenceStore = (\n  key: string\n) => PreferenceStore & { remove: () => void };\n\n/** {@link browserStore}, able to remove what it holds. */\nfunction browserStoreWithRemove(\n  key: string\n): PreferenceStore & { remove: () => void } {\n  return {\n    ...browserStore(key),\n    remove: () => window.localStorage.removeItem(key),\n  };\n}\n\n/** The stores handed out so far, by opener and then user id. */\nconst userStores = new WeakMap<\n  OpenPreferenceStore,\n  Map<string, PreferenceStore>\n>();\n\n/** The store under one user's own key, moving the earlier record on a read. */\nfunction keyedStore(\n  userId: string,\n  open: OpenPreferenceStore\n): PreferenceStore {\n  const own = open(`${SHELL_PREFERENCES_KEY}:${userId}`);\n  const before = open(SHELL_PREFERENCES_KEY);\n  return {\n    read: () => {\n      const kept = own.read();\n      if (kept !== null) return kept;\n      const moved = before.read();\n      if (moved === null) return null;\n      own.write(moved);\n      before.remove();\n      return moved;\n    },\n    write: own.write,\n  };\n}\n\n/**\n * A stored layout, accepted only if every entry is a usable percentage.\n *\n * Partial acceptance would be worse than rejection here: the library\n * distributes a layout across ALL panels, so a map missing one or carrying a\n * `NaN` resolves to a layout nobody chose. The whole map is the unit.\n */\n/**\n * The stored layouts, dropping any entry that is not usable.\n *\n * Per-topology rather than all-or-nothing: a layout written under a panel set\n * that no longer exists should cost the author only that arrangement's widths,\n * not the ones they set for every other arrangement.\n */\nfunction readLayouts(value: unknown): Record<string, Record<string, number>> {\n  if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n    return {};\n  }\n  const layouts: Record<string, Record<string, number>> = {};\n  for (const [key, layout] of Object.entries(value)) {\n    if (isLayout(layout)) layouts[key] = layout;\n  }\n  return layouts;\n}\n\nfunction isLayout(value: unknown): value is Record<string, number> {\n  if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n    return false;\n  }\n  const entries = Object.entries(value as Record<string, unknown>);\n  return (\n    entries.length > 0 &&\n    entries.every(\n      ([, size]) =>\n        typeof size === \"number\" && Number.isFinite(size) && size > 0\n    )\n  );\n}\n\n/**\n * Preferences parsed from whatever was stored.\n *\n * Every field is validated separately and falls back on its own, rather than\n * one malformed field discarding the rest. A layout written under a different\n * panel set should reset the layout, not the author's panel choice with it.\n *\n * Only the fields named below are read, and anything else in the record is\n * ignored rather than refused. Records written by an earlier release still\n * carry `showEmptyElements`, a preference that no longer exists because empty\n * containers are always shown: such a record loads whole, without it.\n */\nexport function readPreferences(store: PreferenceStore): ShellPreferences {\n  let raw: unknown;\n  try {\n    const stored = store.read();\n    if (stored === null) return DEFAULT_PREFERENCES;\n    raw = JSON.parse(stored);\n  } catch {\n    // Unreadable storage or malformed JSON. Neither says anything about the\n    // author's intent, so the defaults are the honest answer.\n    return DEFAULT_PREFERENCES;\n  }\n\n  if (typeof raw !== \"object\" || raw === null) return DEFAULT_PREFERENCES;\n  const record = raw as Record<string, unknown>;\n\n  const left = storedPanel(record.leftPanel, record.leftPanelView);\n  return {\n    leftPanel: left.panel,\n    leftPanelView: left.view,\n    leftPinned:\n      typeof record.leftPinned === \"boolean\"\n        ? record.leftPinned\n        : DEFAULT_PREFERENCES.leftPinned,\n    // Shown unless a stored true says otherwise, which covers every\n    // preference written before a side could be hidden.\n    leftPanelHidden: record.leftPanelHidden === true,\n    inspectorHidden: record.inspectorHidden === true,\n    // Fit when the stored value is not a zoom, which includes every preference\n    // written before there was one. `readZoom` refuses a scale outside the\n    // bounds rather than painting the canvas somewhere the control cannot be\n    // reached to undo it.\n    zoom: readZoom(record.zoom) ?? DEFAULT_PREFERENCES.zoom,\n    editingBreakpoint:\n      typeof record.editingBreakpoint === \"string\" &&\n      record.editingBreakpoint !== \"\"\n        ? record.editingBreakpoint\n        : DEFAULT_PREFERENCES.editingBreakpoint,\n    layouts: readLayouts(record.layouts),\n    // On unless a stored false says otherwise, which covers every preference\n    // written before the keys could be turned off.\n    panelKeys: record.panelKeys !== false,\n    sectionFolds: readSectionFolds(record.sectionFolds),\n    // Off unless a stored true says otherwise.\n    showCssNames: record.showCssNames === true,\n  };\n}\n\n/** Preferences written back, ignoring a store that refuses. */\nexport function writePreferences(\n  store: PreferenceStore,\n  preferences: ShellPreferences\n): void {\n  try {\n    // Narrowed on the way out for the reason it is checked on the way in: what\n    // is stored is a value this can read back, not whatever shape the running\n    // editor happens to hold.\n    store.write(\n      JSON.stringify({ ...preferences, zoom: writeZoom(preferences.zoom) })\n    );\n  } catch {\n    // A quota error or unavailable storage. Losing a panel width is not worth\n    // interrupting an edit over, and there is nothing the author could do.\n  }\n}\n\n/**\n * The panel a rail click selects.\n *\n * Clicking the open panel's own rail item CLOSES it. That is what makes the\n * rail a toggle rather than a one-way switch, and it is the only way to reach a\n * full-width canvas without a separate control.\n */\nexport function panelAfterRailClick(\n  current: LeftPanel | null,\n  clicked: LeftPanel\n): LeftPanel | null {\n  return current === clicked ? null : clicked;\n}\n","\"use client\";\n\n/**\n * Whether the shell around a subtree is currently interactive.\n *\n * Its own module rather than a member of `builder-shell`, because the answer has\n * two kinds of consumer and they sit on opposite sides of that file. The shell\n * PROVIDES it; the notice machinery and the command palette CONSUME it. Declared\n * in the shell, a consumer that the shell also imports — `builder-notices` is\n * both — has to import back into it, which is an import cycle for a boolean.\n *\n * @module shell-active\n */\nimport * as React from \"react\";\n\n/**\n * Whether the shell around this subtree is currently interactive.\n *\n * Defaults to `true`, which covers both callers outside a shell entirely and the\n * server render, where the width is unknowable — the same assumption the shell's\n * own width hook makes and for the same reason.\n */\nexport const ShellActiveContext: React.Context<boolean> =\n  React.createContext(true);\n\n/**\n * Whether the surrounding shell is interactive, for content that has to answer for itself.\n *\n * The shell hides its slots behind `hidden` and `inert` below its minimum width, which is enough\n * for anything rendering in place. It is NOT enough for two other cases. Anything that portals to\n * the document body escapes the wrapper — a dialog would sit over the narrow-screen notice, fully\n * interactive. And anything DECIDING WHERE TO SPEAK has to know as well: `hidden` and `inert` do\n * not unmount, so a component behind the notice is still mounted and would go on reporting into a\n * subtree that is excluded from the accessibility tree.\n *\n * Such a component reads this instead of re-deriving the width, so one media query decides them\n * all and they cannot disagree.\n *\n * @experimental\n */\nexport function useShellIsActive(): boolean {\n  return React.useContext(ShellActiveContext);\n}\n","/**\n * Notices about work the builder started and could not finish.\n *\n * A control that reports its own failure beside itself is the better surface,\n * and every control here does that where it can. This exists for the case it\n * cannot: a failure that arrives after the control reporting it has gone.\n *\n * ## Why the state cannot live in the control\n *\n * The style inspector renders {@link class-selector} with `key={nodeId}`, so\n * changing selection UNMOUNTS it — deliberately, because an unkeyed selector is\n * reused across the change and Enter then applies the previous block's pending\n * choice to the new block. A site-style write is asynchronous and an author\n * does not wait for it, so a refusal can land after that unmount, on an\n * instance whose `setState` reaches nothing. The class was not created and\n * nothing says so.\n *\n * The key is load-bearing, so the failure is what moves. This holds it ABOVE\n * the keyed subtree, in the shell, which no selection change unmounts.\n *\n * ## Why the builder owns it rather than the host\n *\n * A host callback would be optional, like every other host prop here, and a\n * host that omitted it would swallow the failure exactly as before — with a\n * contract making it look handled. Owning the surface means every host gets it,\n * including one with no notification system of its own.\n *\n * ## What belongs here\n *\n * Only a failure with nowhere else to appear. A notice that duplicates a\n * message already on screen makes the author read the same sentence twice and\n * teaches them to ignore the region, so a control that can still be READ\n * reports for itself and stays silent here.\n *\n * Read rather than merely mounted, and the difference is the whole of\n * {@link useSurvivingReport}. Below its minimum width the shell puts its\n * subtree behind `hidden` and `inert`, and neither unmounts anything: a control\n * behind that notice still renders while being excluded from paint and from the\n * accessibility tree, so \"it is mounted, let it speak for itself\" sends the\n * message somewhere nobody can reach.\n *\n * ## Where it must render\n *\n * Two constraints, and they pull in opposite directions.\n *\n * OUTSIDE the subtree the shell makes `hidden` and `inert`, because that is\n * exactly when this surface is needed and an inert region is excluded from the\n * accessibility tree. A region inside it is unreachable by eye and by screen\n * reader at the same moment.\n *\n * INSIDE a scope that declares `--nx-builder-*`, because custom properties\n * inherit down and never across: with neither ancestor supplying them, every\n * border, background and text declaration resolves to nothing — a transparent\n * box with host-default text, which in dark mode is a failure message the\n * author cannot read.\n *\n * `.nx-builder-tokens` is what satisfies both. `.nx-builder-chrome` would not:\n * it identifies the editor's ROOT as well as declaring the tokens, so a\n * floating region claiming it puts a second root in the document and every\n * selector meaning \"the editor\" matches whichever comes first — and it paints a\n * background and a colour, so the region would also be claiming the frame.\n *\n * Mounted UNCONDITIONALLY rather than switched between the shell's two\n * branches. A live region has to exist before text is put into it, and one\n * remounted whenever the width crosses the threshold is created at the moment\n * it is needed; one permanent mount also keeps there being exactly one, since\n * two live regions interfere and some messages are announced by neither.\n *\n * @module builder-notices\n */\nimport { Button, useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useShellIsActive } from \"./shell-active\";\n\n/** One thing that failed, in the words an author reads. */\nexport interface BuilderNotice {\n  /** Identity for the list, and what dismissing addresses. */\n  readonly id: string;\n  /** The sentence shown. Already written for an author, not a log line. */\n  readonly message: string;\n}\n\n/** Raise a notice. Returns nothing: nobody waits on a report. */\nexport type RaiseNotice = (message: string) => void;\n\n/**\n * The sink, or nothing when no shell is above.\n *\n * `null` rather than a no-op default so {@link useNoticeSink} can tell \"no\n * provider\" from \"a provider that did nothing\", and so a component rendered\n * outside a shell — which the tests do constantly — keeps working.\n */\nconst NoticeSinkContext = React.createContext<RaiseNotice | null>(null);\n\n/**\n * Report a failure the caller cannot display itself.\n *\n * Answers a no-op when nothing above provides a sink, because a control must\n * not require a shell to render. The caller therefore cannot use a return value\n * to decide whether the author was told, and none is offered: a control that\n * needs to be sure reports for itself while it still can.\n */\nexport function useNoticeSink(): RaiseNotice {\n  const sink = React.useContext(NoticeSinkContext);\n  return React.useMemo(() => sink ?? (() => undefined), [sink]);\n}\n\n/**\n * Report a failure that may outlive the control raising it.\n *\n * Two surfaces need this and they had a copy each: the class selector, keyed by\n * node, and the class manager, mounted only while its panel is the open one.\n * Both dispatch a site-style write, both can be unmounted before it answers,\n * and both must still tell the author.\n *\n * WHERE is the shared question and is answered here; WHETHER the caller can\n * still show it is not, so that stays with the caller. The selector's inline\n * message is scoped to the node the request was made against and must be\n * withheld when the author has moved to another one — a rule the manager has no\n * equivalent of. So `showInline` answers whether it took responsibility, and\n * the notice is raised only when nothing did.\n *\n * The two are exclusive on purpose: a region repeating what is already on\n * screen is one an author learns to stop reading.\n */\nexport function useSurvivingReport(): (\n  reason: string,\n  showInline: () => boolean\n) => void {\n  const raiseNotice = useNoticeSink();\n  /*\n   * Whether the caller can still draw. A ref rather than state because nothing\n   * renders from it and setting it must schedule no work: it is read inside a\n   * callback that has already outlived the render it came from.\n   */\n  const mounted = React.useRef(true);\n  React.useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n    };\n  }, []);\n  /*\n   * The other half of \"can still draw\", and the reason being mounted is not it.\n   *\n   * The shell puts its whole subtree behind `hidden` and `inert` below its\n   * minimum width, and neither attribute unmounts anything — so a caller behind\n   * the narrow-width notice is still mounted, still renders, and is excluded\n   * from both the layout and the accessibility tree. Deciding on `mounted`\n   * alone stores the message inline on a surface nobody can reach, and the\n   * author leaves without learning the write was refused.\n   *\n   * Tracked through a ref, because the callback below is invoked long after the\n   * render that created it — a value closed over at request time describes the\n   * shell as it was when the request STARTED, which is exactly the state that\n   * has since changed.\n   *\n   * Synchronised from a COMMITTED-phase effect rather than assigned during\n   * render. A render can be abandoned: React may begin rendering a widening\n   * shell and drop that work while the hidden subtree is still the one on\n   * screen, and a render-time assignment would have already reported the shell\n   * as readable. The message would then be stored inline in the subtree the\n   * author still cannot see, which is the failure this whole hook exists to\n   * prevent, reached by a narrower door.\n   *\n   * Layout timing rather than passive, because passive effects flush after\n   * paint: between the commit that hides the shell and that flush, the ref\n   * would still describe the previous committed state. That window is small and\n   * it is the same window the rest of this file is about, so it is closed\n   * rather than reasoned about.\n   */\n  const shellIsActive = useShellIsActive();\n  const active = React.useRef(shellIsActive);\n  useIsomorphicLayoutEffect(() => {\n    active.current = shellIsActive;\n  }, [shellIsActive]);\n  return (reason, showInline) => {\n    if (mounted.current && active.current && showInline()) return;\n    raiseNotice(reason);\n  };\n}\n\n/** Put a sink in reach of everything the shell renders. */\nexport function NoticeSinkProvider({\n  raise,\n  children,\n}: {\n  raise: RaiseNotice;\n  children: React.ReactNode;\n}): React.ReactElement {\n  return (\n    <NoticeSinkContext.Provider value={raise}>\n      {children}\n    </NoticeSinkContext.Provider>\n  );\n}\n\n/** What the shell holds so a notice outlives the control that raised it. */\nexport interface NoticeQueue {\n  readonly notices: readonly BuilderNotice[];\n  readonly raise: RaiseNotice;\n  readonly dismiss: (id: string) => void;\n}\n\n/**\n * The queue, owned by whoever renders the region.\n *\n * Identity is a counter rather than the message, because the same failure can\n * happen twice and an author who dismissed the first is owed the second. It is\n * a ref rather than state: bumping it must not schedule a render of its own,\n * and nothing reads it except the notice being built.\n */\nexport function useNoticeQueue(): NoticeQueue {\n  const [notices, setNotices] = React.useState<readonly BuilderNotice[]>([]);\n  const nextId = React.useRef(0);\n\n  const raise = React.useCallback((message: string) => {\n    nextId.current += 1;\n    const id = `notice-${nextId.current}`;\n    setNotices(current => {\n      // The same sentence already on screen is the same news. Repeating it\n      // stacks identical rows for one retried action and pushes the rest of\n      // the shell down for no added information.\n      if (current.some(notice => notice.message === message)) return current;\n      return [...current, { id, message }];\n    });\n  }, []);\n\n  const dismiss = React.useCallback((id: string) => {\n    setNotices(current => current.filter(notice => notice.id !== id));\n  }, []);\n\n  return { notices, raise, dismiss };\n}\n\n/**\n * The notices, or nothing at all.\n *\n * The container is ALWAYS mounted, and only its rows come and go. A polite\n * live region has to exist before its content changes: unlike `role=\"alert\"`,\n * one inserted already carrying its message is not reliably announced, so a\n * screen-reader user could miss the only report that a class was not created.\n * Empty it holds no rows and has no box of its own, so the layout carries no\n * permanent gap for a surface that is silent almost always.\n *\n * `role=\"status\"` rather than `role=\"alert\"`: these are reports about an action\n * the author already took, and `alert` interrupts a screen reader mid-sentence\n * for something that is not an emergency. `aria-live=\"polite\"` follows from it\n * and is stated anyway, because the implicit value differs between engines.\n */\nexport function BuilderNoticeRegion({\n  notices,\n  onDismiss,\n}: {\n  notices: readonly BuilderNotice[];\n  onDismiss: (id: string) => void;\n}): React.ReactElement | null {\n  return (\n    <div\n      className=\"nx-notices\"\n      role=\"status\"\n      aria-live=\"polite\"\n      /*\n       * `role=\"status\"` is atomic by default, so adding one notice makes a\n       * screen reader read every notice on screen again. False announces the\n       * row that changed and leaves the rest alone.\n       */\n      aria-atomic=\"false\"\n    >\n      {notices.map(notice => (\n        <div className=\"nx-notices__item\" key={notice.id}>\n          <p className=\"nx-notices__text\">{notice.message}</p>\n          <Button\n            className=\"nx-notices__dismiss\"\n            onClick={() => onDismiss(notice.id)}\n            size=\"sm\"\n            type=\"button\"\n            variant=\"ghost\"\n          >\n            Dismiss\n          </Button>\n        </div>\n      ))}\n    </div>\n  );\n}\n","/**\n * The shell's preferences: read from the author's store, held while the shell\n * is open, and written back only when one has changed.\n *\n * @module shell-preferences\n */\nimport * as React from \"react\";\n\nimport type { CanvasZoom } from \"../canvas/canvas-zoom\";\nimport type { SectionFolds } from \"../inspector/panel-folds\";\nimport {\n  DEFAULT_PREFERENCES,\n  readPreferences,\n  writePreferences,\n  type PreferenceStore,\n  type ShellPreferences,\n} from \"../shell-state\";\n\n/**\n * What the newest completed read of a preference store left behind.\n *\n * TWO fields because there are two different questions downstream, and one\n * value cannot answer both:\n *\n * - `count` answers \"has a NEW record arrived\", which is what a remount is\n *   keyed on. Any read qualifies: the panel group has to re-register against\n *   whatever layout landed, whoever it belongs to.\n * - `store` answers \"whose record is `preferences` holding right now\", which is\n *   what any guard protecting a WRITE needs. The count cannot answer it — it is\n *   monotonic, so it is already nonzero for the previous store the moment a host\n *   swaps in a new one, and a write let through in that window spreads the old\n *   store's record and persists it into the new store, replacing the layout and\n *   the zoom of whichever user or workspace the new store belongs to.\n *\n * `store` is the store OBJECT rather than a name or an index, for the reason\n * the identity is already the read's dependency: it is the thing itself, and no\n * two live stores can compare equal without being the same store.\n *\n * `null` is the state before any read has completed, and it is deliberately not\n * a fourth thing to test for: every caller compares this against the store it\n * is about to act on, and `null` is not any store, so \"no read yet\" and \"a\n * different store's read\" answer alike without either being spelled out.\n */\ninterface PreferencesLoad {\n  readonly count: number;\n  readonly store: PreferenceStore | null;\n}\n\n/** Before any read has reached state. */\nconst NO_LOAD: PreferencesLoad = { count: 0, store: null };\n\n/**\n * Preferences, restored AFTER mount and written back whenever they change.\n *\n * Reading storage in the initializer is the obvious shape and it is wrong here.\n * On a server render the default store answers `null`, so the server emits the\n * defaults; the client initializer reads `localStorage` and emits a restored\n * panel. React 19 treats that divergence as a hydration failure and rebuilds\n * the subtree — so a returning author's restored layout arrives as a flash and\n * a discarded tree rather than as a layout.\n *\n * Both first renders therefore start from the defaults, and the stored\n * preferences are applied in an effect. The cost is one frame of default\n * chrome; the alternative is a mismatch on every load for anyone who has ever\n * moved a panel.\n */\nexport function usePreferences(\n  store: PreferenceStore\n): readonly [\n  ShellPreferences,\n  (change: (current: ShellPreferences) => ShellPreferences) => void,\n  number,\n  boolean,\n] {\n  const [preferences, setPreferences] =\n    React.useState<ShellPreferences>(DEFAULT_PREFERENCES);\n  const [load, setLoad] = React.useState<PreferencesLoad>(NO_LOAD);\n\n  React.useEffect(() => {\n    const restored = readPreferences(store);\n    // Compared before setting so a host with no stored preferences does not\n    // take a second render for a value that did not change.\n    setPreferences(current =>\n      shallowEqualPreferences(current, restored) ? current : restored\n    );\n    // Set in the SAME effect as the preferences it describes, which is what\n    // makes `store` below an honest account of whose record `preferences`\n    // holds: React applies both updates in one commit, so no render can see\n    // one without the other.\n    setLoad(current => ({ count: current.count + 1, store }));\n  }, [store]);\n\n  // The newest preferences, reachable from a callback that must not go stale.\n  const latest = React.useRef(preferences);\n  latest.current = preferences;\n\n  /**\n   * Takes a CHANGE rather than a value, and this is load-bearing.\n   *\n   * `react-resizable-panels` calls `onLayoutChanged` once a drag settles, from\n   * a handler React captured when the panel was rendered. Handed a whole\n   * record built by spreading `preferences` from that render, a drag begun\n   * before an unrelated change would write the OLD record back with only the\n   * layout replaced — silently discarding whichever field moved in between.\n   *\n   * Measured, not theorised: opening a panel and then dragging its separator\n   * wrote `leftPanel: null` back over the open panel, so the panel vanished on\n   * the next load. jsdom cannot see this — its inert `ResizeObserver` means\n   * `onLayoutChanged` never fires there — which is why it took a browser.\n   */\n  const update = React.useCallback(\n    (change: (current: ShellPreferences) => ShellPreferences) => {\n      const next = change(latest.current);\n      latest.current = next;\n      setPreferences(next);\n      writePreferences(store, next);\n    },\n    [store]\n  );\n\n  /*\n   * The store-specific answer is derived HERE rather than handed out for a\n   * caller to work out, because the comparison is only sound against the same\n   * store the read was keyed on — and that is this argument. Returning\n   * `load.store` instead would leave every caller re-deriving it, and a caller\n   * holding a different store variable (the shell resolves a fallback of its\n   * own) would compare the wrong pair while looking correct.\n   */\n  return [preferences, update, load.count, load.store === store] as const;\n}\n\n/**\n * Whether two preference records say the same thing.\n *\n * EVERY field has to be compared here, because this is what the restore\n * effect gates on: a field missing from this function reads as \"unchanged\"\n * for any two records that differ only in it, so a stored non-default value\n * for that field is silently dropped on mount whenever the rest of the record\n * already matches the default — which a fresh session with nothing else\n * customised does by construction.\n *\n * The layout is compared by its entries rather than by identity: `readPreferences`\n * builds a fresh object every call, so identity is always false and the restore\n * effect would set state on every mount even when nothing changed.\n */\n/** Whether two zooms mean the same thing, which is not object identity. */\nfunction sameZoom(a: CanvasZoom, b: CanvasZoom): boolean {\n  if (a.kind !== b.kind) return false;\n  return a.kind === \"fixed\" && b.kind === \"fixed\" ? a.scale === b.scale : true;\n}\n\n/**\n * The preferences compared by value. Listed once, so a field added to\n * `ShellPreferences` is compared by adding it here; one left out reads as\n * \"unchanged\" and is dropped on load. `zoom` and `layouts` are compared below.\n */\nconst SCALAR_PREFERENCES = [\n  \"leftPanel\",\n  \"leftPanelView\",\n  \"leftPanelHidden\",\n  \"inspectorHidden\",\n  \"leftPinned\",\n  \"panelKeys\",\n  \"showCssNames\",\n  \"editingBreakpoint\",\n] as const satisfies readonly (keyof ShellPreferences)[];\n\n/** Whether two records of section folds say the same. */\nfunction sameFolds(\n  a: SectionFolds | undefined,\n  b: SectionFolds | undefined\n): boolean {\n  if (a === b) return true;\n  const left = a ?? {};\n  const right = b ?? {};\n  const keys = Object.keys(left);\n  return (\n    keys.length === Object.keys(right).length &&\n    keys.every(key => left[key] === right[key])\n  );\n}\n\nfunction shallowEqualPreferences(\n  a: ShellPreferences,\n  b: ShellPreferences\n): boolean {\n  if (SCALAR_PREFERENCES.some(key => a[key] !== b[key])) return false;\n  if (!sameZoom(a.zoom, b.zoom)) return false;\n  if (!sameFolds(a.sectionFolds, b.sectionFolds)) return false;\n  if (a.layouts === b.layouts) return true;\n  const topologies = Object.keys(a.layouts);\n  if (topologies.length !== Object.keys(b.layouts).length) return false;\n  return topologies.every(topology => {\n    const left = a.layouts[topology];\n    const right = b.layouts[topology];\n    if (left === undefined || right === undefined) return false;\n    const ids = Object.keys(left);\n    return (\n      ids.length === Object.keys(right).length &&\n      ids.every(id => left[id] === right[id])\n    );\n  });\n}\n","/**\n * The editor chrome's tooltip: the one every control beside the canvas uses.\n *\n * Two things the shared `@nextlyhq/ui` tooltip cannot know, because they are\n * the editor's:\n *\n * - **The canvas is a frame.** A pointer leaving a control for the canvas\n *   passes into another document, so this one sees no further move, and Radix,\n *   waiting to learn whether the pointer is heading for the tooltip, kept it\n *   open over the canvas. The frame's own element does receive `pointerover`\n *   as the pointer enters it, so that closes the tooltip. Moving onto the\n *   tooltip itself still keeps it (WCAG 1.4.13), and so does keyboard focus on\n *   its control: for an icon-only control the tooltip is its only visible\n *   name, and the author is still on it.\n * - **Rows sit close.** Below its control by default, over the next row, which\n *   the author is not reading while pointing here; above, it covered the value\n *   of the row before. Kept clear of the panel's edges.\n *\n * Each surface keeps its own `TooltipProvider`, which sets the delay.\n *\n * @module chrome-tooltip\n */\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { isIFrame } from \"./canvas/dom-kind\";\n\n/** How far a tooltip keeps from the edges of what holds it, in pixels. */\nconst COLLISION_PADDING = 8;\n\nexport interface ChromeTooltipProps {\n  /** What the tooltip says. */\n  content: React.ReactNode;\n  /** The control it names: one element, which becomes the trigger. */\n  children: React.ReactElement;\n  /** Which side of the control it opens on; below when absent. */\n  side?: \"top\" | \"right\" | \"bottom\" | \"left\";\n  align?: \"start\" | \"center\" | \"end\";\n  /** Classes for the tooltip's content. */\n  className?: string;\n  /**\n   * Keeps the tooltip closed while its control stays wrapped: a control whose\n   * tooltip comes and goes keeps one element, so focus on it survives.\n   */\n  disabled?: boolean;\n}\n\n/**\n * A tooltip's open state that also closes when the pointer moves into a frame,\n * unless its control has keyboard focus.\n */\nfunction useClosedByFrames(): {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  trigger: React.RefObject<HTMLButtonElement | null>;\n} {\n  const [open, setOpen] = React.useState(false);\n  const trigger = React.useRef<HTMLButtonElement | null>(null);\n  React.useEffect(() => {\n    if (!open) return;\n    const intoFrame = (event: PointerEvent) => {\n      if (!isIFrame(event.target)) return;\n      // `:focus-visible`, not focus: a clicked control keeps focus too, and\n      // its tooltip was opened by the pointer that has now left it.\n      if (trigger.current?.matches(\":focus-visible\") === true) return;\n      setOpen(false);\n    };\n    // The trigger's own document: the shell can be drawn inside a frame of\n    // its own, where the canvas frame's events never reach the outer one.\n    const at = trigger.current?.ownerDocument ?? document;\n    at.addEventListener(\"pointerover\", intoFrame, true);\n    return () => at.removeEventListener(\"pointerover\", intoFrame, true);\n  }, [open]);\n  return { open, onOpenChange: setOpen, trigger };\n}\n\nexport function ChromeTooltip({\n  content,\n  children,\n  side = \"bottom\",\n  align = \"center\",\n  className,\n  disabled = false,\n}: ChromeTooltipProps): React.JSX.Element {\n  const { trigger, open, onOpenChange } = useClosedByFrames();\n  return (\n    <Tooltip open={open && !disabled} onOpenChange={onOpenChange}>\n      <TooltipTrigger asChild ref={trigger}>\n        {children}\n      </TooltipTrigger>\n      <TooltipContent\n        side={side}\n        align={align}\n        collisionPadding={COLLISION_PADDING}\n        {...(className === undefined ? {} : { className })}\n      >\n        {content}\n      </TooltipContent>\n    </Tooltip>\n  );\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 * The editor's left rail: the daily tools at the top, Settings and Help at the\n * bottom, each an icon named by its tooltip (with its key) and its accessible\n * name, so the canvas keeps the width labels would take.\n *\n * A panel the host cannot fill yet is left out rather than drawn disabled, so\n * the rail only ever offers what works; it grows as the panels behind it are\n * built.\n *\n * @module editor-rail\n */\nimport {\n  TooltipProvider,\n  useShortcuts,\n  type ActiveShortcut,\n} from \"@nextlyhq/ui\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport {\n  CircleHelp,\n  Component,\n  Files,\n  Layers,\n  Palette,\n  Plus,\n  Settings,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../chrome-tooltip\";\nimport { EDITOR_WORDS } from \"../editor-words\";\nimport { LEFT_PANELS, RAIL_WIDTH, type LeftPanel } from \"../shell-state\";\n\n/**\n * Each panel's name, from the editor's words, its icon, and the single key\n * that opens it (as in Webflow and Framer). The keys fire only when nothing is\n * being typed and no modifier is held; none of them is another shortcut's.\n */\nconst PANEL_CHROME: Record<\n  LeftPanel,\n  {\n    label: string;\n    Icon: React.ComponentType<{ className?: string }>;\n    key?: string;\n  }\n> = {\n  add: { label: EDITOR_WORDS.add, Icon: Plus, key: \"a\" },\n  layers: { label: EDITOR_WORDS.layers, Icon: Layers, key: \"l\" },\n  pages: { label: EDITOR_WORDS.pages, Icon: Files, key: \"p\" },\n  components: { label: EDITOR_WORDS.components, Icon: Component, key: \"c\" },\n  design: { label: EDITOR_WORDS.design, Icon: Palette, key: \"d\" },\n};\n\n/** A panel's name, as the rail shows it and the open panel's region is named. */\nexport function panelLabel(panel: LeftPanel): string {\n  return PANEL_CHROME[panel].label;\n}\n\n// A 36px square holding the icon alone; its name is its tooltip and its\n// accessible name. The ring sits off the item by a gap of the rail's own\n// surface: on the open panel's item, filled with the accent, a ring drawn\n// against the fill is the same colour as it and does not show.\nconst ITEM_CLASS =\n  \"focus-visible:ring-ring inline-flex size-9 items-center justify-center rounded-md focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--nx-builder-panel)] focus-visible:outline-none\";\n\nfunction RailItem({\n  label,\n  shortcut,\n  Icon,\n  pressed,\n  onClick,\n  ...data\n}: {\n  label: string;\n  /** The single key that opens it, shown in its tooltip. */\n  shortcut?: string;\n  Icon: React.ComponentType<{ className?: string }>;\n  pressed?: boolean;\n  onClick: (button: HTMLElement) => void;\n} & Record<`data-${string}`, string>) {\n  const key = shortcut?.toUpperCase();\n  return (\n    // The editor's own tooltip, which closes as the pointer moves onto the\n    // canvas; to the right, beside the rail rather than over its next item.\n    <ChromeTooltip\n      side=\"right\"\n      className=\"flex items-center gap-2\"\n      content={\n        <>\n          <span>{label}</span>\n          {key === undefined ? null : (\n            <kbd className=\"rounded border border-border px-1 font-mono text-[11px] text-muted-foreground\">\n              {key}\n            </kbd>\n          )}\n        </>\n      }\n    >\n      <button\n        type=\"button\"\n        data-builder-animates\n        aria-pressed={pressed}\n        aria-label={label}\n        {...(key === undefined ? {} : { \"aria-keyshortcuts\": key })}\n        onClick={event => onClick(event.currentTarget)}\n        className={cn(\n          ITEM_CLASS,\n          pressed === true\n            ? \"bg-[color:var(--nx-builder-accent)] text-[color:var(--nx-builder-accent-text)]\"\n            : // A soft wash of the text colour on hover, quiet in both schemes.\n              \"text-[color:var(--nx-builder-text-muted)] hover:bg-[color-mix(in_oklch,var(--nx-builder-text)_8%,transparent)] hover:text-[color:var(--nx-builder-text)]\"\n        )}\n        {...data}\n      >\n        <Icon className=\"size-4\" aria-hidden=\"true\" />\n      </button>\n    </ChromeTooltip>\n  );\n}\n\n/**\n * What every editor's panel-key layer is named after. Each editor registers its\n * own layer, this name and an id, so Help can tell its editor's keys apart from\n * a second editor's on the same page.\n */\nexport const PANEL_KEYS_LAYER = \"Editor panels\";\n\n/**\n * The panel keys an editor offers, as Help lists them: one per panel it can\n * fill that has a key, in rail order. The one list the keys are registered\n * from, so a row in Help is a key that works.\n */\nexport function panelKeyShortcuts(\n  isAvailable: (panel: LeftPanel) => boolean,\n  layer: string = PANEL_KEYS_LAYER\n): (ActiveShortcut & { panel: LeftPanel })[] {\n  return LEFT_PANELS.filter(isAvailable).flatMap(panel => {\n    const { label, key } = PANEL_CHROME[panel];\n    return key === undefined\n      ? []\n      : [\n          {\n            panel,\n            keys: key,\n            description: `Open or close ${label}`,\n            layer,\n          },\n        ];\n  });\n}\n\n/**\n * The panels' single keys: each opens its panel, or closes it when it is the\n * one open, as clicking its item does. Never while text is being typed and\n * never with a modifier held, so an author typing on the canvas or in a field\n * never switches panels. And only while `claims` says the key is this rail's,\n * so a rail hidden behind its editor's narrow-window notice, or beside a second\n * editor the author is in, passes the key on rather than switching panels in an\n * editor nobody is looking at.\n */\nfunction usePanelKeys(\n  shortcuts: readonly (ActiveShortcut & { panel: LeftPanel })[],\n  onSelect: (panel: LeftPanel) => void,\n  claims: (() => boolean) | undefined,\n  layer: string\n): void {\n  // Read at press time through a ref: the manager asks `when` then, and a\n  // predicate captured at registration would answer for an older render.\n  const latest = React.useRef(claims);\n  latest.current = claims;\n  useShortcuts(\n    shortcuts.map(({ panel, keys, description }) => ({\n      keys,\n      description,\n      whenTyping: false,\n      when: () => latest.current?.() ?? true,\n      run: () => onSelect(panel),\n    })),\n    { name: layer }\n  );\n}\n\nexport interface EditorRailProps {\n  /** The panel open now, or none. */\n  openPanel: LeftPanel | null;\n  /** Whether the host can fill a panel; one it cannot is not offered. */\n  isAvailable: (panel: LeftPanel) => boolean;\n  /** A rail item was chosen. */\n  onSelect: (panel: LeftPanel) => void;\n  /** Help was chosen, from this button, which focus returns to. */\n  onHelp: (button: HTMLElement) => void;\n  /** The rail's own element, for region navigation. */\n  railRef: (element: HTMLElement | null) => void;\n  /**\n   * Settings was chosen, from this button, which focus returns to: the host's\n   * Settings dialog. Absent, Settings is a panel like the others, offered\n   * where the host can fill it.\n   */\n  onSettings?: (button: HTMLElement) => void;\n  /** Whether the Settings dialog is open, shown as the item pressed. */\n  settingsOpen?: boolean;\n  /**\n   * Whether a panel key pressed now is this rail's to answer: the shell's own\n   * check that it is showing and the author is in it. Absent, the keys answer\n   * whenever nothing is being typed.\n   */\n  claimsKeys?: () => boolean;\n  /**\n   * Whether the panel keys are on. Off, none is registered and no item names\n   * one; on when absent.\n   */\n  keysOn?: boolean;\n  /** The layer the panel keys register in: this editor's own. */\n  keysLayer?: string;\n}\n\nexport function EditorRail({\n  openPanel,\n  isAvailable,\n  onSelect,\n  onHelp,\n  railRef,\n  onSettings,\n  settingsOpen = false,\n  claimsKeys,\n  keysOn = true,\n  keysLayer = PANEL_KEYS_LAYER,\n}: EditorRailProps): React.JSX.Element {\n  usePanelKeys(\n    keysOn ? panelKeyShortcuts(isAvailable, keysLayer) : [],\n    onSelect,\n    claimsKeys,\n    keysLayer\n  );\n  const item = (panel: LeftPanel) => {\n    const { label, Icon } = PANEL_CHROME[panel];\n    // A key that is off is not offered in the tooltip or to assistive\n    // technology either.\n    const key = keysOn ? PANEL_CHROME[panel].key : undefined;\n    return (\n      <li key={panel} className=\"flex justify-center\">\n        <RailItem\n          label={label}\n          {...(key === undefined ? {} : { shortcut: key })}\n          Icon={Icon}\n          pressed={openPanel === panel}\n          onClick={() => onSelect(panel)}\n          data-panel={panel}\n        />\n      </li>\n    );\n  };\n  return (\n    <nav\n      ref={railRef}\n      tabIndex={-1}\n      aria-label=\"Editor panels\"\n      style={{ width: RAIL_WIDTH }}\n      className=\"border-[color:var(--nx-builder-divider)] flex shrink-0 flex-col border-r py-2\"\n    >\n      {/* One provider for the rail's tooltips, so moving from item to item\n          shows the next name at once. */}\n      <TooltipProvider delayDuration={300}>\n        <ul className=\"flex flex-col gap-1\">\n          {LEFT_PANELS.filter(isAvailable).map(item)}\n        </ul>\n        <ul className=\"mt-auto flex flex-col gap-1\">\n          {onSettings === undefined ? null : (\n            <li className=\"flex justify-center\">\n              <RailItem\n                label={EDITOR_WORDS.settings}\n                Icon={Settings}\n                pressed={settingsOpen}\n                onClick={onSettings}\n                data-rail-action=\"settings\"\n              />\n            </li>\n          )}\n          <li className=\"flex justify-center\">\n            <RailItem\n              label={EDITOR_WORDS.help}\n              Icon={CircleHelp}\n              onClick={onHelp}\n              data-rail-action=\"help\"\n            />\n          </li>\n        </ul>\n      </TooltipProvider>\n    </nav>\n  );\n}\n","/**\n * Where the Page Builder's documentation is published.\n *\n * One base, used in development too: the docs are a public site rather than\n * something a local app serves, so a link that worked only in production would\n * send a contributor checking it somewhere else.\n *\n * @module docs-links\n */\n\n/** The published documentation site. */\nconst DOCS_BASE = \"https://nextlyhq.com/docs\";\n\n/** A documentation page Help links to. */\nexport interface DocsLink {\n  readonly label: string;\n  readonly href: string;\n}\n\n/** The Page Builder's pages, in the order Help offers them. */\nexport const PAGE_BUILDER_DOCS: readonly DocsLink[] = [\n  { label: \"Page Builder docs\", href: `${DOCS_BASE}/page-builder` },\n  { label: \"Using the editor\", href: `${DOCS_BASE}/page-builder/editor` },\n];\n\n/**\n * Where the docs explain the canvas route a site mounts to draw the canvas\n * inside its own layout: the page a fallback's Details link opens.\n */\nexport const CANVAS_ROUTE_DOCS_HREF: string = `${DOCS_BASE}/page-builder#draw-the-canvas-in-your-sites-layout`;\n\n/**\n * Where the docs explain how the site's background jobs are run: the usage\n * counts are filled in by one, and on a site nothing runs them for they never\n * finish, so the counting note links here.\n */\nexport const BACKGROUND_JOBS_DOCS_HREF: string = `${DOCS_BASE}/jobs#running-the-queue`;\n\n/**\n * Where the docs explain how site code meets the site's Content Security\n * Policy: the link beside what Settings says to add to that policy.\n */\nexport const SITE_CODE_POLICY_DOCS_HREF: string = `${DOCS_BASE}/page-builder/site-code#your-content-security-policy`;\n\n/**\n * Where the docs explain how a site's text is set: Site text, type sizes,\n * fluid sizes, text styles, the Body and Headings fonts and where fonts are\n * kept. Linked from the Design panel's Type tab, where those are set.\n */\nexport const HOW_TEXT_WORKS_DOCS_HREF: string = `${DOCS_BASE}/page-builder/how-text-works`;\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 * The keyboard shortcuts the Help dialog lists, from the registry that holds\n * them — so a rebound key moves in Help with it, and a shortcut nobody bound\n * cannot appear there.\n *\n * One registry, not one per provider: a provider nested on the page's target\n * shares the page's manager rather than building a second, so the editor's\n * bindings and the page's around it (the save the document's form binds, its\n * Escape) arrive in one list, most precedent first. A key several layers bind\n * is listed once, with the binding that comes first, because that is the one\n * the key runs here; listing the others would describe a keystroke that does\n * something else.\n *\n * @module help-shortcuts\n */\nimport {\n  chordMatches,\n  parseKeys,\n  type ActiveShortcut,\n  type KeyChord,\n  type KeySequence,\n  type ModifierState,\n} from \"@nextlyhq/ui\";\n\nimport { keyHint } from \"./key-hint\";\n\n/** One line of the list: what happens, and every key that does it. */\nexport interface ShortcutRow {\n  description: string;\n  keys: readonly string[];\n}\n\n/** The keystroke a chord describes, as the event that would carry it. */\nfunction pressOf(chord: KeyChord, apple: boolean): ModifierState {\n  return {\n    ctrlKey: chord.ctrl || (chord.mod && !apple),\n    metaKey: chord.meta || (chord.mod && apple),\n    altKey: chord.alt,\n    shiftKey: chord.shift,\n  };\n}\n\n/**\n * Whether two bindings take the same keys on this platform.\n *\n * Decided by the shortcut manager's own parser and matcher rather than by\n * comparing the spellings: `mod+k` and `ctrl+k` are one key off Apple and two\n * on it, and `shift+mod+z` is `Mod+Shift+Z`. Each step of one binding is\n * pressed as an event and asked of the other's matching step, as the manager\n * would ask it.\n */\nfunction sameKeys(a: KeySequence, b: KeySequence, apple: boolean): boolean {\n  return (\n    a.length === b.length &&\n    a.every((chord, step) => {\n      const other = b[step];\n      return (\n        other !== undefined &&\n        chordMatches(chord, other.key, pressOf(other, apple), apple)\n      );\n    })\n  );\n}\n\n/** A spec as the manager parses it, or null for one it refuses. */\nfunction sequenceOf(spec: string): KeySequence | null {\n  try {\n    return parseKeys(spec);\n  } catch {\n    return null;\n  }\n}\n\n/**\n * The bindings as rows, from the manager's list in its own order.\n *\n * Each key keeps only its first binding, the one that takes it. Rows are one\n * per description, carrying every key that does it — Delete and Backspace are\n * one action — and only keys this platform can spell. A binding with no\n * description says nothing to an author and is left out, but it still takes\n * its key from the layers below it.\n */\nexport function helpShortcuts(\n  active: readonly ActiveShortcut[],\n  apple: boolean\n): ShortcutRow[] {\n  const taken: KeySequence[] = [];\n  const rows = new Map<string, string[]>();\n  for (const shortcut of active) {\n    const sequence = sequenceOf(shortcut.keys);\n    // A spec the parser refuses names no key anyone can press.\n    if (sequence === null) continue;\n    // A sequence (\"g d\") is the admin's site navigation around the editor:\n    // the editor binds none, and its Help explains what the editor does. A\n    // sequence shares no key with a single press, so it takes none here.\n    if (sequence.length > 1) continue;\n    if (taken.some(earlier => sameKeys(earlier, sequence, apple))) continue;\n    taken.push(sequence);\n    if (shortcut.description.trim() === \"\") continue;\n    const shown = keyHint(shortcut.keys, apple);\n    if (shown === null) continue;\n    const keys = rows.get(shortcut.description) ?? [];\n    if (!keys.includes(shown)) keys.push(shown);\n    rows.set(shortcut.description, keys);\n  }\n  return [...rows].map(([description, keys]) => ({ description, keys }));\n}\n","/**\n * Holding the keyboard while something modal is over the editor.\n *\n * A focus trap keeps TAB inside a dialog and does nothing about shortcuts: the\n * canvas's bindings are registered on the document, so Delete, Mod+D and\n * Alt+Arrow still reach the page behind the modal, and Mod+K still opens the\n * command palette over it. An author correcting a name in a form can destroy\n * the block they are naming.\n *\n * One implementation, because two surfaces need it — the palette, which has had\n * it since it shipped, and any dialog the editor raises over the canvas. Written\n * twice it would agree until one of them learned something about depth, which is\n * the part that is easy to get wrong.\n *\n * @module modal-keyboard-hold\n */\n\nimport { useShortcuts } from \"@nextlyhq/ui\";\n\n/**\n * Block the editor's shortcuts for as long as `active`.\n *\n * Registered at the CALLER's own depth. `useShortcuts` reads the depth from the\n * surrounding context and only a `ShortcutScope` increments it, so nothing here\n * nests the hold — and nesting is not what would make it work anyway. The host\n * chooses how deeply its own shortcuts are scoped, so any depth this picked\n * could be tied or beaten by a scope the host nests one level further.\n *\n * `priority: 1` is what carries it: the manager sorts priority ABOVE depth, so\n * the hold outranks an ordinary layer however deeply that layer sits. Priority\n * is the one axis the host does not control.\n *\n * The manager already exempts text insertion and Tab, so a form's fields and\n * its focus trap keep working underneath this.\n *\n * `name` identifies the holder in the manager's own diagnostics, which is worth\n * having now that more than one layer raises its priority: two holds at equal\n * priority fall back to depth, and a name is what tells them apart in a trace.\n */\nexport function useModalKeyboardHold(name: string, active: boolean): void {\n  useShortcuts([], { name, enabled: active, priority: 1, blocking: true });\n}\n","/**\n * Help: the editor's keyboard shortcuts and where its documentation is.\n *\n * A modal rather than a panel, so it never reserves a region and shrinks the\n * canvas. It holds the keyboard while it is open, so a key pressed in it does\n * not edit the page behind it, and Radix keeps focus inside it and closes it on\n * Escape; focus then goes back to the control that opened it.\n *\n * @module help-dialog\n */\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogHeader,\n  DialogTitle,\n  detectApplePlatform,\n  Label,\n  Switch,\n  useActiveShortcuts,\n  type ActiveShortcut,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { EDITOR_WORDS } from \"../editor-words\";\n\nimport { PAGE_BUILDER_DOCS } from \"./docs-links\";\nimport { helpShortcuts, type ShortcutRow } from \"./help-shortcuts\";\nimport { useModalKeyboardHold } from \"./modal-keyboard-hold\";\n\n/**\n * Keys that are not bindings in any registry, so no registry can report them:\n * the platform's own context-menu key, which the browser turns into the same\n * event a right-click sends. Listed by hand, and only these.\n *\n * The row says where it works because it does not work everywhere: the event\n * comes from whatever holds focus, and reaches a block's menu only when that is\n * a link or button inside the block. With focus on the canvas or on a block\n * with no control in it, the key does nothing, and a row promising the menu\n * would mislead.\n */\nconst PLATFORM_KEYS: readonly ShortcutRow[] = [\n  {\n    description: \"Open the block's menu from a link or button inside it\",\n    keys: [\"Shift+F10\", \"Menu key\"],\n  },\n];\n\nfunction ShortcutList({ rows }: { rows: readonly ShortcutRow[] }) {\n  const headingId = React.useId();\n  return (\n    <section aria-labelledby={headingId} className=\"space-y-2\">\n      <h2 id={headingId} className=\"text-sm font-semibold\">\n        Keyboard shortcuts\n      </h2>\n      <dl className=\"space-y-1.5 text-sm\">\n        {rows.map(row => (\n          <div\n            key={row.description}\n            className=\"flex items-baseline justify-between gap-4\"\n          >\n            <dt>{row.description}</dt>\n            <dd className=\"flex shrink-0 gap-1\">\n              {row.keys.map(key => (\n                <kbd\n                  key={key}\n                  className=\"rounded border border-[color:var(--nx-builder-border)] px-1.5 py-0.5 font-mono text-xs\"\n                >\n                  {key}\n                </kbd>\n              ))}\n            </dd>\n          </div>\n        ))}\n      </dl>\n    </section>\n  );\n}\n\n/** The rail's single-letter panel keys: whether they are on, and the switch. */\nexport interface PanelKeysSetting {\n  on: boolean;\n  onChange: (on: boolean) => void;\n  /**\n   * The keys this editor's rail registers while they are on. Help lists these\n   * rather than the panel keys the shared manager holds, which include a\n   * second editor's on the same page.\n   */\n  shortcuts: readonly ActiveShortcut[];\n  /** The layer they register in: this editor's own. */\n  layer: string;\n  /**\n   * The name every editor's panel-key layer begins with. Help leaves all of\n   * them to `shortcuts`, a second editor's included.\n   */\n  family: string;\n}\n\n/**\n * The bindings Help lists: the manager's, with the panel keys taken from this\n * editor alone, and only while they are on. Last, so a binding above them that\n * takes the same key still wins its row, as it wins the key.\n */\nfunction listedShortcuts(\n  active: readonly ActiveShortcut[],\n  panelKeys: PanelKeysSetting | undefined\n): readonly ActiveShortcut[] {\n  if (panelKeys === undefined) return active;\n  const panelKeysOf = (shortcut: ActiveShortcut) =>\n    shortcut.layer.startsWith(panelKeys.family);\n  const others = active.filter(shortcut => !panelKeysOf(shortcut));\n  const own = panelKeys.on ? panelKeys.shortcuts : [];\n  // In this editor's own layer's place in the manager's order, so a binding\n  // below it never takes its rows and one above it still does; last where it\n  // registered none.\n  const at = active.findIndex(shortcut => shortcut.layer === panelKeys.layer);\n  if (at === -1) return [...others, ...own];\n  const before = active.slice(0, at).filter(shortcut => !panelKeysOf(shortcut));\n  return [...before, ...own, ...others.slice(before.length)];\n}\n\n/** What the switch's hint says: the keys this editor offers, by name. */\nfunction panelKeysHint(shortcuts: readonly ActiveShortcut[]): string {\n  const letters = new Intl.ListFormat(\"en\", { type: \"conjunction\" }).format(\n    shortcuts.map(shortcut => shortcut.keys.toUpperCase())\n  );\n  const what =\n    letters === \"\" ? \"Single letters open panels\" : `${letters} open panels`;\n  return `${what}. Turn them off if you use speech input or press them by accident.`;\n}\n\n/**\n * The switch for the panel keys, beside the list that shows them: a key with\n * no modifier can be set off by speech input or a stray press, so an author\n * can turn them off (WCAG 2.1.4).\n */\nfunction PanelKeysSwitch({\n  setting,\n}: {\n  setting: PanelKeysSetting;\n}): React.JSX.Element {\n  const id = React.useId();\n  const hintId = React.useId();\n  return (\n    <div className=\"flex items-start justify-between gap-4 text-sm\">\n      <div className=\"space-y-0.5\">\n        <Label htmlFor={id}>Single-letter shortcuts</Label>\n        <p id={hintId} className=\"text-xs text-muted-foreground\">\n          {panelKeysHint(setting.shortcuts)}\n        </p>\n      </div>\n      <Switch\n        id={id}\n        aria-describedby={hintId}\n        checked={setting.on}\n        onCheckedChange={setting.onChange}\n      />\n    </div>\n  );\n}\n\nexport interface HelpDialogProps {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /**\n   * Where focus goes when Help closes: the control that opened it.\n   *\n   * Radix returns focus to a dialog's own trigger, and Help has none — it\n   * opens from the rail, outside the dialog — so without this, closing it\n   * left focus on the page's body and a keyboard author back at the top.\n   */\n  returnFocus?: () => HTMLElement | null;\n  /** The panel keys' switch, where the editor has them. */\n  panelKeys?: PanelKeysSetting;\n}\n\nexport function HelpDialog({\n  open,\n  onOpenChange,\n  returnFocus,\n  panelKeys,\n}: HelpDialogProps): React.JSX.Element {\n  useModalKeyboardHold(\"builder-help-modal\", open);\n  // Every binding in effect, the editor's and the page's around it: a\n  // provider nested on the page's target shares the page's manager. The hold\n  // above binds nothing, so it hides nothing from the list.\n  const active = useActiveShortcuts();\n\n  return (\n    <Dialog open={open} onOpenChange={onOpenChange}>\n      <DialogContent\n        className=\"max-h-[80vh] overflow-y-auto sm:max-w-lg\"\n        onCloseAutoFocus={event => {\n          const target = returnFocus?.();\n          if (!target) return;\n          event.preventDefault();\n          target.focus();\n        }}\n      >\n        <DialogHeader>\n          <DialogTitle>{EDITOR_WORDS.help}</DialogTitle>\n          <DialogDescription>\n            Keyboard shortcuts for the Page Builder, and where to read more.\n          </DialogDescription>\n        </DialogHeader>\n        <div className=\"space-y-5\">\n          {/* The platform is read here, where the content draws only once the\n              dialog is open — always in a browser, after hydration. */}\n          <ShortcutList\n            rows={[\n              ...helpShortcuts(\n                listedShortcuts(active, panelKeys),\n                detectApplePlatform()\n              ),\n              ...PLATFORM_KEYS,\n            ]}\n          />\n          {panelKeys === undefined ? null : (\n            <PanelKeysSwitch setting={panelKeys} />\n          )}\n          <section aria-label=\"Documentation\" className=\"space-y-2\">\n            <h2 className=\"text-sm font-semibold\">Documentation</h2>\n            <ul className=\"space-y-1 text-sm\">\n              {PAGE_BUILDER_DOCS.map(link => (\n                <li key={link.href}>\n                  <a\n                    href={link.href}\n                    target=\"_blank\"\n                    rel=\"noopener noreferrer\"\n                    className=\"underline underline-offset-2\"\n                  >\n                    {link.label}\n                  </a>\n                </li>\n              ))}\n            </ul>\n          </section>\n        </div>\n      </DialogContent>\n    </Dialog>\n  );\n}\n","\"use client\";\n\n/**\n * A function that keeps its identity across renders and calls the newest\n * one it was handed.\n *\n * @module latest-callback\n */\nimport { useCallback, useLayoutEffect, useRef } from \"react\";\n\n/**\n * `fn`, as one function for the life of the component that keeps calling the\n * `fn` of the newest render. For a handler handed to a memoised surface: a\n * new closure each render would draw the surface again, and the first\n * render's closure kept instead would act on what that render held.\n *\n * Only for a handler called after rendering (a press, a key, an effect), never\n * during it: the newest `fn` is taken once the render it came from is\n * committed.\n * @experimental\n */\nexport function useLatestCallback<A extends unknown[], R>(\n  fn: (...args: A) => R\n): (...args: A) => R {\n  const latest = useRef(fn);\n  // Before any effect or event of the committed render can call it.\n  useLayoutEffect(() => {\n    latest.current = fn;\n  });\n  return useCallback((...args: A) => latest.current(...args), []);\n}\n\n/**\n * {@link useLatestCallback} for a handler that may be absent: `undefined`\n * while it is, so a surface that draws a control only for a handler there is\n * still knows, and one kept function while it is not.\n * @experimental\n */\nexport function useLatestOptionalCallback<A extends unknown[], R>(\n  fn: ((...args: A) => R) | undefined\n): ((...args: A) => R | undefined) | undefined {\n  const kept = useLatestCallback((...args: A) => fn?.(...args));\n  return fn === undefined ? undefined : kept;\n}\n","\"use client\";\n\n/**\n * The shell's rail and the dialogs it opens: which panels it offers, the\n * help and Settings dialogs, and the host's request to open Settings.\n *\n * @module shell-rail-dialogs\n */\nimport * as React from \"react\";\n\nimport { isLeftPanel, topologyKey, type LeftPanel } from \"../shell-state\";\n\nimport {\n  EditorRail,\n  PANEL_KEYS_LAYER,\n  panelKeyShortcuts,\n  type EditorRailProps,\n} from \"./editor-rail\";\nimport { HelpDialog, type PanelKeysSetting } from \"./help-dialog\";\nimport { useLatestCallback } from \"./latest-callback\";\nimport type { BuilderShellProps } from \"./shell-props\";\n\n/**\n * The panel set about to be rendered, named the same way a persisted layout\n * is keyed. Derived from what is shown because that is what decides the set;\n * the persisted key is derived from the layout's own ids, and the two meet at\n * `topologyKey` rather than being two spellings of one arrangement.\n */\nexport function panelTopology(\n  openPanel: LeftPanel | null,\n  inspectorShown: boolean\n): string {\n  return topologyKey([\n    ...(openPanel === null ? [] : [\"panel\"]),\n    \"canvas\",\n    ...(inspectorShown ? [\"inspector\"] : []),\n  ]);\n}\n\n/**\n * Whether the host can fill a panel. One predicate, so the rail's items and\n * the panel the layout reserves cannot answer differently.\n *\n * A name this shell does not know is never available, whatever the host\n * offers: a request from untyped code can still name a panel that was\n * renamed or removed, Settings among them, and there is no chrome to draw it\n * with.\n */\nexport function panelAvailability(\n  availablePanels: readonly LeftPanel[] | undefined\n): (panel: LeftPanel) => boolean {\n  return panel =>\n    isLeftPanel(panel) &&\n    (availablePanels === undefined || availablePanels.includes(panel));\n}\n\n/**\n * Opens a rail dialog from the item pressed, which focus returns to. One\n * function for the dialog's life, so the memoised rail is handed the same.\n */\nfunction useOpening(\n  dialog: ReturnType<typeof useRailDialog>\n): (button: HTMLElement) => void {\n  const { opener, setOpen } = dialog;\n  return React.useCallback(\n    (button: HTMLElement) => {\n      opener.current = button;\n      setOpen(true);\n    },\n    [opener, setOpen]\n  );\n}\n\n/** What the shell hands the rail and its dialogs. */\ntype RailAndDialogsProps = Pick<\n  EditorRailProps,\n  \"openPanel\" | \"isAvailable\" | \"onSelect\" | \"railRef\"\n> & {\n  active: boolean;\n  renderSettings: BuilderShellProps[\"renderSettings\"];\n  /** Whether a panel key pressed now is this rail's to answer. */\n  claimsKeys: () => boolean;\n  panelKeys: Pick<PanelKeysSetting, \"on\" | \"onChange\">;\n};\n\n/**\n * The rail, with the dialogs its bottom items open: Help, and Settings where\n * the host draws one. They own their open state here, beside the items that\n * open them.\n *\n * Drawn again only when something they show changes. The shell renders again\n * for every change of what it holds, a selection among them, and hands this a\n * new rail ref, a new panel-key check and a new setting each time; those\n * functions are read when called (the rail's keys are registered as it draws,\n * so a key pressed after a render it skipped still acts on the newest\n * preferences), and the setting is handed on as its value, so the memoised\n * rail is handed the same props while only the selection moves. Nothing here\n * shows the selected block. `isAvailable` is read while drawing, so the shell\n * keeps it as one function for as long as the host's panels are the same.\n */\nexport function RailAndDialogs(props: RailAndDialogsProps): React.JSX.Element {\n  const railRef = useLatestCallback(props.railRef);\n  const onSelect = useLatestCallback(props.onSelect);\n  const claimsKeys = useLatestCallback(props.claimsKeys);\n  const onKeysChange = useLatestCallback(props.panelKeys.onChange);\n  return (\n    <KeptRailAndDialogs\n      active={props.active}\n      renderSettings={props.renderSettings}\n      openPanel={props.openPanel}\n      isAvailable={props.isAvailable}\n      onSelect={onSelect}\n      railRef={railRef}\n      claimsKeys={claimsKeys}\n      keysOn={props.panelKeys.on}\n      onKeysChange={onKeysChange}\n    />\n  );\n}\n\n/** Help, memoised: drawn again only as it opens or closes or its keys change. */\nconst KeptHelpDialog = React.memo(HelpDialog);\n\n/**\n * The rail, memoised: drawn again only for what it shows (the panel open,\n * Settings pressed, the keys on or off), not when Settings or Help beside it\n * is drawn again.\n */\nconst KeptEditorRail = React.memo(EditorRail);\n\n/**\n * The rail and its dialogs, memoised, so they draw again only for a prop that\n * changed: a panel opened, the panel keys turned off, a new Settings.\n */\nconst KeptRailAndDialogs = React.memo(function RailAndDialogsKept({\n  active,\n  renderSettings,\n  keysOn,\n  onKeysChange,\n  ...rail\n}: Omit<RailAndDialogsProps, \"panelKeys\"> & {\n  keysOn: boolean;\n  onKeysChange: (on: boolean) => void;\n}): React.JSX.Element {\n  // This editor's own panel-key layer, so Help can find its keys among a\n  // second editor's on the same page.\n  const keysLayer = `${PANEL_KEYS_LAYER} ${React.useId()}`;\n  const help = useRailDialog(active);\n  const settings = useRailDialog(active);\n  useSettingsRequest(\n    React.useContext(SettingsRequestContext),\n    settings.setOpen,\n    active\n  );\n  const openHelp = useOpening(help);\n  const openSettings = useOpening(settings);\n  const { opener: helpOpener } = help;\n  const returnHelpFocus = React.useCallback(\n    () => helpOpener.current,\n    [helpOpener]\n  );\n  // A new setting only when what Help shows of the keys changes, so the rail\n  // drawing again (a panel opened, Settings pressed) leaves Help alone.\n  const { isAvailable } = rail;\n  const panelKeys = React.useMemo(\n    () => ({\n      on: keysOn,\n      onChange: onKeysChange,\n      shortcuts: panelKeyShortcuts(isAvailable, keysLayer),\n      layer: keysLayer,\n      family: PANEL_KEYS_LAYER,\n    }),\n    [keysOn, onKeysChange, isAvailable, keysLayer]\n  );\n  return (\n    <>\n      <KeptEditorRail\n        {...rail}\n        keysOn={keysOn}\n        keysLayer={keysLayer}\n        // Help always, and Settings where the host draws a Settings dialog.\n        onHelp={openHelp}\n        {...(renderSettings === undefined\n          ? {}\n          : { settingsOpen: settings.open, onSettings: openSettings })}\n      />\n      <KeptHelpDialog\n        open={help.open}\n        onOpenChange={help.setOpen}\n        returnFocus={returnHelpFocus}\n        panelKeys={panelKeys}\n      />\n      <HostSettings\n        render={renderSettings}\n        open={settings.open}\n        onOpenChange={settings.setOpen}\n        opener={settings.opener}\n      />\n    </>\n  );\n});\n\n/**\n * The host's Settings dialog, handed whether it is open, when it draws one.\n * Memoised, so the host's `renderSettings` is called again only when it is a\n * new function or the dialog opens or closes: a host that keeps it as one\n * function while what Settings shows is unchanged has none of it drawn again.\n */\nconst HostSettings = React.memo(function HostSettings({\n  render,\n  open,\n  onOpenChange,\n  opener,\n}: {\n  render: BuilderShellProps[\"renderSettings\"];\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  opener: React.RefObject<HTMLElement | null>;\n}): React.ReactNode {\n  if (render === undefined) return null;\n  return render({\n    open,\n    onOpenChange,\n    returnFocus: () => opener.current,\n  });\n});\n\n/**\n * A rail dialog's open state (Help's, Settings'), and the control focus\n * returns to when it closes.\n *\n * It closes when the editor gives way to the narrow-window notice. The\n * regions stay mounted there, hidden and inert, and a modal left open would\n * keep its focus trap and its hold on the keyboard over a notice whose Exit\n * button it would then keep out of reach. Closed rather than hidden, so\n * widening the window again does not bring back a dialog nobody reopened.\n */\n/**\n * The host's open-Settings request, handed from the shell's props to the rail\n * that owns the dialog. A context rather than a prop through the regions in\n * between, which only pass it along.\n */\nexport const SettingsRequestContext: React.Context<\n  BuilderShellProps[\"openSettingsRequest\"]\n> = React.createContext<BuilderShellProps[\"openSettingsRequest\"]>(undefined);\n\n/**\n * Opens Settings once for each new `count` a host sends. A ref, not state,\n * holds the count last applied, so the request is applied at most once and a\n * re-render does not reopen a dialog the author closed.\n */\nfunction useSettingsRequest(\n  request: BuilderShellProps[\"openSettingsRequest\"],\n  setOpen: (open: boolean) => void,\n  active: boolean\n): void {\n  const handled = React.useRef<number | undefined>(undefined);\n  React.useEffect(() => {\n    // Not while the shell has given way to its narrow-window notice: a dialog\n    // there would trap focus over the notice's way out. The request waits,\n    // unconsumed, and opens Settings once the shell is in use again.\n    if (!active) return;\n    if (request === undefined || handled.current === request.count) return;\n    handled.current = request.count;\n    setOpen(true);\n  }, [request, setOpen, active]);\n}\n\nfunction useRailDialog(active: boolean): {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  opener: React.RefObject<HTMLElement | null>;\n} {\n  const [open, setOpen] = React.useState(false);\n  const opener = React.useRef<HTMLElement | null>(null);\n  React.useEffect(() => {\n    if (!active) setOpen(false);\n  }, [active]);\n  return { open, setOpen, opener };\n}\n","\"use client\";\n\n/**\n * The control that says how large the canvas is drawing, and lets an author\n * change it.\n *\n * Both halves matter and the first is the one that was missing. The canvas has\n * always scaled to fit the region the panels leave, so opening a panel took it\n * from 89% to 59.5% with nothing on screen naming either number — an author\n * judging type or spacing was doing it at a size they had not chosen and could\n * not read.\n *\n * ## The percentage is always shown, including while fitting\n *\n * A control that only reported a scale the author had SET would be blank in\n * the state that caused the confusion. Fit is the default and the state an\n * editor spends most of its time in, so the number it produces is exactly the\n * one worth naming.\n *\n * ## Discrete steps, and Fit as a peer of them\n *\n * A menu of steps rather than a slider or a free number: 37% of a page is not\n * a view of anything, and every comparable editor offers steps for the same\n * reason. Fit sits in the same menu rather than beside it as a separate\n * button, because from the author's side it is one question — how big — and\n * splitting it into a mode switch plus a size makes them answer twice.\n *\n * @module canvas-zoom-control\n */\n\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n  useShortcuts,\n} from \"@nextlyhq/ui\";\nimport { Minus, Plus } from \"lucide-react\";\nimport type * as React from \"react\";\nimport { Fragment, useRef } from \"react\";\n\nimport {\n  FIT_ZOOM,\n  ZOOM_STEPS,\n  steppedZoom,\n  writeZoom,\n  type CanvasZoom,\n} from \"./canvas-zoom\";\n\nexport interface CanvasZoomControlProps {\n  /** What the canvas was asked to draw at. */\n  zoom: CanvasZoom;\n  /**\n   * The scale the canvas is ACTUALLY painting at.\n   *\n   * Passed in rather than recomputed, because while fitting it is derived from\n   * a region only the canvas has measured. A control deriving its own would be\n   * a second answer to what is on screen, and the two would disagree for\n   * exactly the frame after a panel opens — which is the moment this exists to\n   * report.\n   */\n  appliedScale: number;\n  /**\n   * What to do with a chosen zoom, or absent where nothing can act on one.\n   *\n   * Absent renders NOTHING. The canvas belongs to the host, so a shell whose\n   * host has not wired this has nowhere to apply a choice: the control would\n   * store a preference, report a percentage the canvas does not honour, and go\n   * on reading 100% whatever was picked. A surface that predates the wiring\n   * should gain no control rather than a dead one.\n   */\n  onChange?: (zoom: CanvasZoom) => void;\n}\n\n/** A scale as a percentage, rounded to whole points. */\nfunction asPercent(scale: number): string {\n  return `${Math.round(scale * 100)}%`;\n}\n\n/**\n * A zoom as the string the menu addresses it by.\n *\n * Routed through `writeZoom` rather than spelled here, so the value a checked\n * item is compared against and the value the preference is stored as are one\n * decision. Written twice they agree until one of them learns a new kind, and\n * the failure is a menu with nothing checked rather than an error.\n */\nfunction choiceValue(zoom: CanvasZoom): string {\n  return String(writeZoom(zoom));\n}\n\n/**\n * Every zoom the menu offers, in the order it offers them.\n *\n * Built once from the steps rather than parsed back out of the chosen string.\n * A parse is a second implementation of what this list already knows, and it\n * has a failure mode the lookup does not: an unrecognised string has to become\n * SOME zoom, so it silently becomes the wrong one.\n */\nconst CHOICES: readonly { value: string; label: string; zoom: CanvasZoom }[] = [\n  { value: choiceValue(FIT_ZOOM), label: \"Fit\", zoom: FIT_ZOOM },\n  ...ZOOM_STEPS.map(step => {\n    const zoom: CanvasZoom = { kind: \"fixed\", scale: step };\n    return { value: choiceValue(zoom), label: asPercent(step), zoom };\n  }),\n];\n\nexport function CanvasZoomControl({\n  zoom,\n  appliedScale,\n  onChange,\n}: CanvasZoomControlProps): React.JSX.Element | null {\n  if (onChange === undefined) return null;\n  const shown = asPercent(appliedScale);\n\n  /*\n   * The steps this control can still take, so a button that cannot move says\n   * so rather than looking operable and doing nothing.\n   *\n   * Compared against the RESULT rather than against the current scale: at the\n   * top step `steppedZoom` returns the zoom it was given, and a disabled state\n   * derived from the scale alone would have to restate the step list to know\n   * that. One list decides both, and it is the one the button runs.\n   *\n   * `Object.is` rather than `!==`, because `writeZoom` returns the scale itself\n   * and a host may construct one the canvas cannot paint. `NaN !== NaN` is\n   * true, so an unchanged result would read as a step being available and both\n   * buttons would offer a press that emits the value they were already given.\n   */\n  const zoomOut = steppedZoom(zoom, appliedScale, \"out\");\n  const zoomIn = steppedZoom(zoom, appliedScale, \"in\");\n  const canZoomOut = !Object.is(writeZoom(zoomOut), writeZoom(zoom));\n  const canZoomIn = !Object.is(writeZoom(zoomIn), writeZoom(zoom));\n\n  return (\n    // Each step button and the menu at the editor's control height, with the\n    // scale's own values as fallbacks for a page that draws this control\n    // outside the editor, where the density tokens aren't declared.\n    <div className=\"nx-zoom-stepper flex items-center gap-0.5\">\n      {/*\n        A stepper AROUND the menu, not instead of it. The menu names the modes\n        — Fit is a mode rather than a number and cannot be stepped to — while\n        the buttons are for the adjustment an author makes repeatedly, which a\n        menu makes a three-action job every time.\n\n        `steppedZoom` already existed and was exported with no caller: the\n        capability was reachable from a host and not from the editor.\n      */}\n      <button\n        type=\"button\"\n        onClick={() => onChange(zoomOut)}\n        disabled={!canZoomOut}\n        aria-label=\"Zoom out\"\n        title=\"Zoom out\"\n        className=\"focus-visible:ring-ring inline-flex size-[var(--nx-builder-control-height,1.75rem)] items-center justify-center rounded disabled:opacity-40 focus-visible:ring-2 focus-visible:outline-none\"\n      >\n        <Minus className=\"size-3.5\" aria-hidden=\"true\" />\n      </button>\n      {/*\n        Not modal. A modal menu marks the whole editor around it aria-hidden\n        while its controls stay focusable (axe: aria-hidden-focus). This is a\n        choice beside the canvas, not a dialog: Escape, a click outside and\n        Tab still close it, and focus returns to the trigger.\n      */}\n      <DropdownMenu modal={false}>\n        <DropdownMenuTrigger\n          className=\"nx-zoom-control\"\n          /*\n           * The accessible name carries the MODE as well as the number, because\n           * \"89%\" alone does not say whether it will move when a panel opens —\n           * and that is the whole difference between the two states. In the\n           * words drawn, so someone who says \"Fit 60%\" reaches it.\n           */\n          aria-label={\n            zoom.kind === \"fit\"\n              ? `Canvas zoom: Fit, ${shown}`\n              : `Canvas zoom: ${shown}`\n          }\n        >\n          <span aria-hidden=\"true\">\n            {zoom.kind === \"fit\" ? `Fit · ${shown}` : shown}\n          </span>\n        </DropdownMenuTrigger>\n        <DropdownMenuContent align=\"start\">\n          {/* A RADIO group, so the open menu says which mode is active.\n\n            The trigger cannot: Fit resolves to exactly 100% at the widest\n            tier, which is the state an editor opens in, so \"100%\" is the same\n            two characters for a canvas that will resize when a panel opens and\n            one that will not. The mark is the only place a sighted author can\n            read the difference, and a checked radio is also what tells a\n            screen reader which item is current.\n\n            Nothing is marked when the zoom is a fixed scale the steps do not\n            contain — a host can pass one, and a stored value can outlive the\n            step list. That is honest: the menu genuinely does not hold it, and\n            marking the nearest step would claim the author chose something\n            they did not. */}\n          <DropdownMenuRadioGroup\n            value={choiceValue(zoom)}\n            onValueChange={next => {\n              const choice = CHOICES.find(\n                candidate => candidate.value === next\n              );\n              if (choice !== undefined) onChange(choice.zoom);\n            }}\n          >\n            {CHOICES.map((choice, index) => (\n              <Fragment key={choice.value}>\n                {index === 1 ? <DropdownMenuSeparator /> : null}\n                <DropdownMenuRadioItem value={choice.value}>\n                  {choice.label}\n                </DropdownMenuRadioItem>\n              </Fragment>\n            ))}\n          </DropdownMenuRadioGroup>\n        </DropdownMenuContent>\n      </DropdownMenu>\n      <button\n        type=\"button\"\n        onClick={() => onChange(zoomIn)}\n        disabled={!canZoomIn}\n        aria-label=\"Zoom in\"\n        title=\"Zoom in\"\n        className=\"focus-visible:ring-ring inline-flex size-[var(--nx-builder-control-height,1.75rem)] items-center justify-center rounded disabled:opacity-40 focus-visible:ring-2 focus-visible:outline-none\"\n      >\n        <Plus className=\"size-3.5\" aria-hidden=\"true\" />\n      </button>\n    </div>\n  );\n}\n\n/** The zoom an actual-size press asks for. */\nconst ACTUAL_SIZE: CanvasZoom = { kind: \"fixed\", scale: 1 };\n\n/**\n * The zoom keys: mod+0 for actual size, Shift+1 to fit.\n *\n * Shift+1 is bound twice because the key it reports depends on the layout: a\n * US layout reports \"!\", and a layout where the digit itself needs Shift\n * reports \"1\" with Shift held. Both carry the same description, so Help lists\n * them as one line. Neither fires while the author is typing: on the second\n * kind of layout Shift+1 is how a \"1\" is typed.\n *\n * Nothing is bound where the host wired no zoom, for the reason the control\n * draws nothing there: a key that changes a number nothing applies is a dead\n * control. `active` is read at press time, so a shell hidden behind its\n * narrow-window notice lets the keys through to whatever else binds them,\n * and so is `claims`: where two shells share the shortcut manager, only the\n * one the author is in answers.\n */\nexport function useZoomShortcuts(\n  onChange: ((zoom: CanvasZoom) => void) | undefined,\n  active: boolean,\n  claims: () => boolean = () => true\n): void {\n  const latest = useRef({ onChange, active, claims });\n  latest.current = { onChange, active, claims };\n  const when = (): boolean =>\n    latest.current.active &&\n    latest.current.onChange !== undefined &&\n    latest.current.claims();\n  const fit = (): void => latest.current.onChange?.(FIT_ZOOM);\n  useShortcuts(\n    onChange === undefined\n      ? []\n      : [\n          {\n            keys: \"mod+0\",\n            description: \"Show the page at actual size\",\n            when,\n            run: () => latest.current.onChange?.(ACTUAL_SIZE),\n          },\n          {\n            keys: \"shift+1\",\n            description: \"Fit the page to the canvas\",\n            when,\n            whenTyping: false,\n            run: fit,\n          },\n          {\n            keys: \"!\",\n            // No description: it is Shift+1 as a US layout reports it, the\n            // same keystroke, so Help lists Shift+1 alone rather than a\n            // second key cap that reads as a different key.\n            description: \"\",\n            when,\n            whenTyping: false,\n            run: fit,\n          },\n        ],\n    { name: \"Canvas zoom\" }\n  );\n}\n","\"use client\";\n\n/**\n * The shell's canvas region: the strip and notices above the canvas, the\n * canvas scrolled in its region, and the panel body around them.\n *\n * @module shell-canvas-region\n */\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useCanvasFrame } from \"../canvas/canvas-frame-context\";\nimport { CANVAS_FRAME_BOX_ATTRIBUTE } from \"../canvas/geometry-dom\";\n\n/**\n * The canvas's region: a named `section`, never `<main>`.\n *\n * HTML allows one non-hidden `main` per document, and every mount this shell\n * has is inside a host that already owns it — the admin's dashboard layout\n * renders one, and the editor is embedded in it. A second gives assistive\n * technology two competing primary landmarks and makes every strict `main`\n * locator ambiguous. A `section` carrying an accessible name is still exposed\n * as a landmark, as a `region`.\n *\n * The ref and `tabIndex` belong to this element deliberately: F6 region\n * cycling focuses it, and dropping either would lose the canvas as a cycle\n * target — which reads as a focus bug rather than a markup change.\n */\n/**\n * Whether `element` has content past its own box to scroll to, kept current\n * as it or what it holds changes size: the painted frame grows past the\n * region at a zoom, and the region narrows with the panels beside it.\n */\nfunction useScrollsItsContent(element: HTMLElement | null): boolean {\n  const [overflows, setOverflows] = React.useState(false);\n  useIsomorphicLayoutEffect(() => {\n    if (element === null) return;\n    const measure = () => {\n      setOverflows(\n        element.scrollWidth > element.clientWidth ||\n          element.scrollHeight > element.clientHeight\n      );\n    };\n    measure();\n    const view = element.ownerDocument.defaultView;\n    if (view === null || typeof view.ResizeObserver !== \"function\") return;\n    const sizes = new view.ResizeObserver(measure);\n    /*\n     * The region, and the painted frame's box inside it, whose size the zoom\n     * changes while the region's own stays put. Found again whenever what\n     * the region holds changes, since the frame mounts after the region.\n     */\n    const observe = () => {\n      sizes.disconnect();\n      sizes.observe(element);\n      for (const box of Array.from(\n        element.querySelectorAll(`[${CANVAS_FRAME_BOX_ATTRIBUTE}]`)\n      )) {\n        sizes.observe(box);\n      }\n      measure();\n    };\n    observe();\n    const contents = new view.MutationObserver(observe);\n    contents.observe(element, { childList: true, subtree: true });\n    return () => {\n      contents.disconnect();\n      sizes.disconnect();\n    };\n  }, [element]);\n  return overflows;\n}\n\nfunction CanvasRegion({\n  regionRef,\n  children,\n}: {\n  regionRef: (element: HTMLElement | null) => void;\n  children?: React.ReactNode;\n}): React.JSX.Element {\n  // The frame the canvas is drawn in, which focus arriving on the region is\n  // handed on to.\n  const canvasFrame = useCanvasFrame();\n  const [element, setElement] = React.useState<HTMLElement | null>(null);\n  const ref = React.useCallback(\n    (next: HTMLElement | null) => {\n      regionRef(next);\n      setElement(next);\n    },\n    [regionRef]\n  );\n  const overflows = useScrollsItsContent(element);\n  // Steps aside for the frame only while there is nothing here to scroll.\n  const handsOn = canvasFrame.frame !== null && !overflows;\n  return (\n    <section\n      ref={ref}\n      /*\n       * `0`, not `-1`, wherever this region SCROLLS: nothing inside it that\n       * the keyboard can reach scrolls it — blocks are selected by pointer,\n       * not by tab, and arrow keys in a frame scroll only the frame's own\n       * page — so at `-1` a keyboard user could not scroll the canvas at all.\n       * A canvas in this document, or a frame painted past the region at a\n       * zoom.\n       *\n       * Otherwise a canvas in a frame is its own tab stop, and its page\n       * scrolls inside it, so the region steps aside: `-1` keeps it\n       * focusable for F6, and focus arriving on it goes on into the\n       * frame. Kept as a stop as well it would be a trap — Shift+Tab\n       * out of the frame would land here and be sent back in.\n       */\n      tabIndex={handsOn ? -1 : 0}\n      onFocus={event => {\n        if (!handsOn || event.target !== event.currentTarget) return;\n        canvasFrame.frame?.focus();\n      }}\n      aria-label=\"Canvas\"\n      /*\n       * Unpadded, so the page meets the region's edges and reads as the page\n       * rather than a card inside a box. The frame is fitted into this\n       * element's content box, so at the region's width it touches the\n       * panels' dividers, and a narrower frame is centred in the well with\n       * its hairline edge. Where the frame meets the region, the region\n       * clips that edge, so it never doubles a divider.\n       */\n      className=\"nx-canvas-scroller h-full overflow-auto\"\n    >\n      {children}\n    </section>\n  );\n}\n\n/**\n * Whether a host's node draws anything: `undefined`, `null` and a boolean\n * (what `cond && <Strip />` leaves) draw nothing, so no slot is made for\n * them.\n */\nfunction drawsSomething(node: React.ReactNode): boolean {\n  return node !== undefined && node !== null && typeof node !== \"boolean\";\n}\n\n/**\n * The canvas panel's contents: the strip, where the host gives one, above the\n * canvas's region rather than inside it (the region is what scrolls, so the\n * strip stays pinned while the page scrolls under it, its edges on the\n * region's as the page's are), then the region, with the checklist floated\n * over it.\n */\nexport function CanvasPanelBody({\n  canvasStrip,\n  checklist,\n  regionRef,\n  children,\n}: {\n  canvasStrip: React.ReactNode | undefined;\n  checklist: React.ReactNode | undefined;\n  regionRef: (element: HTMLElement | null) => void;\n  children?: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <div className=\"flex h-full flex-col\">\n      {!drawsSomething(canvasStrip) ? null : (\n        <div className=\"nx-canvas-strip-slot shrink-0\">{canvasStrip}</div>\n      )}\n      {/* The canvas's region: see `CanvasRegion`. */}\n      <div className=\"relative min-h-0 flex-1\">\n        <CanvasRegion regionRef={regionRef}>{children}</CanvasRegion>\n        {checklist === undefined ? null : (\n          // The positioner takes no pointer events, so it cannot swallow a\n          // click aimed at the page underneath it; the card itself takes them\n          // back.\n          <div className=\"pointer-events-none absolute inset-x-0 bottom-0 flex justify-end p-4\">\n            <div className=\"pointer-events-auto\">{checklist}</div>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n","/**\n * Moving between the shell's regions by keyboard: F6 and Shift+F6 cycle them,\n * claimed by one shell at a time, the sides shortcut, and Escape from a\n * separator back to its region.\n *\n * @module shell-region-cycling\n */\nimport { useShortcuts } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { isHTMLElement } from \"../canvas/dom-kind\";\n\n/**\n * The regions F6 cycles between, in the order a sighted user reads them.\n *\n * A shell of this size is unusable by keyboard without region navigation: an\n * author who tabs out of the inspector should not traverse every control in the\n * canvas to reach the rail. F6 is the platform convention for exactly this.\n *\n * The top bar comes first: it holds the editor's own controls (exit, undo and\n * redo, the devices, the zoom, the side toggles), and it is where a reader's\n * eye starts.\n */\nconst REGIONS = [\"header\", \"rail\", \"panel\", \"canvas\", \"inspector\"] as const;\nexport type Region = (typeof REGIONS)[number];\n\n/**\n * How many shells are ACTIVE right now — mounted and wide enough to be used.\n *\n * Read only to decide whether \"focus is nowhere in particular\" identifies a\n * shell unambiguously. With one usable editor on the page it does; with several\n * it does not, and the tie has to be declined rather than won by whichever\n * registered last.\n *\n * Active rather than merely mounted, and that distinction only became\n * observable once each shell measured its OWN container: siblings in columns of\n * different widths can now disagree about whether they fit, so a form can hold\n * one usable editor beside several showing their narrow notices. Counting every\n * mount there makes the one editor that CAN answer decline, because it sees\n * more than one — and the others decline too, since their binding is disabled.\n * F6 would reach nothing at all. A shell behind its notice is not a candidate\n * for the key, so it is not part of the ambiguity either.\n */\nlet activeShells = 0;\n\nfunction useActiveShellCount(active: boolean): () => number {\n  React.useEffect(() => {\n    if (!active) return;\n    activeShells += 1;\n    return () => {\n      activeShells -= 1;\n    };\n  }, [active]);\n  return () => activeShells;\n}\n\n/**\n * Whether THIS shell should act on F6 right now.\n *\n * The binding is registered on the document, so on a page holding a shell\n * beside other controls — the field mount, embedded in an entry form — every\n * shell sees every press. Eligibility therefore cannot come from viewport\n * state alone: with several page-builder fields in one form, all of them were\n * eligible at once and the most recently registered answered, which moved\n * focus into an editor the author was not in.\n *\n * Ownership is asked of the shell ROOT, not of the regions. The two are\n * different questions and only look like one: the root answers \"is the author\n * inside this editor\", while the region list answers \"where can cycling land\".\n * The chrome header — the exit button and whatever the host puts in the top\n * bar — is inside the editor and inside no region, so asking the regions\n * rejected the shell whenever focus was on one of those controls and left F6\n * doing nothing from the very chrome it belongs to.\n *\n * The `document.body` case is what keeps the key working from a cold page: the\n * full Edit view owns its page and nothing inside it has focus yet, and\n * refusing there would make F6 look broken until focus happened to land\n * somewhere it recognised. It is allowed only while this is the sole shell,\n * because with more than one the press names none of them.\n */\nfunction shellClaimsRegionCycling(\n  root: HTMLElement | null,\n  shellCount: number\n): boolean {\n  // The host document's own reading, deliberately not the focused node inside\n  // a frame: focus inside a same-origin iframe reads here as the iframe, which\n  // the shell contains, while the node inside it belongs to another document\n  // that no element here contains.\n  const active = document.activeElement;\n  if (root?.contains(active)) return true;\n  // `null` as well as `body`: a document that has never been clicked reports\n  // no active element at all in some engines, which is the same \"nowhere\".\n  const nowhere = active === null || active === document.body;\n  return nowhere && shellCount === 1;\n}\n\n/**\n * mod+backslash, hiding or showing both sides of the editor.\n *\n * Read through a ref so the binding runs the current toggle, which closes over\n * this render's panels. Never while typing (a backslash is text there), and\n * only for the shell the author is in, by the same check F6 uses.\n */\nexport function useSidesShortcut(\n  toggle: React.RefObject<() => void>,\n  enabled: boolean,\n  claims: () => boolean\n): void {\n  const latest = React.useRef({ enabled, claims });\n  latest.current = { enabled, claims };\n  useShortcuts(\n    [\n      {\n        keys: \"mod+\\\\\",\n        description: \"Hide or show the side panels\",\n        whenTyping: false,\n        when: () => latest.current.enabled && latest.current.claims(),\n        run: () => toggle.current(),\n      },\n    ],\n    { name: \"Builder side panels\" }\n  );\n}\n\n/**\n * F6 region cycling, registered with the shared shortcut manager.\n *\n * Through the manager rather than a private key listener, because two\n * independent key layers is how \"Escape navigates out of the editor while a drag\n * owns it\" happens — the failure the manager exists to prevent.\n */\nexport function useRegionCycling(\n  regionRefs: React.RefObject<Record<Region, HTMLElement | null>>,\n  rootRef: React.RefObject<HTMLElement | null>,\n  enabled: boolean\n): () => boolean {\n  const shellCount = useActiveShellCount(enabled);\n  // Read through a ref so the binding's `when` sees the CURRENT answer. The\n  // manager checks it at press time, and a value captured when the binding was\n  // registered would keep reporting whatever was true then.\n  const enabledRef = React.useRef(enabled);\n  enabledRef.current = enabled;\n\n  useShortcuts(\n    [\n      {\n        keys: \"F6\",\n        // Off while the shell is hidden behind the narrow-viewport notice. The\n        // subtree stays mounted there to preserve the caller's slots, which\n        // leaves this binding registered over regions that are all `inert`:\n        // pressing F6 on the notice consumed the key, focused nothing, and —\n        // where the host shares the shortcut manager — took the keystroke from\n        // whatever binding of its own would otherwise have handled it.\n        //\n        // `when` rather than skipping registration, because it is the\n        // manager's own way of saying \"not right now\": a binding whose\n        // condition is false is passed over and the key goes on to the next\n        // layer, which is exactly the behaviour the host needs back.\n        //\n        // Focus is consulted for the same reason it is passed on: a shell the\n        // author is not in should let the key reach whatever they ARE in.\n        when: () =>\n          enabledRef.current &&\n          shellClaimsRegionCycling(rootRef.current, shellCount()),\n        description: \"Move to the next area of the editor\",\n        // The manager's default asks whether the FIRST chord carries a modifier\n        // or is Escape, and answers no for a bare function key — so F6 would be\n        // held back by any focused text field. That default is right for the\n        // letter keys it was written for and backwards here: moving between\n        // areas of the editor is the one thing an author needs MOST while a\n        // caption or a field has focus, because it is how they get back out\n        // without reaching for the mouse.\n        whenTyping: true,\n        run: () => {\n          focusNextRegion(regionRefs.current);\n        },\n      },\n      {\n        // Back through the same regions, as the platform convention has it:\n        // from the inspector to the canvas, and from the top bar round to the\n        // inspector. Held back and passed on exactly as F6 is.\n        keys: \"shift+F6\",\n        when: () =>\n          enabledRef.current &&\n          shellClaimsRegionCycling(rootRef.current, shellCount()),\n        description: \"Move to the previous area of the editor\",\n        whenTyping: true,\n        run: () => {\n          focusNextRegion(regionRefs.current, -1);\n        },\n      },\n    ],\n    { name: \"Builder shell\" }\n  );\n  // The same question for every key this shell answers on behalf of the\n  // whole editor: whether the author is in THIS shell, so a second shell\n  // sharing the shortcut manager does not take the keystroke.\n  return () => shellClaimsRegionCycling(rootRef.current, shellCount());\n}\n\n/**\n * Move focus to the next rendered region, wrapping around, or with `step` -1\n * to the previous one (Shift+F6).\n *\n * A named function rather than the body of the binding, because TWO paths have\n * to perform this and they must not be two implementations of it — see\n * `useSeparatorRegionEscape` for why the second exists.\n */\nfunction focusNextRegion(\n  map: Record<Region, HTMLElement | null> | null,\n  step: 1 | -1 = 1\n): void {\n  if (!map) return;\n  // Only regions that are actually rendered. The left panel is absent whenever\n  // the rail has nothing open, and cycling the static list would land on it,\n  // focus nothing, and leave the key looking broken for every press after the\n  // first.\n  const present = REGIONS.filter(region => map[region] !== null);\n  if (present.length === 0) return;\n\n  // The host's own reading, for the reason `shellClaimsRegionCycling` gives.\n  const active = document.activeElement;\n  const currentIndex = present.findIndex(region =>\n    map[region]?.contains(active)\n  );\n  // From outside any region, F6 enters the first rather than doing nothing —\n  // otherwise the key appears broken until focus happens to land somewhere it\n  // recognises; Shift+F6 from outside enters the last.\n  const from = currentIndex < 0 && step < 0 ? 0 : currentIndex;\n  const next = present[(from + step + present.length) % present.length];\n  if (next !== undefined) map[next]?.focus();\n}\n\n/**\n * Let F6 escape a focused drag handle.\n *\n * The separators run their own key listener, and it claims F6: it cycles\n * between separators and calls `preventDefault()`. The shared shortcut manager\n * deliberately skips an event that has already been prevented — two layers both\n * acting on one keystroke is the failure it exists to stop — so the shell's\n * region binding never ran. In the default topology there is exactly ONE\n * separator, so F6 from a handle re-focused that same handle for ever, which is\n * the state an author lands in immediately after resizing anything.\n *\n * Handled in the CAPTURE phase on the shell root, which is the only place that\n * runs before the separator's own listener at the target. Propagation is stopped\n * so the manager does not then cycle a second time on the way back up.\n *\n * The region binding stays registered: it is what handles F6 from outside this\n * subtree, and what puts the shortcut in front of anything that lists them.\n */\nexport function useSeparatorRegionEscape(\n  regionRefs: React.RefObject<Record<Region, HTMLElement | null>>,\n  enabled: boolean\n): (event: React.KeyboardEvent<HTMLElement>) => void {\n  return React.useCallback(\n    (event: React.KeyboardEvent<HTMLElement>) => {\n      if (event.key !== \"F6\" || !enabled) return;\n      // Only from a separator. Everywhere else the manager is the right owner,\n      // and intercepting here would take the key from a host binding that has\n      // every right to it.\n      // By node kind rather than `instanceof HTMLElement`, which answers only\n      // for elements this window built.\n      const target = event.target;\n      if (\n        !isHTMLElement(target) ||\n        target.getAttribute(\"role\") !== \"separator\"\n      ) {\n        return;\n      }\n      event.preventDefault();\n      event.stopPropagation();\n      // Shift+F6 from a handle goes back, as it does everywhere else.\n      focusNextRegion(regionRefs.current, event.shiftKey ? -1 : 1);\n    },\n    [regionRefs, enabled]\n  );\n}\n","/**\n * The shell's side panels: which one shows, whether each side is open, and\n * focus kept inside the shell when a side closes under it.\n *\n * @module shell-side-panels\n */\nimport * as React from \"react\";\n\nimport {\n  LEFT_PANELS,\n  panelAfterRailClick,\n  type LeftPanel,\n  type ShellPreferences,\n} from \"../shell-state\";\n\nimport { useSidesShortcut, type Region } from \"./shell-region-cycling\";\n\n/**\n * The left panel to show when the author asks for the left side back: the one\n * they had open, else the first the host offers, in the rail's order.\n */\nfunction panelToShow(\n  remembered: LeftPanel | null,\n  isAvailable: (panel: LeftPanel) => boolean\n): LeftPanel | null {\n  if (remembered !== null && isAvailable(remembered)) return remembered;\n  return LEFT_PANELS.find(isAvailable) ?? remembered;\n}\n\n/**\n * Move focus out of the sides about to be hidden, onto the canvas.\n *\n * A hidden side unmounts the element holding focus, which leaves it on the\n * page body. With two editors on a page, neither claims a key pressed there,\n * so the same shortcut could not bring the sides back.\n */\nfunction keepFocusInShell(\n  regions: Record<Region, HTMLElement | null>,\n  hiding: readonly Region[]\n): void {\n  // The host's own reading, for the reason `shellClaimsRegionCycling` gives.\n  const focused = document.activeElement;\n  if (!hiding.some(region => regions[region]?.contains(focused) === true)) {\n    return;\n  }\n  (regions.canvas ?? regions.header)?.focus();\n}\n\n/**\n * Which sides of the editor show, and the actions that change them: the\n * rail, the top bar's two buttons and mod+backslash.\n *\n * `isAvailable` is the shell's one answer to \"can the host fill this panel\",\n * so the panel shown here and the item the rail draws cannot disagree.\n */\nexport function useSidePanels(\n  preferences: ShellPreferences,\n  update: (change: (current: ShellPreferences) => ShellPreferences) => void,\n  isAvailable: (panel: LeftPanel) => boolean,\n  active: boolean,\n  claims: () => boolean,\n  regionRefs: React.RefObject<Record<Region, HTMLElement | null>>\n): {\n  openPanel: LeftPanel | null;\n  inspectorShown: boolean;\n  leftShown: boolean;\n  selectPanel: (panel: LeftPanel) => void;\n  /** Absent when the host offers no left panel: there is nothing to show. */\n  toggleLeft: (() => void) | undefined;\n  toggleInspector: () => void;\n} {\n  const restored = preferences.leftPanel;\n  // A hidden left side shows no panel, but keeps which one was open.\n  const openPanel =\n    !preferences.leftPanelHidden && restored !== null && isAvailable(restored)\n      ? restored\n      : null;\n  const inspectorShown = !preferences.inspectorHidden;\n  // From the rail. While the left side is hidden, choosing a panel shows it\n  // rather than toggling: the author asked to see that panel.\n  const selectPanel = (panel: LeftPanel) => {\n    // Closing the open panel, by its item or its key, unmounts what may hold\n    // focus: it goes to the canvas, as hiding a side sends it.\n    if (openPanel === panel) keepFocusInShell(regionRefs.current, [\"panel\"]);\n    update(current =>\n      current.leftPanelHidden\n        ? { ...current, leftPanel: panel, leftPanelHidden: false }\n        : {\n            ...current,\n            leftPanel: panelAfterRailClick(current.leftPanel, panel),\n          }\n    );\n  };\n  /*\n   * The top bar's left-panel button. Showing it with no panel chosen opens\n   * the first panel the host offers, Add where it offers that.\n   */\n  const leftShown = openPanel !== null;\n  const toggleLeft = () => {\n    if (leftShown) keepFocusInShell(regionRefs.current, [\"panel\"]);\n    update(current =>\n      leftShown\n        ? { ...current, leftPanelHidden: true }\n        : {\n            ...current,\n            leftPanel: panelToShow(current.leftPanel, isAvailable),\n            leftPanelHidden: false,\n          }\n    );\n  };\n  const toggleInspector = () => {\n    if (inspectorShown) keepFocusInShell(regionRefs.current, [\"inspector\"]);\n    update(current => ({\n      ...current,\n      inspectorHidden: !current.inspectorHidden,\n    }));\n  };\n  /*\n   * mod+backslash: hide both sides when either is showing, so one press\n   * always gives the canvas the whole width; show both when neither is.\n   */\n  const toggleSides = () => {\n    const anyShown = leftShown || inspectorShown;\n    if (anyShown) keepFocusInShell(regionRefs.current, [\"panel\", \"inspector\"]);\n    update(current => ({\n      ...current,\n      leftPanelHidden: anyShown,\n      inspectorHidden: anyShown,\n      ...(anyShown\n        ? {}\n        : { leftPanel: panelToShow(current.leftPanel, isAvailable) }),\n    }));\n  };\n  const toggleSidesRef = React.useRef(toggleSides);\n  toggleSidesRef.current = toggleSides;\n  useSidesShortcut(toggleSidesRef, active, claims);\n  return {\n    openPanel,\n    inspectorShown,\n    leftShown,\n    selectPanel,\n    toggleLeft: LEFT_PANELS.some(isAvailable) ? toggleLeft : undefined,\n    toggleInspector,\n  };\n}\n","/**\n * Development-time warnings for requirements nothing else can check.\n *\n * The editor's stylesheet supplements the design system's rather than restating\n * it, so the shell renders correctly only when the host has loaded BOTH. Nothing\n * at build time can see whether it did: the second sheet is a side-effect import\n * in the host's own application, and its absence produces a shell that mounts,\n * carries every class it should, and merely looks wrong — the most expensive\n * kind of failure to trace back to a missing import.\n *\n * `@nextlyhq/ui` has a module of the same shape and keeps it private, so this is\n * a second instance of the pattern rather than a second copy of an answer: the\n * two warn about different contracts and name different packages. The rules are\n * taken from it deliberately, because they are the ones that make a warning\n * useful rather than noise.\n *\n * - **Development only, proven rather than assumed.** The gate requires a\n *   POSITIVE development signal. Asking whether the environment is production\n *   fails open — a browser bundle that never defines `process` leaves that\n *   comparison false, and every warning would reach real users' consoles.\n * - **Once per message.** The shell re-renders on every panel drag; the same\n *   line on every frame trains people to ignore the console.\n * - **Never throws.** A missing stylesheet degrades the editor's appearance. It\n *   must not take down the page.\n *\n * @module dev-warn\n */\n\n/** Messages already emitted this session, keyed by the message itself. */\nconst emitted = new Set<string>();\n\n/**\n * The one field this module reads, declared rather than pulled in with\n * `@types/node`: this package targets the browser, and bundlers replace\n * `process.env.NODE_ENV` at build time.\n */\ndeclare const process: { env?: { NODE_ENV?: string } | undefined } | undefined;\n\n/**\n * The environments a warning may speak in.\n *\n * `test` sits alongside `development` so a suite asserting that a warning fires\n * is exercising the same path a developer relies on, rather than passing because\n * the gate silenced it.\n */\nconst SPEAKING_ENVIRONMENTS = new Set([\"development\", \"test\"]);\n\n/** Whether this runtime has positively identified itself as a development one. */\nfunction isDevelopmentRuntime(): boolean {\n  if (typeof process === \"undefined\") return false;\n  const env = process?.env?.NODE_ENV;\n  return env !== undefined && SPEAKING_ENVIRONMENTS.has(env);\n}\n\n/**\n * Warn once, in development, about a requirement that is unmet.\n *\n * @param condition - The requirement. Nothing is emitted while this holds.\n * @param message - What is wrong and what to do about it, written for someone\n *   reading a console with no other context.\n */\nexport function devWarnOnce(condition: boolean, message: string): void {\n  if (condition) return;\n  if (!isDevelopmentRuntime()) return;\n  if (emitted.has(message)) return;\n  emitted.add(message);\n  console.warn(`[@nextlyhq/builder] ${message}`);\n}\n\n/**\n * Forget which messages have been emitted.\n *\n * For tests, which need each case to observe its own warning rather than\n * inheriting an earlier one's suppression.\n */\nexport function resetDevWarnings(): void {\n  emitted.clear();\n}\n","/**\n * The design system's stylesheet the shell draws with: checked for on the\n * host page, and the side panels' class.\n *\n * @module shell-stylesheet\n */\nimport * as React from \"react\";\n\nimport { devWarnOnce } from \"./dev-warn\";\n\n/**\n * One design-system token, read off the mounted shell.\n *\n * Chosen over any `--nx-builder-*` because those are declared in this package's\n * own stylesheet and would resolve whether or not the design system's had been\n * loaded — the check would pass in exactly the case it exists to catch. The\n * `--nx-*` layer is declared only by `@nextlyhq/ui`, so its absence is the\n * question being asked.\n */\nconst REQUIRED_HOST_TOKEN = \"--nx-background\";\n\n/**\n * A token this package's OWN stylesheet declares, used as a positive control.\n *\n * Without it the check cannot tell the two ways of resolving to nothing apart:\n * a host that never imported the design system's sheet, and an environment that\n * applies no stylesheets whatsoever. jsdom is the second, so a bare absence test\n * would warn on every unit test that mounts the shell — noise indistinguishable\n * from the real defect, in the place developers read warnings most.\n *\n * Reading both makes the instrument observable: when this one resolves, styles\n * ARE being applied, and the other one's absence means what it says.\n */\nconst OWN_STYLESHEET_TOKEN = \"--nx-builder-surface\";\n\n/**\n * The one surface both sides of the editor sit on, the rail's own: the left\n * panels and the Inspector are the panel surface around the canvas's grey\n * well, divided from it by the resize handle's single line. One class, so the\n * two sides cannot drift apart.\n */\nexport const SIDE_PANEL_CLASS =\n  \"bg-[color:var(--nx-builder-panel)] h-full overflow-auto\";\n\n/**\n * The resize handles between a side panel and the canvas: their 1px line in\n * the divider token, which turns to the foreground under more contrast and to\n * the system's text colour in forced colours (the base partial).\n */\nexport const PANEL_DIVIDER_CLASS =\n  \"nx-builder-divider-line bg-[color:var(--nx-builder-divider)]\";\n\n/**\n * Tell a developer when the design system's stylesheet has not been loaded.\n *\n * The editor's own sheet supplements that one rather than restating it, so a\n * host that imports only `@nextlyhq/builder/styles.css` gets a shell that mounts\n * with every class name in place and renders wrong — unstyled tooltips and drag\n * handles, and chrome colours resolving to nothing. Nothing at build time can\n * see a missing side-effect import in someone else's application, so this is the\n * only layer the requirement can be enforced from.\n */\nexport function useDesignSystemStylesheet(\n  rootRef: React.RefObject<HTMLElement | null>\n): void {\n  React.useEffect(() => {\n    const root = rootRef.current;\n    if (!root || typeof window === \"undefined\") return;\n    const styles = window.getComputedStyle(root);\n    const own = styles.getPropertyValue(OWN_STYLESHEET_TOKEN).trim();\n    // Nothing resolves here, so the absence of the other token says nothing\n    // about the host. Reporting it anyway would put a warning about a missing\n    // import in front of every developer running the suite.\n    if (own === \"\") return;\n    devWarnOnce(\n      styles.getPropertyValue(REQUIRED_HOST_TOKEN).trim() !== \"\",\n      `The design system's stylesheet is not loaded, so the editor will render ` +\n        `without its colours, tooltips or drag handles. Import ` +\n        `\"@nextlyhq/ui/styles.css\" (or the admin's stylesheet) alongside ` +\n        `\"@nextlyhq/builder/styles.css\" — the editor's sheet supplements it and ` +\n        `does not replace it.`\n    );\n  }, [rootRef]);\n}\n","/**\n * Whether the editor's top bar is crowded: whether its controls, with the\n * page title at its shortest, still need more room than the bar has.\n *\n * The bar gives way in one order as room runs out. The title shortens first\n * (its column lets it alone shrink, down to a floor), and only once it is at\n * that floor do the words marked `data-topbar-word` step aside, each leaving\n * its icon and its accessible name: Preview's word, and the page data\n * meter's \"what's this?\". Save, Publish and the active width never shorten.\n *\n * A fixed bar width cannot say when that is, since what the bar holds\n * changes with the page (a long title or a short one, Save or \"✓ Saved\",\n * the meter shown or not), so the bar is measured instead: each column's\n * controls at the width they draw at, the shortening title at its floor,\n * and each word that has stepped aside at the width it would take back.\n *\n * @module top-bar-room\n */\nimport * as React from \"react\";\n\nimport { isHTMLElement } from \"../canvas/dom-kind\";\n\n/** Marks the control that shortens first: the page's title. */\nconst TOP_BAR_SHORTENS = \"data-topbar-shortens\";\n\n/** Marks words that step aside once the title is at its shortest. */\nconst TOP_BAR_WORD = \"data-topbar-word\";\n\n/** The bar's measurements that decide whether it is crowded. */\nexport interface TopBarRoom {\n  /** The room the bar's columns share: its width less its padding. */\n  readonly available: number;\n  /** What the columns' own controls take, the title at its floor. */\n  readonly controls: number;\n  /** What the gaps between the columns take. */\n  readonly gaps: number;\n  /**\n   * What the words that have stepped aside would take back, each with the\n   * gap beside it: nothing while none has.\n   */\n  readonly words: number;\n}\n\n/**\n * Whether the bar is crowded: whether its controls, with every word drawn,\n * need more than the room it has. Half a pixel of slack, so a width that\n * rounds to the room is not read as short of it.\n */\nexport function topBarCrowded(room: TopBarRoom): boolean {\n  return room.controls + room.gaps + room.words > room.available + 0.5;\n}\n\n/** Whether an element takes part in its row's layout. */\nfunction laidOut(element: Element): element is HTMLElement {\n  if (!isHTMLElement(element)) return false;\n  const style = getComputedStyle(element);\n  return (\n    style.display !== \"none\" &&\n    style.position !== \"absolute\" &&\n    style.position !== \"fixed\"\n  );\n}\n\n/** A flex row's gap between items, in pixels. */\nfunction gapOf(element: Element): number {\n  return parseFloat(getComputedStyle(element).columnGap) || 0;\n}\n\n/**\n * What a column's controls take: each at its laid-out width, the shortening\n * title at its floor (its `min-width`), and the gaps between them. The bar\n * is in the editor's own document, never the canvas's frame, so its layout\n * widths (`offsetWidth`) are read directly; whole pixels, which the half\n * pixel of slack and the measuring of both states alike absorb.\n */\nfunction columnNeeds(column: Element): number {\n  const items = [...column.children].filter(laidOut);\n  let total = gapOf(column) * Math.max(0, items.length - 1);\n  for (const item of items) {\n    total += item.hasAttribute(TOP_BAR_SHORTENS)\n      ? parseFloat(getComputedStyle(item).minWidth) || 0\n      : item.offsetWidth;\n  }\n  return total;\n}\n\n/**\n * What the words that have stepped aside would take back: a hidden word is\n * out of its row, so it frees its own width (its `scrollWidth`, which a\n * clipped word still reports) and the gap its row kept beside it.\n */\nfunction hiddenWords(bar: Element): number {\n  let total = 0;\n  for (const word of bar.querySelectorAll(`[${TOP_BAR_WORD}]`)) {\n    if (laidOut(word)) continue;\n    total += word.scrollWidth;\n    if (word.parentElement !== null) total += gapOf(word.parentElement);\n  }\n  return total;\n}\n\n/** The bar measured, as {@link topBarCrowded} reads it. */\nexport function measureTopBar(bar: Element): TopBarRoom {\n  const style = getComputedStyle(bar);\n  const columns = [...bar.children].filter(laidOut);\n  return {\n    available:\n      bar.clientWidth -\n      (parseFloat(style.paddingLeft) || 0) -\n      (parseFloat(style.paddingRight) || 0),\n    controls: columns.reduce((sum, column) => sum + columnNeeds(column), 0),\n    gaps: gapOf(bar) * Math.max(0, columns.length - 1),\n    words: hiddenWords(bar),\n  };\n}\n\n/**\n * The top bar's own ref, handed on to `headerRef` as well, and whether the\n * bar it holds is crowded ({@link useTopBarCrowded}).\n */\nexport function useTopBarRoom(\n  headerRef: (element: HTMLElement | null) => void\n): {\n  readonly ref: (element: HTMLElement | null) => void;\n  readonly crowded: boolean;\n} {\n  const [bar, setBar] = React.useState<HTMLElement | null>(null);\n  const crowded = useTopBarCrowded(bar);\n  const ref = React.useCallback(\n    (element: HTMLElement | null) => {\n      headerRef(element);\n      setBar(element);\n    },\n    [headerRef]\n  );\n  return { ref, crowded };\n}\n\n/**\n * Whether the bar `bar` holds is crowded, measured again whenever the bar\n * or anything in its columns changes size, and whenever a column's controls\n * come or go.\n *\n * Without `ResizeObserver` (jsdom) nothing is measured and the bar reads as\n * not crowded, so every word is drawn.\n */\nfunction useTopBarCrowded(bar: HTMLElement | null): boolean {\n  const [crowded, setCrowded] = React.useState(false);\n  React.useLayoutEffect(() => {\n    if (bar === null || typeof ResizeObserver === \"undefined\") return;\n    let frame = 0;\n    const measure = () => {\n      frame = 0;\n      setCrowded(topBarCrowded(measureTopBar(bar)));\n    };\n    // Once a frame at most: a label changing sets off several observers.\n    const schedule = () => {\n      if (frame === 0) frame = requestAnimationFrame(measure);\n    };\n    const sizes = new ResizeObserver(schedule);\n    const watch = () => {\n      sizes.disconnect();\n      sizes.observe(bar);\n      for (const column of bar.children) {\n        for (const item of column.children) sizes.observe(item);\n      }\n      schedule();\n    };\n    // Controls come and go (the meter, a chip, Save's mark): the new ones\n    // are watched too.\n    const shape = new MutationObserver(watch);\n    shape.observe(bar, { childList: true, subtree: true });\n    watch();\n    return () => {\n      sizes.disconnect();\n      shape.disconnect();\n      if (frame !== 0) cancelAnimationFrame(frame);\n    };\n  }, [bar]);\n  return crowded;\n}\n","\"use client\";\n\n/**\n * The shell's top bar: the exit, the host's items in its three columns, the\n * zoom and the toggles that show or hide each side panel.\n *\n * @module shell-top-bar\n */\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport {\n  ArrowLeft,\n  PanelLeftClose,\n  PanelLeftOpen,\n  PanelRightClose,\n  PanelRightOpen,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { CanvasZoom } from \"../canvas/canvas-zoom\";\nimport { CanvasZoomControl } from \"../canvas/canvas-zoom-control\";\nimport { ChromeTooltip } from \"../chrome-tooltip\";\n\nimport {\n  useLatestCallback,\n  useLatestOptionalCallback,\n} from \"./latest-callback\";\nimport type { BuilderShellProps } from \"./shell-props\";\nimport { PANEL_DIVIDER_CLASS } from \"./shell-stylesheet\";\nimport { useTopBarRoom } from \"./top-bar-room\";\n\n/**\n * The exit's words where the host names no other: it returns to the document\n * that opened the editor.\n */\nexport const DEFAULT_EXIT_LABEL = \"Exit editor\";\n\n/**\n * The editor's top bar: three columns, the outer two equal while there is\n * room, so the centre one (the devices and the zoom) stays in the middle of\n * the editor. The shell draws its own controls here (exit, the zoom, the side\n * toggles) around what the host puts in each column.\n *\n * As room runs out the bar gives way in one order: the title shortens first,\n * and once it is at its shortest the bar is crowded (`data-crowded`), and the\n * words marked `data-topbar-word` step aside, keeping their icons and names\n * (`top-bar-room`). Nothing else shortens.\n *\n * Drawn again only when something it shows changes. The shell renders again\n * for every change of what it holds, a selection among them, and hands the\n * bar a new header ref and new handlers each time; those are read when\n * called, so the memoised bar is handed the same functions, and a host whose\n * columns keep their identity has its whole bar left alone. Whether a handler\n * is there at all is kept as given, since the bar draws the exit and the\n * left panel's toggle only for a handler there is.\n */\nexport function ShellTopBar(props: TopBarProps): React.JSX.Element {\n  const headerRef = useLatestCallback(props.headerRef);\n  const onExit = useLatestOptionalCallback(props.onExit);\n  const onLeft = useLatestOptionalCallback(props.onLeft);\n  const onInspector = useLatestCallback(props.onInspector);\n  return (\n    <KeptTopBar\n      {...props}\n      headerRef={headerRef}\n      onExit={onExit}\n      onLeft={onLeft}\n      onInspector={onInspector}\n    />\n  );\n}\n\n/** The top bar's props, from the shell's own and the host's. */\ntype TopBarProps = Pick<\n  BuilderShellProps,\n  \"onExit\" | \"exitLabel\" | \"title\" | \"topBar\" | \"topBarCenter\" | \"topBarEnd\"\n> & {\n  headerRef: (element: HTMLElement | null) => void;\n  zoom: CanvasZoom;\n  appliedScale: number;\n  onZoomPick: ((next: CanvasZoom) => void) | undefined;\n  leftShown: boolean;\n  inspectorShown: boolean;\n  /** Absent when the host offers no left panel, so there is nothing to show. */\n  onLeft: (() => void) | undefined;\n  onInspector: () => void;\n};\n\n/** The bar itself, memoised, so it draws again only for a prop that changed. */\nconst KeptTopBar = React.memo(function TopBar({\n  headerRef,\n  onExit,\n  exitLabel = DEFAULT_EXIT_LABEL,\n  title,\n  topBar,\n  topBarCenter,\n  topBarEnd,\n  zoom,\n  appliedScale,\n  onZoomPick,\n  leftShown,\n  inspectorShown,\n  onLeft,\n  onInspector,\n}: TopBarProps): React.JSX.Element {\n  // The bar itself, kept here as well as handed to the shell, so it can be\n  // measured for room.\n  const { ref, crowded } = useTopBarRoom(headerRef);\n  return (\n    <header\n      ref={ref}\n      // Focusable by F6, not by Tab: Tab reaches the controls inside it.\n      tabIndex={-1}\n      // Three columns, the outer two equal while there is room, so the\n      // centre column (the devices and the zoom) sits in the middle of the\n      // editor. The end column never takes less than its controls need, so\n      // Save, Publish and the buttons beside them are always whole and never\n      // drawn over the centre; when the sides cannot both have half, the\n      // start column, whose title shortens, is the one that gives way. A\n      // container, so controls inside can give way by width.\n      // `nx-builder-topbar` sets every control inside at the editor's density.\n      className=\"nx-builder-topbar border-[color:var(--nx-builder-divider)] @container/topbar grid h-12 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(max-content,1fr)] items-center gap-2 border-b px-2\"\n      aria-label=\"Editor actions\"\n      // Crowded once the title is at its shortest: the words that step\n      // aside next do so (`nx-builder-topbar` in the stylesheet).\n      data-crowded={crowded ? \"\" : undefined}\n    >\n      <div data-topbar=\"start\" className=\"flex min-w-0 items-center gap-2\">\n        {/*\n         * Rendered only when there is somewhere to go. A button carrying no\n         * handler still looks operable — it takes focus, it depresses — and\n         * teaches the author that leaving does nothing, which is worse than\n         * offering no exit at all.\n         */}\n        {onExit ? (\n          <button\n            type=\"button\"\n            onClick={onExit}\n            data-builder-animates\n            /*\n             * The NAME stays the exit's words (\"Exit editor\", or where the\n             * host's exit goes) while the label becomes a glyph.\n             * This is the only way out of the editor — `ChromeSuppression`\n             * withholds the navigation rail from a surface that cannot be left,\n             * on the grounds that an author with unsaved work and no way out is\n             * the worst state the editor can reach — so it keeps a real\n             * accessible name and a tooltip rather than relying on the arrow\n             * being self-evident.\n             *\n             * An arrow rather than a cross: this goes back, to the document\n             * that opened the editor or the list the host names, and a cross\n             * reads as discarding rather than as going back.\n             */\n            aria-label={exitLabel}\n            title={exitLabel}\n            // A square at the editor's control height, as the bar's others are.\n            // Never squeezed by a long title beside it: the title shortens.\n            className=\"border-[color:var(--nx-builder-border)] focus-visible:ring-ring inline-flex size-[var(--nx-builder-control-height)] shrink-0 items-center justify-center rounded-md border focus-visible:ring-2 focus-visible:outline-none\"\n          >\n            <ArrowLeft className=\"size-4\" aria-hidden=\"true\" />\n          </button>\n        ) : null}\n        {title !== undefined && title !== \"\" ? (\n          <span\n            title={title}\n            // The control that shortens first, as far as nothing.\n            data-topbar-shortens=\"\"\n            className=\"min-w-0 shrink truncate text-sm font-medium\"\n          >\n            {title}\n          </span>\n        ) : null}\n        {topBar}\n      </div>\n      <div data-topbar=\"centre\" className=\"flex items-center gap-2\">\n        {topBarCenter}\n        {/*\n          Rendered by the shell, not handed to the host as a slot, because the\n          shell owns preferences and this control edits one. A host drawing its\n          own would hold the value in a second place, and the two would correct\n          each other on every open.\n\n          Only where the host has WIRED it, though. The canvas belongs to the\n          host, so without `onZoomChange` there is nothing to apply a choice to:\n          the control would store a preference, report a percentage the canvas\n          does not honour, and read 100% whatever was picked. A shell that\n          predates this — the README example and the playground harness among\n          them — should gain no control rather than a dead one.\n        */}\n        <CanvasZoomControl\n          zoom={zoom}\n          appliedScale={appliedScale}\n          onChange={onZoomPick}\n        />\n      </div>\n      <div\n        data-topbar=\"end\"\n        className=\"flex min-w-0 items-center justify-end gap-2\"\n      >\n        {/* The panel buttons first, then the document's own controls after a\n          thin rule, so the bar ends on the action that leads, as the\n          accepted layout has it. */}\n        <SidePanelToggles\n          leftShown={leftShown}\n          inspectorShown={inspectorShown}\n          onLeft={onLeft}\n          onInspector={onInspector}\n        />\n        <EndControls topBarEnd={topBarEnd} />\n      </div>\n    </header>\n  );\n});\n\n/**\n * The host's controls at the bar's end, after a thin rule. `null` and\n * `false` are what a conditional slot gives when it is empty, so they draw\n * no rule either. Its own component, so the bar's layout reads apart from\n * which of its slots are filled.\n */\nfunction EndControls({\n  topBarEnd,\n}: Pick<BuilderShellProps, \"topBarEnd\">): React.JSX.Element | null {\n  if (topBarEnd === undefined || topBarEnd === null || topBarEnd === false) {\n    return null;\n  }\n  return (\n    <>\n      <span\n        aria-hidden=\"true\"\n        className={cn(\"h-5 w-px shrink-0\", PANEL_DIVIDER_CLASS)}\n      />\n      {topBarEnd}\n    </>\n  );\n}\n\n/** One side-panel toggle: its stable name, its side, and each state's icon. */\ninterface SidePanelToggle {\n  /** The accessible name, kept as the state changes; pressed says which way. */\n  label: string;\n  /** The side as the tooltip names it: \"the left panel\", \"the right panel\". */\n  side: \"left\" | \"right\";\n  shown: boolean;\n  onClick: () => void;\n  /** Drawn while the panel shows: the panel closing, what a press does. */\n  CloseIcon: typeof PanelLeftClose;\n  /** Drawn while the panel is hidden: the panel opening. */\n  OpenIcon: typeof PanelLeftOpen;\n}\n\n/**\n * A toggle whose look says what pressing it does. While its panel shows, it\n * draws the panel's close icon on a fill and its tooltip reads \"Hide the left\n * panel\"; while hidden, the open icon with no fill and \"Show the left panel\".\n * The name stays the panel's and `aria-pressed` carries the state, so a\n * screen reader hears \"Left panel, pressed\" rather than a name that changes\n * under the author. The fill is `nx-builder-panel-toggle`'s, drawn from\n * `data-shown`, in the base partial.\n */\nfunction PanelToggleButton({\n  label,\n  side,\n  shown,\n  onClick,\n  CloseIcon,\n  OpenIcon,\n}: SidePanelToggle): React.JSX.Element {\n  const Icon = shown ? CloseIcon : OpenIcon;\n  return (\n    <ChromeTooltip content={`${shown ? \"Hide\" : \"Show\"} the ${side} panel`}>\n      <button\n        type=\"button\"\n        aria-pressed={shown}\n        aria-label={label}\n        data-shown={shown ? \"true\" : \"false\"}\n        data-builder-animates\n        onClick={onClick}\n        className=\"nx-builder-panel-toggle focus-visible:ring-ring inline-flex size-[var(--nx-builder-control-height)] items-center justify-center rounded-md focus-visible:ring-2 focus-visible:outline-none\"\n      >\n        <Icon className=\"size-4\" aria-hidden=\"true\" />\n      </button>\n    </ChromeTooltip>\n  );\n}\n\n/**\n * The top bar's buttons that show or hide each side of the editor, so the\n * canvas can take the room. The left one is drawn only when the host offers a\n * left panel, since with none it could show nothing.\n */\nfunction SidePanelToggles({\n  leftShown,\n  inspectorShown,\n  onLeft,\n  onInspector,\n}: {\n  leftShown: boolean;\n  inspectorShown: boolean;\n  onLeft: (() => void) | undefined;\n  onInspector: () => void;\n}): React.JSX.Element {\n  return (\n    <div className=\"flex shrink-0 items-center gap-0.5\">\n      {onLeft === undefined ? null : (\n        <PanelToggleButton\n          label=\"Left panel\"\n          side=\"left\"\n          shown={leftShown}\n          onClick={onLeft}\n          CloseIcon={PanelLeftClose}\n          OpenIcon={PanelLeftOpen}\n        />\n      )}\n      <PanelToggleButton\n        label=\"Inspector\"\n        side=\"right\"\n        shown={inspectorShown}\n        onClick={onInspector}\n        CloseIcon={PanelRightClose}\n        OpenIcon={PanelRightOpen}\n      />\n    </div>\n  );\n}\n","/**\n * Showing the inspector from a control in the shell's slots, for one that\n * takes the author to a block's setting (a page check's fix): the setting\n * opens in the inspector, so a hidden inspector is shown first. Lent by the\n * shell around its top bar; absent outside a shell, where there is no hidden\n * inspector to show.\n *\n * @module shell/show-inspector\n */\nimport * as React from \"react\";\n\n/** Show the inspector, where it is hidden. */\nexport const ShowInspectorContext: React.Context<(() => void) | undefined> =\n  React.createContext<(() => void) | undefined>(undefined);\n","\"use client\";\n\n/**\n * The shell's regions laid out: the top bar, the rail, the switched panel,\n * the canvas and the inspector, with their resizable widths.\n *\n * @module shell-regions\n */\nimport {\n  ResizableHandle,\n  ResizablePanel,\n  ResizablePanelGroup,\n} from \"@nextlyhq/ui\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport * as React from \"react\";\n\nimport type { CanvasZoom } from \"../canvas/canvas-zoom\";\nimport { useZoomShortcuts } from \"../canvas/canvas-zoom-control\";\nimport {\n  BUILDER_CHROME_CLASS,\n  MIN_CANVAS_PANEL_WIDTH,\n  PANEL_BOUNDS,\n  topologyKey,\n  type ShellPreferences,\n} from \"../shell-state\";\n\nimport { panelLabel } from \"./editor-rail\";\nimport { CanvasPanelBody } from \"./shell-canvas-region\";\nimport type { BuilderShellProps, PanelView } from \"./shell-props\";\nimport {\n  panelAvailability,\n  panelTopology,\n  RailAndDialogs,\n} from \"./shell-rail-dialogs\";\nimport {\n  useRegionCycling,\n  useSeparatorRegionEscape,\n  type Region,\n} from \"./shell-region-cycling\";\nimport { useSidePanels } from \"./shell-side-panels\";\nimport {\n  PANEL_DIVIDER_CLASS,\n  SIDE_PANEL_CLASS,\n  useDesignSystemStylesheet,\n} from \"./shell-stylesheet\";\nimport { ShellTopBar } from \"./shell-top-bar\";\nimport { ShowInspectorContext } from \"./show-inspector\";\n\nexport function ShellRegions({\n  appliedScale = 1,\n  onZoomPick,\n  renderPanel,\n  renderSettings,\n  availablePanels,\n  children,\n  inspector,\n  title,\n  topBar,\n  topBarCenter,\n  topBarEnd,\n  breadcrumb,\n  checklist,\n  canvasStrip,\n  onExit,\n  exitLabel,\n  preferences,\n  update,\n  className,\n  active,\n  loadCount,\n}: Omit<BuilderShellProps, \"store\"> & {\n  /** The zoom picker, or absent where the host wired none. */\n  onZoomPick: ((next: CanvasZoom) => void) | undefined;\n  preferences: ShellPreferences;\n  update: (change: (current: ShellPreferences) => ShellPreferences) => void;\n  /**\n   * Whether this subtree is the one the author is using.\n   *\n   * False while it sits mounted-but-hidden behind the narrow-viewport notice,\n   * which is a state it cannot detect for itself: from in here a hidden shell\n   * and a visible one render identically.\n   */\n  active: boolean;\n  /**\n   * How many times preferences have been loaded from a store.\n   *\n   * Restoring a layout happens once per load, and this is what \"once\" is\n   * counted against: the group is remounted per load so the library\n   * re-reads the restored layout at panel registration.\n   *\n   * ANY load, deliberately — unlike the write guard on the token effect, which\n   * has to know WHOSE record arrived. A remount is a response to a new layout\n   * being on screen, and the panels have to re-register against it whichever\n   * store produced it: the swap that makes a count useless for deciding a write\n   * is exactly a case that must remount. So the count and the identity are two\n   * separate answers rather than one this could share.\n   */\n  loadCount: number;\n}): React.JSX.Element {\n  const regionRefs = React.useRef<Record<Region, HTMLElement | null>>({\n    header: null,\n    rail: null,\n    panel: null,\n    canvas: null,\n    inspector: null,\n  });\n  // Declared before the hook that reads it: `chromeRef` is the shell's own root\n  // element, which is what decides whether the author is inside this editor at\n  // all — the chrome header sits outside every region but inside this.\n  const chromeRef = React.useRef<HTMLDivElement | null>(null);\n  const claimsKeys = useRegionCycling(regionRefs, chromeRef, active);\n  useZoomShortcuts(onZoomPick, active, claimsKeys);\n  const onKeyDownCapture = useSeparatorRegionEscape(regionRefs, active);\n  useDesignSystemStylesheet(chromeRef);\n\n  // Whether the host can fill a panel: see `panelAvailability`. One function\n  // while the host's panels are the same, since the memoised rail reads it\n  // as it draws and a new one each render would draw it again.\n  const isAvailable = React.useMemo(\n    () => panelAvailability(availablePanels),\n    [availablePanels]\n  );\n\n  /**\n   * The open panel, NORMALISED against what the host can fill.\n   *\n   * Preferences outlive the code that wrote them, and availability can change\n   * between mounts — a store restoring `layers` while the host now offers only\n   * `add` would reserve a left panel whose content renders nothing. Leaving the\n   * item off the rail does not help: nobody clicked it, the selection was\n   * restored.\n   *\n   * Treated as closed instead, which is the same answer the shell gives for a\n   * panel name it no longer recognises.\n   */\n  const {\n    openPanel,\n    inspectorShown,\n    leftShown,\n    selectPanel,\n    toggleLeft,\n    toggleInspector,\n  } = useSidePanels(\n    preferences,\n    update,\n    isAvailable,\n    active,\n    claimsKeys,\n    regionRefs\n  );\n  const mountedTopology = panelTopology(openPanel, inspectorShown);\n  // For a control in the top bar that opens a block's setting: the setting\n  // opens in the inspector, so a hidden one is shown.\n  const showInspector = React.useCallback(\n    () =>\n      update(current =>\n        current.inspectorHidden\n          ? { ...current, inspectorHidden: false }\n          : current\n      ),\n    [update]\n  );\n\n  const panelView: PanelView = {\n    current: preferences.leftPanelView,\n    choose: view => update(current => ({ ...current, leftPanelView: view })),\n  };\n\n  return (\n    <div\n      ref={chromeRef}\n      onKeyDownCapture={onKeyDownCapture}\n      className={cn(\n        BUILDER_CHROME_CLASS,\n        \"flex h-full w-full flex-col overflow-hidden\",\n        className\n      )}\n    >\n      <ShowInspectorContext.Provider value={showInspector}>\n        <ShellTopBar\n          headerRef={element => {\n            regionRefs.current.header = element;\n          }}\n          onExit={onExit}\n          exitLabel={exitLabel}\n          title={title}\n          topBar={topBar}\n          topBarCenter={topBarCenter}\n          topBarEnd={topBarEnd}\n          zoom={preferences.zoom}\n          appliedScale={appliedScale}\n          onZoomPick={onZoomPick}\n          leftShown={leftShown}\n          inspectorShown={inspectorShown}\n          onLeft={toggleLeft}\n          onInspector={toggleInspector}\n        />\n      </ShowInspectorContext.Provider>\n\n      <div className=\"flex min-h-0 flex-1\">\n        <RailAndDialogs\n          active={active}\n          renderSettings={renderSettings}\n          railRef={element => {\n            regionRefs.current.rail = element;\n          }}\n          openPanel={openPanel}\n          isAvailable={isAvailable}\n          onSelect={selectPanel}\n          // The panel keys answer only for the shell that is showing and that\n          // the author is in, the check F6 and mod+\\ already make, and only\n          // while the author has not turned them off in Help.\n          claimsKeys={() => active && claimsKeys()}\n          panelKeys={{\n            // On unless turned off, as a preference written before there\n            // was a switch reads.\n            on: preferences.panelKeys !== false,\n            onChange: on => update(current => ({ ...current, panelKeys: on })),\n          }}\n        />\n\n        <ResizablePanelGroup\n          // Remounted when a store is LOADED, which is the only way the library\n          // applies a layout: it reads `defaultLayout` when the panels REGISTER\n          // and a later prop change merely assigns it. Restoration therefore\n          // happens where the library already does it, rather than being\n          // reapplied afterwards through the imperative API — which is what made\n          // the units, the key order and the mount timing this component's\n          // problems to solve.\n          key={loadCount}\n          orientation=\"horizontal\"\n          // Selected by the panel set actually mounted, so an arrangement with\n          // no stored layout falls through to the panels' declared widths\n          // instead of inheriting another arrangement's.\n          defaultLayout={preferences.layouts[mountedTopology]}\n          onLayoutChanged={(layout, meta) => {\n            // The group reports every layout it settles on, not only the ones a\n            // person asked for. Mounting, recomputing constraints and reacting\n            // to a changed default all arrive here too, and the mount pass\n            // arrives BEFORE the restored layout has taken effect — so writing\n            // unconditionally saves the freshly measured default over the\n            // layout being restored, and the panel widths reset on every\n            // reload while appearing to persist within a session.\n            //\n            // `isUserInteraction` is the library's own account of which of\n            // those it was: true only for a pointer drag or a resize key on a\n            // separator. Dragging a separator is the one event that states an\n            // intent about widths, and it is the only one worth remembering.\n            if (!meta.isUserInteraction) return;\n            // Stored under the topology it was measured for, and keyed from the\n            // layout's OWN ids rather than from a separate description of the\n            // panel set. `defaultLayout` consumes the same flex-grow weights\n            // this reports, so the value makes a round trip in one unit and\n            // never meets the percentage side of the API.\n            update(current => ({\n              ...current,\n              layouts: {\n                ...current.layouts,\n                [topologyKey(Object.keys(layout))]: { ...layout },\n              },\n            }));\n          }}\n          className=\"min-w-0 flex-1\"\n        >\n          {openPanel !== null ? (\n            <>\n              <ResizablePanel\n                id=\"panel\"\n                minSize={PANEL_BOUNDS.left.min}\n                maxSize={PANEL_BOUNDS.left.max}\n                defaultSize={PANEL_BOUNDS.left.initial}\n              >\n                <section\n                  ref={element => {\n                    regionRefs.current.panel = element;\n                  }}\n                  tabIndex={-1}\n                  aria-label={panelLabel(openPanel)}\n                  className={SIDE_PANEL_CLASS}\n                >\n                  {/* Keyed by the panel, because the prop's contract says the\n                      result is keyed by the panel and React's default\n                      reconciliation does not honour that. A caller rendering one\n                      component for several panels — `<MyPanel kind={panel} />`,\n                      which is what this package's own README suggests — puts the\n                      same element type at the same position, so switching from\n                      Layers to Tokens UPDATES that instance rather than mounting\n                      a new one: its state, its effects and any uncontrolled\n                      input values follow the author into a different tool. */}\n                  <React.Fragment key={openPanel}>\n                    {renderPanel?.(openPanel, panelView)}\n                  </React.Fragment>\n                </section>\n              </ResizablePanel>\n              {/* Named for what it DIVIDES rather than for itself. A keyboard\n                  user lands here between two regions and hears its position;\n                  \"Panel and canvas\" is what makes the position mean something.\n                  The panel side is named by its role rather than by which\n                  panel is open, because the name would otherwise change under\n                  a user who is standing on it. */}\n              <ResizableHandle\n                withGrip\n                aria-label=\"Panel and canvas\"\n                className={PANEL_DIVIDER_CLASS}\n              />\n            </>\n          ) : null}\n\n          <ResizablePanel id=\"canvas\" minSize={MIN_CANVAS_PANEL_WIDTH}>\n            <CanvasPanelBody\n              canvasStrip={canvasStrip}\n              checklist={checklist}\n              regionRef={element => {\n                regionRefs.current.canvas = element;\n              }}\n            >\n              {children}\n            </CanvasPanelBody>\n          </ResizablePanel>\n\n          {inspectorShown ? (\n            <>\n              <ResizableHandle\n                withGrip\n                aria-label=\"Canvas and inspector\"\n                className={PANEL_DIVIDER_CLASS}\n              />\n\n              <ResizablePanel\n                id=\"inspector\"\n                minSize={PANEL_BOUNDS.inspector.min}\n                maxSize={PANEL_BOUNDS.inspector.max}\n                defaultSize={PANEL_BOUNDS.inspector.initial}\n              >\n                <aside\n                  ref={element => {\n                    regionRefs.current.inspector = element;\n                  }}\n                  tabIndex={-1}\n                  aria-label=\"Inspector\"\n                  className={SIDE_PANEL_CLASS}\n                >\n                  {inspector}\n                </aside>\n              </ResizablePanel>\n            </>\n          ) : null}\n        </ResizablePanelGroup>\n      </div>\n\n      {/*\n        No `aria-label`. A `<footer>` nested inside a section is `generic`, and\n        `aria-label` is PROHIBITED on that role — so the name was not announced\n        and the element was invalid. Nothing is lost: the breadcrumb inside\n        names itself (\"Current location\"), which is the thing a\n        reader actually lands on.\n      */}\n      <footer className=\"border-[color:var(--nx-builder-divider)] text-[color:var(--nx-builder-text-muted)] flex h-8 shrink-0 items-center gap-2 border-t px-3 text-xs\">\n        {breadcrumb}\n      </footer>\n    </div>\n  );\n}\n","\"use client\";\n\nimport {\n  PortalProvider,\n  ShortcutProvider,\n  TooltipProvider,\n} from \"@nextlyhq/ui\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport * as React from \"react\";\n\nimport { CanvasFrameShortcuts } from \"../canvas/canvas-frame-context\";\nimport { FIT_ZOOM, type CanvasZoom } from \"../canvas/canvas-zoom\";\nimport { HoveredBlockProvider } from \"../canvas/hovered-block\";\nimport { InsertionPreviewProvider } from \"../canvas/insertion-preview\";\nimport { CssNamesContext, type CssNames } from \"../inspector/css-names-context\";\nimport type { SectionFolds } from \"../inspector/panel-folds\";\nimport {\n  PanelFoldsContext,\n  type PanelFolds,\n} from \"../inspector/panel-folds-context\";\nimport {\n  browserStore,\n  BUILDER_CHROME_CLASS,\n  BUILDER_TOKENS_CLASS,\n  DEFAULT_PREFERENCES,\n  fitsFullShell,\n  MIN_SHELL_WIDTH,\n  SHELL_PREFERENCES_KEY,\n  type PreferenceStore,\n} from \"../shell-state\";\n\nimport {\n  BuilderNoticeRegion,\n  NoticeSinkProvider,\n  useNoticeQueue,\n} from \"./builder-notices\";\nimport { ShellActiveContext, useShellIsActive } from \"./shell-active\";\nimport { usePreferences } from \"./shell-preferences\";\nimport type { BuilderShellProps } from \"./shell-props\";\nimport { SettingsRequestContext } from \"./shell-rail-dialogs\";\nimport { ShellRegions } from \"./shell-regions\";\nimport { DEFAULT_EXIT_LABEL } from \"./shell-top-bar\";\n\nexport type {\n  BuilderShellProps,\n  PanelView,\n  SettingsDialogState,\n} from \"./shell-props\";\n\n/** No section folded, shared so its identity is stable. */\nconst NO_FOLDS: SectionFolds = {};\n\n/**\n * The editor shell: rail, one switched panel, canvas, inspector, bars.\n *\n * PURELY PRESENTATIONAL, and that is a contract rather than a current state.\n * It owns which panel is open and how wide the regions are — chrome state, its\n * own business — and owns nothing about the document. Selection arrives as a\n * prop and leaves as a callback.\n *\n * The reason is not tidiness. Document ops INVALIDATE selection: a remove\n * deletes the selected node, a move relocates it. If the shell held selection it\n * would have to be updated in step with every op, which is two things changing\n * together — the drift this codebase keeps paying for. Held outside, selection\n * can be DERIVED from the post-op document (\"does this id still resolve?\"),\n * which cannot go out of step because there is only one thing to read.\n *\n * Content is passed as slots rather than rendered here, so the layers panel, the\n * inserter and the inspector can be built independently without this file\n * changing. It knows the SHAPE of the editor, never what fills it.\n *\n * This module holds the shell itself; each of its areas is a module of its\n * own: the props (`shell-props`), the preferences (`shell-preferences`), the\n * design system's stylesheet (`shell-stylesheet`), keyboard movement between\n * regions (`shell-region-cycling`), the rail and its dialogs\n * (`shell-rail-dialogs`), the top bar (`shell-top-bar`), the side panels\n * (`shell-side-panels`), the canvas region (`shell-canvas-region`) and the\n * regions laid out (`shell-regions`).\n *\n * @module builder-shell\n */\n\n/**\n * Whether the shell's own CONTAINER can carry the full layout, as it changes.\n *\n * The container rather than the viewport, because that is what the shell sizes\n * to — `h-full w-full`, no viewport units anywhere. The two agree only when the\n * shell happens to fill the window, so an editor embedded in a narrow column on\n * a wide display was told it fitted and compressed its regions past their\n * minimums.\n *\n * Starts as `true` on purpose. The alternative is measuring during render,\n * which the server cannot do — it would emit the narrow-viewport message and the\n * client would replace it, a hydration mismatch on every desktop load. Assuming\n * the supported case and correcting after mount makes both first renders\n * identical.\n */\nfunction useFitsFullShell(): [(node: HTMLElement | null) => void, boolean] {\n  const [fits, setFits] = React.useState(true);\n  const observer = React.useRef<ResizeObserver | null>(null);\n\n  /*\n   * A CALLBACK ref, not an effect over a `useRef`.\n   *\n   * The observed element is REPLACED when the answer flips — the notice and the\n   * shell root are different nodes, and only one of them is on screen at a time\n   * — so an effect keyed on mount would observe whichever rendered first and go\n   * on observing it after React swapped it out.\n   */\n  const measure = React.useCallback((node: HTMLElement | null) => {\n    observer.current?.disconnect();\n    observer.current = null;\n    if (node === null) return;\n    // jsdom implements no `ResizeObserver`. Falling back to `fits` rather than\n    // to a notice matches the initial state's reasoning: a shell that cannot\n    // measure renders fully rather than showing a message it has no evidence\n    // for.\n    if (typeof ResizeObserver === \"undefined\") {\n      setFits(true);\n      return;\n    }\n    const next = new ResizeObserver(entries => {\n      const entry = entries[entries.length - 1];\n      if (entry === undefined) return;\n      // The CONTENT box of the measuring wrapper, which is by construction the\n      // space the regions are laid out in.\n      //\n      // Two properties make that the right quantity, and both are easy to lose:\n      //\n      // The wrapper carries the caller's `className` and nothing else, so its\n      // content box is the space INSIDE whatever padding or border the host\n      // applied — decoration the regions never receive. A border box would\n      // report a 1280px root with `p-6` as fitting while leaving 1232px to lay\n      // out in.\n      //\n      // It is also the SAME element whichever branch renders, so no branch's\n      // own padding can move the threshold. The notice is `p-6` and sits inside\n      // this box, where it is invisible to the measurement; measuring a branch\n      // instead would make the answer depend on which one happened to be up.\n      //\n      // `contentRect` rather than `getBoundingClientRect`: both are layout\n      // sizes, so a transformed ancestor — this editor has canvas zoom — does\n      // not scale the number against a minimum expressed in CSS pixels.\n\n      // The comparison itself comes from `shell-state`, which exports and tests\n      // it. Repeating `>= MIN_SHELL_WIDTH` here would be a second answer to one\n      // question, and the two would first disagree exactly at the boundary the\n      // helper's tests pin.\n      setFits(fitsFullShell(entry.contentRect.width));\n    });\n    next.observe(node);\n    observer.current = next;\n  }, []);\n\n  React.useEffect(\n    () => () => {\n      observer.current?.disconnect();\n      observer.current = null;\n    },\n    []\n  );\n\n  return [measure, fits];\n}\n\n/**\n * Re-exported from the leaf that declares it, so the shell stays the name callers reach for.\n *\n * The declaration moved out because `builder-notices` consumes it and the shell imports\n * `builder-notices`, which would make the two import each other.\n */\nexport { useShellIsActive };\n\n/**\n * The shell, or a message saying where to edit instead.\n *\n * Below the supported width the shell does not try to compress: the rail, both\n * panels and a usable canvas do not fit at their minimums, and an editor that\n * merely gets cramped is worse than one that says it needs more width — the\n * author otherwise discovers the limit by failing at a task.\n *\n * @experimental\n */\nexport function BuilderShell({\n  store,\n  openPanelRequest,\n  onZoomChange,\n  editingBreakpointRequest,\n  onEditingBreakpointChange,\n  appliedScale = 1,\n  notices: supplied,\n  ...props\n}: BuilderShellProps): React.JSX.Element {\n  // The browser store is built once: rebuilt each render it would change\n  // `usePreferences`' callback identity every render, and the write effect with\n  // it. Only the FALLBACK needs that treatment though. Capturing the caller's\n  // `store` alongside it pinned whichever one arrived first, so a host that\n  // swaps stores — signing into a second workspace, promoting a memory store to\n  // a persisted one — went on reading and writing the store it had replaced.\n  const fallbackStore = React.useRef<PreferenceStore | null>(null);\n  fallbackStore.current ??= browserStore(SHELL_PREFERENCES_KEY);\n  const resolvedStore = store ?? fallbackStore.current;\n  const [preferences, update, loadCount, loadedFromCurrentStore] =\n    usePreferences(resolvedStore);\n  const [measureShell, shellFits] = useFitsFullShell();\n\n  /*\n   * Applies an `openPanelRequest` change AT MOST ONCE — a ref rather than\n   * state, because recording that a token was handled is not itself something a\n   * re-render should follow from.\n   *\n   * The ref deliberately survives a store swap. A token already applied belongs\n   * to the session the author pressed the control in, so re-applying it to the\n   * store that replaced it would open a panel nobody asked this store for.\n   *\n   * FORCES `leftPanel` to the requested panel rather than routing through\n   * `panelAfterRailClick`: that helper TOGGLES, and toggling is exactly wrong\n   * for a control whose contract is \"show the panel this fills\" — never\n   * \"close it if it happens to already be open\", which is what a second rail\n   * click on the same item means.\n   *\n   * No availability check against `availablePanels` here: `ShellRegions`\n   * below already normalises `preferences.leftPanel` against it when deriving\n   * the panel it actually renders, so a request naming a panel the host\n   * cannot fill is absorbed there rather than needing a second check here.\n   */\n  const handledPanelRequest = React.useRef<number | undefined>(undefined);\n  React.useEffect(() => {\n    if (openPanelRequest === undefined) return;\n    /*\n     * Nothing is applied until THIS store's read has landed, and that ordering\n     * is the whole of this guard.\n     *\n     * `update` takes the newest preferences this hook has seen and writes the\n     * result straight back through the store it currently holds. Reading a\n     * store is itself an effect, so in the commit a store first arrives in it\n     * has only SCHEDULED that store's record — what `update` would spread here\n     * is still whatever `preferences` held before. Both ways that happens end\n     * in a write of the wrong record:\n     *\n     * - at MOUNT, `preferences` is `DEFAULT_PREFERENCES`, so a token defined on\n     *   the first render persists the defaults over the author's own panel\n     *   widths and zoom.\n     * - after a store SWAP — signing into a second workspace, promoting a\n     *   memory store to a persisted one — `preferences` is the PREVIOUS store's\n     *   record, so a token arriving in the same render writes one user's or\n     *   workspace's saved layout into another's.\n     *\n     * Either way the panel the token asked for opens and looks entirely\n     * correct, which is what makes the write invisible until the next load.\n     *\n     * So the arrival this waits on is store-specific rather than \"some read has\n     * happened\": a COUNT of reads is already nonzero for the outgoing store at\n     * the moment of a swap, which is precisely the window the second case sits\n     * in. Once it is true, it stays true for as long as the store does — a read\n     * cannot fail (`readPreferences` answers with the defaults for unreadable\n     * or malformed storage) and one that remembers nothing still answers — so\n     * this delays a token by a single render and can never hold one\n     * indefinitely. A token arriving any later than that render applies in the\n     * same flush it arrived in.\n     */\n    if (!loadedFromCurrentStore) return;\n    if (handledPanelRequest.current === openPanelRequest.count) return;\n    handledPanelRequest.current = openPanelRequest.count;\n    const { panel, view, unlessHidden = false } = openPanelRequest;\n    update(current =>\n      // The author's own hiding outranks a request the editor made itself.\n      unlessHidden && current.leftPanelHidden\n        ? current\n        : {\n            ...current,\n            leftPanel: panel,\n            leftPanelHidden: false,\n            leftPanelView: view ?? current.leftPanelView,\n          }\n    );\n  }, [openPanelRequest, update, loadedFromCurrentStore]);\n\n  /*\n   * Applies an `editingBreakpointRequest` at most once per count, and only\n   * once this store's own preferences have loaded, for the reasons the panel\n   * request above waits: applied earlier it would write the defaults, or\n   * another store's record, over the author's own.\n   */\n  const handledDeviceRequest = React.useRef<number | undefined>(undefined);\n  React.useEffect(() => {\n    if (editingBreakpointRequest === undefined) return;\n    if (!loadedFromCurrentStore) return;\n    if (handledDeviceRequest.current === editingBreakpointRequest.count) return;\n    handledDeviceRequest.current = editingBreakpointRequest.count;\n    const breakpoint = editingBreakpointRequest.breakpoint;\n    update(current =>\n      current.editingBreakpoint === breakpoint\n        ? current\n        : { ...current, editingBreakpoint: breakpoint, zoom: FIT_ZOOM }\n    );\n  }, [editingBreakpointRequest, update, loadedFromCurrentStore]);\n\n  /*\n   * A zoom chosen outside this shell, stored here.\n   *\n   * Compared by VALUE rather than by object identity: a host rebuilding the\n   * object each render — which the conventional inline handler does — would\n   * write preferences on every render, and every write reports back out, which\n   * is a loop rather than a preference.\n   */\n  /*\n   * The zoom picker, resolved here rather than where it is drawn.\n   *\n   * `undefined` when the host has wired nothing, which is what makes the\n   * control render nothing — see its own documentation for why a dead one is\n   * worse than none. Deciding it at the render site put the branch inside a\n   * region that is already the largest function in this file.\n   */\n  const onZoomPick = React.useMemo(\n    () =>\n      onZoomChange === undefined\n        ? undefined\n        : (next: CanvasZoom) => update(current => ({ ...current, zoom: next })),\n    [onZoomChange, update]\n  );\n\n  /*\n   * The zoom, reported on every value it takes, including the first, so a host\n   * never has to assume the default.\n   *\n   * The callback is held in a ref rather than read straight from the prop. A\n   * host passing the conventional inline callback hands this a NEW function\n   * identity on every one of its own renders; as a dependency, that identity\n   * would re-run the effect with nothing changed and call the host back again,\n   * and a host whose state update itself re-renders closes that into a loop.\n   *\n   * Whether a listener EXISTS is a dependency, though.\n   *\n   * A host can resolve `onZoomChange` from its own state, so the prop moves\n   * from `undefined` to a callback after the first render. Keyed on the value\n   * alone, the effect would not re-run at that moment and the host would carry\n   * the default zoom until the author happened to pick another — its canvas\n   * drawn at a scale the control does not claim.\n   */\n  const onZoomChangeRef = React.useRef(onZoomChange);\n  React.useEffect(() => {\n    onZoomChangeRef.current = onZoomChange;\n  });\n  const reportingZoom = onZoomChange !== undefined;\n  React.useEffect(() => {\n    onZoomChangeRef.current?.(preferences.zoom);\n  }, [reportingZoom, preferences.zoom]);\n\n  // The device, reported the way the zoom is and for the same reasons.\n  const onEditingBreakpointChangeRef = React.useRef(onEditingBreakpointChange);\n  React.useEffect(() => {\n    onEditingBreakpointChangeRef.current = onEditingBreakpointChange;\n  });\n  const reportingDevice = onEditingBreakpointChange !== undefined;\n  React.useEffect(() => {\n    onEditingBreakpointChangeRef.current?.(preferences.editingBreakpoint);\n  }, [reportingDevice, preferences.editingBreakpoint]);\n\n  /*\n   * Where overlays inside this shell portal to. State rather than a ref,\n   * because `PortalProvider` has to RE-RENDER once the node exists; a ref\n   * mutation would leave the provider holding `null` for the life of the mount.\n   */\n  const [overlayHost, setOverlayHost] = React.useState<HTMLDivElement | null>(\n    null\n  );\n  /*\n   * Reports from controls that could not make one themselves. Owned at this\n   * level because it must survive everything below it being unmounted, which\n   * is exactly what the inspector's per-node keys do on every selection change.\n   */\n  // The shell's own queue is built whether or not the host supplied one — a\n  // hook cannot be skipped — and the host's wins, so the region below and the\n  // sink provided to every region report through the queue the host raises\n  // into.\n  const own = useNoticeQueue();\n  const notices = supplied ?? own;\n  // The block panel's section folds, kept with the other preferences and lent\n  // to the inspector, which is rendered below as a prop.\n  // \"Show CSS names\", kept with the other preferences and lent to the panel.\n  const showCssNames = preferences.showCssNames === true;\n  const cssNames = React.useMemo<CssNames>(\n    () => ({\n      shown: showCssNames,\n      set: shown => update(current => ({ ...current, showCssNames: shown })),\n    }),\n    [showCssNames, update]\n  );\n  const sectionFolds = preferences.sectionFolds ?? NO_FOLDS;\n  const panelFolds = React.useMemo<PanelFolds>(\n    () => ({\n      folds: sectionFolds,\n      change: next =>\n        update(current => ({\n          ...current,\n          sectionFolds: next(current.sectionFolds ?? NO_FOLDS),\n        })),\n    }),\n    [sectionFolds, update]\n  );\n\n  return (\n    <ShellProviders>\n      {/* The same manager, listening in the canvas's frame as well, so a key\n          pressed with focus inside the page reaches every binding above. */}\n      <CanvasFrameShortcuts />\n      {/* Provided here rather than required of the host: the shell's own\n          controls carry tooltips, so a shell that renders them depends on this\n          and should not make it someone else's setup step. Radix nests\n          providers safely — a host with its own keeps its delay. */}\n      <TooltipProvider delayDuration={300}>\n        {/*\n         * THE measured element, and the only one.\n         *\n         * Always rendered, whichever branch is showing, so it always has a box\n         * to measure — which is what makes the decision reversible. Observing a\n         * branch instead made the answer depend on that branch's own padding\n         * and, in the editor's case, on a wrapper that is `display: contents`\n         * when visible and `hidden` when narrow and therefore reports 0.\n         *\n         * It carries the caller's `className` and nothing else of its own, so\n         * its CONTENT box is the space inside whatever padding, border or grid\n         * area the host gave the shell — which is precisely the space its\n         * children have to lay out in. Both branches are sized from it rather\n         * than from the host directly, so neither can disagree with the\n         * measurement.\n         */}\n        <div\n          ref={measureShell}\n          className={cn(\"h-full w-full\", props.className)}\n        >\n          {/*\n           * The notice surface, mounted OUTSIDE the wrapper the shell makes\n           * `hidden` and `inert`, and mounted unconditionally.\n           *\n           * Both properties are load-bearing and they fix different failures.\n           *\n           * Outside, because inert content is excluded from the accessibility\n           * tree and `hidden` takes it out of paint — so a region inside the\n           * wrapper is unreachable by eye AND by screen reader exactly when the\n           * narrow-width notice is up. A refusal that arrives while an author\n           * is narrowing the window has to land somewhere they can still read.\n           *\n           * Unconditionally, rather than switched between the two branches\n           * below, because a live region has to EXIST before the text is put\n           * into it: a region inserted and populated together is routinely\n           * missed, and one that remounts every time the width crosses the\n           * threshold is inserted at the worst possible moment. A single\n           * permanent mount also keeps there being exactly one — two live\n           * regions interfere and some messages are announced by neither.\n           *\n           * The token scope is what the old placement inside the chrome was\n           * for: `--nx-builder-*` inherit down and never across, so a surface\n           * outside the chrome needs them declared on an ancestor of its own.\n           * It takes the TOKEN class rather than the chrome class, because the\n           * chrome class also identifies the editor's root — a second element\n           * carrying it would be matched by every selector and query that means\n           * \"the editor\", the empty-slot selector among them.\n           *\n           * `display: contents` declares the tokens while generating no box, so\n           * nothing is added to the layout the branches below measure — and the\n           * region is `position: fixed` regardless, since nothing here creates\n           * a containing block.\n           */}\n          <div className={cn(BUILDER_TOKENS_CLASS, \"contents\")}>\n            <BuilderNoticeRegion\n              notices={notices.notices}\n              onDismiss={notices.dismiss}\n            />\n          </div>\n          {!shellFits ? (\n            <div\n              // No caller `className` here: the wrapper above owns the host's\n              // positioning now, and repeating it would apply a grid area or a\n              // border twice.\n              className={cn(\n                BUILDER_CHROME_CLASS,\n                \"flex h-full w-full flex-col items-center justify-center gap-3 p-6 text-center\"\n              )}\n            >\n              {/*\n               * Worded as WIDTH rather than as a screen, because the shell\n               * measures the space it was given. An editor embedded in a narrow\n               * column on a large display is the case that named the wrong\n               * cause: the author's screen is fine and widening it changes\n               * nothing.\n               */}\n              <p className=\"text-sm font-medium\">\n                The page editor needs more width\n              </p>\n              {/*\n               * The escape sentence and the button below it are ONE UNIT with the\n               * handler: all three present, or all three absent.\n               *\n               * Keeping the copy while dropping the control would instruct the\n               * author to go somewhere and then offer nothing to get there — and\n               * keeping a button with no handler is worse, because it looks\n               * operable. A host that supplies no `onExit` has no destination to\n               * offer, and an embedded one needs none: the author is already\n               * inside the surrounding form and can scroll to the rest of it.\n               */}\n              {props.onExit ? (\n                <>\n                  <p className=\"text-[color:var(--nx-builder-text-muted)] max-w-sm text-sm\">\n                    The editor needs at least {MIN_SHELL_WIDTH}px of width. In a\n                    narrower space you can still edit this page&apos;s content\n                    from the admin.\n                  </p>\n                  <button\n                    type=\"button\"\n                    onClick={props.onExit}\n                    className=\"border-[color:var(--nx-builder-border)] focus-visible:ring-ring rounded-md border px-3 py-1.5 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none\"\n                  >\n                    {/* The same words as the top bar's arrow, so the two\n                        ways out say the same place. */}\n                    {props.exitLabel ?? DEFAULT_EXIT_LABEL}\n                  </button>\n                </>\n              ) : (\n                <p className=\"text-[color:var(--nx-builder-text-muted)] max-w-sm text-sm\">\n                  The editor needs at least {MIN_SHELL_WIDTH}px of width.\n                </p>\n              )}\n            </div>\n          ) : null}\n\n          {/* The editor stays MOUNTED while the notice is up, rather than being\n            swapped out for it.\n\n            Returning the notice instead unmounted every slot the caller had\n            given us — canvas, inspector, panels — and React discards the state\n            inside them: a half-written caption, an open picker, whatever the\n            host was holding locally. Narrowing a window or rotating a tablet is\n            a transient act, and widening it again produced fresh, empty slot\n            instances with no way for the host to have saved anything, because\n            nothing told it the subtree was going away.\n\n            `hidden` takes it out of layout and paint; `inert` takes it out of\n            the tab order and the accessibility tree, so nothing behind the\n            notice is reachable by keyboard or screen reader. The cost is that\n            the editor goes on occupying memory while hidden, which is the\n            deliberate trade: an author's unsaved work is worth more than the\n            allocation. */}\n          <div\n            hidden={!shellFits}\n            inert={!shellFits}\n            // `display: contents` while visible, so this wrapper adds no box of\n            // its own and the shell keeps sizing against the caller's container.\n            // Omitted while hidden, where the `hidden` attribute's own\n            // `display: none` has to be the one that applies.\n            className={shellFits ? \"contents\" : undefined}\n          >\n            {/* Published as context as well as applied as attributes, because `hidden` and `inert`\n              only reach what renders INSIDE this wrapper. Slot content that reads this answers for\n              itself; content that PORTALS is contained by `overlayHost` below instead. */}\n            <ShellActiveContext.Provider value={shellFits}>\n              {/*\n               * Overlays portal to a host INSIDE the inert wrapper, so `hidden`\n               * and `inert` reach them.\n               *\n               * A portalled dropdown is not a descendant of the region that\n               * opened it, so neither attribute could ever reach it: an open\n               * `Select` stayed visible and clickable on top of the notice\n               * saying the editor was unavailable. Redirecting the portal is a\n               * boundary rather than a rule each control has to remember, which\n               * matters because the set of portalling components is open ended\n               * and the next one added would not know to check.\n               *\n               * WHERE it sits is the whole design, and two placements are wrong\n               * for different reasons. Inside a region clips it: the panel, the\n               * canvas and the inspector are each `overflow-auto`, so a dropdown\n               * opened near a panel edge would be cut off — a silent visual\n               * failure, worse than the interactive one being fixed. Inside the\n               * shell ROOT is also wrong, because that root is\n               * `overflow-hidden`. Here it is a sibling of the shell root:\n               * within the element carrying `hidden`/`inert`, and outside every\n               * box that clips.\n               *\n               * Taken out of flow so it can never affect the layout it sits\n               * beside. It stays a DOM descendant of the inert wrapper, which is\n               * what `inert` follows, and nothing here creates a containing\n               * block, so the fixed-position content each overlay renders is\n               * still positioned against the viewport.\n               */}\n              <div\n                ref={setOverlayHost}\n                data-slot=\"builder-overlay-host\"\n                className=\"absolute h-0 w-0\"\n              />\n              {/*\n               * `null` until the host mounts, which `usePortalContainer` reads\n               * as \"use the default\". That is one commit of the old behaviour\n               * rather than a crash, and no overlay can be open that early.\n               */}\n              <PortalProvider container={overlayHost}>\n                {/* Wraps the regions rather than sitting beside them: the\n                    inspector and the panels are `ReactNode` props, so they\n                    become descendants of this provider by being RENDERED here,\n                    wherever the host created them. */}\n                <NoticeSinkProvider raise={notices.raise}>\n                  <SettingsRequestContext.Provider\n                    value={props.openSettingsRequest}\n                  >\n                    <PanelFoldsContext.Provider value={panelFolds}>\n                      <CssNamesContext.Provider value={cssNames}>\n                        <ShellRegions\n                          appliedScale={appliedScale}\n                          onZoomPick={onZoomPick}\n                          {...props}\n                          preferences={preferences}\n                          update={update}\n                          active={shellFits}\n                          loadCount={loadCount}\n                          /*\n                           * The caller's `className` stops here: the measuring wrapper\n                           * above carries it. Passing it on would apply the host's grid\n                           * area, height or border a second time, on a box nested inside\n                           * the one already carrying it.\n                           */\n                          className={undefined}\n                        />\n                      </CssNamesContext.Provider>\n                    </PanelFoldsContext.Provider>\n                  </SettingsRequestContext.Provider>\n                </NoticeSinkProvider>\n              </PortalProvider>\n            </ShellActiveContext.Provider>\n          </div>\n        </div>\n      </TooltipProvider>\n    </ShellProviders>\n  );\n}\n\n/**\n * What every shell provides to everything inside it: the shortcut manager,\n * one hovered block for its panels and its canvas, so a Layers row the\n * pointer is over outlines its block on the page, and the Add panel's\n * highlighted place, which the canvas draws its insertion line at.\n */\nfunction ShellProviders({\n  children,\n}: {\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <ShortcutProvider>\n      <HoveredBlockProvider>\n        {/* The Add panel's highlighted place, which the canvas draws. */}\n        <InsertionPreviewProvider>{children}</InsertionPreviewProvider>\n      </HoveredBlockProvider>\n    </ShortcutProvider>\n  );\n}\n\nexport { DEFAULT_PREFERENCES };\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 * A Columns row's layout as tiles, and where it stacks: what each choice\n * writes, and which empty columns it adds or removes with it.\n *\n * A Content control: how many columns a row holds is its structure. Every\n * choice writes the row's own style values, whatever the Style tab is\n * editing, and nothing on its columns: a layout is its\n * `grid-template-columns`, and stacking is the row laid out as a flex column\n * at a device and below. Column order is never written per column, so moving\n * one never leaves a stale order behind.\n *\n * @module columns-layout\n */\nimport {\n  BASE_BREAKPOINT,\n  getBlock,\n  makeNode,\n  type BlockNode,\n  type BreakpointSet,\n  type StyleState,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\nimport {\n  readStyleValue,\n  styleClearOp,\n  styleWriteOp,\n  type StyleAddress,\n  type StyleWrite,\n} from \"../styles/style-values\";\n\nimport { offeredTiers } from \"./canvas-width\";\n\n/** The row this control belongs to. */\nexport const COLUMNS_ROW = \"core/columns\";\n\n/** A tile: what it writes, and how many columns it lays out. */\nexport interface ColumnsLayout {\n  readonly key: string;\n  readonly label: string;\n  /** The template it writes, or `undefined` to clear back to the default. */\n  readonly template: string | undefined;\n  /** How many columns it lays out, or `undefined` for any number. */\n  readonly count: number | undefined;\n  /** The tracks its glyph draws, as relative widths. */\n  readonly tracks: readonly number[];\n}\n\n/**\n * The six layouts, named for what an author sees rather than as ratios: the\n * same tiles the first-add picker offers. A template stored that none of them\n * writes (`1fr 3fr`) keeps its meaning and reads as the row's own.\n */\nexport const COLUMNS_LAYOUTS: readonly ColumnsLayout[] = [\n  {\n    key: \"2\",\n    label: \"2 equal\",\n    template: \"1fr 1fr\",\n    count: 2,\n    tracks: [1, 1],\n  },\n  {\n    key: \"3\",\n    label: \"3 equal\",\n    template: \"repeat(3, 1fr)\",\n    count: 3,\n    tracks: [1, 1, 1],\n  },\n  {\n    key: \"4\",\n    label: \"4 equal\",\n    template: \"repeat(4, 1fr)\",\n    count: 4,\n    tracks: [1, 1, 1, 1],\n  },\n  {\n    key: \"wide-left\",\n    label: \"Wide left\",\n    template: \"2fr 1fr\",\n    count: 2,\n    tracks: [2, 1],\n  },\n  {\n    key: \"wide-right\",\n    label: \"Wide right\",\n    template: \"1fr 2fr\",\n    count: 2,\n    tracks: [1, 2],\n  },\n  {\n    key: \"wide-middle\",\n    label: \"Wide middle\",\n    template: \"1fr 2fr 1fr\",\n    count: 3,\n    tracks: [1, 2, 1],\n  },\n];\n\n/** The template a row's block gives it by default: equal columns that wrap. */\nexport function defaultTemplate(row: BlockNode): string | undefined {\n  const base = (\n    getBlock(row.type)?.baseStyles as\n      | { base?: { base?: Record<string, unknown> } }\n      | undefined\n  )?.base?.base?.gridTemplateColumns;\n  return typeof base === \"string\" ? base : undefined;\n}\n\n/**\n * The tile a template is. None set, or the block's own default, is equal\n * columns, so it reads as the tile of as many as the row holds (a row placed\n * and left as it came reads \"2 equal\"), or `none` where no tile lays out that\n * many. A template no tile writes is `custom`: the row's own, set in Style.\n */\nexport function layoutOf(\n  stored: StyleValue | undefined,\n  byDefault: string | undefined,\n  count: number\n): string {\n  const written = typeof stored === \"string\" ? stored.trim() : undefined;\n  if (\n    stored === undefined ||\n    (written !== undefined && written === byDefault?.trim())\n  ) {\n    return (\n      COLUMNS_LAYOUTS.find(\n        layout => layout.count === count && layout.tracks.every(t => t === 1)\n      )?.key ?? \"none\"\n    );\n  }\n  return (\n    COLUMNS_LAYOUTS.find(layout => layout.template === written)?.key ?? \"custom\"\n  );\n}\n\ntype Address = Pick<StyleAddress, \"state\" | \"breakpoint\">;\n\n/** The styles a write leaves, read off its op, or the ones it started from. */\nfunction stylesAfter(\n  write: StyleWrite,\n  current: BlockNode[\"styles\"]\n): BlockNode[\"styles\"] {\n  if (!write.ok || write.op === null) return current;\n  const op = write.op as {\n    unset?: readonly string[];\n    patch?: { styles?: BlockNode[\"styles\"] };\n  };\n  if (op.unset?.includes(\"styles\") === true) return undefined;\n  return op.patch?.styles ?? current;\n}\n\n/**\n * Several writes and clears on one node as ONE op: each step starts from the\n * styles the one before left, and the last op that changed anything carries\n * them all, since a style op holds the node's whole styles.\n */\nexport function chainedStyleOp(\n  node: BlockNode,\n  steps: readonly {\n    readonly address: StyleAddress;\n    readonly value: StyleValue | null;\n  }[]\n): BuilderOp | null {\n  let styles = node.styles;\n  let last: BuilderOp | null = null;\n  for (const step of steps) {\n    const write =\n      step.value === null\n        ? styleClearOp(node.id, styles, step.address)\n        : styleWriteOp(node.id, styles, step.address, step.value);\n    if (!write.ok) return null;\n    if (write.op !== null) last = write.op;\n    styles = stylesAfter(write, styles);\n  }\n  return last;\n}\n\n/** The type, version and defaults a new column is made with, from the row. */\nfunction columnShape(\n  row: BlockNode\n):\n  | { type: string; version: number; props: Record<string, unknown> }\n  | undefined {\n  const allowed = getBlock(row.type)?.slots?.children?.allow;\n  const type = allowed?.length === 1 ? allowed[0] : undefined;\n  const definition = type === undefined ? undefined : getBlock(type);\n  if (type === undefined || definition === undefined) return undefined;\n  return {\n    type,\n    version: definition.version,\n    props: {\n      ...(definition.defaultProps as Record<string, unknown> | undefined),\n    },\n  };\n}\n\n/**\n * Whether a column's props are only what its block gives every new one.\n *\n * Every column is made with its definition's defaults, so a prop is the\n * author's only where it differs from them: a key the defaults lack, or a\n * value other than the default's.\n */\nfunction propsAreDefaults(column: BlockNode): boolean {\n  const defaults = (getBlock(column.type)?.defaultProps ?? {}) as Record<\n    string,\n    unknown\n  >;\n  return Object.entries(column.props ?? {}).every(\n    ([key, value]) =>\n      key in defaults && JSON.stringify(value) === JSON.stringify(defaults[key])\n  );\n}\n\n/** What a column is made of: the fields every node has, judged on their own. */\nconst STRUCTURAL = new Set([\"id\", \"type\", \"version\", \"props\", \"slots\"]);\n\n/** Whether a stored value says nothing: absent, off, empty. */\nfunction saysNothing(value: unknown): boolean {\n  if (value === undefined || value === null || value === false) return true;\n  if (value === \"\") return true;\n  if (Array.isArray(value)) return value.length === 0;\n  if (typeof value === \"object\") return Object.keys(value).length === 0;\n  return false;\n}\n\n/**\n * Whether a column is blank, so removing it loses nothing: no blocks in it,\n * no props but its defaults, and nothing else an author set on it.\n *\n * \"Nothing else\" is every other field the node carries, named or not, so a\n * styled column, a named one, one with visibility rules or any field added\n * to nodes later is still the author's: judged by what is stored rather than\n * by a list that would have to keep up.\n */\nfunction isEmpty(column: BlockNode): boolean {\n  return (\n    Object.values(column.slots ?? {}).every(\n      children => children.length === 0\n    ) &&\n    propsAreDefaults(column) &&\n    Object.entries(column).every(\n      ([key, value]) => STRUCTURAL.has(key) || saysNothing(value)\n    )\n  );\n}\n\nexport type LayoutPlan =\n  | {\n      readonly ok: true;\n      /** Everything the tile writes: its template, then its columns. */\n      readonly ops: readonly BuilderOp[];\n      /** Only the empty columns it adds or removes to match its count. */\n      readonly columnOps: readonly BuilderOp[];\n    }\n  | { readonly ok: false; readonly reason: string };\n\n/** Ops adding empty columns at the row's end until it holds `count`. */\nfunction addedColumns(row: BlockNode, count: number): BuilderOp[] | undefined {\n  const have = row.slots?.children?.length ?? 0;\n  if (count <= have) return [];\n  const shape = columnShape(row);\n  if (shape === undefined) return undefined;\n  return Array.from({ length: count - have }, (_, offset) => ({\n    kind: \"insert\" as const,\n    node: makeNode(shape.type, shape.version, shape.props, { children: [] }),\n    at: { parentId: row.id, slot: \"children\", index: have + offset },\n  }));\n}\n\n/** Why a layout of `count` columns cannot be laid out on this row. */\nfunction refusal(count: number, holding: number): string {\n  return `Needs ${count} ${count === 1 ? \"column\" : \"columns\"}. This row has ${holding} with content; empty one out first.`;\n}\n\n/**\n * Ops removing empty columns until the row holds `count`, the ones added\n * last first, or why not: a column holding content is never removed.\n */\nfunction removedColumns(\n  row: BlockNode,\n  count: number\n): BuilderOp[] | { readonly reason: string } {\n  const columns = row.slots?.children ?? [];\n  const extra = columns.length - count;\n  if (extra <= 0) return [];\n  const empty = columns.filter(isEmpty);\n  if (empty.length < extra) {\n    return { reason: refusal(count, columns.length - empty.length) };\n  }\n  return empty\n    .reverse()\n    .slice(0, extra)\n    .map(column => ({ kind: \"remove\" as const, id: column.id }));\n}\n\n/**\n * What choosing a tile does: its template, and the empty columns added or\n * removed to match its count, as ops for one step. A tile that would remove\n * a column holding content is refused, with why.\n */\nexport function planLayout(\n  row: BlockNode,\n  key: string,\n  at: Address\n): LayoutPlan {\n  const layout = COLUMNS_LAYOUTS.find(each => each.key === key);\n  if (layout === undefined) return { ok: false, reason: \"Not a layout.\" };\n  const count = layout.count ?? row.slots?.children?.length ?? 0;\n  const removed = removedColumns(row, count);\n  if (!Array.isArray(removed)) return { ok: false, reason: removed.reason };\n  const added = addedColumns(row, count);\n  if (added === undefined) return { ok: false, reason: \"No column to add.\" };\n  const style = chainedStyleOp(row, [\n    {\n      address: { ...at, property: \"gridTemplateColumns\", path: [] },\n      value: layout.template ?? null,\n    },\n  ]);\n  const columnOps = [...added, ...removed];\n  return {\n    ok: true,\n    ops: [...(style === null ? [] : [style]), ...columnOps],\n    columnOps,\n  };\n}\n\n/** The tiers a row can stack at, by width, as the device switcher names them. */\nexport interface StackTiers {\n  readonly tablet?: string;\n  readonly mobile?: string;\n  /**\n   * Every tier at a tablet's width or narrower, widest first, with the stack\n   * choice it falls under: where a stack written before, at a tier no longer\n   * the widest of its kind, is still found and cleared.\n   */\n  readonly managed?: readonly {\n    readonly id: string;\n    readonly on: \"tablet\" | \"mobile\";\n  }[];\n}\n\nexport function stackTiers(breakpoints: BreakpointSet | undefined): StackTiers {\n  // Chosen from the tiers the device switcher offers: of two at one width\n  // the later wins in the browser, and a stack written at the other would be\n  // overridden by it. Every stored tier is still managed, so a stack written\n  // at either is found and cleared.\n  const widest = (fits: (width: number) => boolean) =>\n    offeredTiers(breakpoints).find(tier => fits(tier.maxWidth))?.id;\n  const tablet = widest(width => width > 640 && width <= 1024);\n  const mobile = widest(width => width <= 640);\n  // Widest first, and of two at one width the later first: the order the\n  // browser lets them win in, so a stack is read where it is applied.\n  const managed = (breakpoints?.viewport ?? [])\n    .map((tier, index) => ({ tier, index }))\n    .filter(({ tier }) => tier.maxWidth !== undefined && tier.maxWidth <= 1024)\n    .sort(\n      (a, b) =>\n        (b.tier.maxWidth ?? 0) - (a.tier.maxWidth ?? 0) || b.index - a.index\n    )\n    .map(({ tier }) => ({\n      id: tier.id,\n      on:\n        (tier.maxWidth ?? 0) > 640 ? (\"tablet\" as const) : (\"mobile\" as const),\n    }));\n  return {\n    ...(tablet === undefined ? {} : { tablet }),\n    ...(mobile === undefined ? {} : { mobile }),\n    ...(managed.length === 0 ? {} : { managed }),\n  };\n}\n\nexport type StackOn = \"tablet\" | \"mobile\" | \"never\";\n\n/** The stack this control writes at a tier, if that is what the tier holds. */\nfunction stackAt(\n  row: BlockNode,\n  breakpoint: string,\n  state: StyleState\n): { reversed: boolean } | undefined {\n  const read = (property: string) =>\n    readStyleValue(row.styles, { state, breakpoint, property, path: [] });\n  const direction = read(\"flexDirection\");\n  if (read(\"display\") !== \"flex\") return undefined;\n  if (direction !== \"column\" && direction !== \"column-reverse\")\n    return undefined;\n  return { reversed: direction === \"column-reverse\" };\n}\n\n/** A stack reaching the row at a tier from elsewhere (a shared style it wears). */\nexport interface ReachedStack {\n  readonly id: string;\n  readonly reversed: boolean;\n}\n\n/**\n * What the cascade applies to the row at a tier: the winning declaration of a\n * CSS property there, where it was set, and whether the row set it itself.\n */\nexport type AppliedAt = (\n  tier: string,\n  cssProperty: \"display\" | \"flex-direction\" | \"grid-template-columns\"\n) => { value: string; breakpoint: string; own: boolean } | undefined;\n\n/**\n * The stacks reaching the row from elsewhere, tier by tier, as the cascade\n * applies them: a flex column set AT that tier by something other than the\n * row. The row's own stacks are read from what it stores, which is what the\n * control writes and clears.\n */\nexport function reachedStacks(\n  tiers: StackTiers,\n  applied: AppliedAt | undefined\n): ReachedStack[] {\n  if (applied === undefined) return [];\n  const reached: ReachedStack[] = [];\n  for (const tier of tiers.managed ?? []) {\n    const display = applied(tier.id, \"display\");\n    const direction = applied(tier.id, \"flex-direction\");\n    if (display?.value !== \"flex\" || display.breakpoint !== tier.id) continue;\n    if (display.own || direction === undefined || direction.own) continue;\n    if (direction.value !== \"column\" && direction.value !== \"column-reverse\")\n      continue;\n    reached.push({\n      id: tier.id,\n      reversed: direction.value === \"column-reverse\",\n    });\n  }\n  return reached;\n}\n\n/**\n * Where a row stacks, and whether it is reversed: its own stack, else one\n * reaching it from elsewhere, read widest tier first.\n */\nexport function stackOf(\n  row: BlockNode,\n  tiers: StackTiers,\n  state: StyleState,\n  reached: readonly ReachedStack[] = []\n): { on: StackOn; reversed: boolean } {\n  for (const tier of tiers.managed ?? []) {\n    const stack =\n      stackAt(row, tier.id, state) ?? reached.find(each => each.id === tier.id);\n    if (stack !== undefined) return { on: tier.on, reversed: stack.reversed };\n  }\n  return { on: \"never\", reversed: false };\n}\n\n/**\n * Whether the row stores a layout of its own: a template on its base\n * values, or a stack at any device. What the Content section's dot says.\n */\nexport function layoutHoldsValue(row: BlockNode, tiers: StackTiers): boolean {\n  const template = readStyleValue(row.styles, {\n    state: \"base\",\n    breakpoint: BASE_BREAKPOINT,\n    property: \"gridTemplateColumns\",\n    path: [],\n  });\n  return template !== undefined || stackOf(row, tiers, \"base\").on !== \"never\";\n}\n\n/** The display the block lays a row out with, from its own defaults. */\nfunction defaultDisplay(row: BlockNode): string {\n  const base = (\n    getBlock(row.type)?.baseStyles as\n      | { base?: { base?: Record<string, unknown> } }\n      | undefined\n  )?.base?.base?.display;\n  return typeof base === \"string\" ? base : \"block\";\n}\n\n/**\n * The tiers where a stack reaching the row must be masked: every one for\n * Never, else those wider than the chosen tier, where the row's own stack\n * does not reach. Masked with the block's own display, set on the row.\n */\nfunction maskedStacks(\n  tiers: StackTiers,\n  chosen: string | undefined,\n  reached: readonly ReachedStack[]\n): string[] {\n  const order = (tiers.managed ?? []).map(tier => tier.id);\n  const limit = chosen === undefined ? order.length : order.indexOf(chosen);\n  return reached\n    .filter(each => order.indexOf(each.id) < limit)\n    .map(each => each.id);\n}\n\n/**\n * Stacking as ONE op on the row: cleared at both tiers, then, unless Never,\n * the row laid out as a flex column at the chosen tier, which applies there\n * and below; reversed, the last column comes first.\n */\nexport function planStack(\n  row: BlockNode,\n  on: StackOn,\n  reversed: boolean,\n  {\n    tiers,\n    state,\n    reached = [],\n  }: {\n    tiers: StackTiers;\n    state: StyleState;\n    reached?: readonly ReachedStack[];\n  }\n): BuilderOp | null {\n  const steps: { address: StyleAddress; value: StyleValue | null }[] = [];\n  // Only a stack this control wrote is cleared: a display set at a tier for\n  // another reason (hidden on mobile) is the author's and stays.\n  for (const tier of tiers.managed ?? []) {\n    if (stackAt(row, tier.id, state) === undefined) continue;\n    for (const property of [\"display\", \"flexDirection\"]) {\n      steps.push({\n        address: { state, breakpoint: tier.id, property, path: [] },\n        value: null,\n      });\n    }\n  }\n  const breakpoint = on === \"never\" ? undefined : tiers[on];\n  // A stack from a shared style is not the row's to clear: laid over instead,\n  // where the choice says the row should not stack.\n  for (const tier of maskedStacks(tiers, breakpoint, reached)) {\n    steps.push({\n      address: { state, breakpoint: tier, property: \"display\", path: [] },\n      value: defaultDisplay(row),\n    });\n  }\n  if (breakpoint !== undefined) {\n    steps.push(\n      {\n        address: { state, breakpoint, property: \"display\", path: [] },\n        value: \"flex\",\n      },\n      {\n        address: { state, breakpoint, property: \"flexDirection\", path: [] },\n        value: reversed ? \"column-reverse\" : \"column\",\n      }\n    );\n  }\n  return chainedStyleOp(row, steps);\n}\n","/**\n * What \"an empty container\" means, in the two places the editor has to ask.\n *\n * {@link emptySlotOf} answers it about a stored NODE: which of a block's\n * declared regions is empty. Asked by two callers that must agree — the\n * inserter, deciding whether a new block goes INSIDE the selection or beside\n * it, and the canvas appender, deciding which containers to offer a \"+\" for. A\n * second copy of it would agree on the day it was written and drift afterwards,\n * and the drift would be silent because an appender offering to fill a\n * container the inserter then fills elsewhere looks correct from both sides.\n *\n * {@link EMPTY_CONTAINER_SELECTOR} answers it about a RENDERED element: which\n * elements the editor draws an empty-container affordance on. Both the\n * stylesheet's dashed box and the appender's control read it, for the same\n * reason the two callers above share `emptySlotOf`.\n *\n * @module empty-slot\n */\nimport type { BlockNode } from \"@nextlyhq/blocks-engine\";\nimport { SLOTS_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport type { SlotSource } from \"../panels/add/inserter\";\nimport { BUILDER_CHROME_CLASS, CANVAS_ROOT_CLASS } from \"../shell-state\";\n\n/**\n * The rendered element an empty-container affordance may be drawn on.\n *\n * `builder-chrome.css` gives exactly this selector the 44px dashed box that\n * makes an otherwise sizeless container visible, and the canvas appender draws\n * its \"+\" on exactly the elements it matches. ONE spelling, asked by both,\n * rather than each deciding for itself which containers it covers.\n *\n * The two used to differ, and the difference was not visible from either side.\n * The appender drew for any node whose first declared slot was empty\n * ({@link emptySlotOf} below), which is a question about the DOCUMENT; the\n * stylesheet asks a question about the RENDER. A block whose root element\n * carries content of its own — `core/accordion-item` renders a `<summary>`\n * beside its slot — has an empty slot and a root that is not `:empty`, so the\n * stylesheet declined it and the appender did not. The appender was then\n * placing a fixed-size control on a container that had been given no box to\n * place it in, and on a root measuring less than the control it centred there.\n *\n * ## The WHOLE rule, not the element-level part of it\n *\n * Both conditions are here, because both decide whether a box is drawn and\n * the affordance is only correct where one is:\n *\n * - inside a builder shell ({@link BUILDER_CHROME_CLASS}). A consumer can\n *   compose the exported appender with a bare `Canvas` and no shell at all —\n *   the product path does not, since `BlocksField` mounts the canvas inside\n *   `BuilderShell`, but nothing stops a host or a harness doing it. The rule\n *   then never applies, the container keeps its natural size of nothing, and a\n *   control drawn on the element-level match alone is a focusable button with\n *   no area: reachable by keyboard, announced by name, and invisible. That is\n *   the same defect declining an unrendered container removed, arriving through\n *   a partial condition.\n * - inside a canvas ({@link CANVAS_ROOT_CLASS}).\n *\n * The canvas condition is additionally answered elsewhere for the appender —\n * it measures nothing outside a canvas root — and it stays in the selector\n * anyway, because this is the stylesheet's rule rather than a subset of it\n * chosen for the appender. There is no preference condition: empty containers\n * always show, so no setting takes the box away. `Element.matches` evaluates\n * ancestors, so asking it of the element the stylesheet would ask it of gets\n * the same answer the browser gives the rule.\n *\n * A stylesheet cannot import a constant, so `builder-chrome.css` spells this\n * out and `builder-chrome-attributes.test.ts` is what holds the two in step.\n *\n * `:empty` is asked of the element carrying {@link SLOTS_ATTRIBUTE}, which is\n * the same element that carries `NODE_ID_ATTRIBUTE` — `block-boundary.tsx`\n * applies both markers to a block's single root — so the element found by node\n * id is the element this question is about, with no second address to resolve.\n */\nexport const EMPTY_CONTAINER_SELECTOR: string = `.${BUILDER_CHROME_CLASS} .${CANVAS_ROOT_CLASS} [${SLOTS_ATTRIBUTE}]:empty`;\n\n/**\n * An open disclosure whose slot holds nothing: a Question emptied of its\n * answer. Its root renders a `<summary>` beside the slot, so it is never\n * `:empty` and {@link EMPTY_CONTAINER_SELECTOR} cannot match it; this matches\n * it by what it holds, a summary and nothing else.\n *\n * Open only: a closed one shows its title alone, as on the page, and draws\n * no start. The frame's sheet draws the empty-container box under the\n * summary (its `::after`), and the canvas appender draws its \"+\" there, so\n * the two ask the same question, as they do of an empty container. Scoped as\n * an empty container is, to a canvas inside the builder's chrome.\n */\nexport const EMPTY_DISCLOSURE_SELECTOR: string =\n  `.${BUILDER_CHROME_CLASS} .${CANVAS_ROOT_CLASS} ` +\n  `details[${SLOTS_ATTRIBUTE}][open]:not(:has(> :not(summary)))`;\n\n/**\n * A rendered text element emptied of its words: a block's own heading or\n * paragraph, or a value a component placement exposes, cleared.\n *\n * The frame's sheet gives it a line of height, so an author can still click\n * what they cleared rather than lose it at zero height. TEXT only: a spacer or\n * an image that draws nothing inside it has a size of its own, and the canvas\n * keeps it as the published page does. Scoped as an empty container is, to a\n * canvas inside the builder's chrome, and like it always shown.\n */\nexport const EMPTY_TEXT_SELECTOR: string =\n  `.${BUILDER_CHROME_CLASS} .${CANVAS_ROOT_CLASS} ` +\n  `:is([data-nx-node], [data-nx-prop])` +\n  `:is(h1, h2, h3, h4, h5, h6, p, li, blockquote, figcaption, dt, dd, pre):empty`;\n\n/**\n * The block's first declared slot, or the one the canvas draws in its place,\n * when it holds nothing.\n *\n * FIRST rather than any: a block with several regions has an order, and the\n * one an author means by \"inside this\" is the one it declares first. Answering\n * with some other empty region would put content where nobody pointed.\n *\n * @param node - the node to inspect\n * @param slots - what each block type declares; absent means nothing is known\n * @returns the slot's name, or `null` when this is not an empty container\n */\nexport function emptySlotOf(\n  node: BlockNode,\n  slots: SlotSource | undefined\n): string | null {\n  const declared = slots?.slotsOf(node.type);\n  // The region the canvas draws in place of the first, where it draws\n  // another: an empty list's empty state is the region an author sees.\n  const shown = slots?.shownSlotOf?.(node);\n  const first =\n    shown !== undefined && declared?.includes(shown) === true\n      ? shown\n      : declared?.[0];\n  if (first === undefined) return null;\n  return (node.slots?.[first]?.length ?? 0) === 0 ? first : null;\n}\n","/**\n * Shortcuts over a block's Style values: a Section's height, a Button's size\n * and its full width. Each writes the ordinary Style value at the device and\n * state being edited, and reads back from what is stored there, so a value\n * set any other way shows as none of its choices rather than as a wrong one.\n *\n * @module block-shortcuts\n */\nimport {\n  DEFAULT_TOKEN_PREFIX,\n  getBlock,\n  getStyleProperty,\n  isStyleLeaf,\n  isTokenRef,\n  scaledTokenText,\n  tokenCustomProperty,\n  type BlockNode,\n  type BreakpointId,\n  type StyleState,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { chainedStyleOp } from \"../canvas/columns-layout\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport type { StyleProvenance } from \"./style-provenance\";\nimport { readStyleValue } from \"./style-values\";\n\n/** The core blocks these shortcuts belong to. */\nexport const SECTION_BLOCK = \"core/section\";\nexport const BUTTON_BLOCK = \"core/button\";\nexport const SPACER_BLOCK = \"core/spacer\";\nexport const ICON_BLOCK = \"core/icon\";\n\n/** Where a shortcut writes: the state and the device being edited. */\nexport interface ShortcutAt {\n  readonly state: StyleState;\n  readonly breakpoint: BreakpointId;\n  /**\n   * The prefix the site's tokens are written under, which a value reaching\n   * from elsewhere names its tokens with; the default prefix when omitted.\n   */\n  readonly tokenPrefix?: string;\n}\n\n/** The value Medium writes for the text size over one reaching from elsewhere. */\nconst OWN_TEXT = \"inherit\";\n\n/**\n * What reaches the edited address from elsewhere (a wider device, a shared\n * style, another state) for a CSS property, as the cascade writes it, beneath\n * any value set here; none where nothing does.\n */\nexport type Reaching = (cssProperty: string) => string | undefined;\n\nconst NOTHING_REACHES: Reaching = () => undefined;\n\n/** One CSS property's answer from the panel's trace: the winner, and beneath. */\nexport interface ReachingAnswer {\n  readonly provenance: StyleProvenance;\n  readonly beneath: StyleProvenance;\n}\n\n/**\n * What reaches the edited address from elsewhere, read from the trace: the\n * winner when it comes from elsewhere, and, when the winner is set here, the\n * value beneath it, which is what clearing it would leave in force. So Medium\n * over a local Small with a Large beneath writes the button's own size rather\n * than clearing back to Large.\n */\nexport function reachingBeneath(\n  answerOf: (cssProperty: string) => ReachingAnswer | undefined\n): Reaching {\n  return cssProperty => {\n    const answer = answerOf(cssProperty);\n    if (answer === undefined) return undefined;\n    const under =\n      answer.provenance.kind === \"authored\"\n        ? answer.beneath\n        : answer.provenance;\n    return under.kind === \"inherited\" ? under.entry.value : undefined;\n  };\n}\n\n/** A value stored at the edited address, for one top-level property. */\nfunction storedAt(\n  node: BlockNode,\n  at: ShortcutAt,\n  property: string\n): StyleValue | undefined {\n  return readStyleValue(node.styles, { ...at, property, path: [] });\n}\n\n/** One write, or with `null` a clear, of a property at the edited address. */\nfunction written(\n  node: BlockNode,\n  at: ShortcutAt,\n  steps: readonly (readonly [string, StyleValue | null])[]\n): BuilderOp | null {\n  return chainedStyleOp(\n    node,\n    steps.map(([property, value]) => ({\n      address: { ...at, property, path: [] },\n      value,\n    }))\n  );\n}\n\n// --- a Section's height\n\n/** At least the screen's height: `svh`, so a phone's toolbar hides none of it. */\n/** What Full screen writes as a Section's min height. */\nexport const FULL_SCREEN = \"100svh\";\n\nexport type HeightChoice = \"auto\" | \"screen\";\n\n/**\n * Fit content while no min height is set here, Full screen for its own, else\n * none.\n */\nexport function heightOf(\n  node: BlockNode,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): HeightChoice | undefined {\n  const shown = storedAt(node, at, \"minHeight\") ?? reaching(\"min-height\");\n  // `auto` is what Fit content writes over a min height reaching from\n  // elsewhere.\n  if (shown === undefined || shown === \"auto\") return \"auto\";\n  return shown === FULL_SCREEN ? \"screen\" : undefined;\n}\n\n/**\n * Full screen writes its min height here; Fit content clears it, or, where\n * one reaches from elsewhere, writes `auto` over it, since a clear would\n * leave that one in force.\n */\nexport function planHeight(\n  node: BlockNode,\n  choice: HeightChoice,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): BuilderOp | null {\n  if (choice === \"screen\")\n    return written(node, at, [[\"minHeight\", FULL_SCREEN]]);\n  const over = reaching(\"min-height\") === undefined ? null : \"auto\";\n  return written(node, at, [[\"minHeight\", over]]);\n}\n\n// --- a Spacer's height\n\n/**\n * A Spacer's height set to one of the site's spacing variables, at the edited\n * state and device, so the space follows the site's scale as it changes.\n */\nexport function planSpacerHeight(\n  node: BlockNode,\n  identity: string,\n  at: ShortcutAt\n): BuilderOp | null {\n  return written(node, at, [[\"height\", { $token: identity }]]);\n}\n\n// --- a Button's size\n\nexport type SizeChoice = \"small\" | \"medium\" | \"large\";\n\n/**\n * How Small and Large differ from the button's own: its padding tokens\n * scaled, so the sizes follow the site's design and keep their order, and\n * its text in em, relative to what it inherits.\n */\nexport const SIZES = {\n  small: { times: 0.75, text: \"0.875em\" },\n  large: { times: 1.25, text: \"1.125em\" },\n} as const;\n\n/** The block's own padding, side by side, as its definition sets it. */\nfunction basePadding(node: BlockNode): Record<string, unknown> | undefined {\n  const base = (\n    getBlock(node.type)?.baseStyles as\n      | { base?: { base?: Record<string, unknown> } }\n      | undefined\n  )?.base?.base?.padding;\n  return typeof base === \"object\" && base !== null && !Array.isArray(base)\n    ? (base as Record<string, unknown>)\n    : undefined;\n}\n\n/**\n * The block's padding with every side's token scaled, or `undefined` where a\n * side is not a token: a literal has no design to follow.\n */\nfunction scaledPadding(\n  node: BlockNode,\n  times: number\n): Record<string, StyleValue> | undefined {\n  const base = basePadding(node);\n  if (base === undefined) return undefined;\n  const sides: Record<string, StyleValue> = {};\n  for (const [side, value] of Object.entries(base)) {\n    if (!isTokenRef(value)) return undefined;\n    // Unscaled, the token alone: what the button's own padding is.\n    sides[side] =\n      times === 1 ? { $token: value.$token } : { $token: value.$token, times };\n  }\n  return sides;\n}\n\n/** Whether two paddings say the same, side by side, whatever their order. */\nfunction samePadding(\n  stored: StyleValue | undefined,\n  expected: Record<string, StyleValue>\n): boolean {\n  if (typeof stored !== \"object\" || stored === null || Array.isArray(stored))\n    return false;\n  const sides = stored as Record<string, StyleValue>;\n  const keys = Object.keys(expected);\n  return (\n    Object.keys(sides).length === keys.length &&\n    keys.every(side => sameScaledToken(sides[side], expected[side]))\n  );\n}\n\n/**\n * Whether two token references name the same token at the same scale, read\n * field by field: a reference's keys may arrive in any order.\n */\nfunction sameScaledToken(\n  stored: StyleValue | undefined,\n  expected: StyleValue | undefined\n): boolean {\n  return (\n    isTokenRef(stored) &&\n    isTokenRef(expected) &&\n    stored.$token === expected.$token &&\n    stored.times === expected.times\n  );\n}\n\n/** Whether the button can be sized: its padding is its design's tokens. */\nexport function sizesOffered(node: BlockNode): boolean {\n  return scaledPadding(node, 1) !== undefined;\n}\n\n/**\n * Medium while neither its padding nor its text size is set here, Small or\n * Large where both are what that size writes, else none of the three.\n */\nexport function sizeOf(\n  node: BlockNode,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): SizeChoice | undefined {\n  const padding = storedAt(node, at, \"padding\");\n  const text = storedAt(node, at, \"fontSize\");\n  if (padding === undefined && text === undefined) {\n    return reachingSize(node, reaching, at.tokenPrefix ?? DEFAULT_TOKEN_PREFIX);\n  }\n  // What Medium writes over a size reaching from elsewhere: the button's own\n  // padding tokens and its inherited text size.\n  const own = scaledPadding(node, 1);\n  if (own !== undefined && samePadding(padding, own) && text === OWN_TEXT) {\n    return \"medium\";\n  }\n  for (const size of [\"small\", \"large\"] as const) {\n    const scaled = scaledPadding(node, SIZES[size].times);\n    if (\n      scaled !== undefined &&\n      samePadding(padding, scaled) &&\n      text === SIZES[size].text\n    ) {\n      return size;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Each padding side's CSS property, as the catalog compiles the side: what\n * the cascade reports reaching, side by side.\n */\nconst PADDING_SIDES: ReadonlyMap<string, string> = (() => {\n  const shape = getStyleProperty(\"padding\")?.shape;\n  if (\n    shape === undefined ||\n    isStyleLeaf(shape) ||\n    shape.kind !== \"logicalSides\"\n  ) {\n    return new Map();\n  }\n  return new Map(\n    Object.entries(shape.sides).map(\n      ([side, leaf]) => [side, leaf.cssProperty] as const\n    )\n  );\n})();\n\n/** Whether a side's padding, or the text size, reaches from elsewhere. */\nfunction sizeReaches(reaching: Reaching): boolean {\n  return (\n    reaching(\"font-size\") !== undefined ||\n    [...PADDING_SIDES.values()].some(\n      cssProperty => reaching(cssProperty) !== undefined\n    )\n  );\n}\n\n/**\n * Whether a side's reaching text is its own token scaled by `times`, spelled\n * exactly as the compiler writes it under the site's prefix: a token whose name\n * merely ends the same way (`brand.button.padding-y`) is another token.\n */\nfunction reachesScaled(\n  text: string | undefined,\n  token: string,\n  times: number,\n  prefix: string\n): boolean {\n  return (\n    text ===\n    scaledTokenText(`var(${tokenCustomProperty(token, prefix)})`, times)\n  );\n}\n\n/**\n * The size a value reaching from elsewhere draws, as the cascade writes it:\n * Medium where neither the text size nor any padding side reaches, Small or\n * Large where the text size and all four sides are what that size writes,\n * each side its own token at the size's factor, and anything else none.\n */\nfunction reachingSize(\n  node: BlockNode,\n  reaching: Reaching,\n  prefix: string\n): SizeChoice | undefined {\n  if (!sizeReaches(reaching)) return \"medium\";\n  const own = scaledPadding(node, 1);\n  if (own === undefined) return undefined;\n  for (const size of [\"small\", \"large\"] as const) {\n    const { times, text } = SIZES[size];\n    if (\n      reaching(\"font-size\") === text &&\n      [...PADDING_SIDES].every(([side, cssProperty]) => {\n        const token = own[side];\n        return (\n          isTokenRef(token) &&\n          reachesScaled(reaching(cssProperty), token.$token, times, prefix)\n        );\n      })\n    ) {\n      return size;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Small or Large writes its padding and text size here. Medium clears both,\n * or, where a size reaches from elsewhere, writes the button's own padding\n * and text size over it, since a clear would leave that one in force.\n */\nexport function planSize(\n  node: BlockNode,\n  size: SizeChoice,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): BuilderOp | null {\n  if (size === \"medium\") {\n    const over = sizeReaches(reaching);\n    return written(node, at, [\n      [\"padding\", over ? (scaledPadding(node, 1) ?? null) : null],\n      [\"fontSize\", over ? OWN_TEXT : null],\n    ]);\n  }\n  const padding = scaledPadding(node, SIZES[size].times);\n  if (padding === undefined) return null;\n  return written(node, at, [\n    [\"padding\", padding],\n    [\"fontSize\", SIZES[size].text],\n  ]);\n}\n\n// --- an Icon's size\n\n/**\n * What Small and Large set an Icon's font size to, since the glyph is drawn\n * at the font size: a step below and above its own 1.5rem, in rem so an icon\n * keeps its size wherever it is placed.\n */\nexport const ICON_SIZES = {\n  small: \"1rem\",\n  large: \"2rem\",\n} as const;\n\n/** The font size the block's definition draws it at, when it sets one. */\nfunction baseFontSize(node: BlockNode): string | undefined {\n  const size = (\n    getBlock(node.type)?.baseStyles as\n      | { base?: { base?: Record<string, unknown> } }\n      | undefined\n  )?.base?.base?.fontSize;\n  return typeof size === \"string\" ? size : undefined;\n}\n\n/**\n * Medium while no font size is set here or reaches, or the icon's own is\n * what shows; Small or Large where its size is shown; else none of the three.\n */\nexport function iconSizeOf(\n  node: BlockNode,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): SizeChoice | undefined {\n  const shown = storedAt(node, at, \"fontSize\") ?? reaching(\"font-size\");\n  if (shown === undefined || shown === baseFontSize(node)) return \"medium\";\n  if (shown === ICON_SIZES.small) return \"small\";\n  if (shown === ICON_SIZES.large) return \"large\";\n  return undefined;\n}\n\n/**\n * Small or Large writes its font size here. Medium clears it, or, where a\n * size reaches from elsewhere, writes the icon's own over it, since a clear\n * would leave that one in force.\n */\nexport function planIconSize(\n  node: BlockNode,\n  size: SizeChoice,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): BuilderOp | null {\n  if (size !== \"medium\") {\n    return written(node, at, [[\"fontSize\", ICON_SIZES[size]]]);\n  }\n  const over =\n    reaching(\"font-size\") === undefined ? null : (baseFontSize(node) ?? null);\n  return written(node, at, [[\"fontSize\", over]]);\n}\n\n// --- a Button's full width\n\n/** Whether the button is as wide as its container here, set or reaching. */\nexport function fullWidthOf(\n  node: BlockNode,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): boolean {\n  return (storedAt(node, at, \"width\") ?? reaching(\"width\")) === \"100%\";\n}\n\n/**\n * On writes a width of 100% here. Off clears it, or, where a width reaches\n * from elsewhere, writes `auto` over it.\n */\nexport function planFullWidth(\n  node: BlockNode,\n  on: boolean,\n  at: ShortcutAt,\n  reaching: Reaching = NOTHING_REACHES\n): BuilderOp | null {\n  if (on) return written(node, at, [[\"width\", \"100%\"]]);\n  const over = reaching(\"width\") === undefined ? null : \"auto\";\n  return written(node, at, [[\"width\", over]]);\n}\n","/**\n * Where an insert could land around the selected block: the candidates inside\n * it and after it, in the order the kind of block being added tries them, and\n * the position each one inserts at.\n *\n * @module insertion-candidates\n */\n\nimport {\n  allBlocks,\n  findNode,\n  locateNode,\n  type AnyBlockDefinition,\n  type BlockDocument,\n  type BlockNode,\n  type PlacementTarget,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { emptySlotOf } from \"../../canvas/empty-slot\";\nimport { positionOf, type OpPosition } from \"../../op-vocabulary\";\nimport { SECTION_BLOCK } from \"../../styles/block-shortcuts\";\n\nimport type { InsertEntry, SlotSource } from \"./inserter-types\";\n\n/**\n * What kind of block an entry adds, which decides the order its places are\n * tried in.\n *\n * - `content`: anything that is not a layout block (Heading, Text, Image,\n *   Button, Divider, Accordion, Gallery…), which goes inside a selected block\n *   that holds blocks.\n * - `layout`: a block in the Layout group that holds blocks (Box, Columns,\n *   Column, Card), which goes after the selection, so Box then Box stays two\n *   siblings.\n * - `band`: a Section or a saved section, a band of the page, which goes\n *   after the top-level block holding a nested selection.\n */\nexport type EntryRole = \"content\" | \"layout\" | \"band\";\n\n/**\n * One place a click in the Add panel may put a block, and what it goes after.\n *\n * `afterId` names the block the new one follows (\"Adding after Heading\"), and\n * is absent at the end of the page and inside a container. `between` is an\n * explicit place someone chose, a gap between two blocks: `afterId` and\n * `beforeId` name the blocks either side, either absent at an end.\n */\nexport interface InsertionCandidate {\n  readonly kind:\n    | \"after-selection\"\n    | \"after-ancestor\"\n    | \"document-end\"\n    | \"inside\"\n    | \"between\";\n  readonly at: OpPosition;\n  readonly target: PlacementTarget;\n  readonly afterId?: string;\n  /** The block a `between` place comes before. */\n  readonly beforeId?: string;\n  /** The container a block goes inside, for `inside`. */\n  readonly insideId?: string;\n}\n\n/** What {@link insertionCandidates} reads besides the page and selection. */\nexport interface InsertionOptions {\n  /** A container someone chose to add into (its \"+\"): that place only. */\n  readonly inside?: string;\n  /** A place someone chose, such as a gap between two blocks: that only. */\n  readonly at?: OpPosition;\n  /**\n   * A block someone chose to add right after (a gap's \"+\"): the place just\n   * after it, in its own region, only. Resolved against the page as it is\n   * now, so an undo that moves the block moves the place with it.\n   */\n  readonly after?: string;\n  /** The regions each block type declares, for \"inside\". */\n  readonly slots?: SlotSource;\n  /** What kind of block is being added; a content block when absent. */\n  readonly role?: EntryRole;\n}\n\n/**\n * Where a click may put a block, in the order the places are tried. The ONE\n * answer every surface asks: a click or Enter on an Add panel tile, the\n * Components panel, search, the panel's line and each tile's description.\n *\n * - An explicit place (`at`, a gap's `after`, or a container's `inside`) is\n *   that place only.\n * - Nothing selected, or a selection the page no longer holds: the end of\n *   the page.\n * - A Section or saved section with a selection inside another block: after\n *   the top-level block holding it, so a band never lands inside a band.\n * - A content block with a selection that holds blocks: inside it, at the\n *   end of its shown region, then after it, then after each block around\n *   it, out to the page.\n * - A layout block (or a Section at the top level) with a selection that\n *   holds blocks: after it, then after each block around it, and inside it\n *   only last, for a block that belongs only there (a Column in Columns).\n * - A selection that holds no blocks: after it, then outward.\n *\n * Which place a given block takes is {@link insertionFor}'s question, asked\n * of the placement rule: the first that accepts it.\n */\nexport function insertionCandidates(\n  document: BlockDocument,\n  selectedId: string | null,\n  options: InsertionOptions = {}\n): InsertionCandidate[] {\n  if (options.at !== undefined) return explicitCandidates(document, options.at);\n  if (options.after !== undefined) {\n    const location = locateNode(document.nodes, options.after);\n    const after =\n      location === undefined\n        ? undefined\n        : afterCandidate(location, options.after, true);\n    return after === undefined ? [] : explicitCandidates(document, after.at);\n  }\n  if (options.inside !== undefined) {\n    return insideCandidates(document, options.inside, options.slots);\n  }\n  const end: InsertionCandidate = {\n    kind: \"document-end\",\n    at: { index: document.nodes.length },\n    target: { kind: \"root\" },\n  };\n  if (selectedId === null) return [end];\n  const after = afterCandidates(document, selectedId);\n  if (after.length === 0) return [end];\n  const outermost = after.at(-1);\n  if (\n    options.role === \"band\" &&\n    after.length > 1 &&\n    outermost?.target.kind === \"root\"\n  ) {\n    return [outermost];\n  }\n  const inside = insideCandidates(document, selectedId, options.slots);\n  return (options.role ?? \"content\") === \"content\"\n    ? [...inside, ...after]\n    : [...after, ...inside];\n}\n\n/**\n * After the selected block, in its own region, then after each block it sits\n * in, out to the page: a block a region refuses goes after the nearest\n * container that can hold it.\n */\nfunction afterCandidates(\n  document: BlockDocument,\n  selectedId: string\n): InsertionCandidate[] {\n  const candidates: InsertionCandidate[] = [];\n  let current: string | undefined = selectedId;\n  // Bounded by the document's depth: each step moves one parent out.\n  while (current !== undefined) {\n    const location = locateNode(document.nodes, current);\n    const after =\n      location === undefined\n        ? undefined\n        : afterCandidate(location, current, current === selectedId);\n    if (location === undefined || after === undefined) break;\n    candidates.push(after);\n    current = location.parent?.id;\n  }\n  return candidates;\n}\n\n/**\n * An explicit place, named by the blocks either side of it: \"between Hero\n * and Pricing\", or after the last block of its region. None when the\n * container it is in is gone.\n */\nfunction explicitCandidates(\n  document: BlockDocument,\n  at: OpPosition\n): InsertionCandidate[] {\n  const region = regionAt(document, at);\n  if (region === undefined) return [];\n  const { held, target, containerId } = region;\n  const before = held[at.index]?.id;\n  const after = at.index > 0 ? held[at.index - 1]?.id : undefined;\n  if (before !== undefined) {\n    return [\n      {\n        kind: \"between\",\n        at,\n        target,\n        ...(after === undefined ? {} : { afterId: after }),\n        beforeId: before,\n      },\n    ];\n  }\n  if (after !== undefined) {\n    return [{ kind: \"after-ancestor\", at, target, afterId: after }];\n  }\n  return containerId === undefined\n    ? [{ kind: \"document-end\", at, target }]\n    : [{ kind: \"inside\", at, target, insideId: containerId }];\n}\n\n/**\n * The region a position is in: the blocks it holds, the target it implies,\n * and the container it belongs to (none at the page's top level). None when\n * that container is gone.\n */\nfunction regionAt(\n  document: BlockDocument,\n  at: OpPosition\n):\n  | {\n      readonly held: readonly BlockNode[];\n      readonly target: PlacementTarget;\n      readonly containerId?: string;\n    }\n  | undefined {\n  if (at.parentId === undefined) {\n    return { held: document.nodes, target: { kind: \"root\" } };\n  }\n  const parent = findNode(document.nodes, at.parentId);\n  if (parent === undefined) return undefined;\n  const slot = at.slot ?? \"\";\n  return {\n    held: parent.slots?.[slot] ?? [],\n    target: { kind: \"slot\", parentType: parent.type, slot },\n    containerId: parent.id,\n  };\n}\n\n/** The end of a container's region the author chose to add into, if it has one. */\nfunction insideCandidates(\n  document: BlockDocument,\n  insideId: string,\n  slots: SlotSource | undefined\n): InsertionCandidate[] {\n  const container = findNode(document.nodes, insideId);\n  if (container === undefined) return [];\n  const slot =\n    emptySlotOf(container, slots) ??\n    slots?.shownSlotOf?.(container) ??\n    Object.keys(container.slots ?? {})[0];\n  if (slot === undefined) return [];\n  const held = container.slots?.[slot] ?? [];\n  return [\n    {\n      kind: \"inside\",\n      at: { parentId: container.id, slot, index: held.length },\n      target: { kind: \"slot\", parentType: container.type, slot },\n      insideId: container.id,\n    },\n  ];\n}\n\n/**\n * The place just after one block in its own region, or `undefined` where no op\n * can name it (a parent with no named slot).\n */\nfunction afterCandidate(\n  location: NonNullable<ReturnType<typeof locateNode>>,\n  id: string,\n  selected: boolean\n): InsertionCandidate | undefined {\n  let here: OpPosition;\n  try {\n    here = positionOf(location);\n  } catch {\n    return undefined;\n  }\n  return {\n    kind: selected ? \"after-selection\" : \"after-ancestor\",\n    at: { ...here, index: here.index + 1 },\n    target:\n      location.parent === undefined\n        ? { kind: \"root\" }\n        : {\n            kind: \"slot\",\n            parentType: location.parent.type,\n            slot: location.slot ?? \"\",\n          },\n    afterId: id,\n  };\n}\n\n/**\n * The place a block takes: the first of the candidates whose region accepts\n * it, by the caller's reading of the placement rule, or `undefined` when none\n * does (and the panel says why).\n */\nexport function insertionFor<T>(\n  candidates: readonly InsertionCandidate[],\n  accepts: (candidate: InsertionCandidate) => T | undefined\n): { readonly candidate: InsertionCandidate; readonly answer: T } | undefined {\n  for (const candidate of candidates) {\n    const answer = accepts(candidate);\n    if (answer !== undefined) return { candidate, answer };\n  }\n  return undefined;\n}\n\n/**\n * The group the block library files its layout blocks under: a block in it\n * that holds blocks is a layout block.\n */\nconst LAYOUT_CATEGORY = \"layout\";\n\n/**\n * Each entry's {@link EntryRole}, by entry id, read from what its blocks\n * already declare: their group and their regions. A plugin block needs no\n * field of its own to be placed as a layout block.\n *\n * - a saved section is a `band`, and so is a Section block;\n * - a block is `layout` when it is in the Layout group and holds blocks;\n * - a component is `layout` when any of its top-level blocks is one;\n * - everything else is `content`.\n *\n * `definitions` are the palette's own, read before the registry's, as the\n * insert reads them; a component's blocks may be outside the palette, so the\n * registry answers for the rest.\n */\nexport function entryRoles(\n  catalog: readonly InsertEntry[],\n  definitions: readonly AnyBlockDefinition[] | undefined\n): ReadonlyMap<string, EntryRole> {\n  const isLayout = layoutTest(definitions);\n  const roles = new Map<string, EntryRole>();\n  for (const entry of catalog) {\n    roles.set(entry.id, roleOf(entry, isLayout));\n  }\n  return roles;\n}\n\n/**\n * Whether a block type is a layout block: in the Layout group, and holding\n * blocks. The one reading every role here is derived from.\n */\nfunction layoutTest(\n  definitions: readonly AnyBlockDefinition[] | undefined\n): (type: string) => boolean {\n  const byName = definitionsByName(definitions);\n  return type => {\n    const definition = byName.get(type);\n    return (\n      definition?.editor?.category === LAYOUT_CATEGORY &&\n      Object.keys(definition.slots ?? {}).length > 0\n    );\n  };\n}\n\n/**\n * The role of a run of blocks placed together, such as pasted ones, from the\n * types its top-level blocks draw: a band when one is a Section, a layout\n * block when one is a layout block, and content otherwise. The same reading a\n * saved section's or a component's tile takes, so a pasted run lands where a\n * click on such a tile would put it.\n */\nexport function runRole(\n  types: readonly string[],\n  definitions?: readonly AnyBlockDefinition[]\n): EntryRole {\n  if (types.includes(SECTION_BLOCK)) return \"band\";\n  return types.some(layoutTest(definitions)) ? \"layout\" : \"content\";\n}\n\n/** One entry's role, given which block types are layout blocks. */\nfunction roleOf(\n  entry: InsertEntry,\n  isLayout: (type: string) => boolean\n): EntryRole {\n  if (entry.kind === \"pattern\") return \"band\";\n  if (entry.kind === \"component\") {\n    return entry.roots.some(isLayout) ? \"layout\" : \"content\";\n  }\n  if (entry.blockName === SECTION_BLOCK) return \"band\";\n  return isLayout(entry.blockName) ? \"layout\" : \"content\";\n}\n\n/**\n * Every registered block definition by name, with the supplied ones written\n * second, so they WIN for a name in both: the palette offered that\n * definition, so the insert must build, and place, that block. Read ONCE, so\n * one reading answers every lookup of a catalogue's build.\n */\nexport function definitionsByName(\n  definitions: readonly AnyBlockDefinition[] | undefined\n): ReadonlyMap<string, AnyBlockDefinition> {\n  const byName = new Map<string, AnyBlockDefinition>();\n  for (const definition of allBlocks()) byName.set(definition.name, definition);\n  for (const definition of definitions ?? []) {\n    byName.set(definition.name, definition);\n  }\n  return byName;\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 palette's search and grouping: which entries a query finds, the groups\n * by category in the order the palette shows them, and each category's\n * heading.\n *\n * @module inserter-palette\n */\n\nimport { EDITOR_WORDS } from \"../../editor-words\";\n\nimport {\n  COMPONENT_CATEGORY,\n  type InsertEntry,\n  UNCATEGORISED,\n} from \"./inserter-types\";\n\n/**\n * Narrow the catalog by what the author typed.\n *\n * Matches the label, the namespaced block name, the declared keywords and the\n * description — the block name included because it is what appears in\n * documentation and in an agent's output, so someone who knows `core/heading`\n * should not have to guess that it is labelled \"Heading\".\n *\n * An empty or whitespace-only query returns the list unchanged rather than\n * nothing: the panel opens with no query, and a filter that treated that as\n * \"match nothing\" would show an empty palette on open.\n */\nexport function filterEntries<TEntry extends InsertEntry>(\n  entries: readonly TEntry[],\n  query: string\n): TEntry[] {\n  const needle = query.trim().toLowerCase();\n  if (needle === \"\") return [...entries];\n  return entries.filter(entry =>\n    searchableWords(entry).some(field => field.toLowerCase().includes(needle))\n  );\n}\n\n/**\n * The words one entry is matched on.\n *\n * A block additionally carries its namespaced name because that is what appears\n * in documentation and in an agent's output. A pattern has no such identity to\n * offer — its stored id is a row key nobody types — so the tier decides the\n * list rather than every field being read off whichever entry arrives.\n */\nfunction searchableWords(entry: InsertEntry): readonly string[] {\n  const shared = [entry.label, entry.description, ...entry.keywords];\n  return entry.kind === \"block\" ? [entry.blockName, ...shared] : shared;\n}\n\n/** A category heading and the entries under it, in the order the panel draws them. */\nexport interface InsertGroup<TEntry extends InsertEntry = InsertEntry> {\n  readonly category: string;\n  readonly entries: readonly TEntry[];\n}\n\n/**\n * Group entries under their categories.\n *\n * `preferred` names the headings a library wants offered first — a page starts\n * as structure, so \"layout\" belongs above \"interactive\", and neither\n * first-appearance nor an alphabetical sort produces that. It is a caller's\n * declaration rather than a constant here, because categories are free strings\n * contributed by any plugin and this module has no standing to rank them.\n *\n * Categories outside `preferred` follow, in first-appearance order. A plugin\n * that ships an unranked category still gets a heading rather than being hidden\n * behind a list it was never named in — dropping it would make a block\n * unreachable through the very panel that exists to reach it.\n */\nexport function groupByCategory<TEntry extends InsertEntry>(\n  entries: readonly TEntry[],\n  preferred: readonly string[] = []\n): InsertGroup<TEntry>[] {\n  const groups = new Map<string, TEntry[]>();\n  for (const entry of entries) {\n    const bucket = groups.get(entry.category);\n    if (bucket === undefined) groups.set(entry.category, [entry]);\n    else bucket.push(entry);\n  }\n\n  // Ranked first, in the order declared; then everything else as it arrived.\n  // `preferred` may name categories nothing claims, so it is filtered against\n  // what is actually present rather than trusted to describe this catalogue.\n  const ranked = preferred.filter(category => groups.has(category));\n  const rest = [...groups.keys()].filter(\n    category => !ranked.includes(category)\n  );\n\n  return [...ranked, ...rest].map(category => ({\n    category,\n    entries: groups.get(category) ?? [],\n  }));\n}\n\n/**\n * The groups the Add panel draws, in its order: the categories the host ranks\n * (the library's own), then the site's components, then any other category a\n * plugin declared, then the blocks that declared none.\n *\n * Derived from {@link groupByCategory} rather than grouped again, so the two\n * cannot disagree about which entries share a heading; this only decides where\n * the two headings the panel itself names sit. The components follow the\n * ranked categories because they are what an author reaches for next once the\n * basic blocks are passed. The uncategorised go last, because \"More blocks\" is\n * a remainder and reads as one only at the end.\n */\nexport function paletteGroups<TEntry extends InsertEntry>(\n  entries: readonly TEntry[],\n  preferred: readonly string[] = [],\n  blockOrder: readonly string[] = []\n): InsertGroup<TEntry>[] {\n  const groups = groupByCategory(entries, [\n    ...preferred,\n    COMPONENT_CATEGORY,\n  ]).map(group => ({\n    ...group,\n    entries: inBlockOrder(group.entries, blockOrder),\n  }));\n  return [\n    ...groups.filter(group => group.category !== UNCATEGORISED),\n    ...groups.filter(group => group.category === UNCATEGORISED),\n  ];\n}\n\n/**\n * A group's entries with the blocks the host ranks first, in its order, and\n * everything else after them as it arrived (by label). A sort that keeps\n * ties in place, so a block's variations stay right behind it.\n */\nfunction inBlockOrder<TEntry extends InsertEntry>(\n  entries: readonly TEntry[],\n  blockOrder: readonly string[]\n): TEntry[] {\n  if (blockOrder.length === 0) return [...entries];\n  const rank = new Map(blockOrder.map((name, index) => [name, index]));\n  const rankOf = (entry: TEntry): number =>\n    (entry.kind === \"block\" ? rank.get(entry.blockName) : undefined) ??\n    blockOrder.length;\n  return [...entries].sort((a, b) => rankOf(a) - rankOf(b));\n}\n\n/**\n * The words a category's heading is drawn with.\n *\n * The library's category ids are words for code (\"content\"), so the ones it\n * declares are named as an author reads them; \"content\" is \"Text\" because that\n * is what the blocks under it are. The two groups the panel itself makes are\n * named here too. A plugin's category is a free string it chose to be read,\n * so it is drawn as written.\n */\nexport function categoryHeading(category: string): string {\n  return Object.hasOwn(CATEGORY_HEADINGS, category)\n    ? (CATEGORY_HEADINGS[category] ?? category)\n    : category;\n}\n\n/**\n * The headings {@link categoryHeading} names, keyed by category id. Read with\n * `Object.hasOwn` because a category is a plugin's free string, and a plain\n * object would answer \"constructor\" with an inherited function.\n */\nconst CATEGORY_HEADINGS: Readonly<Record<string, string>> = {\n  layout: \"Layout\",\n  content: \"Text\",\n  // What a template draws of the entry itself.\n  entry: \"Entry\",\n  media: \"Media\",\n  interactive: \"Interactive\",\n  // The two groups the panel makes are named with the editor's words.\n  [COMPONENT_CATEGORY]: `Your ${EDITOR_WORDS.components.toLowerCase()}`,\n  [UNCATEGORISED]: `More ${EDITOR_WORDS.blocks.toLowerCase()}`,\n};\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 * 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 * 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 * 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 * 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 * 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 * 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 * An Accordion's Icon, chosen in its Content tab: \"+ / −\", \"Chevron\" or\n * \"None\".\n *\n * Which icon the questions show is what the block shows, so it is a Content\n * choice, though it writes a style value: the accordion's own\n * `disclosureIcon` at its base values, whatever device or state the Style\n * tab is editing, as a Gallery's Columns tiles write its grid. How the icon\n * sits (Icon position) stays in Style.\n *\n * What the tiles read is the accordion's own base value, read as the engine\n * reads a keyword, else the block's default; a stored \"browser\", which is no\n * longer offered, draws the plus (`disclosure.ts`), so it reads as one.\n *\n * @module accordion-icon\n */\nimport {\n  asciiLower,\n  BASE_BREAKPOINT,\n  decodeIdentifier,\n  getBlock,\n  trimCssWhitespace,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { chainedStyleOp } from \"../../canvas/columns-layout\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { readStyleValue, type StyleAddress } from \"../../styles/style-values\";\n\n/** The Accordion's registered name. */\nexport const ACCORDION_BLOCK = \"core/accordion\";\n\n/** The icons the Content tab offers, in its order. */\nexport const ACCORDION_ICONS = [\"plus\", \"chevron\", \"none\"] as const;\n\n/** One of {@link ACCORDION_ICONS}. */\nexport type AccordionIcon = (typeof ACCORDION_ICONS)[number];\n\n/** What each icon is called. */\nexport const ACCORDION_ICON_WORDS: Readonly<Record<AccordionIcon, string>> = {\n  plus: \"+ / −\",\n  chevron: \"Chevron\",\n  none: \"None\",\n};\n\n/** The style key the choice writes. */\nconst PROPERTY = \"disclosureIcon\";\n\n/** Where the choice writes: the accordion's own base values. */\nconst ADDRESS: StyleAddress = {\n  state: \"base\",\n  breakpoint: BASE_BREAKPOINT,\n  property: PROPERTY,\n  path: [],\n};\n\n/** A stored keyword as one of the offered icons, if it reads as one. */\nfunction offeredIcon(value: unknown): AccordionIcon | undefined {\n  if (typeof value !== \"string\") return undefined;\n  const keyword = asciiLower(decodeIdentifier(trimCssWhitespace(value)));\n  // The browser's marker is no longer drawn: a stored one draws the plus.\n  if (keyword === \"browser\") return \"plus\";\n  return ACCORDION_ICONS.find(each => each === keyword);\n}\n\n/** The icon the block's own defaults draw, read from its definition. */\nfunction defaultIcon(type: string): AccordionIcon | undefined {\n  const base = getBlock(type)?.baseStyles?.base?.[BASE_BREAKPOINT];\n  return offeredIcon(base?.[PROPERTY]);\n}\n\n/**\n * The icon the tiles show as chosen: the accordion's own base value, else\n * the one reaching it from elsewhere at its base values (a shared style it\n * wears, read from the canvas's cascade by the caller), else its default.\n * `undefined` where the one in force is not an offered icon (a CSS-wide\n * keyword stored by hand), so no tile claims it.\n */\nexport function accordionIconOf(\n  node: BlockNode,\n  inherited?: string\n): AccordionIcon | undefined {\n  const stored = readStyleValue(node.styles, ADDRESS);\n  if (stored !== undefined) return offeredIcon(stored);\n  return inherited === undefined\n    ? defaultIcon(node.type)\n    : offeredIcon(inherited);\n}\n\n/** Choosing an icon, as ONE op; `null` where it changes nothing. */\nexport function planAccordionIcon(\n  node: BlockNode,\n  icon: AccordionIcon\n): BuilderOp | null {\n  return chainedStyleOp(node, [{ address: ADDRESS, value: icon }]);\n}\n\n/**\n * Removing the accordion's own icon, as ONE op, so what a shared style or\n * the block's default sets shows again; `null` where it holds none.\n */\nexport function planAccordionIconReset(node: BlockNode): BuilderOp | null {\n  return chainedStyleOp(node, [{ address: ADDRESS, value: null }]);\n}\n\n/** Whether the accordion stores an icon of its own, for its section's dot. */\nexport function accordionIconHoldsValue(node: BlockNode): boolean {\n  return readStyleValue(node.styles, ADDRESS) !== undefined;\n}\n","/**\n * The prop types the Content tab has a control for.\n *\n * Its own module, free of React, so the inspection (`inspector.ts`) can say\n * which props are supported from this one list while the controls themselves\n * live in `content-controls.tsx`, which is typed as a record over exactly\n * these names: adding a type here without a control, or a control without a\n * type, fails to compile.\n *\n * @module content-control-types\n */\n\nexport const CONTENT_CONTROL_TYPES = [\n  \"text\",\n  \"textarea\",\n  \"url\",\n  \"number\",\n  \"checkbox\",\n  \"select\",\n  \"media\",\n  \"icon\",\n  \"richText\",\n  \"array\",\n  \"relation\",\n  // The blocks field an Entry content block draws, among its template's\n  // collection's.\n  \"entryField\",\n] as const;\n\nexport type ContentControlType = (typeof CONTENT_CONTROL_TYPES)[number];\n\n/** Whether the Content tab has a control for a prop of this type. */\nexport function hasContentControl(type: string): type is ContentControlType {\n  return (CONTENT_CONTROL_TYPES as readonly string[]).includes(type);\n}\n","/**\n * A Gallery's pictures, as the editor adds and names them.\n *\n * A gallery holds real Image blocks, so adding pictures is inserting Image\n * children, each made as any new Image is (its block's version and defaults)\n * with the library file's id: nothing else is invented. Every add from the\n * Content tab, the canvas's empty state and a drop of files goes through\n * {@link addPicturesOps}, so the three store alike.\n *\n * A picture inside a gallery is read here too: its place among the gallery's\n * pictures, the gallery's name and what the gallery says a click does, for\n * the inspector's title and the picture's \"When clicked\".\n *\n * @module gallery-pictures\n */\nimport {\n  findNode,\n  getBlock,\n  locateNode,\n  makeNode,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport { whenClickedOf } from \"@nextlyhq/blocks-react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { authoredName } from \"../../panels/layers/layers\";\n\n/** The block whose pictures these are. */\nexport const GALLERY_BLOCK = \"core/gallery\";\n\n/** The slot a gallery holds its pictures in. */\nconst PICTURES_SLOT = \"children\";\n\n/** What a gallery is called where the author has not named it. */\nconst GALLERY_WORD = \"Gallery\";\n\n/** Whether a node is a gallery. */\nexport function isGallery(node: BlockNode | undefined): boolean {\n  return node?.type === GALLERY_BLOCK;\n}\n\n/**\n * The block a picture is, read from the gallery's own definition: the one\n * block its slot allows. `undefined` where the gallery is not registered or\n * allows anything other than exactly one block.\n */\nfunction pictureBlockOf(gallery: BlockNode) {\n  const allowed = getBlock(gallery.type)?.slots?.[PICTURES_SLOT]?.allow;\n  const type = allowed?.length === 1 ? allowed[0] : undefined;\n  return type === undefined ? undefined : getBlock(type);\n}\n\n/**\n * The ops that add one picture per library file to a gallery, in the order\n * given, after the pictures it holds: one insert each, for ONE step of the\n * history when applied together. Empty for no files; `null` where the node\n * is not a gallery or its picture block is not known.\n */\nexport function addPicturesOps(\n  document: BlockDocument,\n  galleryId: string,\n  mediaIds: readonly string[]\n): BuilderOp[] | null {\n  const gallery = findNode(document.nodes, galleryId);\n  if (gallery === undefined || !isGallery(gallery)) return null;\n  const picture = pictureBlockOf(gallery);\n  if (picture === undefined) return null;\n  const have = gallery.slots?.[PICTURES_SLOT]?.length ?? 0;\n  const defaults = (picture.defaultProps ?? {}) as Record<string, unknown>;\n  return mediaIds.map((mediaId, offset) => ({\n    kind: \"insert\" as const,\n    node: makeNode(picture.name, picture.version, {\n      ...structuredClone(defaults),\n      mediaId,\n    }),\n    at: { parentId: galleryId, slot: PICTURES_SLOT, index: have + offset },\n  }));\n}\n\n/**\n * Add several library files to a gallery as ONE step: one Image each, in\n * the order given. Answers whether they landed; a lock or a node that is no\n * gallery refuses the whole add.\n */\nexport function addPicturesTo(\n  editor: Pick<EditorState, \"document\" | \"applyAll\">,\n  galleryId: string,\n  mediaIds: readonly string[]\n): boolean {\n  const ops = addPicturesOps(editor.document, galleryId, mediaIds);\n  if (ops === null || ops.length === 0) return false;\n  return editor.applyAll(ops) !== null;\n}\n\n/**\n * Whether a lock keeps a gallery's pictures as they are: asked of one\n * picture's add, through the same question `apply` asks.\n */\nexport function picturesHeld(\n  editor: Pick<EditorState, \"document\" | \"lockRefusalFor\">,\n  galleryId: string\n): boolean {\n  const ops = addPicturesOps(editor.document, galleryId, [\"held\"]);\n  return ops === null || editor.lockRefusalFor(ops) !== undefined;\n}\n\n/** What a click on a gallery's pictures does, as the gallery says. */\nexport type GalleryChoice = \"nothing\" | \"enlarge\";\n\n/** A picture inside a gallery, as the inspector names and reads it. */\nexport interface GalleryPicture {\n  readonly galleryId: string;\n  /** Its place among the gallery's pictures, from 1. */\n  readonly position: number;\n  /** The gallery's own name, or \"Gallery\". */\n  readonly galleryName: string;\n  /** What the gallery says a click on its pictures does. */\n  readonly galleryChoice: GalleryChoice;\n}\n\n/**\n * The gallery's \"When clicked\", read as its pictures follow it: the stored\n * choice through `whenClickedOf`, the one reading of a click, and Nothing\n * for anything a gallery does not offer.\n */\nfunction galleryChoiceOf(gallery: BlockNode): GalleryChoice {\n  return whenClickedOf(gallery.props) === \"enlarge\" ? \"enlarge\" : \"nothing\";\n}\n\n/** The picture a node is inside its gallery, or `undefined` outside one. */\nexport function galleryPictureOf(\n  document: BlockDocument,\n  nodeId: string\n): GalleryPicture | undefined {\n  const located = locateNode(document.nodes, nodeId);\n  const gallery = located?.parent;\n  if (located === undefined || gallery === undefined) return undefined;\n  if (!isGallery(gallery) || located.slot !== PICTURES_SLOT) return undefined;\n  return {\n    galleryId: gallery.id,\n    position: located.index + 1,\n    galleryName: authoredName(gallery) ?? GALLERY_WORD,\n    galleryChoice: galleryChoiceOf(gallery),\n  };\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 an author calls a stored key and a block's prop.\n *\n * Its own module, free of React, so the editor's panels and a server answer\n * naming a block's props use one rule: the inspector re-exports it, and the\n * server-safe `@nextlyhq/builder/ops` entry offers it.\n *\n * @module prop-label\n */\nimport type { PropSchema } from \"@nextlyhq/blocks-engine\";\n\n/**\n * A stored key as a human reads it: `backgroundColor` becomes \"Background color\".\n *\n * Here rather than in a panel because both panels label the same way and from\n * the same kind of key — a prop name on the content tab, a catalog key on the\n * style tab — and two spellings of one rule would drift the first time either\n * learned about an acronym or a digit.\n */\nexport function fieldLabel(name: string): string {\n  const spaced = name\n    .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n    .replace(/[-_]+/g, \" \")\n    .trim();\n  const label = spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n  // The editor's spelling, which its own words (\"Colour for\", the Colour\n  // form) already use: a key's American \"color\" read beside them as the same\n  // word spelled two ways in one panel.\n  return label.replace(/\\b([Cc])olor\\b/g, \"$1olour\");\n}\n\n/**\n * What an author calls a prop: the label its block gives it, or its name,\n * spaced and capitalised, when the block gives none.\n */\nexport function propLabel(name: string, schema: PropSchema): string {\n  const given = schema.label;\n  return typeof given === \"string\" && given.trim() !== \"\"\n    ? given\n    : fieldLabel(name);\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 cascade behind the page, for chrome that has to say where a value came from.\n *\n * A control showing \"you set this here\" or \"this comes from `.card`\" or \"this\n * comes from your desktop setting\" is answering a question only the compiler can\n * answer: it has already settled tier order, both breakpoint axes, states\n * joining the base rules, refused values, descendant selectors and specificity.\n * `styleProvenance` reads that answer. This is what fetches it.\n *\n * ## Why the compiler runs a SECOND time here\n *\n * The page the canvas paints is compiled inside `PageRenderer`, and the panel\n * sits outside it. Three shapes were available and this is the one that was\n * ruled on:\n *\n * - Hoisting the compile above the canvas and handing it the finished sheet\n *   compiles once, but the canvas only REUSES a ready-made sheet while its\n *   stamps match. Should they ever drift it recompiles silently, and the\n *   restructure is paid for with nothing left to show and no test that notices.\n * - Having `PageRenderer` report what it compiled is correct by construction,\n *   and puts an editor-only output into the component that renders published\n *   pages — arriving a frame late, so a control would show the previous block's\n *   answer after every click.\n * - Asking again costs a second compile and leaves the render path untouched.\n *   Measured, a hundred-block page compiles in about 1.6ms, so the whole editor\n *   pays roughly three milliseconds per committed edit instead of one and a\n *   half.\n *\n * The deciding argument is the blast radius rather than the cost. Nothing here\n * can change what the canvas paints or what a published page serves; if this is\n * wrong, the thing that is wrong is the indicator, which is the thing under\n * test.\n *\n * **This is not a second implementation.** It calls the same exported function\n * the renderer calls, with the same inputs. The rule that forbids computing one\n * answer twice is about two implementations of a question, not two invocations\n * of one — and the resolver is exported precisely so a consumer can ask.\n *\n * ## The document is NOT pruned first, deliberately\n *\n * `resolvePageStyles` documents a precondition: hand it the document that will\n * RENDER, because a raw one emits rules for nodes a reader withholds and\n * publishes the colours, fonts and `url(...)` of a block nobody was served.\n *\n * That precondition guards PUBLISHING, and nothing here publishes. The sheet is\n * discarded on the next line; only the trace is kept, and it is read in the\n * editor by the panel describing the block an author has selected.\n *\n * Pruning would also make the answer worse where it differs. A node hidden at\n * the breakpoint being edited is still selectable from the Layers panel, and it\n * still has authored values an author is entitled to an explanation of.\n * Compiled from the pruned tree it would have no entries at all, and every one\n * of its controls would report having been set by nobody.\n *\n * @module style-trace\n */\n\nimport type {\n  BlockDocument,\n  DefinitionsById,\n  DocumentLimits,\n  RemotePatternInput,\n  SiteSheetInput,\n  StyleCompileContext,\n} from \"@nextlyhq/blocks-engine\";\nimport type { BlockResolver, PageStyleCascade } from \"@nextlyhq/blocks-react\";\nimport { pageStyleTrace as compileTrace } from \"@nextlyhq/blocks-react\";\n\n/**\n * The declarations the compiler wrote for this document, in cascade order.\n *\n * `undefined` when no compile produced one, which is a real answer rather than a\n * failure — and callers must not read it as \"nothing is authored\". A control\n * told that would report every value as coming from nowhere, which is worse than\n * showing no indicator at all.\n *\n * The compile itself lives in `@nextlyhq/blocks-react`, and that is not\n * indirection for its own sake. Named classes, block bases, the token prefix and\n * the fetch predicate are each reconciled from TWO tiers — the route's context\n * and the site's — by a function private to that package. A context assembled\n * here instead compiles a cascade the page never had, and the shortfall is\n * silent: measured, with only `breakpoints` passed no class declaration reaches\n * the trace at all, so every value arriving from a named class reports as set by\n * nobody and the \"Inherited from `.card`\" indicator can never appear.\n */\nexport function pageStyleTrace(\n  document: BlockDocument,\n  styleContext: StyleCompileContext | undefined,\n  site: SiteSheetInput | undefined,\n  options?: {\n    readonly remotePatterns?: readonly RemotePatternInput[];\n    /**\n     * The resolver the CANVAS is rendering with, when the host named one.\n     *\n     * Forwarded rather than left to the default, because a custom resolver\n     * decides two things the trace depends on: a block's base styles, and\n     * whether a node draws at all. A canvas rendered with one and a trace\n     * compiled without it disagree about which declarations exist, so an origin\n     * goes missing or is attributed to the wrong tier.\n     *\n     * Omitted, the compile falls back to the registry `PageRenderer` uses when a\n     * host names none — the same default, not a second one.\n     */\n    readonly blocks?: BlockResolver;\n    /**\n     * The caps the canvas prepares and compiles under.\n     *\n     * The fourth input of this kind, after the site tier, the fetch policy and\n     * the resolver — every one of them a field the renderer reads and this\n     * wrapper silently defaulted. They fail the same way: the trace describes a\n     * compile the page never ran, and says so confidently.\n     */\n    readonly limits?: DocumentLimits;\n    /**\n     * The component definitions the canvas resolves instances against.\n     *\n     * The fifth input of the kind `limits` describes, and it fails the same\n     * way: a trace compiled without them leaves every instance unresolved, so\n     * the composed nodes the canvas draws — and every declaration they carry\n     * — are missing from the cascade the inspector reads its provenance from.\n     */\n    readonly definitions?: DefinitionsById;\n  }\n): PageStyleCascade | undefined {\n  return compileTrace({\n    document,\n    styleContext,\n    site,\n    ...(options?.remotePatterns === undefined\n      ? {}\n      : { remotePatterns: options.remotePatterns }),\n    ...(options?.blocks === undefined ? {} : { blocks: options.blocks }),\n    ...(options?.limits === undefined ? {} : { limits: options.limits }),\n    ...(options?.definitions === undefined\n      ? {}\n      : { definitions: options.definitions }),\n  });\n}\n","\"use client\";\n\n/**\n * The editor's command palette: one keyboard route to everything the host can do.\n *\n * The palette owns the SURFACE — the hotkey, the dialog, the search, the keyboard model — and\n * knows nothing about what the commands are. Panels, navigation and document edits are all the\n * host's vocabulary, and a palette that reached for them would need to import the shell's panel\n * list, the app's routes and the op store, which is three couplings for a component whose job is\n * to show a list and run what was chosen.\n *\n * So commands arrive as data. That also makes the interesting states reachable in a test without\n * mounting an editor: an empty registry, a command whose `when` is false, a command that throws.\n *\n * ## What is deliberately NOT here\n *\n * Undo, redo and block operations are absent because there is nothing to call. `applyOp` derives\n * an edit's inverse, and no history stack stores one — so a palette entry named \"Undo\" would have\n * to own the history itself, which is the wrong owner and would have to be taken back out. Block\n * operations additionally need a target node, and no selection model exists yet. Both are host\n * concerns the moment they exist, and this component needs no change to gain them: they arrive as\n * more commands.\n */\nimport {\n  CommandDialog,\n  CommandGroup,\n  CommandInput,\n  CommandItem,\n  CommandList,\n  CommandShortcut,\n  commandDefaultFilter,\n  ShortcutScope,\n  useCommandHighlight,\n  useShortcuts,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\nimport { flushSync } from \"react-dom\";\n\nimport { deepActiveElement } from \"../canvas/dom-kind\";\n\nimport { useModalKeyboardHold } from \"./modal-keyboard-hold\";\nimport { useShellIsActive } from \"./shell-active\";\n\n/**\n * The keystroke that OPENS the palette, and the one nearly every editor uses for it.\n *\n * Opening only, never toggling. `CommandDialog` renders cmdk's `<Command>` internally and\n * forwards no props to it, so its vim bindings cannot be turned off from here — and those\n * bindings claim Ctrl+K for \"move selection up\" and call `preventDefault()`. The shortcut manager\n * skips an event another handler already prevented, so on Windows and Linux a toggle would open\n * the palette and then refuse to close it. Escape closes, which is what Radix already gives us\n * and what VS Code does. Better to not make the promise than to keep it on one platform.\n *\n * @experimental\n */\nexport const COMMAND_PALETTE_KEYS = \"mod+k\";\n\n/**\n * One entry in the palette.\n *\n * `id` rather than the label as the identity, because labels are user-facing text that gets\n * reworded, and a React key that changes on a copy edit remounts the row and drops its state.\n *\n * @experimental\n */\nexport interface BuilderCommand {\n  /**\n   * Stable across renames, and UNIQUE across the assembled list.\n   *\n   * Uniqueness is required rather than merely expected: it is the React key and cmdk's selection\n   * identity, and two rows sharing it are both marked selected, with Enter running the first\n   * whichever the user chose. A host that concatenates registries is where this happens.\n   */\n  id: string;\n  /** What the user reads. */\n  label: string;\n  /** Heading this command is listed under. Ungrouped commands are listed first, without one. */\n  group?: string;\n  /**\n   * Extra words that should match this command.\n   *\n   * A palette is only as good as its synonyms: someone looking for \"layers\" should find \"Outline\"\n   * without knowing what it was named.\n   */\n  keywords?: readonly string[];\n  /** The shortcut to DISPLAY, if the host binds one elsewhere. Rendering it here binds nothing. */\n  shortcut?: string;\n  /** Checked whenever the list is built; a command that returns false is not offered. */\n  when?: () => boolean;\n  /** A small glyph before the label. Decorative: the label alone names the row. */\n  icon?: React.ReactNode;\n  /**\n   * Said after the label, more quietly: where a block will go, what a row is, the shortcut's\n   * neighbour. Not searched — what the search matches is the label and `keywords`.\n   */\n  detail?: React.ReactNode;\n  /**\n   * The footer's word for choosing this row while it is highlighted: \"Add\", \"Select\", \"Open\".\n   * \"Run\" when absent, which is what a command does.\n   */\n  verb?: string;\n  /** Runs when the command is chosen. The palette closes first. */\n  run: () => void;\n}\n\n/**\n * How one named group behaves while the author searches.\n *\n * @experimental\n */\nexport interface CommandGroupOptions {\n  /** The group's heading, as the commands name it in `group`. */\n  name: string;\n  /** At most this many matches, best first. Every match when absent. */\n  limit?: number;\n  /**\n   * The host has matched these already — a search made on the server — so each is shown as\n   * given, in the host's order. Scoring them again here could drop a row the server matched on\n   * something the label does not show.\n   */\n  matched?: boolean;\n  /**\n   * Said in the group's place while its results are on their way, or could not be had\n   * (\"Searching pages…\"). Shown even when the group has no rows yet, so the author can tell a\n   * search still running from one that found nothing.\n   */\n  status?: string;\n}\n\n/**\n * What the host gives the palette.\n *\n * @experimental\n */\nexport interface CommandPaletteProps {\n  /**\n   * Everything the palette can run.\n   *\n   * Order within a group is preserved WHILE THE SEARCH IS EMPTY.\n   *\n   * Once the user types, the groups STAY, each under its heading and in the same order, and the\n   * matches inside each are ranked best first by cmdk's scorer over the label and synonyms. The\n   * groups are kinds of thing (blocks to add, blocks on the page, pages, commands), and an author\n   * reads a result by its kind before its rank. cmdk keys SELECTION on an item's value, so the\n   * value here is the `id` alone — anything richer is a concatenation of free-form fields and two\n   * commands can collide, which makes the wrong one run.\n   */\n  commands: readonly BuilderCommand[];\n  /**\n   * Controls the dialog. Omit both to let the palette own its own open state, which is the usual\n   * case; pass them when the host needs to open it from somewhere else as well.\n   */\n  open?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /**\n   * Named groups' order and their behaviour while searching. A group listed here comes in this\n   * order; one that is not follows, in the order its commands first appear.\n   */\n  groups?: readonly CommandGroupOptions[];\n  /**\n   * Told the search as the author types it, trimmed, for a host that searches elsewhere too (the\n   * site's pages, on the server). Its answers come back as commands in a `matched` group.\n   */\n  onSearchChange?: (query: string) => void;\n  /** Placeholder for the search field. */\n  placeholder?: string;\n  /** Shown when nothing matches what was typed. Given the search, so it can quote it. */\n  emptyMessage?: React.ReactNode | ((query: string) => React.ReactNode);\n  /**\n   * Whether the palette may be opened at all.\n   *\n   * Defaults to whether the surrounding shell is interactive, and to `true` outside one. The\n   * dialog PORTALS to the document body, so it escapes the `hidden`/`inert` wrapper the shell\n   * puts its slots behind below its minimum width — without this it would float, fully\n   * interactive, over the narrow-screen notice.\n   *\n   * NARROWS the shell's answer rather than replacing it: passing `false` disables the palette,\n   * and passing `true` does NOT re-enable one inside a shell that has taken itself out of\n   * service. A host condition of its own — `enabled={!readOnly}` — is therefore safe to pass\n   * without also re-deriving the shell's minimum width, which would be a second implementation of\n   * a question the shell already answers.\n   */\n  enabled?: boolean;\n}\n\n/**\n * Commands the host is currently offering, grouped for display.\n *\n * `when` is evaluated here rather than at registration, so a command that becomes available while\n * the palette is open appears on the next render instead of being fixed at mount.\n *\n * NAMED groups keep the order of first appearance rather than being sorted. A palette that\n * reorders itself between openings makes muscle memory impossible, and alphabetical order is not\n * the order anyone thinks in.\n *\n * Ungrouped commands are partitioned to the FRONT rather than taking their place in that order.\n * They render without a heading, so leaving them where they first appeared would let a host that\n * happened to list a grouped command first push a headingless run of items between two named\n * groups, where they read as belonging to the group above them.\n */\nfunction groupAvailable(\n  commands: readonly BuilderCommand[],\n  declared: readonly CommandGroupOptions[] = []\n): { group?: string; commands: BuilderCommand[] }[] {\n  // Declared groups first, in their order, so a group the host has not filled yet (a search still\n  // on its way) already holds its place.\n  const namedOrder: string[] = declared.map(options => options.name);\n  const byGroup = new Map<string | undefined, BuilderCommand[]>(\n    namedOrder.map(name => [name, []])\n  );\n\n  for (const command of commands) {\n    if (command.when && !command.when()) continue;\n    let bucket = byGroup.get(command.group);\n    if (!bucket) {\n      bucket = [];\n      byGroup.set(command.group, bucket);\n      if (command.group !== undefined) namedOrder.push(command.group);\n    }\n    bucket.push(command);\n  }\n\n  const ungrouped = byGroup.get(undefined);\n  return [\n    ...(ungrouped ? [{ group: undefined, commands: ungrouped }] : []),\n    ...namedOrder.map(group => ({\n      group,\n      commands: byGroup.get(group) ?? [],\n    })),\n  ];\n}\n\n/**\n * The palette.\n *\n * Must be rendered inside the shell's `ShortcutProvider` — `useShortcuts` throws otherwise, which\n * is the right failure: a palette that silently registered nothing would look mounted and never\n * open.\n *\n * @experimental\n */\nexport function CommandPalette(props: CommandPaletteProps): React.JSX.Element {\n  return <PaletteSurface {...props} />;\n}\n\n/**\n * The palette's hold on the keyboard while it is open.\n *\n * Through the shared hold rather than its own `useShortcuts`, so a dialog the\n * editor raises and this palette cannot end up disagreeing about depth — which\n * is the part of this that is easy to get wrong and impossible to notice.\n *\n * Separate from the OPENER, and that is the point. Elevating the opener too\n * would put `mod+k` above a blocking layer the host already has up — another\n * modal's — and the palette would open over it, since the manager resolves the\n * deeper exact binding first. The opener stays ambient so an existing modal can\n * refuse it; only the hold is elevated, and only while open.\n */\nfunction ModalKeyboardHold({ active }: { active: boolean }): null {\n  useModalKeyboardHold(\"command-palette-modal\", active);\n  return null;\n}\n\n/** One group as the list draws it: its rows, and what it says in their place. */\ninterface ShownGroup {\n  group?: string;\n  commands: BuilderCommand[];\n  status?: string;\n}\n\n/** What the group says in its rows' place: only while it has no rows. */\nfunction statusShown(shown: ShownGroup): string | undefined {\n  return shown.commands.length > 0 ? undefined : shown.status;\n}\n\n/**\n * What a search shows of each group: its matches, best first, up to its limit.\n *\n * Ranked by the same scorer the palette has always used, over the label and synonyms, so a\n * group's order is cmdk's answer rather than a second one. A group the host matched already\n * keeps every row in the host's order. A group with neither rows nor a status is left out, so\n * no heading stands over nothing.\n */\nfunction searchGroups(\n  available: readonly { group?: string; commands: BuilderCommand[] }[],\n  query: string,\n  declared: readonly CommandGroupOptions[]\n): ShownGroup[] {\n  return available.flatMap(({ group, commands }) => {\n    const options = declared.find(entry => entry.name === group);\n    const ranked =\n      options?.matched === true\n        ? commands\n        : commands\n            .map((command, index) => ({\n              command,\n              index,\n              score: commandDefaultFilter(searchText(command), query),\n            }))\n            .filter(entry => entry.score > 0)\n            // Ties keep the host's order, so equal matches do not shuffle between keystrokes.\n            .sort((a, b) => b.score - a.score || a.index - b.index)\n            .map(entry => entry.command);\n    const shown =\n      options?.limit === undefined ? ranked : ranked.slice(0, options.limit);\n    if (shown.length === 0 && options?.status === undefined) return [];\n    return [{ group, commands: shown, status: options?.status }];\n  });\n}\n\n/** The words a command is found by: its label and its synonyms. */\nfunction searchText(command: BuilderCommand): string {\n  return [command.label, ...(command.keywords ?? [])].join(\" \");\n}\n\n/**\n * The label, with the typed text in bold where it begins a word.\n *\n * Only there. The scorer also finds letters scattered through a word, and bolding \"he\" inside\n * \"the\" marks a match nobody was looking for; such a row is still offered and ranked, just shown\n * plain. A label whose lower-case form changes length is shown plain too, since the positions\n * found in one would not be positions in the other.\n */\nfunction emphasised(label: string, query: string): React.ReactNode {\n  const lower = label.toLowerCase();\n  const wanted = query.toLowerCase();\n  if (wanted === \"\" || lower.length !== label.length) return label;\n  let at = lower.indexOf(wanted);\n  // Bounded by the label's length: each step moves past the last place found.\n  while (at > 0 && /[\\p{L}\\p{N}]/u.test(label.charAt(at - 1))) {\n    at = lower.indexOf(wanted, at + 1);\n  }\n  if (at === -1) return label;\n  const end = at + wanted.length;\n  return (\n    <>\n      {label.slice(0, at)}\n      <mark className=\"bg-transparent font-semibold text-inherit\">\n        {label.slice(at, end)}\n      </mark>\n      {label.slice(end)}\n    </>\n  );\n}\n\n/** A key, as the footer names it. */\nfunction Key({ children }: { children: React.ReactNode }): React.JSX.Element {\n  return (\n    <kbd className=\"rounded border border-border bg-muted px-1 font-mono text-[11px] text-muted-foreground\">\n      {children}\n    </kbd>\n  );\n}\n\n/**\n * The keys that work here, with the highlighted row's own verb for Enter.\n *\n * Reads the highlight from the palette rather than keeping a copy: the palette moves it for\n * reasons this never sees (a pointer, a filter), and a copy would name the wrong row.\n */\nfunction PaletteFooter({\n  verbs,\n}: {\n  verbs: ReadonlyMap<string, string>;\n}): React.JSX.Element {\n  const highlighted = useCommandHighlight();\n  const verb = verbs.get(highlighted);\n  return (\n    <div className=\"flex items-center gap-4 border-t border-border px-3 py-2 text-xs text-muted-foreground\">\n      {verb === undefined ? null : (\n        <>\n          <span>\n            <Key>↑</Key> <Key>↓</Key> Move\n          </span>\n          <span>\n            <Key>↵</Key> {verb}\n          </span>\n        </>\n      )}\n      <span>\n        <Key>Esc</Key> Close\n      </span>\n    </div>\n  );\n}\n\n/**\n * One group's heading and rows, or what it says in their place.\n *\n * A status shows beside the rows rather than instead of them only when there are none: a search\n * still running says so, and one that failed says that, without hiding what is already there.\n */\nfunction PaletteGroup({\n  shown,\n  query,\n  choose,\n}: {\n  shown: ShownGroup;\n  query: string;\n  choose: (command: BuilderCommand) => void;\n}): React.JSX.Element {\n  return (\n    <CommandGroup heading={shown.group}>\n      {/* Drawn in the group's place, and hidden from a screen reader, which\n          hears it from the palette's own status line outside the list: a\n          listbox may hold only options and their groups. */}\n      {statusShown(shown) === undefined ? null : (\n        <div\n          aria-hidden=\"true\"\n          className=\"px-3 py-2 text-sm text-muted-foreground\"\n        >\n          {shown.status}\n        </div>\n      )}\n      {shown.commands.map(command => (\n        <CommandItem\n          // The searchable metadata is part of the key, so renaming a command REMOUNTS\n          // its row. cmdk stores an item's keywords when its value is registered and\n          // refreshes them only when that value changes — and the value is the id,\n          // stable by contract. Without this the row shows its new label while cmdk\n          // keeps filtering on the old one, so searching for what is on screen hides it.\n          //\n          // A JSON TUPLE rather than the fields joined by a delimiter, for the reason\n          // the cmdk value has the same shape: joining free-form strings is not\n          // injective. `keywords: [\"open\\u0000settings\"]` and `[\"open\", \"settings\"]`\n          // produce the same delimited string, so that rename would not remount and\n          // cmdk would keep the old metadata — the defect this key exists to prevent.\n          key={JSON.stringify([\n            command.id,\n            command.label,\n            command.keywords ?? [],\n          ])}\n          // The id ALONE, because cmdk keys selection on this value and a concatenation\n          // of free-form fields is not injective: `keywords: [\"page\"], id: \"settings x\"`\n          // and `keywords: [\"page\", \"settings\"], id: \"x\"` produce the same string, and\n          // cmdk then highlights both rows and activates the first whichever is chosen.\n          // What the search should MATCH goes to `keywords`, which cmdk reads separately.\n          //\n          // ENCODED because cmdk trims the value before using it as the identity, so\n          // `\"save\"` and `\"save \"` — distinct ids by the type's contract — would collide\n          // again through normalisation rather than through concatenation. The quotes\n          // `JSON.stringify` adds sit at both ends, so there is no edge whitespace for the\n          // trim to reach.\n          //\n          // `JSON.stringify` rather than `encodeURIComponent`, which is not TOTAL over the\n          // strings `id: string` admits: a lone UTF-16 surrogate — `\"\\ud800\"`, which\n          // survives a JSON round trip — raises `URIError` and takes the whole palette\n          // down during render. Well-formed stringify escapes it instead.\n          value={JSON.stringify(command.id)}\n          keywords={[command.label, ...(command.keywords ?? [])]}\n          onSelect={() => choose(command)}\n        >\n          {command.icon === undefined ? null : (\n            <span\n              aria-hidden=\"true\"\n              className=\"flex shrink-0 items-center text-muted-foreground\"\n            >\n              {command.icon}\n            </span>\n          )}\n          <span className=\"min-w-0 flex-1 truncate\">\n            {emphasised(command.label, query)}\n          </span>\n          {command.detail === undefined ? null : (\n            <span className=\"max-w-[45%] shrink-0 truncate text-xs text-muted-foreground\">\n              {command.detail}\n            </span>\n          )}\n          {command.shortcut && (\n            <CommandShortcut>{command.shortcut}</CommandShortcut>\n          )}\n        </CommandItem>\n      ))}\n    </CommandGroup>\n  );\n}\n\n/**\n * What the list shows for this search, and the footer's verb for each row.\n *\n * Every available command, grouped, and refused when two share an id. While\n * searching, each group's matches (see {@link searchGroups}); otherwise every\n * group that has a row.\n */\nfunction shownGroups(\n  commands: readonly BuilderCommand[],\n  declared: readonly CommandGroupOptions[],\n  query: string\n): { groups: ShownGroup[]; verbs: ReadonlyMap<string, string> } {\n  const searching = query.length > 0;\n  // Grouped FIRST, then flattened. Filtering `commands` again along a second path would be a\n  // second answer to \"is this command available\", and the two would agree only until someone\n  // changed one — silently offering a different set while the user is searching, which is the\n  // half nobody looks at.\n  const available = groupAvailable(commands, declared);\n\n  // Refused rather than rendered. A duplicate id makes cmdk run the WRONG command, silently and\n  // only through the keyboard — the failure a caller is least able to see and least likely to\n  // attribute to their registry. Throwing is the same choice `useShortcuts` makes outside a\n  // provider, and for the same reason: a palette that looks mounted and misfires is worse than\n  // one that refuses to mount.\n  //\n  // Over the AVAILABLE list, so a `when` that hides one of a colliding pair is a resolution\n  // rather than a latent fault.\n  const seen = new Set<string>();\n  for (const { commands: groupCommands } of available) {\n    for (const command of groupCommands) {\n      if (seen.has(command.id)) {\n        throw new Error(\n          `CommandPalette received two available commands with the id \"${command.id}\". ` +\n            \"Ids are the selection identity, so a duplicate runs the wrong command.\"\n        );\n      }\n      seen.add(command.id);\n    }\n  }\n  const groups: ShownGroup[] = searching\n    ? searchGroups(available, query, declared)\n    : available.filter(group => group.commands.length > 0);\n  // The footer's verb for each row, by the value cmdk highlights it under.\n  const verbs = new Map(\n    groups.flatMap(group =>\n      group.commands.map(\n        command => [JSON.stringify(command.id), command.verb ?? \"Run\"] as const\n      )\n    )\n  );\n\n  return { groups, verbs };\n}\n\n/**\n * The search text, and a setter that tells a host the trimmed search in the\n * SAME update as the keystroke.\n *\n * Not after the render that shows it: a host's own results (a group marked\n * `matched`, which this palette shows unfiltered) are answers to the search\n * they came from, and told only afterwards the host would leave them on screen\n * under the new search for a render, where Enter could choose one. Told here,\n * the host's change and the new text render together. Read through a ref, so a\n * host passing a fresh function each render changes nothing.\n */\nfunction useSearchText(\n  onSearchChange: ((query: string) => void) | undefined\n): [string, (next: string) => void] {\n  const [search, setSearch] = React.useState(\"\");\n  const listener = React.useRef(onSearchChange);\n  listener.current = onSearchChange;\n  // What the host was last told, so a keystroke that changes only the edge\n  // spaces tells it nothing.\n  const told = React.useRef(\"\");\n  const change = React.useCallback((next: string) => {\n    setSearch(next);\n    const query = next.trim();\n    if (query === told.current) return;\n    told.current = query;\n    listener.current?.(query);\n  }, []);\n  return [search, change];\n}\n\n/** The groups, or the empty message, and the keys that work on them. */\nfunction PaletteList({\n  groups,\n  verbs,\n  query,\n  emptyMessage,\n  choose,\n}: {\n  groups: readonly ShownGroup[];\n  verbs: ReadonlyMap<string, string>;\n  query: string;\n  emptyMessage: CommandPaletteProps[\"emptyMessage\"];\n  choose: (command: BuilderCommand) => void;\n}): React.JSX.Element {\n  const nothing = groups.length === 0;\n  const statuses = groups\n    .map(statusShown)\n    .filter(status => status !== undefined)\n    .join(\" \");\n  const empty = nothing\n    ? typeof emptyMessage === \"function\"\n      ? emptyMessage(query)\n      : emptyMessage\n    : null;\n  return (\n    <>\n      <CommandList>\n        {/* Drawn in the list, and hidden from a screen reader, which hears it\n            from the status line below: a listbox may hold only options and\n            their groups, and one holding only words fails as a list. */}\n        {nothing ? (\n          <div\n            aria-hidden=\"true\"\n            className=\"px-4 py-8 text-center text-sm text-muted-foreground\"\n          >\n            {empty}\n          </div>\n        ) : null}\n        {groups.map((shown, index) => (\n          <React.Fragment\n            key={\n              shown.group === undefined ? \"ungrouped\" : `group:${shown.group}`\n            }\n          >\n            {/* A drawn rule, not a `separator`: a listbox may hold only\n                options and their groups. */}\n            {index > 0 && (\n              <div\n                aria-hidden=\"true\"\n                data-palette-divider=\"\"\n                className=\"my-2 h-px bg-border\"\n              />\n            )}\n            <PaletteGroup shown={shown} query={query} choose={choose} />\n          </React.Fragment>\n        ))}\n      </CommandList>\n      {/* What a group's search is doing, or that nothing was found, said\n          outside the list, where a status may be; mounted before it has\n          anything to say, so the first words are announced. */}\n      <p role=\"status\" className=\"sr-only\">\n        {nothing ? empty : statuses}\n      </p>\n      {nothing ? null : <PaletteFooter verbs={verbs} />}\n    </>\n  );\n}\n\nfunction PaletteSurface({\n  commands,\n  open: controlledOpen,\n  onOpenChange,\n  groups: declaredGroups = [],\n  onSearchChange,\n  placeholder = \"Search commands…\",\n  emptyMessage = \"No matching commands.\",\n  enabled: enabledProp,\n}: CommandPaletteProps): React.JSX.Element {\n  // The shell's own answer, so the width that hides its slots is the width that disables the\n  // palette. `true` outside a shell, which is what a standalone caller wants.\n  const shellIsActive = useShellIsActive();\n  // The prop NARROWS the shell's answer rather than replacing it. A host passing a condition of\n  // its own — `enabled={!readOnly}` — would otherwise re-enable the palette whenever that\n  // condition held, including on a viewport where the shell has hidden everything else, which is\n  // the case this prop exists to cover.\n  const enabled = (enabledProp ?? true) && shellIsActive;\n  const [search, setSearch] = useSearchText(onSearchChange);\n  const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false);\n  const isControlled = controlledOpen !== undefined;\n  // One expression decides whether the palette is showing, so `enabled` cannot be honoured by the\n  // hotkey and ignored by the dialog. A host that disables itself while the palette is already\n  // open closes it by that alone, without needing to drive `open` as well.\n  const open = enabled && (isControlled ? controlledOpen : uncontrolledOpen);\n\n  // Masking the state is not enough: `open` above hides it, but the stored `true` survives, so\n  // re-enabling — a shell widening back past its minimum — would reopen the palette without\n  // anyone having pressed the hotkey. Cleared rather than masked, so closing is permanent.\n  //\n  // A CONTROLLED host owns that state instead, and clearing our copy would leave its `open` still\n  // true and reopen the palette the moment the shell widens. It is told, so its state clears too.\n  React.useEffect(() => {\n    if (enabled) return;\n    setUncontrolledOpen(false);\n    if (isControlled && controlledOpen) onOpenChange?.(false);\n  }, [enabled, isControlled, controlledOpen, onOpenChange]);\n\n  // What had focus when the palette opened, so closing can hand it back. Radix restores focus to\n  // the dialog's TRIGGER, and a palette opened by a keystroke has none — so without this, closing\n  // drops focus onto `<body>` and a keyboard user starts again from the top of the document.\n  const openedFrom = React.useRef<Element | null>(null);\n\n  const setOpen = React.useCallback(\n    (next: boolean) => {\n      if (!isControlled) setUncontrolledOpen(next);\n      onOpenChange?.(next);\n    },\n    [isControlled, onOpenChange]\n  );\n\n  // Recorded on the open TRANSITION, in a layout effect so it happens before Radix moves focus\n  // into the dialog. The transition rather than `setOpen`, because a controlling host opens the\n  // palette by flipping `open` and never calls it.\n  const wasOpen = React.useRef(false);\n  React.useLayoutEffect(() => {\n    const opening = !wasOpen.current && open;\n    wasOpen.current = open;\n    if (!opening) return;\n    // Any focusable ELEMENT. An `<svg tabindex=\"0\">` becomes `activeElement` and is not an\n    // `HTMLElement`, so narrowing here discards a legitimate origin.\n    //\n    // Only when no origin is outstanding. Reopening before the 200ms exit animation finishes\n    // leaves focus inside the dialog that is still unmounting, so capturing then would record the\n    // palette's OWN search input — and by the final close that element is gone, so there is\n    // nothing to restore and focus lands on `<body>`. A completed close clears this, so an\n    // ordinary second opening still records a fresh origin.\n    //\n    // Read through any focused frame, so an origin inside the canvas frame is the control itself\n    // rather than the iframe, whose inner focus the browser restores as it chooses.\n    if (openedFrom.current === null)\n      openedFrom.current = deepActiveElement(document);\n  }, [open]);\n\n  // Radix fires this when it is actually returning focus, which is AFTER the exit animation. A\n  // timer started at close time cannot know that duration — measured against this dialog's\n  // 200ms `animate-out`, the search input is still connected when a zero-delay callback runs, so\n  // focus looks settled, nothing is restored, and it lands on `<body>` once the animation ends.\n  //\n  // Radix's own default is to focus the trigger; this dialog is opened by a keystroke and has\n  // none, so the default resolves to nothing and the event is prevented in favour of the origin.\n  const handleCloseAutoFocus = React.useCallback((event: Event) => {\n    const target = openedFrom.current;\n    openedFrom.current = null;\n    if (!target?.isConnected) return;\n    // `focus` is on the `HTMLOrSVGElement` mixin rather than on `Element`.\n    const refocus = (target as Partial<HTMLOrSVGElement>).focus;\n    if (typeof refocus !== \"function\") return;\n    // Only once nothing else has claimed focus — a command that moved it deliberately wins.\n    // This document's own reading: focus a command put inside a frame shows here as the iframe,\n    // which is not `<body>`, so the command still wins.\n    const active = document.activeElement;\n    if (active && active !== document.body && active.isConnected) return;\n    event.preventDefault();\n    refocus.call(target);\n  }, []);\n\n  // Cleared when the palette shuts, so a stale search never greets the next opening.\n  React.useEffect(() => {\n    if (!open) setSearch(\"\");\n  }, [open, setSearch]);\n\n  // Read through a ref so the binding's `run` never goes stale, without re-registering the layer\n  // on every render — re-registering would move it to the top of its depth and change precedence\n  // for a reason the caller never asked for.\n  const latest = React.useRef({ open, setOpen });\n  latest.current = { open, setOpen };\n\n  useShortcuts(\n    [\n      {\n        keys: COMMAND_PALETTE_KEYS,\n        description: \"Open the command palette\",\n        // `mod+k` carries a non-shift modifier, so the manager lets it fire while the user is\n        // typing. That is what a palette needs: it has to be reachable from inside the very\n        // fields it might act on.\n        run: event => {\n          // The browser binds `mod+k` to the address bar in some hosts, and the palette losing\n          // the keystroke to the chrome is the one failure a user cannot work around.\n          event.preventDefault();\n          // Open, never toggle — see COMMAND_PALETTE_KEYS. Pressing it again while open is a\n          // no-op rather than a close.\n          latest.current.setOpen(true);\n        },\n      },\n    ],\n    {\n      name: \"command-palette\",\n      enabled,\n      // NOT blocking, and at the HOST's depth. The hold while open belongs to\n      // `ModalKeyboardHold` below; an opener that blocked, or that sat deeper than the host,\n      // would answer `mod+k` over a modal the host already has up.\n    }\n  );\n\n  // ONE normalised query decides the mode AND is what the matcher scores against. What it must\n  // NOT do is reach the input: a controlled value that trims rewrites the user's text as they\n  // type, so pressing Space after `open` gives back `open`, the next key produces `opens`, and\n  // `open settings` is unreachable. The raw string stays editable; the normalised one is derived.\n  const query = search.trim();\n  const { groups, verbs } = shownGroups(commands, declaredGroups, query);\n\n  const choose = React.useCallback(\n    (command: BuilderCommand) => {\n      // Closed BEFORE running, and FLUSHED rather than queued.\n      //\n      // What the flush buys is the FOCUS TRAP, not the unmount. Radix keeps the content mounted\n      // for the exit animation either way, so `run()` always executes with the dialog still in\n      // the DOM — but the modal content is trapped only while the dialog is open\n      // (`trapFocus: context.open`), and its close handler always prevents the scope's own\n      // restore. So a synchronous close leaves a mounted, focus-inert dialog, and anything the\n      // command focuses keeps focus.\n      //\n      // Queue the close instead and React batches it: `run()` then executes while the trap is\n      // still armed, and a command that focuses an element outside the palette has focus pulled\n      // straight back inside it.\n      //\n      // Deferring `run()` until the dialog is truly gone would also work and is worse: Radix\n      // dispatches its close-auto-focus from a `setTimeout` after the animation, so every command\n      // would wait out the 200ms `animate-out` before doing anything.\n      flushSync(() => setOpen(false));\n      command.run();\n    },\n    [setOpen]\n  );\n\n  return (\n    <>\n      <ShortcutScope>\n        <ModalKeyboardHold active={open} />\n      </ShortcutScope>\n      <CommandDialog\n        open={open}\n        onOpenChange={setOpen}\n        // Names the search input. cmdk renders a hidden label for the command root and points the\n        // input's `aria-labelledby` at it, so leaving this unset produces an EMPTY label — an\n        // explicit reference to nothing, which stops the placeholder naming the field and leaves\n        // screen-reader users on an unlabelled search control.\n        commandProps={{\n          label: \"Command palette\",\n          // The list is filtered and ranked HERE (`searchGroups`), not by cmdk: a group's limit\n          // and a host's own matches are things cmdk cannot express, and two filters over one\n          // list would disagree about what is offered. The scorer is still cmdk's, given the\n          // label and synonyms only (an item's value is an encoded id, and opaque fragments of it\n          // would surface unrelated commands) and the NORMALISED query, so a whitespace-only\n          // input is no search to anyone.\n          shouldFilter: false,\n        }}\n        contentProps={{ onCloseAutoFocus: handleCloseAutoFocus }}\n        // Visually hidden, but the dialog's accessible name and description all the same: the\n        // search field's placeholder is not a substitute — it names the INPUT, not the dialog that\n        // wraps it. `CommandDialog` draws both from these.\n        title=\"Command palette\"\n        description=\"Search for a command and press Enter to run it.\"\n      >\n        <CommandInput\n          placeholder={placeholder}\n          value={search}\n          onValueChange={setSearch}\n        />\n        <PaletteList\n          groups={groups}\n          verbs={verbs}\n          query={query}\n          emptyMessage={emptyMessage}\n          choose={choose}\n        />\n      </CommandDialog>\n    </>\n  );\n}\n","/**\n * The rendered page's node elements, read from the marker the renderer puts on\n * them.\n *\n * Its own module so the canvas and the geometry watch every overlay shares can\n * both import it without importing each other.\n *\n * @module rendered-nodes\n */\n\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\n/**\n * Every element the renderer marked as a node, in document order.\n *\n * The companion of the canvas's `nodeElement`: both answer from the same marker,\n * and a caller that needs all of them should not walk the tree with its own\n * selector.\n *\n * Chrome drawn INSIDE the canvas root carries no node marker, so it is excluded\n * by construction rather than by a filter that would have to be kept in step\n * with whatever chrome arrives next.\n */\nexport function nodeElements(root: HTMLElement): readonly Element[] {\n  const found: Element[] = [];\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    found.push(element);\n  });\n  return found;\n}\n\n/**\n * The node elements in a subtree, the subtree's own root included: what a\n * node arriving in the rendered tree brings with it, or takes with it when it\n * leaves.\n */\nexport function nodeElementsIn(subtree: Element): readonly Element[] {\n  const found: Element[] = subtree.hasAttribute(NODE_ID_ATTRIBUTE)\n    ? [subtree]\n    : [];\n  subtree.querySelectorAll(`[${NODE_ID_ATTRIBUTE}]`).forEach(element => {\n    found.push(element);\n  });\n  return found;\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 marker for editor chrome drawn inside the canvas.\n *\n * @module canvas-chrome\n */\n\n/**\n * Marks editor chrome drawn over the page, which is not part of the page.\n *\n * A click on the canvas background CLEARS the selection, and the overlay sits\n * inside the canvas root — so without this a press on any control drawn over\n * the page resolves to \"no node\" and deselects the very block that control\n * acts on. The floating toolbar would run its action and then watch itself\n * disappear.\n *\n * An attribute rather than each overlay calling `stopPropagation`: the rule\n * belongs to what chrome IS, and the version where every new overlay has to\n * remember it is the version where the next one does not. The drop indicator\n * needs no marker only because it takes no pointer events at all.\n */\nexport const CHROME_ATTRIBUTE = \"data-nx-chrome\";\n\n/**\n * The block toolbar's class, drawn by `BlockToolbar`: how the chrome around\n * it, and a test laying it out, find the bar. Here beside the chrome marker\n * rather than in the toolbar's module, which imports a great deal.\n */\nexport const BLOCK_TOOLBAR_CLASS = \"nx-block-toolbar\";\n","/**\n * Where a header or footer's tag sits on the canvas.\n *\n * Inside the region, always: a mark hanging outside it sat over the page's\n * first or last block, covering its text and taking the pointer from it, so\n * hover flickered along the strip it covered. The tag sits at the region's\n * top left, and drops to its bottom left only where the top left is\n * scrolled off screen and the bottom left is not, so it stays in sight. A\n * region shorter than the tag draws none: the outline marks it alone.\n *\n * Across, it starts at the region's left edge and is kept within the part of\n * the frame that is on screen: at 100% a desktop page is wider than the\n * canvas, and a mark pinned to the right edge was off screen until the author\n * scrolled sideways.\n *\n * Pure arithmetic over measured boxes, so both rules are tested without a\n * layout engine.\n *\n * @module canvas-region-placement\n */\n\n/**\n * Which corner inside its region a tag sits in, on its left side, or\n * `\"none\"` for a region shorter than the tag (a short header far zoomed\n * out), where any corner would put it over the page.\n */\nexport type RegionMarkPlacement = \"top\" | \"bottom\" | \"none\";\n\n/**\n * Which corner inside its region a tag is drawn in.\n *\n * `edge` is the region's box and `viewport` the height of what is on screen,\n * both in the frame's own pixels; `height` is the tag's, its gap included.\n * The top wherever it shows, or where the bottom shows no better; none\n * where the region is shorter than the tag.\n */\nexport function regionMarkPlacement(args: {\n  readonly edge: { readonly top: number; readonly bottom: number };\n  readonly height: number;\n  readonly viewport: number;\n}): RegionMarkPlacement {\n  const { edge, height, viewport } = args;\n  if (edge.bottom - edge.top < height) return \"none\";\n  const topShows = edge.top >= 0 && edge.top + height <= viewport;\n  const bottomShows =\n    edge.bottom - height >= Math.max(edge.top, 0) && edge.bottom <= viewport;\n  return topShows || !bottomShows ? \"top\" : \"bottom\";\n}\n\n/** The gap between a region's left edge and its mark, at rest and on screen. */\nexport const REGION_MARK_INSET = 8;\n\n/**\n * How far from the region's left edge its mark starts, in the frame's\n * pixels: the inset, or further in when the region's left part is scrolled\n * off screen, so the mark starts where the visible part does. Never so far\n * that a mark of `width` would leave the region on the right.\n *\n * `visible` is the span of the frame on screen and `region` the region's own,\n * both in the frame's pixels.\n */\nexport function regionMarkLeft(args: {\n  readonly region: { readonly left: number; readonly right: number };\n  readonly visible: { readonly left: number; readonly right: number };\n  readonly width: number;\n}): number {\n  const { region, visible, width } = args;\n  const wanted = Math.max(visible.left - region.left, 0) + REGION_MARK_INSET;\n  const most = region.right - region.left - width - REGION_MARK_INSET;\n  return Math.max(REGION_MARK_INSET, Math.min(wanted, most));\n}\n","/**\n * What colour a page's ground is, read the way the canvas needs it: whether a\n * colour is opaque, how light it is, and from those whether the page under the\n * editor's marks is dark.\n *\n * One module, because two places ask: the canvas root, marking whether the\n * site paints an opaque ground of its own, and the frame's layer, choosing the\n * hues its marks take for the page beneath them. Two copies of \"is this ground\n * dark\" would drift, and a mark drawn in the wrong hue is the result.\n *\n * @module site-ground\n */\nimport {\n  parseColor,\n  relativeLuminance,\n  type Rgb,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * The largest relative luminance a ground can have and still be dark: the\n * point where white text and black text contrast with it equally.\n */\nconst DARK_GROUND_LUMINANCE = 0.179;\n\n/**\n * Whether a token value is a dark ground. A value this engine cannot read as a\n * colour — a named colour, `oklch()`, a reference to another property — says\n * nothing about how light it is, so it is not called dark: the canvas keeps the\n * page's light default rather than switching every native control to a dark\n * scheme over what may be a light ground.\n */\nexport function isDarkGround(value: string): boolean {\n  const luminance = groundLuminance(value.trim());\n  return luminance !== undefined && luminance < DARK_GROUND_LUMINANCE;\n}\n\n/**\n * One numeric colour component, with its percentage sign if it has one: an\n * optional sign, a decimal, an optional exponent, an optional `%`.\n *\n * The SAME grammar as the engine's `NUMERIC_COMPONENT` in `contrast.ts`, which\n * reads `rgb()` and does not export it; mirrored here for the two syntaxes the\n * engine does not read, so a component is a number in all of them alike.\n * Matched whole rather than parsed with `parseFloat`, which reads a prefix and\n * stops — `5e-1` would read as 5 and `12abc` as 12.\n */\nconst NUMERIC_COMPONENT = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?(%?)$/;\n\n/** A component as a number, and whether it was a percentage. */\nfunction numericOf(\n  part: string | undefined\n): { value: number; percent: boolean } | undefined {\n  if (part === undefined) return undefined;\n  const match = NUMERIC_COMPONENT.exec(part);\n  if (match === null) return undefined;\n  const value = Number.parseFloat(part);\n  return Number.isFinite(value)\n    ? { value, percent: match[1] === \"%\" }\n    : undefined;\n}\n\n/** A component as a 0–1 fraction: a percentage of 100, or a number of `scale`. */\nfunction fractionOf(\n  part: string | undefined,\n  scale: number\n): number | undefined {\n  const parsed = numericOf(part);\n  if (parsed === undefined) return undefined;\n  const fraction = parsed.value / (parsed.percent ? 100 : scale);\n  // Clamped, as CSS Color 4 clamps alpha, lightness and saturation.\n  return Math.min(1, Math.max(0, fraction));\n}\n\n/**\n * An `oklch()` or `hsl()`/`hsla()` call, split into its colour components and\n * its alpha: after a `/` in the modern syntax, the fourth comma-separated\n * component in the legacy one. `undefined` for anything else, or a call whose\n * shape is neither.\n */\nfunction colourFunction(text: string): ColourCall | undefined {\n  const call = /^(oklch|hsla?)\\(([^()]*)\\)$/i.exec(text);\n  if (call === null) return undefined;\n  const name = (call[1] ?? \"\").toLowerCase() === \"oklch\" ? \"oklch\" : \"hsl\";\n  const body = call[2] ?? \"\";\n  return body.includes(\",\") ? legacyCall(name, body) : modernCall(name, body);\n}\n\n/** A colour function's name, colour components and alpha, as written. */\ninterface ColourCall {\n  readonly name: \"oklch\" | \"hsl\";\n  readonly components: readonly string[];\n  readonly alpha: string | undefined;\n}\n\n/**\n * The legacy, comma-separated form: `hsl(h, s%, l%)` or `hsla(h, s%, l%, a)`.\n * Only `hsl()` has one, and it takes no slash.\n */\nfunction legacyCall(\n  name: ColourCall[\"name\"],\n  body: string\n): ColourCall | undefined {\n  if (name === \"oklch\" || body.includes(\"/\")) return undefined;\n  const parts = body.split(\",\").map(part => part.trim());\n  if (parts.length !== 3 && parts.length !== 4) return undefined;\n  return { name, components: parts.slice(0, 3), alpha: parts[3] };\n}\n\n/** The modern, space-separated form, with an optional `/ alpha` after it. */\nfunction modernCall(\n  name: ColourCall[\"name\"],\n  body: string\n): ColourCall | undefined {\n  const [channels, alpha, ...rest] = body.split(\"/\");\n  if (rest.length > 0) return undefined;\n  const parts = (channels ?? \"\")\n    .trim()\n    .split(/\\s+/)\n    .filter(part => part !== \"\");\n  if (parts.length !== 3) return undefined;\n  return { name, components: parts, alpha: alpha?.trim() };\n}\n\n/**\n * A colour's alpha, 0–1, or `undefined` when it cannot be told.\n *\n * Hex and `rgb()` from the engine's parser; `oklch()` and `hsl()` from their\n * own alpha component, 1 when they state none. A bare colour keyword is opaque\n * — every named colour is — except `transparent`, and a keyword this cannot\n * place, such as `currentColor`, is unknown, as is a reference or a function\n * this does not read.\n */\nexport function alphaOf(text: string): number | undefined {\n  const rgb = parseColor(text);\n  if (rgb !== undefined) return rgb.a;\n  const call = colourFunction(text);\n  if (call !== undefined) {\n    return call.alpha === undefined ? 1 : fractionOf(call.alpha, 1);\n  }\n  if (!/^[a-z]+$/i.test(text)) return undefined;\n  const keyword = text.toLowerCase();\n  if (keyword === \"transparent\") return 0;\n  return keyword === \"currentcolor\" ? undefined : 1;\n}\n\n/**\n * The relative luminance of a ground colour, or `undefined` when it cannot be\n * told. Hex and `rgb()` go through the engine's own parser. `oklch()`, which\n * Tailwind themes write, carries perceptual lightness directly: its L cubed is\n * the luminance of a grey, close enough for a dark-or-light call. `hsl()`,\n * which shadcn-style themes write, converts to rgb by the standard formula.\n *\n * A TRANSLUCENT colour has no lightness of its own: what a visitor sees is the\n * surface behind it, which the canvas cannot see either. So any alpha below 1,\n * in any of these syntaxes, is `undefined` — `#0000` is not a dark ground — and\n * so is an alpha this cannot read.\n */\nfunction groundLuminance(text: string): number | undefined {\n  if (alphaOf(text) !== 1) return undefined;\n  const rgb = parseColor(text);\n  if (rgb !== undefined) return relativeLuminance(rgb);\n  const call = colourFunction(text);\n  if (call === undefined) return undefined;\n  const [first, second, third] = call.components;\n  if (call.name === \"oklch\") {\n    // L is a number in 0–1, or a percentage.\n    const lightness = fractionOf(first, 1);\n    return lightness === undefined ? undefined : lightness ** 3;\n  }\n  // Hue as a number, in degrees if it says so; saturation and lightness as\n  // percentages, or the bare numbers CSS Color 4 also accepts for them.\n  const hue = numericOf(first?.replace(/deg$/i, \"\"));\n  const saturation = fractionOf(second, 100);\n  const lightness = fractionOf(third, 100);\n  if (\n    hue === undefined ||\n    hue.percent ||\n    saturation === undefined ||\n    lightness === undefined\n  ) {\n    return undefined;\n  }\n  return relativeLuminance(hslToRgb(hue.value, saturation, lightness));\n}\n\n/** An HSL colour as 0–255 channels, by the CSS Color 4 conversion. */\nfunction hslToRgb(hue: number, saturation: number, lightness: number): Rgb {\n  const h = ((hue % 360) + 360) % 360;\n  const a = saturation * Math.min(lightness, 1 - lightness);\n  const channel = (n: number): number => {\n    const k = (n + h / 30) % 12;\n    return Math.round(\n      (lightness - a * Math.max(-1, Math.min(k - 3, 9 - k, 1))) * 255\n    );\n  };\n  return { r: channel(0), g: channel(8), b: channel(4), a: 1 };\n}\n\n/** Whether an event started inside editor chrome rather than inside the page. */\n\n/**\n * The alpha of a computed colour written as a function this module's colour\n * reader does not otherwise read — `color(display-p3 0 0 0 / 0.5)`, which a\n * browser can keep in a computed value — from its `/ alpha` part, 1 without\n * one; `undefined` for anything that is not a colour function.\n */\nexport function computedAlphaOf(text: string): number | undefined {\n  const call = /^[a-z-]+\\(([^()]*)\\)$/i.exec(text);\n  if (call === null) return undefined;\n  const alpha = (call[1] ?? \"\").split(\"/\")[1];\n  return alpha === undefined ? 1 : fractionOf(alpha.trim(), 1);\n}\n\n/**\n * A background colour's channels and alpha, for compositing: the `rgb()` a\n * browser computes for most colours, or an `hsl()`. `undefined` for a colour\n * this module cannot turn into channels, such as `oklch()`.\n */\nfunction channelsOf(text: string): Rgb | undefined {\n  const rgb = parseColor(text);\n  if (rgb !== undefined) return rgb;\n  const call = colourFunction(text);\n  if (call?.name !== \"hsl\") return undefined;\n  const [first, second, third] = call.components;\n  const hue = numericOf(first?.replace(/deg$/i, \"\"));\n  const saturation = fractionOf(second, 100);\n  const lightness = fractionOf(third, 100);\n  const alpha = call.alpha === undefined ? 1 : fractionOf(call.alpha, 1);\n  if (\n    hue === undefined ||\n    hue.percent ||\n    saturation === undefined ||\n    lightness === undefined ||\n    alpha === undefined\n  ) {\n    return undefined;\n  }\n  return { ...hslToRgb(hue.value, saturation, lightness), a: alpha };\n}\n\n/**\n * The colour seen where translucent layers are painted over an opaque ground,\n * each over what lies beneath it. `layers` runs innermost first, as they are\n * met walking outwards from the canvas root, so it is applied in reverse:\n * paint order, the outermost ancestor's first.\n */\nfunction composited(ground: Rgb, layers: readonly Rgb[]): Rgb {\n  let seen = ground;\n  for (const layer of [...layers].reverse()) {\n    const over = (top: number, under: number): number =>\n      layer.a * top + (1 - layer.a) * under;\n    seen = {\n      r: over(layer.r, seen.r),\n      g: over(layer.g, seen.g),\n      b: over(layer.b, seen.b),\n      a: 1,\n    };\n  }\n  return seen;\n}\n\n/** The scheme an opaque colour reads as. */\nfunction schemeOfColour(rgb: Rgb): \"dark\" | \"light\" {\n  return relativeLuminance(rgb) < DARK_GROUND_LUMINANCE ? \"dark\" : \"light\";\n}\n\n/**\n * The document's own canvas where nothing paints a ground: white in the light\n * scheme, and the near-black a browser paints in the dark one.\n */\nconst CANVAS_COLOURS: Readonly<Record<\"dark\" | \"light\", Rgb>> = {\n  light: { r: 255, g: 255, b: 255, a: 1 },\n  dark: { r: 18, g: 18, b: 18, a: 1 },\n};\n\n/**\n * The scheme the page beneath the editor's marks is drawn in, from the colour\n * it actually paints.\n *\n * Read from the first ancestor, from the canvas root outwards, that paints an\n * opaque background, with every translucent background painted over it on\n * the way composited in paint order, because that is the ground the marks are\n * seen against: a heavy tint over a white page is a dark ground. Not from\n * `color-scheme`: a site that offers a dark set declares `light dark` whatever\n * the page in front of the author is showing, so the declaration says which\n * schemes are possible, not which one is drawn. Only where nothing paints an\n * opaque ground does the document's own canvas show, and that follows the\n * scheme the browser uses for it.\n */\nexport function pageSchemeOf(root: HTMLElement): \"dark\" | \"light\" {\n  const view = root.ownerDocument.defaultView;\n  if (view === null) return \"light\";\n  const { layers, opaque } = paintedBeneath(root, view);\n  if (opaque !== null) return schemeOver(opaque, layers);\n  const canvas = canvasSchemeOf(root.ownerDocument, view);\n  return layers.length === 0\n    ? canvas\n    : schemeOfColour(composited(CANVAS_COLOURS[canvas], layers));\n}\n\n/**\n * What is painted from the canvas root outwards: the translucent backgrounds\n * met, innermost first, and the first opaque one beneath them, or `null` when\n * none is reached or its colour cannot be read.\n */\nfunction paintedBeneath(\n  root: HTMLElement,\n  view: Window\n): { layers: Rgb[]; opaque: string | null } {\n  const layers: Rgb[] = [];\n  for (let at: Element | null = root; at !== null; at = at.parentElement) {\n    const colour = view.getComputedStyle(at).backgroundColor.trim();\n    const alpha = alphaOf(colour) ?? computedAlphaOf(colour);\n    if (alpha === 1) {\n      return {\n        layers,\n        opaque: groundLuminance(colour) === undefined ? null : colour,\n      };\n    }\n    // A layer that cannot be read as channels is left out: the ground\n    // beneath it still decides, as it did before any layer was counted.\n    const channels =\n      alpha === undefined || alpha === 0 ? undefined : channelsOf(colour);\n    if (channels !== undefined) layers.push(channels);\n  }\n  return { layers, opaque: null };\n}\n\n/**\n * The scheme of an opaque ground with translucent layers over it; by the\n * ground alone where it cannot be read as channels (`oklch()`).\n */\nfunction schemeOver(opaque: string, layers: readonly Rgb[]): \"dark\" | \"light\" {\n  const ground = channelsOf(opaque);\n  if (ground === undefined || layers.length === 0) {\n    return isDarkGround(opaque) ? \"dark\" : \"light\";\n  }\n  return schemeOfColour(composited(ground, layers));\n}\n\n/** The scheme the browser paints a document's own canvas in. */\nfunction canvasSchemeOf(document: Document, view: Window): \"dark\" | \"light\" {\n  const declared = view.getComputedStyle(document.documentElement).colorScheme;\n  if (!declared.includes(\"dark\")) return \"light\";\n  if (!declared.includes(\"light\")) return \"dark\";\n  return view.matchMedia?.(\"(prefers-color-scheme: dark)\").matches\n    ? \"dark\"\n    : \"light\";\n}\n","/**\n * The regions of a page's layout, its header and footer, drawn on the canvas\n * around the page.\n *\n * A layout's header and footer are what a visitor sees around the page, so the\n * canvas draws them, from the PUBLISHED documents the host hands over. They\n * are not the page's to edit: nothing in them can be dragged onto or typed\n * into, and their links and forms are inert. Each is selected as a whole, by\n * a click or by Enter or Space on its one Tab stop, and the host's sidebar\n * then says where it comes from (`region-selection` holds which one).\n *\n * Drawn as part of the canvas's rendered subtree, inside the canvas root, so\n * whatever surface the canvas lives on (today the admin page, later the\n * editor's own frame) carries them with the page.\n *\n * What marks a region is drawn inside it, never over the page: the outline on\n * the region's own edge, and a small tag at its top left (its bottom left\n * where the top is scrolled away; `canvas-region-placement` has where). A\n * mark hanging past the region covered the page's first or last block, and\n * hover flickered along the strip it covered.\n *\n * A region is drawn again only when what it is drawn from changes: its\n * document, its definitions, its sheet and the canvas's shared inputs. The\n * hover cue is the stylesheet's (`:hover`, `:focus-visible`), not React state,\n * and what its async blocks drew (a logo, a button) is kept between draws, so\n * an insert on the page or the pointer resting on the footer never blinks it.\n *\n * @module canvas-regions\n */\nimport type {\n  BlockDocument,\n  DefinitionsById,\n  RegionArea,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  createStandaloneContext,\n  PageRenderer,\n  type PageRendererProps,\n  type PartSheet,\n} from \"@nextlyhq/blocks-react\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport {\n  memo,\n  useMemo,\n  useRef,\n  useState,\n  type JSX,\n  type KeyboardEvent,\n  type MouseEvent,\n  type RefObject,\n} from \"react\";\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport {\n  inputDocuments,\n  useCanvasFrame,\n  type CanvasFrame,\n} from \"./canvas-frame-context\";\nimport {\n  REGION_MARK_INSET,\n  regionMarkLeft,\n  regionMarkPlacement,\n  type RegionMarkPlacement,\n} from \"./canvas-region-placement\";\nimport {\n  boxInFrameViewport,\n  canvasContentRect,\n  canvasRootFrom,\n  onScreenBandOf,\n  screenScrollers,\n  scrollEventTarget,\n} from \"./geometry-dom\";\nimport { pageSchemeOf } from \"./site-ground\";\n\n/**\n * The class on a Layout region's frame. Its blocks are a document of their\n * own, drawn inside the canvas around the page's, so a mark that belongs to\n * the page's blocks is kept off anything inside it.\n */\nexport const CANVAS_REGION_CLASS = \"nx-canvas-region\";\n\n/** One region of the page's layout, as the host hands it to the canvas. */\nexport interface CanvasRegion {\n  /** Which area: drawn before the page for a header, after it for a footer. */\n  readonly area: RegionArea;\n  /** The region's document: one instance of the component filling the area. */\n  readonly document: BlockDocument;\n  /** The PUBLISHED definitions that document reaches, nested ones included. */\n  readonly definitions?: DefinitionsById;\n  /**\n   * What the region is and where it comes from, as it is announced: \"Site\n   * header, from the Main header & footer\".\n   */\n  readonly label: string;\n  /** Its tag while the pointer or focus is on it: \"Site header · Main\". */\n  readonly badge: string;\n  /** Its tag while it is selected: \"Site header\". */\n  readonly name: string;\n  /**\n   * The way to edit what it comes from, for someone who may: a link that\n   * opens in a new tab, offered where a block of it is named off the canvas\n   * (the page data panel). Absent for anyone else.\n   */\n  readonly edit?: {\n    readonly href: string;\n    /** The visible text. */\n    readonly text: string;\n    /** The accessible name, which says it opens in a new tab. */\n    readonly name: string;\n  };\n}\n\n/** The attribute naming a drawn region's area, for a host scrolling to it. */\nexport const REGION_ATTRIBUTE = \"data-nx-region\";\n\n/** The attribute a drawn region carries while it is selected. */\nconst REGION_SELECTED_ATTRIBUTE = \"data-selected\";\n\n/**\n * One region on the canvas, selected as a whole.\n *\n * Its content is `inert`: the region's links and forms cannot be followed or\n * focused, and the pointer falls through to the region itself, which answers\n * a click by asking to be selected. The region is its own one Tab stop, named\n * for what it is and where it comes from; Enter or Space selects it.\n *\n * Marked as chrome, so the canvas's block selection, hit-testing and link\n * guard all leave it alone: it is not part of the document being edited.\n */\nexport function CanvasRegionFrame({\n  region,\n  rendered,\n  sheet,\n  selected,\n  onSelect,\n  onEdit,\n  dimmed,\n}: {\n  region: CanvasRegion;\n  /** The canvas's own renderer inputs, less what belongs to the page alone. */\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined;\n  /** How this part treats the site sheet, and the scope it compiles under. */\n  sheet: PartSheet;\n  /** Whether this region is the canvas's selection. */\n  selected: boolean;\n  /** Ask for this region to be selected; absent, the region selects nothing. */\n  onSelect: ((area: RegionArea) => void) | undefined;\n  /**\n   * Ask to edit this region in place: a double-click, or Enter while it is\n   * selected. Absent, the region is only ever selected.\n   */\n  onEdit: ((area: RegionArea) => void) | undefined;\n  /**\n   * Whether another region is edited in place: then this one is out of\n   * reach, as the page is, and hidden from assistive technology.\n   */\n  dimmed: boolean;\n}): JSX.Element {\n  const frame = useRef<HTMLDivElement | null>(null);\n  const tag = useRef<HTMLSpanElement | null>(null);\n  const canvas = useCanvasFrame();\n  const place = useMarkPlace(frame, tag, canvas, selected);\n  const choose = (): void => {\n    if (!selected) onSelect?.(region.area);\n  };\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    if (event.target !== event.currentTarget) return;\n    if (event.key !== \"Enter\" && event.key !== \" \") return;\n    // Space would scroll the canvas; Enter is the region's own here.\n    event.preventDefault();\n    // Enter selects the region, and Enter again edits it.\n    if (event.key === \"Enter\" && selected && onEdit !== undefined) {\n      onEdit(region.area);\n      return;\n    }\n    choose();\n  };\n  // A double-click goes straight in: selected on its first click, edited on\n  // the second. Kept from the canvas's own double-click, which opens a\n  // block's text and has no block here.\n  const edit = (event: MouseEvent<HTMLDivElement>): void => {\n    if (onEdit === undefined) return;\n    event.stopPropagation();\n    onEdit(region.area);\n  };\n\n  return (\n    <div\n      ref={frame}\n      className={CANVAS_REGION_CLASS}\n      {...{ [CHROME_ATTRIBUTE]: \"\", [REGION_ATTRIBUTE]: region.area }}\n      {...(selected ? { [REGION_SELECTED_ATTRIBUTE]: \"\" } : {})}\n      role=\"button\"\n      aria-pressed={selected}\n      tabIndex={0}\n      onClick={choose}\n      onDoubleClick={edit}\n      onKeyDown={onKeyDown}\n      // Out of reach and unheard while another region is edited in place.\n      inert={dimmed}\n      aria-hidden={dimmed ? \"true\" : undefined}\n      // The ground under the marks, judged as the pointer arrives, since a\n      // hover cue changes no state and so runs no effect.\n      onPointerEnter={() => markScheme(frame.current)}\n    >\n      {/* Its drawn content is a picture of the region, not its name: hidden\n          from a screen reader, and named by the text after it. Not an\n          aria-label, which would have to hold every word the content draws. */}\n      <div className=\"nx-canvas-region__content\" inert aria-hidden=\"true\">\n        <RegionContent\n          document={region.document}\n          definitions={region.definitions}\n          rendered={rendered}\n          sheet={sheet}\n        />\n      </div>\n      <span className=\"nx-canvas-region__name\">{region.label}</span>\n      <span\n        ref={tag}\n        className=\"nx-canvas-region__tag\"\n        data-placement={place.placement}\n        style={{ left: place.left }}\n        // The region's own name says what the tag does.\n        aria-hidden=\"true\"\n      >\n        {selected ? region.name : region.badge}\n      </span>\n    </div>\n  );\n}\n\n/**\n * The region being edited in place: drawn from the live document being\n * edited, its blocks addressed and within reach, so it is edited as a page\n * is. No longer chrome and no longer a button: a click lands on its blocks.\n * It keeps its area's attribute, so the dim over the rest of the canvas is\n * measured around it, and its edge where it meets the page.\n */\nexport function EditedRegionFrame({\n  area,\n  document,\n  definitions,\n  rendered,\n  sheet,\n}: {\n  area: RegionArea;\n  /** Its document as it stands, edit by edit. */\n  document: BlockDocument;\n  definitions: DefinitionsById | undefined;\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined;\n  sheet: PartSheet;\n}): JSX.Element {\n  return (\n    <div\n      className={CANVAS_REGION_CLASS}\n      {...{ [REGION_ATTRIBUTE]: area, [REGION_EDITED_ATTRIBUTE]: \"\" }}\n    >\n      <RegionContent\n        document={document}\n        definitions={definitions}\n        rendered={rendered}\n        sheet={sheet}\n        addressed\n      />\n    </div>\n  );\n}\n\n/** The attribute a region carries while it is edited in place. */\nexport const REGION_EDITED_ATTRIBUTE = \"data-nx-region-edited\";\n\n/**\n * State on the region the page's ground it is drawn over, so its marks take\n * the hue for that ground, as the block marks over the page do.\n */\nfunction markScheme(region: HTMLElement | null): void {\n  const root = rootOf(region);\n  if (region === null || root === null) return;\n  region.setAttribute(PAGE_SCHEME_ATTRIBUTE, pageSchemeOf(root));\n}\n\n/** The attribute stating the page's ground under a region's marks. */\nconst PAGE_SCHEME_ATTRIBUTE = \"data-nx-page-scheme\";\n\n/** What a region's content is drawn from. */\ninterface RegionContentProps {\n  document: BlockDocument;\n  definitions: DefinitionsById | undefined;\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined;\n  sheet: PartSheet;\n  /** Whether its blocks carry their addresses: only while it is edited. */\n  addressed?: boolean;\n}\n\n/**\n * The region's own document, drawn with the canvas's inputs, and drawn again\n * only when one of them changes (`sameRegionDraw`).\n */\nconst RegionContent = memo(function RegionContent({\n  document,\n  definitions,\n  rendered,\n  sheet,\n  addressed = false,\n}: RegionContentProps): JSX.Element {\n  const {\n    styles: _pageStyles,\n    definitions: _pageDefinitions,\n    ...shared\n  } = rendered ?? {};\n  // One context for as long as the region is drawn, where the canvas hands\n  // none: what its async blocks drew is kept per context.\n  const ownContext = useMemo(() => createStandaloneContext(), []);\n  return (\n    <PageRenderer\n      {...shared}\n      context={shared.context ?? ownContext}\n      {...sheet}\n      document={document}\n      {...(definitions === undefined || definitions.size === 0\n        ? {}\n        : { definitions })}\n      // An image or a button already drawn stays drawn when the region is\n      // drawn again, rather than blinking out while it runs again. Never on\n      // a published page, which this is not.\n      keepAsyncOutputs\n      // Addressed while it is edited in place, so the canvas's hover,\n      // selection, inline editing and drag find its blocks as a page's.\n      nodeAttribute={addressed}\n    />\n  );\n}, sameRegionDraw);\n\n/**\n * Whether two draws of a region's content would draw the same: the same\n * document and definitions, and the canvas's inputs and the part's sheet\n * equal field by field. The canvas hands a new object for each after an edit\n * on the page (an insert, a style), with the same values in it; the page's\n * own styles and definitions are not the region's and are never read.\n */\nfunction sameRegionDraw(\n  before: RegionContentProps,\n  after: RegionContentProps\n): boolean {\n  return (\n    before.document === after.document &&\n    before.definitions === after.definitions &&\n    before.addressed === after.addressed &&\n    sameFields(regionInputs(before.rendered), regionInputs(after.rendered)) &&\n    before.sheet.siteStyles === after.sheet.siteStyles &&\n    sameFields(before.sheet.styleContext, after.sheet.styleContext)\n  );\n}\n\n/** The canvas's inputs a region reads: all but the page's own. */\nfunction regionInputs(\n  rendered: RegionContentProps[\"rendered\"]\n): object | undefined {\n  if (rendered === undefined) return undefined;\n  const { styles: _styles, definitions: _definitions, ...shared } = rendered;\n  return shared;\n}\n\n/** Whether two objects hold the same values under the same keys. */\nfunction sameFields(\n  before: object | undefined,\n  after: object | undefined\n): boolean {\n  if (before === after) return true;\n  if (before === undefined || after === undefined) return false;\n  const keys = Object.keys(before);\n  if (keys.length !== Object.keys(after).length) return false;\n  return keys.every(\n    key =>\n      Object.hasOwn(after, key) &&\n      Object.is(\n        (before as Record<string, unknown>)[key],\n        (after as Record<string, unknown>)[key]\n      )\n  );\n}\n\n/** Where the tag sits: which corner inside the region, and how far in. */\ninterface MarkPlace {\n  readonly placement: RegionMarkPlacement;\n  readonly left: number;\n}\n\n/**\n * The tag's place, measured whenever it changes size (its words changing on\n * selection, at once; on hover, a frame later) and whenever the page or the\n * canvas around the frame scrolls or resizes, so a tag that would leave the\n * screen is brought back onto it. The ground under the marks is judged with\n * it.\n */\nfunction useMarkPlace(\n  frame: RefObject<HTMLDivElement | null>,\n  mark: RefObject<HTMLSpanElement | null>,\n  canvas: CanvasFrame,\n  selected: boolean\n): MarkPlace {\n  const [place, setPlace] = useState<MarkPlace>(AT_REST);\n  useIsomorphicLayoutEffect(() => {\n    const measure = (): void => {\n      markScheme(frame.current);\n      const next = markPlaceOf(frame.current, mark.current, canvas);\n      if (next === undefined) return;\n      setPlace(now =>\n        now.placement === next.placement && now.left === next.left ? now : next\n      );\n    };\n    measure();\n    let pending = 0;\n    const later = (): void => {\n      const view = frame.current?.ownerDocument.defaultView;\n      if (view === null || view === undefined || pending !== 0) return;\n      pending = view.requestAnimationFrame(() => {\n        pending = 0;\n        measure();\n      });\n    };\n    // What moves the part on screen: the canvas's scroller and, around a\n    // frame, the editor's (`screenScrollers`), and either window's size.\n    const root = rootOf(frame.current);\n    const scrollers = root === null ? [] : screenScrollers(root, canvas.frame);\n    for (const scroller of scrollers) {\n      scrollEventTarget(scroller).addEventListener(\"scroll\", later, {\n        passive: true,\n      });\n    }\n    const documents = inputDocuments(canvas);\n    for (const doc of documents) {\n      doc.defaultView?.addEventListener(\"resize\", later);\n    }\n    // The mark's own size, which the stylesheet changes on hover and focus\n    // without a render. Read from the mark's window, which in a frame is not\n    // this one's.\n    const Observer = mark.current?.ownerDocument.defaultView?.ResizeObserver;\n    const sized = Observer === undefined ? undefined : new Observer(later);\n    if (mark.current !== null) sized?.observe(mark.current);\n    return () => {\n      sized?.disconnect();\n      for (const scroller of scrollers) {\n        scrollEventTarget(scroller).removeEventListener(\"scroll\", later);\n      }\n      for (const doc of documents) {\n        doc.defaultView?.removeEventListener(\"resize\", later);\n      }\n      if (pending !== 0) {\n        frame.current?.ownerDocument.defaultView?.cancelAnimationFrame(pending);\n      }\n    };\n  }, [frame, mark, canvas, selected]);\n  return place;\n}\n\n/** At the top, at the inset: where a tag sits before anything is measured. */\nconst AT_REST: MarkPlace = { placement: \"top\", left: REGION_MARK_INSET };\n\n/** The canvas root a region is drawn in, or `null` before it is. */\nfunction rootOf(region: HTMLElement | null): HTMLElement | null {\n  return region === null ? null : canvasRootFrom(region, CANVAS_ROOT_CLASS);\n}\n\n/**\n * The tag's place from the boxes as drawn, or nothing before they are: the\n * region's and the tag's boxes and the part of the canvas on screen, all in\n * the canvas's content coordinates, read through the one geometry module.\n */\nfunction markPlaceOf(\n  region: HTMLElement | null,\n  mark: HTMLElement | null,\n  canvas: CanvasFrame\n): MarkPlace | undefined {\n  const root = rootOf(region);\n  if (region === null || mark === null || root === null) return undefined;\n  const box = canvasContentRect(region, root);\n  const size = canvasContentRect(mark, root);\n  const band = onScreenBandOf(root, canvas.frame);\n  // The tag's inset from the edge it sits against, as drawn: it needs that\n  // room as well as its own height, or it reaches past the region's other\n  // edge over the page.\n  const inset =\n    mark.getAttribute(\"data-placement\") === \"bottom\"\n      ? box.y + box.height - (size.y + size.height)\n      : size.y - box.y;\n  return {\n    placement: regionMarkPlacement({\n      edge: { top: box.y - band.y, bottom: box.y + box.height - band.y },\n      height: size.height + Math.max(inset, 0),\n      viewport: band.height,\n    }),\n    left: regionMarkLeft({\n      region: { left: box.x, right: box.x + box.width },\n      visible: { left: band.x, right: band.x + band.width },\n      width: size.width,\n    }),\n  };\n}\n\n/** The attribute on a band drawn where an area has no region, naming the area. */\nexport const EMPTY_REGION_ATTRIBUTE = \"data-nx-region-empty\";\n\n/** A rectangle in the editor's own coordinates, where a menu opens from. */\nexport interface EmptyRegionAnchor {\n  readonly x: number;\n  readonly y: number;\n  readonly width: number;\n  readonly height: number;\n}\n\n/**\n * What the host has the band say and offer where an area has no region: why\n * the area is empty, and either the two ways to fill it or who to ask.\n * @experimental Settles with the site's empty header and footer.\n */\nexport interface EmptyRegionBandProps {\n  /** The area has nothing yet, and what that means for the site's pages. */\n  readonly sentence: string;\n  readonly actions:\n    | {\n        /** Fill it with a new one, as \"Create a header\" says. */\n        readonly create: string;\n        readonly onCreate: () => void;\n        /** Choose one already made, as \"Use a component\" says. */\n        readonly use: string;\n        /**\n         * Open the choice, from the button's place in the editor's own\n         * coordinates: the menu is drawn there, over the canvas.\n         */\n        readonly onUse: (anchor: EmptyRegionAnchor) => void;\n        /** While a choice is being written: both wait. */\n        readonly busy?: boolean;\n      }\n    | {\n        /** For someone who may not fill it: who can. */\n        readonly ask: string;\n      };\n}\n\n/**\n * The band drawn in an area's place on the canvas while the page's header &\n * footer set has nothing there: a dashed box saying so, with the host's ways\n * to fill it. Drawn in the editor's canvas alone, in the region's place and\n * never in the page: a visitor's page draws nothing there.\n *\n * Its buttons are the frame's own, styled by the frame's sheet with the\n * values the editor hands it, since the editor's stylesheet does not reach\n * into the frame. The choice it opens is the host's, drawn over the canvas\n * in the editor's document, from the button's place mapped there.\n */\nexport function EmptyRegionBand({\n  area,\n  band,\n}: {\n  readonly area: RegionArea;\n  readonly band: EmptyRegionBandProps;\n}): JSX.Element {\n  const canvas = useCanvasFrame();\n  const { actions } = band;\n  // The button's box in the frame, mapped corner by corner to the editor's\n  // coordinates, as a context menu opened in the frame is.\n  const anchorOf = (element: HTMLElement): EmptyRegionAnchor => {\n    const box = boxInFrameViewport(element);\n    const start = canvas.toHost({ x: box.x, y: box.y });\n    const end = canvas.toHost({\n      x: box.x + box.width,\n      y: box.y + box.height,\n    });\n    return {\n      x: start.x,\n      y: start.y,\n      width: end.x - start.x,\n      height: end.y - start.y,\n    };\n  };\n  return (\n    <div\n      className=\"nx-canvas-region-empty\"\n      {...{ [CHROME_ATTRIBUTE]: \"\", [EMPTY_REGION_ATTRIBUTE]: area }}\n      role=\"group\"\n      aria-label={area === \"header\" ? \"Site header\" : \"Site footer\"}\n      // A press here is the band's, never a selection on the canvas.\n      onPointerDown={event => event.stopPropagation()}\n      onClick={event => event.stopPropagation()}\n      onDoubleClick={event => event.stopPropagation()}\n    >\n      <p className=\"nx-canvas-region-empty__sentence\">{band.sentence}</p>\n      {\"ask\" in actions ? (\n        <p className=\"nx-canvas-region-empty__ask\">{actions.ask}</p>\n      ) : (\n        <div className=\"nx-canvas-region-empty__actions\">\n          <button\n            type=\"button\"\n            data-nx-region-empty-action=\"create\"\n            disabled={actions.busy === true}\n            onClick={() => actions.onCreate()}\n          >\n            {actions.create}\n          </button>\n          <button\n            type=\"button\"\n            data-nx-region-empty-action=\"use\"\n            aria-haspopup=\"listbox\"\n            disabled={actions.busy === true}\n            onClick={event => actions.onUse(anchorOf(event.currentTarget))}\n          >\n            {actions.use}\n            <span aria-hidden=\"true\"> ▾</span>\n          </button>\n        </div>\n      )}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The entry a template is previewed with, handed by the host to whatever in\n * the editor reads it: the canvas's notes, and the inspector's.\n *\n * A template draws every entry of its collection, so while one is edited the\n * host previews it with a real entry, chosen beside the canvas. This is that\n * entry as the editor knows it: its values as the person editing reads them,\n * drafts included, its published values as a visitor reads them, and the\n * fields a visitor may read. Where no entry can be previewed, it says so\n * instead. Outside a template there is no previewed entry at all, and the\n * hook answers `undefined`.\n *\n * A context rather than a member of `ContentServices`, for the reason the\n * visitor-unreadable context gives: the services are one object per language\n * and person, while this answer changes whenever the author previews another\n * entry.\n *\n * @module previewed-entry\n */\n\nimport type { BindingFieldShape } from \"@nextlyhq/blocks-engine\";\nimport { createContext, useContext, type ReactNode } from \"react\";\n\n/**\n * The entry a template is previewed with, or why there is none.\n *\n * - `entry`: an entry of the template's collection. `editorValues` are what\n *   the person editing reads, a waiting working draft included;\n *   `publicValues` are the published entry as an anonymous visitor reads it,\n *   or `null` where the visitor may not read it (a draft never published,\n *   or a collection the public may not read); `fields` are the collection's\n *   fields as a visitor may read them.\n * - `none`: no entry to preview. `reason` says why as far as the person may\n *   know it: `empty` when there is no entry they may read, which reads the\n *   same whether the collection holds none or holds only entries they may\n *   not read; `loading` while the first answer is on its way; `unavailable`\n *   when the entry could not be read.\n *\n * @experimental Settles when collection templates ship.\n */\nexport type PreviewedEntry =\n  | {\n      readonly kind: \"entry\";\n      /** The template's collection. */\n      readonly collection: string;\n      readonly id: string;\n      readonly title: string;\n      readonly publicValues: Readonly<Record<string, unknown>> | null;\n      readonly editorValues: Readonly<Record<string, unknown>>;\n      readonly fields: readonly BindingFieldShape[];\n    }\n  | {\n      readonly kind: \"none\";\n      readonly reason: \"empty\" | \"loading\" | \"unavailable\";\n    };\n\n/**\n * One top-level blocks field of a template's collection: what an Entry\n * content block may draw.\n *\n * @experimental Settles when collection templates ship.\n */\nexport interface PreviewedBlocksField {\n  /** The field's name, which the block stores. */\n  readonly name: string;\n  /** What the admin calls it: \"Body\". */\n  readonly label: string;\n}\n\n/**\n * The collection a template draws, as its editor names it: its names, its\n * top-level blocks fields, and where one of its entries is edited.\n *\n * - `blocksFields` is `undefined` while they are not known (the first\n *   answer is on its way, or the author may not read the collection), so a\n *   choice is never called removed for want of an answer.\n *\n * @experimental Settles when collection templates ship.\n */\nexport interface PreviewedCollection {\n  /** The collection's slug. */\n  readonly slug: string;\n  /** Its name for one entry, as a sentence reads it: \"post\". */\n  readonly singular: string;\n  /** Its name, as a heading reads it: \"Posts\". */\n  readonly plural: string;\n  /** Its top-level blocks fields, in the collection's order. */\n  readonly blocksFields: readonly PreviewedBlocksField[] | undefined;\n  /**\n   * What a field of the collection is called, by its name: its label where\n   * it is one of {@link blocksFields}, else its name in words as the admin\n   * words a key (\"membersOnly\" is \"Members Only\"), for a field the\n   * collection no longer has. The one name a field is shown by, on the\n   * canvas, in Layers and in the inspector alike.\n   */\n  readonly fieldLabel: (name: string) => string;\n  /** The admin address where entry `id` is edited. */\n  readonly entryHref: (id: string) => string;\n}\n\n/**\n * The keys that preview the next and the previous entry of a template's\n * collection: Shift with the block-move chord, so the two read as related\n * and never collide (a chord's modifiers are matched exactly).\n *\n * @experimental Settles when collection templates ship.\n */\nexport const PREVIEWED_ENTRY_KEYS: {\n  readonly next: \"shift+alt+ArrowDown\";\n  readonly previous: \"shift+alt+ArrowUp\";\n} = Object.freeze({\n  next: \"shift+alt+ArrowDown\",\n  previous: \"shift+alt+ArrowUp\",\n});\n\n/** No provider: the document is not a template. */\nconst PreviewedEntryContext = createContext<PreviewedEntry | undefined>(\n  undefined\n);\n\n/** No provider, or one that names no collection: not a template. */\nconst PreviewedCollectionContext = createContext<\n  PreviewedCollection | undefined\n>(undefined);\n\n/**\n * Hands the editor the entry a template is previewed with. The host mounts\n * it only around a template's editor, so a page, a component or a Layout\n * reads `undefined`.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function PreviewedEntryProvider({\n  value,\n  collection,\n  children,\n}: {\n  readonly value: PreviewedEntry;\n  /**\n   * The template's collection, for what reads its fields: an Entry content\n   * block's mark, its inspector and its canvas notes.\n   */\n  readonly collection?: PreviewedCollection | undefined;\n  readonly children?: ReactNode;\n}): React.JSX.Element {\n  return (\n    <PreviewedEntryContext.Provider value={value}>\n      <PreviewedCollectionContext.Provider value={collection}>\n        {children}\n      </PreviewedCollectionContext.Provider>\n    </PreviewedEntryContext.Provider>\n  );\n}\n\n/**\n * The entry the template being edited is previewed with, or `undefined`\n * where the document is not a template and nothing is previewed.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function usePreviewedEntry(): PreviewedEntry | undefined {\n  return useContext(PreviewedEntryContext);\n}\n\n/**\n * The collection the template being edited draws, or `undefined` where the\n * document is not a template, or its editor names none.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function usePreviewedCollection(): PreviewedCollection | undefined {\n  return useContext(PreviewedCollectionContext);\n}\n\n/**\n * The words an Entry content block is named by on the canvas and in\n * Layers, with the field it draws: \"Entry content · Body\", or the field's\n * name where the collection's fields are not known.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function entryContentLabel(\n  field: string | undefined,\n  collection: PreviewedCollection | undefined\n): string {\n  if (field === undefined) return ENTRY_CONTENT_NAME;\n  return `${ENTRY_CONTENT_NAME} · ${fieldName(field, collection)}`;\n}\n\n/**\n * The name a field an Entry content block draws is shown by: the\n * collection's (`PreviewedCollection.fieldLabel`), or the field's own name\n * where no template's collection is known.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function fieldName(\n  field: string,\n  collection: PreviewedCollection | undefined\n): string {\n  return collection?.fieldLabel(field) ?? field;\n}\n\n/**\n * Whether the collection is known to have no top-level blocks field named\n * `field`. Never while its fields are not known, so a choice is not called\n * removed for want of an answer.\n */\nexport function entryFieldRemoved(\n  field: string | undefined,\n  collection: PreviewedCollection | undefined\n): boolean {\n  const fields = collection?.blocksFields;\n  return (\n    field !== undefined &&\n    fields !== undefined &&\n    !fields.some(each => each.name === field)\n  );\n}\n\n/** The block's own name, as the Add panel reads it. */\nconst ENTRY_CONTENT_NAME = \"Entry content\";\n","/**\n * The marks the canvas puts on drawn blocks, and what each block's mark is:\n * selected, locked, conditioned, Entry content, and during a drag the block\n * moving and the container a drop would land in or that refuses it. Each\n * answer is worked out once per document, and each mark is written only\n * when it changes.\n *\n * @module canvas-block-marks\n */\n\nimport {\n  entryContentFieldOf,\n  entryContentPlacements,\n  isPlainRecord,\n  placementGatesOf,\n  revealConditioned,\n  walkNodes,\n  DEFAULT_LIMITS,\n  resolveComponentInstances,\n  type BlockDocument,\n  type BlockNode,\n  type DefinitionsById,\n  type DocumentLimits,\n} from \"@nextlyhq/blocks-engine\";\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport type { AppliedConditions } from \"../conditions/applied-conditions\";\nimport {\n  asStoredDefinitions,\n  gatedAsDrawn,\n  gatedAsStored,\n} from \"../conditions/condition-gate\";\nimport { isLocked } from \"../locking\";\n\nimport { isOutermostForAddress, nodeAddressOf } from \"./canvas-addressing\";\nimport { CANVAS_REGION_CLASS, REGION_EDITED_ATTRIBUTE } from \"./canvas-regions\";\nimport { entryContentLabel, type PreviewedCollection } from \"./previewed-entry\";\n\n/**\n * A region of the layout drawn around the page and not edited: a document\n * of its own whose ids may repeat the page's, so the page's marks stay off\n * it. A region edited in place takes the marks, which are then its own.\n */\nconst UNEDITED_REGION = `.${CANVAS_REGION_CLASS}:not([${REGION_EDITED_ATTRIBUTE}])`;\n\n/**\n * Marks the selected block's own element.\n *\n * Boolean by presence rather than carrying the id: the element already states\n * its id through `NODE_ID_ATTRIBUTE`, and repeating it here would be a second\n * copy that a partial re-mark could leave disagreeing with the first.\n *\n * Exported because a host styling the canvas, and a test asserting what is\n * selected, both need to name it — and a string typed twice is a contract with\n * no compiler behind it.\n */\nexport const SELECTED_ATTRIBUTE = \"data-nx-selected\";\n\n/**\n * Marks a node the drag engine will refuse to pick up.\n *\n * Drawn so the grab cursor can be withheld from it. With no drag handle, that\n * cursor is the only thing advertising a block as movable, so offering it on a\n * node `useCanvasDrag` returns early for leaves an author pressing repeatedly\n * at something that will never move — an affordance promising what the engine\n * has already decided against.\n */\nexport const LOCKED_ATTRIBUTE = \"data-nx-locked\";\n\n/** How a block is locked in Layers: by its own lock, or by one around it. */\nexport type LockMark = \"own\" | \"inherited\";\n\n/**\n * Every locked block's mark, from one walk: a block's own lock, else the lock\n * of a block it sits inside, carried down rather than climbed per block.\n */\nexport function lockMarksOf(document: BlockDocument): Map<string, LockMark> {\n  const marks = new Map<string, LockMark>();\n  walkNodes(document.nodes, (node, parent) => {\n    if (isLocked(node)) marks.set(node.id, \"own\");\n    else if (parent !== undefined && marks.has(parent.id)) {\n      marks.set(node.id, \"inherited\");\n    }\n  });\n  return marks;\n}\n\n/**\n * Marks a block whose visibility conditions decide who sees it. The canvas\n * draws it whoever the page would show it to, so the author can see and\n * select it, and this says it isn't shown to everyone: `conditional`, or\n * `unchecked` for one whose conditions the page can't check, which visitors\n * never see.\n */\nexport const CONDITIONED_ATTRIBUTE = \"data-nx-conditioned\";\n\n/**\n * Marks an element whose condition mark is its own block's, a block of a\n * placed component's definition, rather than its placement's: the marks\n * badge each such block apart, where a placement's roots share one badge.\n * Its value names the placement nested in a component whose gate the block\n * carries, when that gate is all it carries, so that placement's roots share\n * one badge too; empty for a block's own conditions.\n */\nexport const CONDITIONED_OWN_ATTRIBUTE = \"data-nx-conditioned-own\";\n\n/**\n * How a conditioned block is marked on the canvas: conditional, or conditions\n * the page can't check, or, while conditions are applied, shown for the\n * previewed entry.\n */\ntype ConditionMark = \"conditional\" | \"unchecked\" | \"shown\";\n\n/**\n * Every conditioned block's mark, and for a composed block gated only by a\n * placement nested in a component, which placement: the badge its roots\n * share.\n */\nexport interface ConditionMarks {\n  readonly marks: ReadonlyMap<string, ConditionMark>;\n  readonly nested: ReadonlyMap<string, string>;\n}\n\n/**\n * Every conditioned block's mark, from one walk, asked of the engine's own\n * gate so the canvas marks exactly the blocks the page judges. `unchecked`\n * names the blocks whose conditions the page can't check, which only a host\n * knowing the collections' fields can say.\n */\nexport function conditionMarksOf(\n  document: BlockDocument,\n  unchecked: ReadonlySet<string> | undefined,\n  composed: { definitions?: DefinitionsById; limits?: DocumentLimits },\n  applied?: AppliedConditions\n): ConditionMarks {\n  const marks = new Map<string, ConditionMark>();\n  const nested = new Map<string, string>();\n  const markIf = (node: BlockNode, gated: boolean): void => {\n    if (marks.has(node.id) || !gated) return;\n    marks.set(\n      node.id,\n      unchecked?.has(node.id) === true ? \"unchecked\" : \"conditional\"\n    );\n  };\n  const bound = {\n    maxNodes: composed.limits?.maxNodes ?? DEFAULT_LIMITS.maxNodes,\n  };\n  // The page's own blocks, a placement among them, by their ids, which are\n  // the addresses the canvas draws them with.\n  walkNodes(document.nodes, node => markIf(node, gatedAsStored(node)), bound);\n  // And the blocks a placed component's definition holds, by the ids the\n  // composed tree gives them, which the canvas draws them with: composed as\n  // the renderer composes, each conditioned placement expanded too. The\n  // page's own conditions are lifted first, as the canvas draws the page, so\n  // what a composed block carries is its definition's: its own conditions,\n  // and the gates of the placements nested inside a component that were\n  // expanded into it, which only the composed tree still holds.\n  if (composed.definitions !== undefined && composed.definitions.size > 0) {\n    // Under the limits the canvas renders with, so a page the site allows\n    // past the default is composed here as it is drawn, from the definitions\n    // as the renderer reads them.\n    const tree = resolveComponentInstances(\n      revealConditioned(document),\n      asStoredDefinitions(composed.definitions, composed.limits),\n      {\n        conditioned: \"carry\",\n        ...(composed.limits === undefined ? {} : { limits: composed.limits }),\n      }\n    ).document;\n    const placements = new Map<string, string>();\n    walkNodes(\n      tree.nodes,\n      node => {\n        markIf(node, gatedAsDrawn(node));\n        const placement = nestedPlacementOf(node);\n        if (placement === undefined) return;\n        // The innermost placement's gate is the first a root carries, the\n        // same for each of its roots, so they share one badge.\n        let group = placements.get(placement);\n        if (group === undefined) {\n          group = `p${String(placements.size + 1)}`;\n          placements.set(placement, group);\n        }\n        nested.set(node.id, group);\n      },\n      bound\n    );\n  }\n  // While conditions are applied, a judged block a visitor would see says so,\n  // and one they would not is drawn as its marker, which says so itself.\n  if (applied !== undefined) {\n    for (const id of applied.shown) marks.set(id, \"shown\");\n    for (const block of applied.hidden) marks.delete(block.id);\n  }\n  return { marks, nested };\n}\n\n/**\n * The gate of the innermost placement nested in a component that a composed\n * block is a root of, as text, when that gate, and not conditions of its own,\n * is what gates it.\n */\nfunction nestedPlacementOf(node: BlockNode): string | undefined {\n  if (gatedAsStored(node) || !isPlainRecord(node.visibility)) return undefined;\n  const gates = placementGatesOf(node.visibility);\n  return gates.length === 0 ? undefined : JSON.stringify(gates[0]);\n}\n\n/**\n * Marks an Entry content block, with the words its at-rest mark's tab reads:\n * \"Entry content · Body\". The block draws the entry's own content rather\n * than the template's, which is edited on the entry, so the canvas says so\n * whether or not it is selected.\n */\nexport const ENTRY_CONTENT_ATTRIBUTE = \"data-nx-entry-content\";\n\n/**\n * Every Entry content block's words, by its id, from one walk: the field it\n * draws named as the template's collection names it.\n */\nexport function entryContentMarksOf(\n  document: BlockDocument,\n  collection: PreviewedCollection | undefined,\n  maxNodes: number | undefined\n): Map<string, string> {\n  const marks = new Map<string, string>();\n  for (const { node } of entryContentPlacements(\n    document.nodes,\n    maxNodes ?? DEFAULT_LIMITS.maxNodes\n  )) {\n    marks.set(\n      node.id,\n      entryContentLabel(entryContentFieldOf(node), collection)\n    );\n  }\n  return marks;\n}\n\n/**\n * The words a block's outermost element carries, by its address, from\n * `marks`: an Entry content block's, or a hidden block's tag. Never inside a\n * Layout region, a document of its own whose ids may repeat the page's.\n */\nexport function outermostMarkFor(\n  element: Element,\n  container: HTMLElement,\n  marks: ReadonlyMap<string, string>\n): string | undefined {\n  if (marks.size === 0) return undefined;\n  const address = nodeAddressOf(element);\n  if (address === null) return undefined;\n  if (element.closest(UNEDITED_REGION) !== null) return undefined;\n  return isOutermostForAddress(element, address, container)\n    ? marks.get(address)\n    : undefined;\n}\n\n/**\n * The mark a drawn element carries: a definition's own conditioned block by\n * its composed id, else the block or placement it is the outermost element\n * of, by its address. Never inside a Layout region, a document of its own\n * whose ids may repeat the page's.\n */\nexport function conditionMarkFor(\n  element: Element,\n  container: HTMLElement,\n  { marks, nested }: ConditionMarks\n): { mark: ConditionMark; own: boolean; nested?: string } | undefined {\n  const address = nodeAddressOf(element);\n  if (address === null) return undefined;\n  if (element.closest(UNEDITED_REGION) !== null) return undefined;\n  const id = element.getAttribute(NODE_ID_ATTRIBUTE);\n  const own = id !== null && id !== address ? marks.get(id) : undefined;\n  const placed = isOutermostForAddress(element, address, container)\n    ? marks.get(address)\n    : undefined;\n  if (own === undefined) {\n    return placed === undefined ? undefined : { mark: placed, own: false };\n  }\n  // A block with conditions of its own that is also the root of a\n  // conditioned placement is drawn only when both hold, so its one badge says\n  // \"Can't be checked\" when either can't be.\n  const placement = id === null ? undefined : nested.get(id);\n  return {\n    mark: placed === \"unchecked\" ? \"unchecked\" : own,\n    own: true,\n    ...(placement === undefined ? {} : { nested: placement }),\n  };\n}\n\n/**\n * Marks every element drawing the block currently being dragged.\n *\n * EVERY element rather than one: a node id is unique in a document and not in\n * the tree drawn from it, so a repeating block is many elements for one id and\n * a mark that stopped at the first would dim one copy of a block that is\n * wholly in flight.\n *\n * Boolean by presence, for the reason {@link SELECTED_ATTRIBUTE} is: the\n * element already states its id.\n */\nexport const DRAG_SOURCE_ATTRIBUTE = \"data-nx-drag-source\";\n\n/**\n * Marks the container a drop would land in.\n *\n * The line says WHERE among siblings; this says WHICH container, and the two\n * are different questions. They come apart exactly where the line alone is\n * ambiguous — the coordinate at the bottom edge of one container is also the\n * top edge of the next, and only this mark separates them.\n */\nexport const DROP_PARENT_ATTRIBUTE = \"data-nx-drop-parent\";\n\n/**\n * Marks the container that will not take the block being dragged.\n *\n * Mutually exclusive with {@link DROP_PARENT_ATTRIBUTE} by construction: the\n * engine answers with a target or a refusal, never both, so an element carrying\n * the two at once is drawing a state that cannot exist.\n */\nexport const DROP_REFUSED_ATTRIBUTE = \"data-nx-drop-refused\";\n\n/**\n * Add or remove a boolean attribute, writing only when the answer changes.\n *\n * The comparison is the point rather than a saving. `setAttribute` queues a\n * mutation record even when the value it writes is the value already there,\n * the empty-container appender observes this subtree, and a drag re-marks on\n * every pointer move — so an unguarded write is a re-measure per frame rather\n * than one per drop.\n *\n * One function rather than the same three lines at each mark: they are one\n * rule, and four copies of it are four chances for the guard to be dropped\n * from whichever copy is edited next.\n */\nexport function setFlag(\n  element: Element,\n  attribute: string,\n  wanted: boolean\n): void {\n  if (wanted === element.hasAttribute(attribute)) return;\n  if (wanted) element.setAttribute(attribute, \"\");\n  else element.removeAttribute(attribute);\n}\n\n/**\n * Set an attribute to a value, or remove it for `undefined`, writing only when\n * it changes, for the reason {@link setFlag} gives.\n */\nexport function setMark(\n  element: Element,\n  attribute: string,\n  value: string | undefined\n): void {\n  if (element.getAttribute(attribute) === (value ?? null)) return;\n  if (value === undefined) element.removeAttribute(attribute);\n  else element.setAttribute(attribute, value);\n}\n","\"use client\";\n\n/**\n * The width beside the device buttons, while the host previews other widths:\n * a button that swaps in a number field to type one, in the warning colour\n * with \"Reset\" beside it while a width other than the device's own is shown.\n *\n * @module canvas-preview-width-field\n */\n\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport * as React from \"react\";\n\nimport { clampPreviewWidth, type PreviewWidthRange } from \"./canvas-width\";\n\n/** The house focus ring, as the device buttons draw it. */\nconst FOCUS_RING =\n  \"focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-[color:var(--nx-builder-surface)] focus-visible:outline-none\";\n\n/**\n * The width shown, as a button to type another, and Reset while it is not\n * the device's own.\n *\n * @experimental\n */\nexport function PreviewWidthText({\n  shown,\n  previewing,\n  deviceWidth,\n  range,\n  onPreviewWidth,\n}: {\n  /** The width the frame is laid out at. */\n  shown: number;\n  /** Whether that is a width other than the device's own. */\n  previewing: boolean;\n  deviceWidth: number;\n  range: PreviewWidthRange;\n  onPreviewWidth: (width: number | null) => void;\n}): React.JSX.Element {\n  const [typing, setTyping] = React.useState(false);\n  const button = React.useRef<HTMLButtonElement | null>(null);\n  const field = React.useRef<HTMLInputElement | null>(null);\n  // Back to the button once the field goes, so focus is not lost with it.\n  const refocus = React.useRef(false);\n\n  React.useEffect(() => {\n    if (typing) {\n      field.current?.focus();\n      field.current?.select();\n    } else if (refocus.current) {\n      refocus.current = false;\n      button.current?.focus();\n    }\n  }, [typing]);\n\n  const close = (): void => {\n    refocus.current = true;\n    setTyping(false);\n  };\n\n  /** Applies a typed width, in the range; the device's own width is none. */\n  const apply = (typed: string): void => {\n    const value = Number(typed);\n    close();\n    if (typed.trim() === \"\" || !Number.isFinite(value)) return;\n    const width = clampPreviewWidth(value, range);\n    onPreviewWidth(width === deviceWidth ? null : width);\n  };\n\n  const tone = previewing\n    ? \"text-[color:var(--nx-builder-warning-text)]\"\n    : undefined;\n\n  return (\n    <>\n      {typing ? (\n        <span className=\"inline-flex h-full items-center gap-0.5 px-1 text-xs\">\n          <input\n            ref={field}\n            type=\"number\"\n            aria-label=\"Preview width\"\n            min={range.min}\n            max={range.max}\n            defaultValue={shown}\n            className=\"nx-preview-width__field h-full w-14 rounded border bg-transparent px-1 text-xs tabular-nums\"\n            onKeyDown={event => {\n              if (event.key === \"Enter\") {\n                event.preventDefault();\n                apply(event.currentTarget.value);\n              } else if (event.key === \"Escape\") {\n                event.preventDefault();\n                // The field's Escape, not the editor's: the selection stays.\n                event.stopPropagation();\n                close();\n              }\n            }}\n            // Leaving the field without Enter changes nothing.\n            onBlur={() => setTyping(false)}\n          />\n          <span aria-hidden=\"true\">px</span>\n        </span>\n      ) : (\n        <button\n          ref={button}\n          type=\"button\"\n          data-nx-active-width=\"\"\n          {...(previewing ? { \"data-previewing\": \"\" } : {})}\n          aria-label={`Preview width, ${String(shown)}px`}\n          onClick={() => setTyping(true)}\n          className={cn(\n            \"inline-flex h-full items-center rounded px-1.5 text-xs tabular-nums\",\n            FOCUS_RING,\n            tone\n          )}\n        >\n          {`${String(shown)}px`}\n        </button>\n      )}\n      {previewing ? (\n        <button\n          type=\"button\"\n          onClick={() => {\n            onPreviewWidth(null);\n            // Reset goes with the width it resets, so focus moves to the width.\n            button.current?.focus();\n          }}\n          className={cn(\n            \"inline-flex h-full items-center rounded px-1.5 text-xs font-medium\",\n            FOCUS_RING,\n            \"text-[color:var(--nx-builder-warning-text)]\"\n          )}\n        >\n          Reset\n        </button>\n      ) : null}\n    </>\n  );\n}\n","/**\n * How a radio group moves under the arrow keys, in one definition.\n *\n * Two controls in this package are radio groups with a roving tab stop — the\n * canvas width switcher and the interaction-state switcher — and both have to\n * agree about which keys move a selection and in which direction. Written out\n * twice they agree on the day they are written: a later change teaching one of\n * them Home and End, or correcting a direction under a right-to-left writing\n * mode, silently leaves the other answering the old way, and nothing about\n * either file looks wrong.\n *\n * Both axes, deliberately. The APG's radio-group pattern maps the vertical\n * arrows onto the same movement as the horizontal ones whatever the visual\n * orientation, so a control laid out in a row still answers to Down — which is\n * what a screen-reader user pressing it expects, and what a control handling\n * only its own axis fails to do.\n *\n * @module roving-radios\n */\n\n/**\n * Which way an arrow key moves within a radio group, or `null` for a key that\n * is not one of them.\n *\n * `null` rather than `0` so a caller cannot accidentally treat \"not an arrow\n * key\" as a move of no distance: the two need different handling, since only\n * the first must leave the event alone for whatever else is listening.\n */\nexport function radioGroupStep(key: string): -1 | 1 | null {\n  if (key === \"ArrowRight\" || key === \"ArrowDown\") return 1;\n  if (key === \"ArrowLeft\" || key === \"ArrowUp\") return -1;\n  return null;\n}\n","\"use client\";\n\n/**\n * The device buttons: which of the site's breakpoints the author is styling.\n *\n * **The chosen device IS the breakpoint being edited.** It is the author's\n * choice and nothing else changes it: opening a panel, or a narrower window,\n * only changes how far the canvas is zoomed to fit. The canvas lays the page\n * out at the device's preview width (`previewWidth` in `canvas-width.ts`), so\n * what the author sees is the layout of the breakpoint they are editing.\n *\n * The base breakpoint is named Desktop. Each device is an icon whose\n * accessible name and tooltip give its name, its exact preview width and the\n * widths it styles (\"Desktop · 1280px · styles for 1024px and wider\"), and\n * the width being styled is always shown as text beside the buttons\n * (\"1280px\"): a rounded number that differs from the real one misleads\n * exactly where an author checks a boundary.\n *\n * **Three buttons at most.** The base and the two widest breakpoints are\n * buttons; the rest are in a menu beside them, its own button rather than part\n * of the radio group. While the device being styled is in the menu, the menu's\n * button shows it. The buttons never change places, so a device is always\n * where the author last found it.\n *\n * **A breakpoint selector, not a device preview.** It says which breakpoint is\n * being styled; it makes no claim that the result matches what a visitor sees\n * on a particular phone or tablet.\n *\n * @module breakpoint-switcher\n */\n\nimport {\n  BASE_BREAKPOINT,\n  type BreakpointId,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport { ChevronDown, Laptop, Monitor, Smartphone, Tablet } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { PreviewWidthText } from \"../canvas/canvas-preview-width-field\";\nimport {\n  baseWidth,\n  offeredTiers,\n  previewWidth,\n  previewWidthRange,\n} from \"../canvas/canvas-width\";\nimport { ChromeTooltip } from \"../chrome-tooltip\";\nimport { radioGroupStep } from \"../roving-radios\";\nimport { authoredBreakpoints, BASE_DEVICE_LABEL } from \"../styles/breakpoints\";\n\n/**\n * Props for BreakpointSwitcher.\n * @experimental\n */\nexport interface BreakpointSwitcherProps {\n  /** The site's saved breakpoints, as the canvas is compiled against them. */\n  breakpoints: BreakpointSet | undefined;\n  /** The breakpoint being edited: one of the site's ids, or the base one. */\n  selected: BreakpointId;\n  /** A device was chosen. */\n  onSelect: (breakpoint: BreakpointId) => void;\n  /**\n   * Whether the saved breakpoints have been read. Until they have, the\n   * buttons are inert: choosing a device against a list that is about to be\n   * replaced would style a breakpoint the site may not have.\n   */\n  status: \"loading\" | \"unavailable\" | \"ready\";\n  /**\n   * The width the canvas previews in place of the chosen device's own, or\n   * `null` at the device's own. Shown in the warning colour with \"Reset\"\n   * beside it; the device chosen stays the one every edit goes to.\n   */\n  previewWidth?: number | null;\n  /**\n   * Where a typed width and Reset go, `null` for the device's own. Given, the\n   * width beside the buttons is a button that swaps in a field to type one;\n   * left out, it is text.\n   */\n  onPreviewWidth?: (width: number | null) => void;\n}\n\n/**\n * The glyph for a device, chosen by the width it applies at rather than by\n * its name, which is whatever the site called it.\n */\nexport function tierIcon(\n  bound: number | undefined\n): React.ComponentType<{ className?: string }> {\n  if (bound === undefined) return Monitor;\n  if (bound <= 640) return Smartphone;\n  if (bound <= 1024) return Tablet;\n  return Laptop;\n}\n\nexport interface DeviceOption {\n  id: BreakpointId;\n  label: string;\n  /** The width the canvas lays this device out at. */\n  preview: number | undefined;\n  /** Where the breakpoint applies, in words, as Settings lists it. */\n  range: string;\n  /**\n   * The same widths as the device's control says them, after \"styles for\":\n   * \"1024px and wider\", \"991px and narrower\". From the same bound as\n   * {@link DeviceOption.range}, so the two cannot disagree.\n   */\n  stylesFor: string;\n}\n\n/**\n * The devices, base first, then each breakpoint from the widest down. One\n * answer for every surface that names them: these buttons, and Settings' list\n * of the site's breakpoints.\n */\nexport function deviceOptions(\n  breakpoints: BreakpointSet | undefined\n): DeviceOption[] {\n  const authored = authoredBreakpoints(\n    breakpoints ?? { viewport: [], container: [] }\n  ).viewport;\n  const from = baseWidth(breakpoints);\n  return [\n    {\n      id: BASE_BREAKPOINT,\n      label: BASE_DEVICE_LABEL,\n      preview: previewWidth(breakpoints, BASE_BREAKPOINT),\n      range: from === undefined ? \"every width\" : `from ${from} pixels`,\n      stylesFor: from === undefined ? \"every width\" : `${from}px and wider`,\n    },\n    ...offeredTiers(breakpoints).map(tier => ({\n      id: tier.id,\n      // The label from the definition the compiler kept for this bound, so two\n      // rows sharing one bound are named by the one that applies.\n      label:\n        authored.find(\n          def => def.id === tier.id && def.maxWidth === tier.maxWidth\n        )?.label ?? tier.id,\n      preview: tier.maxWidth,\n      range: `up to ${tier.maxWidth} pixels`,\n      stylesFor: `${tier.maxWidth}px and narrower`,\n    })),\n  ];\n}\n\n/**\n * What the switcher calls the device for this tier, or `undefined` for a tier\n * it does not offer (a container tier). Read from the switcher's own list, so\n * a surface naming the device being edited says what the switcher says.\n */\nexport function deviceLabel(\n  breakpoints: BreakpointSet | undefined,\n  id: BreakpointId\n): string | undefined {\n  return deviceOptions(breakpoints).find(option => option.id === id)?.label;\n}\n\n/** How many devices are buttons, the base counting as one. */\nconst BUTTON_COUNT = 3;\n\n/**\n * The house focus ring, off the button by a gap of the bar's surface, so it\n * shows on the chosen device's filled button as well as on the others. Without\n * it the buttons fell back to the browser's own outline.\n */\nconst FOCUS_RING =\n  \"focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-[color:var(--nx-builder-surface)] focus-visible:outline-none\";\n\n/** What a device's menu item reads: its name and the width it is previewed at. */\nfunction shownLabel(option: DeviceOption): string {\n  return option.preview === undefined\n    ? option.label\n    : `${option.label} · ${option.preview}px`;\n}\n\n/**\n * A device's accessible name and tooltip: its name, its preview width and the\n * widths it styles, \"Desktop · 1280px · styles for 1024px and wider\".\n */\nfunction deviceName(option: DeviceOption): string {\n  return `${shownLabel(option)} · styles for ${option.stylesFor}`;\n}\n\n/** Why the devices cannot be chosen yet, for a gate that is not open. */\nfunction notReadyReason(status: BreakpointSwitcherProps[\"status\"]): string {\n  return status === \"loading\"\n    ? \"Available once the site's saved styles have loaded.\"\n    : \"Your site's saved styles could not be read, so the canvas cannot be sized against them.\";\n}\n\n/** The glyph a device is drawn with. */\nfunction glyphOf(option: DeviceOption): React.ComponentType<{\n  className?: string;\n}> {\n  return tierIcon(option.id === BASE_BREAKPOINT ? undefined : option.preview);\n}\n\n/** A device's glyph, decoration beside the name its control carries. */\nfunction DeviceGlyph({ device }: { device: DeviceOption }): React.JSX.Element {\n  const Glyph = glyphOf(device);\n  return <Glyph className=\"size-3.5\" aria-hidden=\"true\" />;\n}\n\n/**\n * One device's radio button: its glyph, named and tooltipped with its name,\n * width and range. Until the saved breakpoints are read it is inert, and the\n * browser's own tooltip says why, since a disabled control opens no other.\n */\nfunction DeviceButton({\n  option,\n  isSelected,\n  ready,\n  status,\n  inTabOrder,\n  buttonRef,\n  onSelect,\n}: {\n  option: DeviceOption;\n  isSelected: boolean;\n  ready: boolean;\n  status: BreakpointSwitcherProps[\"status\"];\n  inTabOrder: boolean;\n  buttonRef: (element: HTMLButtonElement | null) => void;\n  onSelect: (breakpoint: BreakpointId) => void;\n}): React.JSX.Element {\n  const name = deviceName(option);\n  return (\n    <ChromeTooltip content={name} disabled={!ready}>\n      <button\n        ref={buttonRef}\n        type=\"button\"\n        role=\"radio\"\n        aria-checked={isSelected}\n        disabled={!ready}\n        aria-label={name}\n        {...(ready ? {} : { title: notReadyReason(status) })}\n        tabIndex={inTabOrder ? 0 : -1}\n        onClick={() => onSelect(option.id)}\n        className={cn(\n          \"inline-flex h-full items-center rounded px-2 text-xs\",\n          FOCUS_RING,\n          isSelected\n            ? \"bg-accent text-accent-foreground\"\n            : \"text-muted-foreground\"\n        )}\n      >\n        <DeviceGlyph device={option} />\n      </button>\n    </ChromeTooltip>\n  );\n}\n\n/**\n * How the menu's button reads: plain, or naming the device being styled when\n * that device is in the menu. Its tooltip says what a button's says, since\n * the button shows the device's glyph alone.\n */\nfunction moreDevicesTrigger(chosen: DeviceOption | undefined): {\n  name: string;\n  tip: string;\n  tone: string;\n} {\n  if (chosen === undefined) {\n    return {\n      name: \"More devices\",\n      tip: \"More devices\",\n      tone: \"text-muted-foreground\",\n    };\n  }\n  return {\n    name: `More devices, styling ${deviceName(chosen)}`,\n    tip: deviceName(chosen),\n    tone: \"bg-accent text-accent-foreground\",\n  };\n}\n\n/**\n * The devices past the third, in a menu of their own.\n *\n * Its button shows the glyph of the device being styled while that device is\n * one of these, and names it; otherwise it is a plain \"More devices\".\n */\nfunction MoreDevices({\n  devices,\n  chosen,\n  ready,\n  onSelect,\n}: {\n  devices: readonly DeviceOption[];\n  chosen: DeviceOption | undefined;\n  ready: boolean;\n  onSelect: (breakpoint: BreakpointId) => void;\n}): React.JSX.Element {\n  const trigger = moreDevicesTrigger(chosen);\n  /*\n   * Held here so a menu already open closes when the saved breakpoints stop\n   * being trusted: disabling the trigger alone leaves an open menu choosing\n   * against the list the switcher has just declared untrusted.\n   */\n  const [open, setOpen] = React.useState(false);\n  return (\n    // Not modal, as the zoom menu: a modal menu hides the focusable editor\n    // around it from assistive technology (axe: aria-hidden-focus).\n    <DropdownMenu modal={false} open={open && ready} onOpenChange={setOpen}>\n      <ChromeTooltip content={trigger.tip} disabled={!ready}>\n        <DropdownMenuTrigger\n          disabled={!ready}\n          aria-label={trigger.name}\n          {...(chosen === undefined ? {} : { \"data-styling\": \"\" })}\n          className={cn(\n            \"inline-flex h-full items-center gap-1 rounded px-1.5 text-xs disabled:opacity-40\",\n            FOCUS_RING,\n            trigger.tone\n          )}\n        >\n          {chosen === undefined ? null : <DeviceGlyph device={chosen} />}\n          <ChevronDown className=\"size-3.5\" aria-hidden=\"true\" />\n        </DropdownMenuTrigger>\n      </ChromeTooltip>\n      <DropdownMenuContent align=\"start\">\n        <DropdownMenuRadioGroup\n          value={chosen?.id ?? \"\"}\n          onValueChange={id => {\n            if (ready) onSelect(id);\n          }}\n        >\n          {devices.map(device => (\n            <DropdownMenuRadioItem\n              key={device.id}\n              value={device.id}\n              aria-label={deviceName(device)}\n            >\n              {shownLabel(device)}\n            </DropdownMenuRadioItem>\n          ))}\n        </DropdownMenuRadioGroup>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/**\n * The width the canvas is laid out at, beside the buttons at every top-bar\n * width: the devices are icons, and this is the number an author styles\n * against. Where the host previews other widths it is a button to type one,\n * and a width other than the device's own is in the warning colour with\n * Reset. Otherwise it is text hidden from assistive technology, which hears\n * it in the chosen device's name and in the switcher's announcement.\n */\nfunction ActiveWidth({\n  deviceWidth,\n  breakpoints,\n  previewed,\n  onPreviewWidth,\n}: {\n  deviceWidth: number;\n  breakpoints: BreakpointSet | undefined;\n  previewed: number | null;\n  onPreviewWidth: ((width: number | null) => void) | undefined;\n}): React.JSX.Element {\n  if (onPreviewWidth === undefined) {\n    return (\n      <span\n        data-nx-active-width=\"\"\n        aria-hidden=\"true\"\n        className=\"px-1.5 text-xs tabular-nums\"\n      >\n        {`${deviceWidth}px`}\n      </span>\n    );\n  }\n  return (\n    <PreviewWidthText\n      shown={previewed ?? deviceWidth}\n      previewing={previewed !== null}\n      deviceWidth={deviceWidth}\n      range={previewWidthRange(breakpoints)}\n      onPreviewWidth={onPreviewWidth}\n    />\n  );\n}\n\n/**\n * The width on a site with no device to switch to, where the host previews\n * other widths: the canvas still takes any width from its handles, so the\n * width and Reset are offered without the buttons. Desktop's own width is\n * the widest a preview reaches.\n */\nfunction WidthWithoutDevices({\n  ready,\n  breakpoints,\n  previewed,\n  onPreviewWidth,\n}: {\n  ready: boolean;\n  breakpoints: BreakpointSet | undefined;\n  previewed: number | null;\n  onPreviewWidth: ((width: number | null) => void) | undefined;\n}): React.JSX.Element | null {\n  if (!ready || onPreviewWidth === undefined) return null;\n  return (\n    <div className=\"inline-flex h-[var(--nx-builder-control-height,1.75rem)] items-center rounded-md border p-0.5\">\n      <ActiveWidth\n        deviceWidth={previewWidthRange(breakpoints).max}\n        breakpoints={breakpoints}\n        previewed={previewed}\n        onPreviewWidth={onPreviewWidth}\n      />\n    </div>\n  );\n}\n\nexport function BreakpointSwitcher({\n  breakpoints,\n  selected,\n  onSelect,\n  status,\n  previewWidth: previewed = null,\n  onPreviewWidth,\n}: BreakpointSwitcherProps): React.JSX.Element | null {\n  const ready = status === \"ready\";\n  const options = React.useMemo(\n    () => deviceOptions(breakpoints),\n    [breakpoints]\n  );\n  const radios = React.useRef<Array<HTMLButtonElement | null>>([]);\n\n  // An id the list does not hold is shown as the base, which is where the\n  // host sends an edit for a breakpoint the site no longer defines.\n  const found = options.findIndex(option => option.id === selected);\n  const activeIndex = found >= 0 ? found : 0;\n  const active = options[activeIndex];\n  const buttons = options.slice(0, BUTTON_COUNT);\n  const overflow = options.slice(BUTTON_COUNT);\n  // The button styled, or none when the device styled is in the menu: the\n  // arrows then start from the first button, which holds the tab stop.\n  const buttonIndex = activeIndex < BUTTON_COUNT ? activeIndex : -1;\n\n  const move = (delta: number): void => {\n    const from = Math.max(buttonIndex, 0);\n    const index = (from + delta + buttons.length) % buttons.length;\n    const next = buttons[index];\n    if (next === undefined) return;\n    radios.current[index]?.focus();\n    onSelect(next.id);\n  };\n\n  // Desktop alone is not a choice: the device buttons appear once the site\n  // has a breakpoint to switch to. A previewed width still has its own.\n  if (options.length < 2) {\n    return (\n      <WidthWithoutDevices\n        ready={ready}\n        breakpoints={breakpoints}\n        previewed={previewed}\n        onPreviewWidth={onPreviewWidth}\n      />\n    );\n  }\n\n  return (\n    // The whole switcher one control high, its border and padding inside that\n    // height, with the device buttons filling what is left; the scale's own\n    // value stands in where the density tokens aren't declared.\n    <div className=\"inline-flex h-[var(--nx-builder-control-height,1.75rem)] items-center gap-0.5 rounded-md border p-0.5\">\n      <div\n        role=\"radiogroup\"\n        aria-label=\"Device\"\n        className=\"nx-breakpoint-switcher inline-flex h-full items-center gap-0.5\"\n        onKeyDown={event => {\n          if (!ready) return;\n          const step = radioGroupStep(event.key);\n          if (step === null) return;\n          event.preventDefault();\n          move(step);\n        }}\n      >\n        {buttons.map((option, index) => (\n          <DeviceButton\n            key={option.id}\n            option={option}\n            isSelected={ready && index === buttonIndex}\n            ready={ready}\n            status={status}\n            inTabOrder={index === Math.max(buttonIndex, 0)}\n            buttonRef={element => {\n              radios.current[index] = element;\n            }}\n            onSelect={onSelect}\n          />\n        ))}\n        {/* Says which device is being styled when the choice changes, for an\n          author who cannot see the buttons. */}\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {ready && active !== undefined\n            ? `Styling ${active.label}${active.preview === undefined ? \"\" : `, ${active.preview} pixels`}`\n            : \"\"}\n        </span>\n      </div>\n      {overflow.length === 0 ? null : (\n        <MoreDevices\n          devices={overflow}\n          chosen={ready && buttonIndex < 0 ? active : undefined}\n          ready={ready}\n          onSelect={onSelect}\n        />\n      )}\n      {ready && active?.preview !== undefined ? (\n        <ActiveWidth\n          deviceWidth={active.preview}\n          breakpoints={breakpoints}\n          previewed={previewed}\n          onPreviewWidth={onPreviewWidth}\n        />\n      ) : null}\n    </div>\n  );\n}\n","/**\n * The blocks the page hides on the device the canvas shows, drawn anyway and\n * striped, so a block a visitor on that device won't see is still there to\n * find, select and edit.\n *\n * Editor-only by construction, as the reveal of a selected hidden block is:\n * the canvas draws a derived document with those blocks' device hiding\n * lifted, and the editor saves its own, so nothing here reaches what is\n * stored or published. The mark on the block's element is edged by the\n * frame's own sheet (`canvas-frame-sheet.ts`) and striped and tagged by the\n * editor's marks over the canvas (`canvas-marks.tsx`); the site sheet never\n * carries it.\n *\n * Which device the canvas shows is read from the width its page is laid out\n * at, the one its media queries answer for, through the same reading the\n * device buttons size the canvas by. So the stripe is drawn exactly where the\n * page's own CSS would hide the block.\n *\n * @module canvas-device-hidden\n */\n\nimport {\n  hiddenOnDevice,\n  revealDeviceHidden,\n  walkNodes,\n  type BlockDocument,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  sharedStyleInputs,\n  type PageRendererProps,\n} from \"@nextlyhq/blocks-react\";\nimport { useMemo } from \"react\";\n\nimport { deviceLabel } from \"../shell/breakpoint-switcher\";\n\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { editedBreakpointAtWidth } from \"./canvas-width\";\n\n/**\n * Marks a block the page hides on the device shown, drawn striped. Its value\n * is the tag the stripe carries: \"Hidden on Mobile · still here in the\n * builder\".\n */\nexport const DEVICE_HIDDEN_ATTRIBUTE = \"data-nx-device-hidden\";\n\n/** The set a site stating no breakpoints at all compiles under: no tiers. */\nconst NO_TIERS: BreakpointSet = { viewport: [], container: [] };\n\n/**\n * The breakpoints the page's own rules are compiled under, so a block is read\n * as hidden on exactly the devices its media queries hide it on: reconciled\n * from the route's context and the site's styles by `sharedStyleInputs`,\n * the same reading `PageRenderer` compiles by, so the site's set wins where\n * both state one. A site stating none (`null`) has no tiers, as the\n * renderer reads it; `undefined` where neither states any.\n */\nexport function drawnBreakpoints(\n  render: Pick<PageRendererProps, \"styleContext\"> | undefined,\n  siteStyles: PageRendererProps[\"siteStyles\"]\n): BreakpointSet | undefined {\n  const site = typeof siteStyles === \"object\" ? siteStyles : undefined;\n  const stated = sharedStyleInputs(render?.styleContext, site).breakpoints;\n  return stated === null ? NO_TIERS : stated;\n}\n\n/** The tag on a block hidden on `device`. */\nfunction deviceHiddenTag(device: string): string {\n  return `Hidden on ${device} · still here in the builder`;\n}\n\n/** The page as the canvas draws it, and the blocks it stripes, by id. */\nexport interface DeviceHiddenDrawing {\n  readonly document: BlockDocument;\n  /** Each striped block's tag, by id. */\n  readonly marks: ReadonlyMap<string, string>;\n}\n\nconst NO_MARKS: ReadonlyMap<string, string> = new Map();\n\n/**\n * The page with every block hidden on `device` drawn, and those blocks'\n * tags. The same document, and no marks, when no block is hidden there.\n */\nexport function deviceHiddenDrawing(\n  document: BlockDocument,\n  breakpoints: BreakpointSet | undefined,\n  device: string\n): DeviceHiddenDrawing {\n  const ids: string[] = [];\n  walkNodes(document.nodes, node => {\n    if (hiddenOnDevice(node.visibility, breakpoints, device)) ids.push(node.id);\n  });\n  if (ids.length === 0) return { document, marks: NO_MARKS };\n  const tag = deviceHiddenTag(deviceLabel(breakpoints, device) ?? device);\n  return {\n    document: revealDeviceHidden(document, ids),\n    marks: new Map(ids.map(id => [id, tag])),\n  };\n}\n\n/**\n * {@link deviceHiddenDrawing} for the device the canvas is laid out at.\n * `striping` false draws the page as a visitor gets it, as \"Preview as\n * visitor\" does: nothing lifted, nothing striped.\n */\nexport function useDeviceHiddenDrawing(\n  document: BlockDocument,\n  breakpoints: BreakpointSet | undefined,\n  striping: boolean\n): DeviceHiddenDrawing {\n  const canvas = useCanvasFrame();\n  // The width the page's media queries read: its window's, scrollbar and\n  // all. Read again whenever the frame reports a new viewport, which is when\n  // that width can have changed.\n  const width = canvas.window?.innerWidth ?? canvas.viewport?.width;\n  const device = editedBreakpointAtWidth(breakpoints, width);\n  return useMemo(\n    () =>\n      striping\n        ? deviceHiddenDrawing(document, breakpoints, device)\n        : { document, marks: NO_MARKS },\n    [document, breakpoints, device, striping]\n  );\n}\n","/**\n * A list to choose one entry from, for the inspector's pickers: the Font\n * control's families and the colour control's variables.\n *\n * One list for both, so the two pickers answer the keyboard the same way:\n * the arrow keys, Home and End move, Enter picks, and a search appears once\n * the list is long enough to need one. Focus sits on the search when there is\n * one and on the list when there is not; either way the active entry is named\n * by `aria-activedescendant`, so a screen reader announces it as it moves.\n *\n * @module choice-list\n */\nimport { Input } from \"@nextlyhq/ui\";\nimport { ChevronRight, Search } from \"lucide-react\";\nimport * as React from \"react\";\n\n/** One entry: what keys it, what it is called, and the group it sits in. */\nexport interface ListedChoice {\n  readonly key: string;\n  readonly label: string;\n  /** The group it is listed under, when the list has groups. */\n  readonly group?: string;\n  /**\n   * What the search matches it by, when not its label alone: a label and\n   * the line drawn under it, so what is searched is what is seen.\n   */\n  readonly search?: string;\n  /**\n   * Listed, and reached by the arrow keys, but never picked: a choice whose\n   * row says why it can't be had yet.\n   */\n  readonly disabled?: boolean;\n}\n\n/** One group of a grouped list: what keys it, and its heading. */\nexport interface ChoiceGroup {\n  readonly group: string;\n  readonly heading: string;\n  /**\n   * Set to start the group folded: drawn as one row, `label`, which opens\n   * it in place, under `heading`, which folded groups listed together share\n   * (\"Singles · Site\"). A search shows a folded group's matching entries.\n   */\n  readonly fold?: {\n    readonly heading: string;\n    readonly label: string;\n    /**\n     * What choosing the folded row does, said to a screen reader as the\n     * row's description: an option may not say it is expanded.\n     */\n    readonly hint?: string;\n  };\n}\n\n/** What a folded row's description says where its group gives none. */\nconst FOLD_HINT = \"Opens its entries here.\";\n\n/** How many entries the list holds before it offers a search. */\nconst SEARCH_FROM = 8;\n\nexport interface ChoiceListProps<C extends ListedChoice> {\n  readonly choices: readonly C[];\n  /** The entry the stored value is, marked in the list. */\n  readonly currentKey: string | undefined;\n  readonly onPick: (choice: C) => void;\n  /**\n   * The author moved onto an entry that can be picked, by an arrow key, Home,\n   * End or the pointer: for a picker that shows the entry before it is\n   * picked, as the Font control draws a family on the canvas.\n   */\n  readonly onActive?: (choice: C) => void;\n  /** What the list is called: \"Fonts\". */\n  readonly label: string;\n  /** What the search is called, and says while empty: \"Search fonts\". */\n  readonly searchLabel: string;\n  /** What the list says when the search matches nothing. */\n  readonly noMatch: string;\n  /**\n   * The headings of the groups, in the order they are listed. Without them\n   * the list is one run of entries. An empty heading draws none.\n   */\n  readonly groups?: ReadonlyArray<ChoiceGroup>;\n  /** What an entry draws: its label unless said otherwise. */\n  readonly renderChoice?: (choice: C) => React.ReactNode;\n\n  /**\n   * An entry's tooltip: its label unless said otherwise, such as a label and\n   * a value the row may cut short.\n   */\n  readonly choiceTitle?: (choice: C) => string;\n  /** An entry's own style, such as a family drawn in itself. */\n  readonly choiceStyle?: (choice: C) => React.CSSProperties | undefined;\n  /** A class each entry carries beside the list's own. */\n  readonly choiceClassName?: string;\n  /**\n   * How many entries the list holds before it offers a search, when a list\n   * needs a figure of its own rather than the pickers' shared one.\n   */\n  readonly searchFrom?: number;\n  /**\n   * Drawn between the search and the rows: a group with nothing to offer,\n   * said where its rows would be.\n   */\n  readonly leading?: React.ReactNode;\n}\n\n/**\n * One row as the list draws it: an entry, or a folded group's one row.\n */\ntype DrawnRow<C extends ListedChoice> =\n  | { readonly kind: \"choice\"; readonly key: string; readonly choice: C }\n  | {\n      readonly kind: \"fold\";\n      readonly key: string;\n      readonly group: ChoiceGroup;\n    };\n\n/** The entries matching `query`, ignoring case, in the order given. */\nfunction matchingChoices<C extends ListedChoice>(\n  choices: readonly C[],\n  query: string\n): readonly C[] {\n  const needle = query.trim().toLowerCase();\n  return needle === \"\"\n    ? choices\n    : choices.filter(choice =>\n        (choice.search ?? choice.label).toLowerCase().includes(needle)\n      );\n}\n\n/**\n * The rows matching `query`, ignoring case, in the order they are DRAWN:\n * grouped, a list draws group by group, and the row it opens on and the one\n * an arrow moves to have to be the ones the author sees there, not the next\n * in the order they were given. A folded group with entries to show is one\n * row in their place.\n */\nfunction drawnRows<C extends ListedChoice>(\n  matching: readonly C[],\n  groups: ChoiceListProps<C>[\"groups\"],\n  isFolded: (group: ChoiceGroup) => boolean\n): readonly DrawnRow<C>[] {\n  const row = (choice: C): DrawnRow<C> => ({\n    kind: \"choice\",\n    key: choice.key,\n    choice,\n  });\n  if (groups === undefined) return matching.map(row);\n  return groups.flatMap((group): DrawnRow<C>[] => {\n    const members = matching.filter(choice => choice.group === group.group);\n    if (members.length === 0) return [];\n    return isFolded(group)\n      ? [{ kind: \"fold\", key: `\\u0000fold:${group.group}`, group }]\n      : members.map(row);\n  });\n}\n\n/**\n * The groups as drawn, in order: each open group on its own, and each run of\n * folded groups together under the headings they share.\n */\nfunction drawnSections(\n  groups: ReadonlyArray<ChoiceGroup>,\n  isFolded: (group: ChoiceGroup) => boolean\n): ReadonlyArray<{ readonly heading: string; readonly groups: ChoiceGroup[] }> {\n  const sections: { heading: string; groups: ChoiceGroup[] }[] = [];\n  for (const group of groups) {\n    const last = sections.at(-1);\n    if (isFolded(group) && last !== undefined && isFolded(last.groups[0])) {\n      last.groups.push(group);\n      continue;\n    }\n    sections.push({ heading: group.heading, groups: [group] });\n  }\n  return sections.map(section =>\n    isFolded(section.groups[0])\n      ? {\n          ...section,\n          heading: [\n            ...new Set(section.groups.map(group => group.fold!.heading)),\n          ].join(\" · \"),\n        }\n      : section\n  );\n}\n\n/**\n * What moving to a row does: it becomes the active one, and an entry that can\n * be picked is said to `onActive`, unless it is the entry said last. Judged by\n * the entry rather than by its place: a search moves a different entry into\n * the active place without the author moving, and the pointer or a key on it\n * then still says it. A pointer resting on one entry says it once.\n */\nfunction activeMover<C extends ListedChoice>(\n  shown: readonly DrawnRow<C>[],\n  setActive: (index: number) => void,\n  said: React.RefObject<string | undefined>,\n  onActive: ((choice: C) => void) | undefined\n): (index: number) => void {\n  return index => {\n    setActive(index);\n    const row = shown[index];\n    if (row?.kind !== \"choice\" || row.choice.disabled === true) return;\n    if (row.choice.key === said.current) return;\n    said.current = row.choice.key;\n    onActive?.(row.choice);\n  };\n}\n\n/**\n * Where the keyboard is while the list is open: on the search, where there is\n * one, which names the active entry itself; otherwise on the list, which does.\n */\nfunction listFocus(\n  searchable: boolean,\n  describedActive: string | undefined\n): { tabIndex: number; \"aria-activedescendant\"?: string } {\n  if (searchable) return { tabIndex: -1 };\n  return describedActive === undefined\n    ? { tabIndex: 0 }\n    : { tabIndex: 0, \"aria-activedescendant\": describedActive };\n}\n\nexport function ChoiceList<C extends ListedChoice>({\n  choices,\n  currentKey,\n  onPick,\n  onActive,\n  label,\n  searchLabel,\n  noMatch,\n  groups,\n  renderChoice,\n  choiceTitle,\n  choiceStyle,\n  choiceClassName,\n  searchFrom = SEARCH_FROM,\n  leading,\n}: ChoiceListProps<C>): React.JSX.Element {\n  const listId = React.useId();\n  const [query, setQuery] = React.useState(\"\");\n  // The folded groups the author opened; a search shows every group.\n  const [opened, setOpened] = React.useState<ReadonlySet<string>>(\n    () => new Set()\n  );\n  const searchable = choices.length > searchFrom;\n  const isFolded = (group: ChoiceGroup): boolean =>\n    group.fold !== undefined && query.trim() === \"\" && !opened.has(group.group);\n  const matching = matchingChoices(choices, query);\n  const shown = drawnRows(matching, groups, isFolded);\n  const [active, setActive] = React.useState(() =>\n    Math.max(\n      0,\n      shown.findIndex(row => row.key === currentKey)\n    )\n  );\n  const activeRow = shown[Math.min(active, shown.length - 1)];\n  const rowId = (row: DrawnRow<C>): string =>\n    `${listId}-${row.key.replace(/[^a-z0-9-]/gi, \"_\")}`;\n\n  const list = React.useRef<HTMLUListElement>(null);\n  const search = React.useRef<HTMLInputElement>(null);\n  React.useEffect(() => {\n    (searchable ? search.current : list.current)?.focus();\n  }, [searchable]);\n  React.useEffect(() => {\n    if (activeRow === undefined) return;\n    document.getElementById(rowId(activeRow))?.scrollIntoView({\n      block: \"nearest\",\n    });\n  });\n\n  /**\n   * A folded group opened in place, the author moved onto its first entry,\n   * so the keyboard goes on from where the row was.\n   */\n  const open = (group: ChoiceGroup): void => {\n    const next = new Set(opened).add(group.group);\n    setOpened(next);\n    const rows = drawnRows(\n      matching,\n      groups,\n      each =>\n        each.fold !== undefined && query.trim() === \"\" && !next.has(each.group)\n    );\n    setActive(\n      Math.max(\n        0,\n        rows.findIndex(\n          row => row.kind === \"choice\" && row.choice.group === group.group\n        )\n      )\n    );\n  };\n\n  /** The author moved to the row at `index`: it is active, and said so. */\n  // The entry last said to `onActive`; the stored one until the author moves.\n  const said = React.useRef<string | undefined>(currentKey);\n  const moveTo = activeMover(shown, setActive, said, onActive);\n\n  /** What pressing a row does: pick an entry, or open a folded group. */\n  const press = (row: DrawnRow<C>): void => {\n    if (row.kind === \"fold\") open(row.group);\n    else if (row.choice.disabled !== true) onPick(row.choice);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent): void => {\n    const last = shown.length - 1;\n    const moves: Record<string, number> = {\n      ArrowDown: Math.min(active + 1, last),\n      ArrowUp: Math.max(active - 1, 0),\n      Home: 0,\n      End: last,\n    };\n    const next = moves[event.key];\n    if (next !== undefined) {\n      event.preventDefault();\n      moveTo(next);\n      return;\n    }\n    if (event.key === \"Enter\" && activeRow !== undefined) {\n      event.preventDefault();\n      press(activeRow);\n    }\n  };\n\n  const describedActive =\n    activeRow === undefined ? undefined : rowId(activeRow);\n\n  /** The id of a folded row's description. */\n  const foldHintId = (row: DrawnRow<C>): string => `${rowId(row)}-hint`;\n\n  const option = (row: DrawnRow<C>): React.JSX.Element => {\n    if (row.kind === \"fold\") {\n      const { fold } = row.group;\n      return (\n        <li\n          key={row.key}\n          id={rowId(row)}\n          role=\"option\"\n          aria-selected={row === activeRow}\n          // An option may not carry aria-expanded, so what choosing it\n          // does is its description, drawn outside the list.\n          aria-describedby={foldHintId(row)}\n          className=\"nx-font-pick__option nx-choice-fold\"\n          title={`Show ${row.group.heading}`}\n          onMouseMove={() => moveTo(shown.indexOf(row))}\n          onClick={() => press(row)}\n        >\n          <span className=\"nx-choice-fold__label\">{fold?.label}</span>\n          <ChevronRight\n            aria-hidden=\"true\"\n            className=\"nx-choice-fold__icon\"\n            size={14}\n          />\n        </li>\n      );\n    }\n    const { choice } = row;\n    return (\n      <li\n        key={row.key}\n        id={rowId(row)}\n        role=\"option\"\n        aria-selected={row === activeRow}\n        aria-disabled={choice.disabled === true ? \"true\" : undefined}\n        data-current={choice.key === currentKey ? \"\" : undefined}\n        className={\n          choiceClassName === undefined\n            ? \"nx-font-pick__option\"\n            : `nx-font-pick__option ${choiceClassName}`\n        }\n        // Cut with an ellipsis when long: whole on hover.\n        title={choiceTitle === undefined ? choice.label : choiceTitle(choice)}\n        style={choiceStyle?.(choice)}\n        onMouseMove={() => moveTo(shown.indexOf(row))}\n        onClick={() => press(row)}\n      >\n        {renderChoice === undefined ? choice.label : renderChoice(choice)}\n      </li>\n    );\n  };\n\n  return (\n    <>\n      {searchable ? (\n        <div className=\"nx-vars__search nx-font-pick__search\">\n          <Search aria-hidden=\"true\" size={16} />\n          <Input\n            ref={search}\n            type=\"search\"\n            role=\"combobox\"\n            aria-label={searchLabel}\n            aria-controls={listId}\n            aria-expanded=\"true\"\n            aria-activedescendant={describedActive}\n            placeholder={searchLabel}\n            value={query}\n            onChange={event => {\n              setQuery(event.target.value);\n              setActive(0);\n            }}\n            onKeyDown={onKeyDown}\n          />\n        </div>\n      ) : null}\n      {leading}\n      <ul\n        ref={list}\n        id={listId}\n        role=\"listbox\"\n        aria-label={label}\n        className=\"nx-font-pick__list\"\n        {...listFocus(searchable, describedActive)}\n        onKeyDown={onKeyDown}\n      >\n        {shown.length === 0 ? (\n          <li className=\"nx-vars__note nx-font-pick__none\" role=\"presentation\">\n            {noMatch}\n          </li>\n        ) : null}\n        {groups === undefined\n          ? shown.map(option)\n          : drawnSections(groups, isFolded).map(({ heading, groups: held }) => {\n              const members = shown.filter(row =>\n                held.some(group =>\n                  row.kind === \"fold\"\n                    ? row.group.group === group.group\n                    : row.choice.group === group.group\n                )\n              );\n              if (members.length === 0) return null;\n              return (\n                <li key={held[0].group} role=\"presentation\">\n                  {/* A group with no heading leads the list unnamed: one\n                      entry standing apart from the groups under it. */}\n                  {heading === \"\" ? null : (\n                    <span\n                      className=\"nx-vars__group-name nx-font-pick__heading\"\n                      aria-hidden=\"true\"\n                    >\n                      {heading}\n                    </span>\n                  )}\n                  <ul\n                    role=\"group\"\n                    aria-label={heading === \"\" ? undefined : heading}\n                    className=\"nx-font-pick__group\"\n                  >\n                    {members.map(option)}\n                  </ul>\n                </li>\n              );\n            })}\n      </ul>\n      {/* Each folded row's description, outside the list, so it is read as\n          the row's description and never as a row or part of its name. */}\n      {shown.map(row =>\n        row.kind === \"fold\" ? (\n          <span\n            key={`${row.key}-hint`}\n            id={foldHintId(row)}\n            className=\"nx-sr-only\"\n          >\n            {row.group.fold?.hint ?? FOLD_HINT}\n          </span>\n        ) : null\n      )}\n    </>\n  );\n}\n","/**\n * A collection list's query as its inspector reads, words and writes it.\n *\n * What is STORED is the engine's: `readListQuery` is the one reading of a\n * list's props, `listSortText` writes the sort back in the spelling it\n * reads, and `listQueryIssues` judges what a save would. This module adds\n * only what an editor needs on top of that, and nothing the engine decides:\n *\n * - which operators an author is offered for a field of each kind, and what\n *   each is called (\"is on or after\" for a date's `greater_than_equal`);\n * - what a sort's direction is called for a field of each kind (\"Newest\n *   first\" for a date, \"A–Z\" for text);\n * - a filter row as one sentence (\"Category is any of News, Guides\");\n * - the edits a row, a key or a bound makes to the stored props, each one\n *   change of the props, so an action is one undo step.\n *\n * Pure, so each rule is tested without a panel.\n *\n * @module list-query-model\n */\nimport {\n  LIST_KIND_OPS,\n  LIST_LIMIT_MAX,\n  LIST_LIMIT_MIN,\n  listSortText,\n  readListQuery,\n  type ListFieldKind,\n  type ListFilter,\n  type ListFilterOp,\n  type ListFilterScalar,\n  type ListSortKey,\n} from \"@nextlyhq/blocks-engine\";\n\n/** One field a list may filter by, as the host's list names it. */\nexport interface QueryField {\n  readonly name: string;\n  readonly label: string;\n  readonly kind: ListFieldKind;\n  /** A choice field's choices, as stored and as named. */\n  readonly options?: readonly {\n    readonly value: string;\n    readonly label: string;\n  }[];\n  /** The collection an entry field points at. */\n  readonly relationTo?: string;\n}\n\n/**\n * One operator an author picks: the stored operator, and for `exists` which\n * way it points, since \"has a value\" and \"is empty\" are one operator with a\n * value of `true` or `false`.\n */\nexport interface OperatorChoice {\n  /** What keys it in a menu: the operator, or `exists:true` / `exists:false`. */\n  readonly key: string;\n  readonly op: ListFilterOp;\n  /** The value an `exists` choice stores. */\n  readonly exists?: boolean;\n  readonly label: string;\n}\n\nconst HAS_VALUE: OperatorChoice = {\n  key: \"exists:true\",\n  op: \"exists\",\n  exists: true,\n  label: \"has a value\",\n};\nconst IS_EMPTY: OperatorChoice = {\n  key: \"exists:false\",\n  op: \"exists\",\n  exists: false,\n  label: \"is empty\",\n};\n\n/** What each operator but `exists` is called, as a number's order is worded. */\nconst OPERATOR_LABELS: Readonly<\n  Record<Exclude<ListFilterOp, \"exists\">, string>\n> = {\n  equals: \"is\",\n  not_equals: \"is not\",\n  contains: \"contains\",\n  in: \"is any of\",\n  not_in: \"is none of\",\n  greater_than: \"is more than\",\n  greater_than_equal: \"is at least\",\n  less_than: \"is less than\",\n  less_than_equal: \"is at most\",\n};\n\n/** A date's order, worded as days: \"is after\", \"is on or before\". */\nconst DATE_LABELS: Readonly<Partial<Record<ListFilterOp, string>>> = {\n  greater_than: \"is after\",\n  greater_than_equal: \"is on or after\",\n  less_than: \"is before\",\n  less_than_equal: \"is on or before\",\n};\n\n/** The choices for a field of `kind`: the engine's operators, each worded. */\nfunction choicesFor(kind: ListFieldKind): readonly OperatorChoice[] {\n  return LIST_KIND_OPS[kind].flatMap(op =>\n    op === \"exists\"\n      ? [HAS_VALUE, IS_EMPTY]\n      : [\n          {\n            key: op,\n            op,\n            label:\n              (kind === \"date\" ? DATE_LABELS[op] : undefined) ??\n              OPERATOR_LABELS[op],\n          },\n        ]\n  );\n}\n\n/**\n * The operators offered for a field of each kind, in menu order: exactly\n * the engine's `LIST_KIND_OPS`, which the save judges a row by, so the menu\n * never offers a row the save refuses. `exists` is offered both ways, as\n * \"has a value\" and \"is empty\".\n */\nexport const OPERATORS: Readonly<\n  Record<ListFieldKind, readonly OperatorChoice[]>\n> = {\n  text: choicesFor(\"text\"),\n  number: choicesFor(\"number\"),\n  date: choicesFor(\"date\"),\n  choice: choicesFor(\"choice\"),\n  boolean: choicesFor(\"boolean\"),\n  entry: choicesFor(\"entry\"),\n};\n\n/** The menu key a stored row's operator is listed under. */\nfunction operatorKey(op: ListFilterOp, value: unknown): string {\n  return op === \"exists\" ? `exists:${String(value === true)}` : op;\n}\n\n/** A stored row's operator as offered for `kind`, if it is one offered. */\nexport function operatorOf(\n  kind: ListFieldKind,\n  op: ListFilterOp,\n  value: unknown\n): OperatorChoice | undefined {\n  const key = operatorKey(op, value);\n  return OPERATORS[kind].find(choice => choice.key === key);\n}\n\n/** Whether an operator takes a list of values: is any of, is none of. */\nexport function takesList(op: ListFilterOp): boolean {\n  return op === \"in\" || op === \"not_in\";\n}\n\n/** What a sort's two directions are called, for a field of each kind. */\nconst DIRECTION_WORDS: Readonly<\n  Record<\n    ListFieldKind,\n    { readonly ascending: string; readonly descending: string }\n  >\n> = {\n  date: { ascending: \"Oldest first\", descending: \"Newest first\" },\n  text: { ascending: \"A–Z\", descending: \"Z–A\" },\n  choice: { ascending: \"A–Z\", descending: \"Z–A\" },\n  number: { ascending: \"Lowest first\", descending: \"Highest first\" },\n  boolean: { ascending: \"No first\", descending: \"Yes first\" },\n  entry: { ascending: \"Ascending\", descending: \"Descending\" },\n};\n\n/** The words for a key's directions, plain where its field is not known. */\nexport function directionWords(kind: ListFieldKind | undefined): {\n  readonly ascending: string;\n  readonly descending: string;\n} {\n  return kind === undefined\n    ? { ascending: \"Ascending\", descending: \"Descending\" }\n    : DIRECTION_WORDS[kind];\n}\n\n/**\n * The direction a newly chosen field sorts in: newest first for a date, as a\n * list of posts is most often read, and ascending for anything else.\n */\nexport function firstDirection(kind: ListFieldKind): boolean {\n  return kind === \"date\";\n}\n\n/** A day as an author reads it: \"1 Sept 2026\". The stored day, never shifted. */\nexport function dayWords(day: string): string {\n  const [year, month, date] = day.split(\"-\").map(Number);\n  return new Intl.DateTimeFormat(\"en-GB\", {\n    day: \"numeric\",\n    month: \"short\",\n    year: \"numeric\",\n    timeZone: \"UTC\",\n  }).format(new Date(Date.UTC(year ?? 0, (month ?? 1) - 1, date ?? 1)));\n}\n\n/** \"A, B\" or \"A, B and 2 more\": a list of values on one short line. */\nfunction listWords(words: readonly string[], shown = 2): string {\n  if (words.length <= shown + 1) return words.join(\", \");\n  return `${words.slice(0, shown).join(\", \")} and ${String(words.length - shown)} more`;\n}\n\n/** How a value is said for a field of each kind. */\nconst VALUE_WORDS: Readonly<\n  Record<\n    ListFieldKind,\n    (\n      value: ListFilterScalar,\n      field: QueryField,\n      entryTitle: (id: string) => string | undefined\n    ) => string\n  >\n> = {\n  boolean: value => (value === true ? \"Yes\" : \"No\"),\n  choice: (value, field) =>\n    field.options?.find(option => option.value === value)?.label ??\n    String(value),\n  entry: (value, _field, entryTitle) => entryTitle(String(value)) ?? \"an entry\",\n  date: value => (typeof value === \"string\" ? dayWords(value) : String(value)),\n  text: value => (typeof value === \"string\" ? `“${value}”` : String(value)),\n  number: value => String(value),\n};\n\n/** One value as an author reads it, for a field of its kind. */\nfunction valueWords(\n  value: ListFilterScalar,\n  field: QueryField | undefined,\n  entryTitle: (id: string) => string | undefined\n): string {\n  return field === undefined\n    ? String(value)\n    : VALUE_WORDS[field.kind](value, field, entryTitle);\n}\n\n/** A filter row as one sentence, in its three parts. */\nexport interface FilterSentence {\n  /** The field: its label, or its stored name marked as gone. */\n  readonly field: string;\n  /** The operator, as the field's kind words it. */\n  readonly operator: string;\n  /** The value, or nothing for an operator that takes none. */\n  readonly value: string;\n}\n\n/** A row as the closed line reads it: \"Category · is any of · News, Guides\". */\nexport function filterSentence(\n  row: {\n    readonly field?: string;\n    readonly op?: ListFilterOp;\n    readonly value?: unknown;\n  },\n  field: QueryField | undefined,\n  entryTitle: (id: string) => string | undefined = () => undefined\n): FilterSentence {\n  const fieldWords =\n    row.field === undefined\n      ? \"Choose a field\"\n      : (field?.label ?? `${row.field} (removed)`);\n  if (row.op === undefined) {\n    return { field: fieldWords, operator: \"\", value: \"\" };\n  }\n  const operator =\n    (field === undefined\n      ? undefined\n      : operatorOf(field.kind, row.op, row.value)\n    )?.label ?? row.op.replaceAll(\"_\", \" \");\n  if (row.op === \"exists\") return { field: fieldWords, operator, value: \"\" };\n  const values = Array.isArray(row.value) ? row.value : [row.value];\n  const scalars = values.filter(\n    (value): value is ListFilterScalar =>\n      typeof value === \"string\" ||\n      typeof value === \"number\" ||\n      typeof value === \"boolean\"\n  );\n  return {\n    field: fieldWords,\n    operator,\n    value:\n      scalars.length === 0\n        ? \"no value\"\n        : listWords(scalars.map(value => valueWords(value, field, entryTitle))),\n  };\n}\n\n/** A row as one line of text, for its title and accessible name. */\nexport function filterLine(sentence: FilterSentence): string {\n  return [sentence.field, sentence.operator, sentence.value]\n    .filter(part => part !== \"\")\n    .join(\" \");\n}\n\n/** A row being edited: any part may be missing until the author chooses it. */\nexport interface DraftFilter {\n  readonly field?: string;\n  readonly op?: ListFilterOp;\n  readonly value?: unknown;\n}\n\n/**\n * A draft row as the stored row it would be, or why it is not one yet, in\n * words naming what to choose. Judged by the engine's own reading of a\n * filter row, so a row the editor writes is one the save accepts.\n */\nexport function completedFilter(\n  draft: DraftFilter,\n  field: QueryField | undefined\n): { readonly filter: ListFilter } | { readonly missing: string } {\n  if (draft.field === undefined || field === undefined) {\n    return { missing: \"Choose a field, or remove this filter.\" };\n  }\n  if (draft.op === undefined) {\n    return { missing: \"Choose how to compare, or remove this filter.\" };\n  }\n  const read = readListQuery({\n    filters: [{ field: draft.field, op: draft.op, value: draft.value }],\n  });\n  const filter = read.query.filters[0];\n  if (filter !== undefined && read.problems.length === 0) return { filter };\n  const what =\n    field.kind === \"entry\"\n      ? `an entry`\n      : field.kind === \"choice\"\n        ? \"a choice\"\n        : field.kind === \"date\"\n          ? \"a day\"\n          : \"a value\";\n  return {\n    missing: `Choose ${what} for ${field.label}, or remove this filter.`,\n  };\n}\n\n/**\n * The value a row starts with when its field or operator changes: what the\n * new operator takes, kept from the old value where it still fits, so\n * changing \"is\" to \"is any of\" keeps the chosen value as the first of a list.\n */\nexport function valueFor(\n  kind: ListFieldKind,\n  choice: OperatorChoice,\n  previous: unknown\n): unknown {\n  if (choice.op === \"exists\") return choice.exists === true;\n  if (kind === \"boolean\") return previous === false ? false : true;\n  const first = Array.isArray(previous) ? previous[0] : previous;\n  if (takesList(choice.op)) {\n    if (Array.isArray(previous)) return previous;\n    return first === undefined || first === \"\" ? [] : [first];\n  }\n  return first;\n}\n\n/** The stored filters with one row replaced, added or removed. */\nexport function withFilter(\n  filters: readonly ListFilter[],\n  index: number,\n  next: ListFilter | undefined\n): ListFilter[] | undefined {\n  const rows =\n    next === undefined\n      ? filters.filter((_, at) => at !== index)\n      : index >= filters.length\n        ? [...filters, next]\n        : filters.map((row, at) => (at === index ? next : row));\n  // No rows removes the prop, so a list with no filters stores none.\n  return rows.length === 0 ? undefined : rows;\n}\n\n/** The stored keys with one moved from `from` to `to`, others in order. */\nexport function movedKey(\n  keys: readonly ListSortKey[],\n  from: number,\n  to: number\n): ListSortKey[] {\n  if (from === to || to < 0 || to >= keys.length) return [...keys];\n  const next = [...keys];\n  const [moved] = next.splice(from, 1);\n  if (moved !== undefined) next.splice(to, 0, moved);\n  return next;\n}\n\n/** The sort as stored for `keys`: `undefined` for none, which removes it. */\nexport function sortValue(keys: readonly ListSortKey[]): string | undefined {\n  return listSortText(keys);\n}\n\n/**\n * A typed bound read as the number it stores, or the message saying what to\n * type instead, judged by the engine's own reading of the prop so the field\n * and the save agree. Empty removes the prop, and the list reads its default.\n */\nexport function readBound(\n  prop: \"limit\" | \"offset\",\n  typed: string\n): { readonly value: number | undefined } | { readonly problem: string } {\n  const text = typed.trim();\n  if (text === \"\") return { value: undefined };\n  const parsed = Number(text);\n  const read = readListQuery({ [prop]: Number.isNaN(parsed) ? text : parsed });\n  const problem = read.problems.find(each => each.prop === prop);\n  if (problem === undefined) return { value: read.query[prop] };\n  return {\n    problem:\n      prop === \"limit\"\n        ? `Show between ${String(LIST_LIMIT_MIN)} and ${String(LIST_LIMIT_MAX)} entries.`\n        : \"Skip a whole number of entries, 0 or more.\",\n  };\n}\n","/**\n * A collection loop's stored `sort`, as its single-key control reads and\n * writes it.\n *\n * The keys are the ENGINE's reading of the prop (`readListQuery`), and the\n * string written back is the engine's spelling of them (`listSortText`), so\n * this control, the list's own sort rows, the validator and the reader agree\n * on what a stored sort says. What is decided here is only what a control\n * editing the FIRST key does with the rest: every further key the chosen\n * collection can still sort by is kept, as stored. Those were written on\n * purpose (by code, the API or the sort rows) to break ties, and a field pick\n * or a direction change must not quietly drop them. A further key the\n * collection cannot sort by is dropped at the next write instead, because the\n * reader refuses a sort naming one and lists in id order, so keeping it would\n * undo the very order the author just chose.\n *\n * Pure, so each rule is tested without a panel.\n *\n * @module loop-sort\n */\nimport {\n  listSortText,\n  readListQuery,\n  type ListSortKey,\n} from \"@nextlyhq/blocks-engine\";\n\n/** One sort key: the field it orders by, and which way. */\nexport type SortKey = ListSortKey;\n\n/** A stored sort, split into the key the control edits and the ones it keeps. */\nexport interface StoredSort {\n  /** The first key, or `undefined` when nothing is stored. */\n  readonly first: SortKey | undefined;\n  /** Every further key, in order. */\n  readonly rest: readonly SortKey[];\n}\n\n/**\n * The stored value read as keys, as the engine reads it: anything but text\n * of field names reads as no sort, and empty keys (`a,,b`) are skipped.\n */\nexport function readSort(value: unknown): StoredSort {\n  const [first, ...rest] = readListQuery({ sort: value }).query.sort;\n  return { first, rest };\n}\n\n/**\n * What the control stores for `first` over what `stored` holds: the new\n * first key, then every further key whose field `sortable` accepts,\n * unchanged. `undefined` for no first key, which removes the sort, further\n * keys and all: \"Default order\" means the reader's own order, not a sort by\n * whatever tie-breakers were left.\n */\nexport function writeSort(\n  stored: StoredSort,\n  first: SortKey | undefined,\n  sortable: (field: string) => boolean\n): string | undefined {\n  if (first === undefined) return undefined;\n  return listSortText([\n    first,\n    ...stored.rest.filter(key => sortable(key.field)),\n  ]);\n}\n\n/** The further keys, for the line that names them. */\nexport function restKeys(stored: StoredSort): readonly SortKey[] {\n  return stored.rest;\n}\n","\"use client\";\n\n/**\n * A collection loop's Content-tab controls: which collection it repeats over,\n * and the order its entries come in.\n *\n * Both props stay text, as stored. A block asks for these controls with\n * `display: \"collection\"` on the prop naming a collection, and\n * `display: \"sort\"` with `collectionProp` on the prop holding its sort keys,\n * so nobody types a slug or a field name from memory.\n *\n * The collections, and each one's sortable fields, are read through the\n * host's `listLoopCollections`, once for both controls; an answer the host\n * keeps is shown at once. Where the host lends\n * none, or the read fails, each prop falls back to the text field it always\n * had, so a loop is never left without a way to be set.\n *\n * A stored value the list does not hold (a collection since removed or not\n * readable by this author, a field the collection no longer has) is still\n * shown, marked, and kept until the author picks another: the control never\n * rewrites what it cannot represent.\n *\n * @module collection-loop-controls\n */\n\nimport { listKindSortable } from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Label,\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@nextlyhq/ui\";\nimport { ArrowDown, ArrowUp, ChevronDown } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChoiceList, type ListedChoice } from \"../../choice-list\";\nimport { propLabel } from \"../inspector\";\n\nimport type {\n  ContentControlProps,\n  LoopCollection,\n  LoopListField,\n} from \"./content-controls\";\nimport { firstDirection } from \"./list-query-model\";\nimport { readSort, restKeys, writeSort, type SortKey } from \"./loop-sort\";\n\ntype ListLoopCollections = NonNullable<\n  NonNullable<ContentControlProps[\"services\"]>[\"listLoopCollections\"]\n>;\n\n/** The host's answer, as the controls hold it. */\nexport type LoopCollections =\n  | { readonly kind: \"loading\" }\n  | { readonly kind: \"ready\"; readonly collections: readonly LoopCollection[] }\n  | { readonly kind: \"failed\" };\n\n/** Shown while the host's read is on its way. */\nconst LOADING: LoopCollections = { kind: \"loading\" };\n\n/**\n * The read in flight, per host function, shared while it runs so the\n * collection and sort controls drawn together make one read. What happens to\n * the answer after that is the host's to decide: the builder keeps nothing\n * past it.\n */\nconst inFlight = new WeakMap<\n  ListLoopCollections,\n  Promise<readonly LoopCollection[]>\n>();\n\n/**\n * Each read's answer, by the read itself, once it has settled. A host that\n * keeps an answer (for one signed-in author, while it holds) hands the same\n * read again, and controls mounting then show its answer in their first\n * frame; a host that reads again hands a new one, which is never found here.\n */\nconst settled = new WeakMap<\n  Promise<readonly LoopCollection[]>,\n  LoopCollections\n>();\n\n/** The host's collections, read once for every control asking while it runs. */\nfunction readShared(\n  list: ListLoopCollections\n): Promise<readonly LoopCollection[]> {\n  const held = inFlight.get(list);\n  if (held !== undefined) return held;\n  const answer = list();\n  if (settled.has(answer)) return answer;\n  inFlight.set(list, answer);\n  const settle = (outcome: LoopCollections) => {\n    settled.set(answer, outcome);\n    if (inFlight.get(list) === answer) inFlight.delete(list);\n  };\n  answer.then(\n    collections => settle({ kind: \"ready\", collections }),\n    () => settle({ kind: \"failed\" })\n  );\n  return answer;\n}\n\n/**\n * The collections, or `undefined` when the host lends no way to list them.\n *\n * Asked as the controls mount, so a block selected after the host's answer\n * arrived shows its collections at once, with no \"loading\" frame and no\n * request; the host decides whether the answer it hands is one it kept.\n */\nexport function useLoopCollections(\n  list: ListLoopCollections | undefined\n): LoopCollections | undefined {\n  // Asked while drawing rather than after, so a kept answer is known in the\n  // first frame; asking again hands the same read, so a repeat costs nothing.\n  const asked = React.useMemo(\n    () => (list === undefined ? undefined : readShared(list)),\n    [list]\n  );\n  const [found, setFound] = React.useState<{\n    readonly asked: Promise<readonly LoopCollection[]>;\n    readonly answer: LoopCollections;\n  }>();\n  // What this frame could show at once: a read that settles after the frame\n  // is still followed below, however soon it settles.\n  const shownAtOnce = asked === undefined ? undefined : settled.get(asked);\n  React.useEffect(() => {\n    if (asked === undefined || shownAtOnce !== undefined) return;\n    let live = true;\n    asked.then(\n      collections => {\n        if (live) setFound({ asked, answer: { kind: \"ready\", collections } });\n      },\n      () => {\n        if (live) setFound({ asked, answer: { kind: \"failed\" } });\n      }\n    );\n    return () => {\n      live = false;\n    };\n  }, [asked, shownAtOnce]);\n  if (asked === undefined) return undefined;\n  // The answer for THIS read only, so a host swapped mid-mount never shows\n  // the previous host's collections.\n  return shownAtOnce ?? (found?.asked === asked ? found.answer : LOADING);\n}\n\n/** A stored text value, trimmed, or `undefined` for anything else or nothing. */\nfunction storedName(value: unknown): string | undefined {\n  if (typeof value !== \"string\") return undefined;\n  const trimmed = value.trim();\n  return trimmed === \"\" ? undefined : trimmed;\n}\n\n/** What each control is given beyond a content control's own props. */\ninterface LoopControlProps extends ContentControlProps {\n  /** The plain text field, drawn when the collections cannot be listed. */\n  readonly fallback: React.ReactNode;\n}\n\n/** One row of a loop picker's list. */\ninterface LoopChoice extends ListedChoice {\n  /** What picking it writes; `undefined` removes the prop. */\n  readonly value: string | undefined;\n}\n\n/**\n * The button that shows a loop prop's value, and the list it opens: searched\n * once long. Its name is the field's label and its value together, so a\n * screen reader hears \"Collection, Blog posts\".\n *\n * Shared by a collection list's own controls, which add groups to the list\n * (related sources above collections), a line above or below it, an icon\n * before the value, and an invalid state for a value a save would refuse.\n */\nexport function LoopPicker<C extends ListedChoice>({\n  id,\n  labelId,\n  value,\n  disabled,\n  list,\n  around,\n  defaultOpen,\n  onPick,\n}: {\n  id: string;\n  labelId: string;\n  /** What the button shows, and how it is marked. */\n  value: PickerValue;\n  disabled: boolean;\n  /** What the open list holds. */\n  list: PickerList<C>;\n  /** Drawn in the open list above and below its rows. */\n  around?: {\n    /** A group with nothing to offer, said under the search, above the rows. */\n    readonly above?: React.ReactNode;\n    /** What the list leaves out. */\n    readonly below?: React.ReactNode;\n  };\n  /** Opened as soon as it is drawn, as a new filter's field menu is. */\n  defaultOpen?: boolean;\n  onPick: (choice: C) => void;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(defaultOpen === true);\n  const valueId = `${id}-value`;\n  const {\n    choices,\n    currentKey,\n    label,\n    searchLabel,\n    noMatch,\n    wide,\n    ...optional\n  } = list;\n  return (\n    <div className=\"nx-font-pick\" {...pickerMarks(value)}>\n      <Popover open={open} onOpenChange={setOpen} modal={false}>\n        <PopoverTrigger asChild>\n          <PickerButton\n            id={id}\n            labelledBy={`${labelId} ${valueId}`}\n            valueId={valueId}\n            shown={value}\n            open={open}\n            disabled={disabled}\n          />\n        </PopoverTrigger>\n        {/* Aligned to the control's right edge, as the font list is: the list\n            may be wider than the control, at the window's right edge. */}\n        <PopoverContent\n          align=\"end\"\n          sideOffset={4}\n          className=\"nx-font-pick__popover\"\n          data-wide={wide === true ? \"\" : undefined}\n          onOpenAutoFocus={event => event.preventDefault()}\n        >\n          <div className=\"nx-font-pick__body\">\n            <ChoiceList\n              choices={choices}\n              currentKey={currentKey}\n              label={label}\n              searchLabel={searchLabel}\n              noMatch={noMatch}\n              // Given only where the caller said, so the list's own defaults hold.\n              {...definedOnly({ ...optional, leading: around?.above })}\n              onPick={choice => {\n                setOpen(false);\n                onPick(choice);\n              }}\n            />\n            {around?.below}\n          </div>\n        </PopoverContent>\n      </Popover>\n    </div>\n  );\n}\n\n/** What a picker's button shows, and how it is marked. */\nexport interface PickerValue {\n  /** The words the button shows. */\n  readonly words: string;\n  /** Whether they are a prompt, or a stored value the list does not hold. */\n  readonly state: \"value\" | \"prompt\" | \"unknown\";\n  /** Drawn before the value, such as the mark of a related source. */\n  readonly icon?: React.ReactNode;\n  /** A value the save would refuse, marked as the field's error. */\n  readonly invalid?: boolean;\n  /** The id of the text describing the value, such as its error. */\n  readonly describedBy?: string | undefined;\n}\n\n/** What a picker's open list holds. */\nexport interface PickerList<C extends ListedChoice> {\n  readonly choices: readonly C[];\n  readonly currentKey: string;\n  readonly label: string;\n  readonly searchLabel: string;\n  readonly noMatch: string;\n  readonly searchFrom?: number;\n  /** The list's group headings, in order, for a list of grouped rows. */\n  readonly groups?: ReadonlyArray<{ group: string; heading: string }>;\n  readonly renderChoice?: (choice: C) => React.ReactNode;\n  /**\n   * Wider than its control, for rows of two lines that would otherwise be\n   * cut: still aligned to the control's end.\n   */\n  readonly wide?: boolean;\n}\n\n/** The button a picker opens from: its value, named with its field's label. */\nconst PickerButton = React.forwardRef<\n  HTMLButtonElement,\n  {\n    id: string;\n    labelledBy: string;\n    valueId: string;\n    shown: PickerValue;\n    open: boolean;\n    disabled: boolean;\n  } & React.ButtonHTMLAttributes<HTMLButtonElement>\n>(function PickerButton(\n  { id, labelledBy, valueId, shown, open, disabled, ...trigger },\n  ref\n) {\n  return (\n    <button\n      {...trigger}\n      ref={ref}\n      type=\"button\"\n      id={id}\n      className=\"nx-font-pick__trigger\"\n      aria-haspopup=\"listbox\"\n      aria-expanded={open}\n      aria-labelledby={labelledBy}\n      aria-invalid={shown.invalid === true || undefined}\n      aria-describedby={shown.describedBy}\n      disabled={disabled}\n    >\n      {shown.icon}\n      <span\n        id={valueId}\n        className=\"nx-font-pick__value\"\n        data-placeholder={shown.state === \"prompt\" ? \"\" : undefined}\n        title={shown.words}\n      >\n        {shown.words}\n      </span>\n      <ChevronDown aria-hidden=\"true\" size={14} />\n    </button>\n  );\n});\n\n/** The marks on a picker: a stored value the list lacks, a refused one. */\nfunction pickerMarks(value: PickerValue): Record<string, string> {\n  return {\n    ...(value.state === \"unknown\" ? { \"data-unknown\": \"\" } : {}),\n    ...(value.invalid === true ? { \"data-invalid\": \"\" } : {}),\n  };\n}\n\n/** The entries of `options` that hold a value, for props that must be absent. */\nfunction definedOnly<T extends Record<string, unknown>>(\n  options: T\n): Partial<T> {\n  return Object.fromEntries(\n    Object.entries(options).filter(([, value]) => value !== undefined)\n  ) as Partial<T>;\n}\n\n/**\n * How many collections the list holds before it offers a search. The list\n * has one row more than that, \"No collection\", which the count leaves out.\n */\nconst COLLECTIONS_SEARCH_FROM = 10;\n\n/** The host's answer once it is one the controls can draw from. */\ntype DrawnCollections = Exclude<LoopCollections, { kind: \"failed\" }>;\n\n/** What a loop control draws with, once the host's list can be drawn from. */\ninterface DrawnLoopProps extends LoopControlProps {\n  readonly listed: DrawnCollections;\n  /** The id of the label naming the field. */\n  readonly labelId: string;\n  /** What the label says. */\n  readonly name: string;\n}\n\n/**\n * A loop control that draws from the host's collections, or the plain text\n * field where it lends none or its read failed.\n */\nfunction withLoopCollections(\n  Drawn: (props: DrawnLoopProps) => React.JSX.Element\n): (props: LoopControlProps) => React.JSX.Element {\n  return function LoopControl(props: LoopControlProps): React.JSX.Element {\n    const listed = useLoopCollections(props.services?.listLoopCollections);\n    if (listed === undefined || listed.kind === \"failed\") {\n      return <>{props.fallback}</>;\n    }\n    return (\n      <Drawn\n        {...props}\n        listed={listed}\n        labelId={`${props.id}-label`}\n        name={props.label ?? propLabel(props.prop.name, props.prop.schema)}\n      />\n    );\n  };\n}\n\n/** The collections in the order the list offers them: by name, ignoring case. */\nexport function alphabetical(\n  collections: readonly LoopCollection[]\n): LoopCollection[] {\n  return [...collections].sort(\n    (a, b) =>\n      a.label.localeCompare(b.label, undefined, { sensitivity: \"base\" }) ||\n      (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0)\n  );\n}\n\n/** What a picker's button shows, and whether it is a prompt or a lost value. */\ninterface Shown {\n  readonly words: string;\n  readonly state: \"value\" | \"prompt\" | \"unknown\";\n}\n\n/** What the collection button shows for the stored slug. */\nfunction collectionShown(\n  listed: DrawnCollections,\n  stored: string | undefined,\n  current: LoopCollection | undefined\n): Shown {\n  if (listed.kind === \"loading\") {\n    return { words: \"Loading collections…\", state: \"prompt\" };\n  }\n  if (stored === undefined) {\n    return { words: \"Choose a collection\", state: \"prompt\" };\n  }\n  return current === undefined\n    ? { words: `${stored} · not available`, state: \"unknown\" }\n    : { words: current.label, state: \"value\" };\n}\n\n/** The collection picker, once the host's list can be drawn from. */\nfunction CollectionField({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  listed,\n  labelId,\n  name,\n}: DrawnLoopProps): React.JSX.Element {\n  const stored = storedName(prop.value);\n  const collections =\n    listed.kind === \"ready\" ? alphabetical(listed.collections) : [];\n  const current = collections.find(each => each.slug === stored);\n  const shown = collectionShown(listed, stored, current);\n  const choices: LoopChoice[] = [\n    { key: \"\", label: \"No collection\", value: undefined },\n    ...collections.map(each => ({\n      key: each.slug,\n      label: each.label,\n      value: each.slug,\n    })),\n  ];\n  return (\n    <div\n      className=\"nx-inspector__field\"\n      data-content-control={prop.schema.type}\n      data-display=\"collection\"\n    >\n      <Label id={labelId} htmlFor={id}>\n        {name}\n      </Label>\n      <LoopPicker\n        id={id}\n        labelId={labelId}\n        value={shown}\n        disabled={disabled || listed.kind === \"loading\"}\n        list={{\n          choices,\n          currentKey: stored ?? \"\",\n          label: \"Collections\",\n          searchLabel: \"Search collections\",\n          noMatch: \"No collection matches.\",\n          searchFrom: COLLECTIONS_SEARCH_FROM + 1,\n        }}\n        onPick={choice => {\n          if (choice.value !== stored) onCommit(prop.name, choice.value);\n        }}\n      />\n    </div>\n  );\n}\n\n/**\n * The collection a loop repeats over, chosen from the site's collections\n * rather than typed as a slug.\n */\nexport const CollectionControl: (props: LoopControlProps) => React.JSX.Element =\n  withLoopCollections(CollectionField);\n\n/**\n * A collection's fields a list may sort by, as the menu lists them: dates\n * first. A relation sorts by its stored id, which the engine's\n * `listKindSortable` leaves out.\n */\nfunction datesFirst(fields: readonly LoopListField[]): LoopListField[] {\n  const sortable = fields.filter(field => listKindSortable(field.kind));\n  return [\n    ...sortable.filter(field => field.kind === \"date\"),\n    ...sortable.filter(field => field.kind !== \"date\"),\n  ];\n}\n\n/** A key's field in words: its label where the collection has it. */\nfunction fieldWords(\n  field: string,\n  fields: readonly LoopListField[]\n): string | undefined {\n  return fields.find(each => each.name === field)?.label;\n}\n\n/** The collection the sort's block names in its `collectionProp`, if any. */\nfunction sortedCollection(\n  prop: DrawnLoopProps[\"prop\"],\n  values: DrawnLoopProps[\"values\"]\n): string | undefined {\n  const from = prop.schema.collectionProp;\n  return typeof from === \"string\" ? storedName(values?.[from]) : undefined;\n}\n\n/** The fields of `collection` the menu offers, dates first; none while loading. */\nfunction sortFieldsFor(\n  listed: DrawnCollections,\n  collection: string | undefined\n): LoopListField[] {\n  if (listed.kind !== \"ready\") return [];\n  const found = listed.collections.find(each => each.slug === collection);\n  return datesFirst(found?.fields ?? []);\n}\n\n/** What the sort button shows for the stored first key. */\nfunction sortShown(\n  waiting: boolean,\n  first: SortKey | undefined,\n  collection: string | undefined,\n  fields: readonly LoopListField[]\n): Shown {\n  if (waiting) return { words: \"Loading fields…\", state: \"prompt\" };\n  if (first === undefined) {\n    return {\n      words:\n        collection === undefined\n          ? \"Choose a collection first\"\n          : \"Default order\",\n      state: \"prompt\",\n    };\n  }\n  const known = fieldWords(first.field, fields);\n  return known === undefined\n    ? { words: `${first.field} · not in this collection`, state: \"unknown\" }\n    : { words: known, state: \"value\" };\n}\n\n/**\n * The key a pick in the sort menu stores, or `undefined` for Default order.\n * A field changed keeps the direction already chosen; a field newly chosen\n * sorts newest first for a date, as a list of posts is most often read, and\n * A to Z for anything else.\n */\nfunction pickedKey(\n  picked: string | undefined,\n  fields: readonly LoopListField[],\n  first: SortKey | undefined\n): SortKey | undefined {\n  const field = fields.find(each => each.name === picked);\n  if (field === undefined) return undefined;\n  return {\n    field: field.name,\n    descending: first?.descending ?? firstDirection(field.kind),\n  };\n}\n\n/** The direction toggle beside the sort menu: pressed is descending. */\nfunction DirectionToggle({\n  descending,\n  disabled,\n  onFlip,\n}: {\n  descending: boolean;\n  disabled: boolean;\n  onFlip: () => void;\n}): React.JSX.Element {\n  return (\n    <Button\n      type=\"button\"\n      size=\"icon-sm\"\n      variant=\"outline\"\n      className=\"nx-inspector__sort-direction\"\n      // Named for the pressed state, so \"Descending, pressed\" and\n      // \"Descending, not pressed\" both read true.\n      aria-label=\"Descending\"\n      aria-pressed={descending}\n      title={descending ? \"Descending\" : \"Ascending\"}\n      disabled={disabled}\n      onClick={onFlip}\n    >\n      {descending ? (\n        <ArrowDown aria-hidden=\"true\" />\n      ) : (\n        <ArrowUp aria-hidden=\"true\" />\n      )}\n    </Button>\n  );\n}\n\n/**\n * The line naming the stored keys after the first: kept as they are where\n * the collection can sort by them, and marked where it cannot, since the\n * next change drops those (see `loop-sort`).\n */\nfunction FurtherKeys({\n  keys,\n  fields,\n}: {\n  keys: readonly SortKey[];\n  fields: readonly LoopListField[];\n}): React.JSX.Element | null {\n  if (keys.length === 0) return null;\n  let lost = false;\n  const words = keys.map(key => {\n    const known = fieldWords(key.field, fields);\n    if (known === undefined) lost = true;\n    const field = known ?? `${key.field} · not in this collection`;\n    return key.descending ? `${field} (descending)` : field;\n  });\n  return (\n    <p className=\"nx-inspector__note\">\n      Then by {words.join(\", \")}.\n      {lost\n        ? \" A key not in this collection is dropped at the next change.\"\n        : null}\n    </p>\n  );\n}\n\n/** The sort menu and its direction, once the host's list can be drawn from. */\nfunction SortField({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  values,\n  listed,\n  labelId,\n  name,\n}: DrawnLoopProps): React.JSX.Element {\n  const collection = sortedCollection(prop, values);\n  const fields = sortFieldsFor(listed, collection);\n  const stored = readSort(prop.value);\n  const first = stored.first;\n  const waiting = listed.kind === \"loading\";\n  const shown = sortShown(waiting, first, collection, fields);\n  const commit = (next: SortKey | undefined) => {\n    const written = writeSort(stored, next, field =>\n      fields.some(each => each.name === field)\n    );\n    if (written !== storedName(prop.value)) onCommit(prop.name, written);\n  };\n  const choices: LoopChoice[] = [\n    { key: \"\", label: \"Default order\", value: undefined },\n    ...fields.map(field => ({\n      key: field.name,\n      label: field.label,\n      value: field.name,\n    })),\n  ];\n  return (\n    <div\n      className=\"nx-inspector__field\"\n      data-content-control={prop.schema.type}\n      data-display=\"sort\"\n    >\n      <Label id={labelId} htmlFor={id}>\n        {name}\n      </Label>\n      <div className=\"nx-inspector__sort\">\n        <LoopPicker\n          id={id}\n          labelId={labelId}\n          value={shown}\n          // A stored sort stays reachable without a collection, so it can be\n          // cleared; with neither, there is nothing to choose from yet.\n          disabled={\n            disabled ||\n            waiting ||\n            (collection === undefined && first === undefined)\n          }\n          list={{\n            choices,\n            currentKey: first?.field ?? \"\",\n            label: \"Fields to sort by\",\n            searchLabel: \"Search fields\",\n            noMatch: \"No field matches.\",\n          }}\n          onPick={choice => commit(pickedKey(choice.value, fields, first))}\n        />\n        <DirectionToggle\n          descending={first?.descending === true}\n          // A key the collection cannot sort by is refused at render, so\n          // flipping it would change nothing on the page: it waits for a\n          // field of this collection to be picked.\n          disabled={\n            disabled ||\n            waiting ||\n            first === undefined ||\n            !fields.some(field => field.name === first.field)\n          }\n          onFlip={() => {\n            if (first !== undefined) {\n              commit({ field: first.field, descending: !first.descending });\n            }\n          }}\n        />\n      </div>\n      <FurtherKeys keys={restKeys(stored)} fields={fields} />\n    </div>\n  );\n}\n\n/**\n * The order a loop's entries come in: a field of its collection, and which\n * way, on one row. Only the first stored key is edited here; see `loop-sort`\n * for why further keys are kept as they are.\n */\nexport const SortControl: (props: LoopControlProps) => React.JSX.Element =\n  withLoopCollections(SortField);\n","/**\n * An edit in progress in one field, and what Escape does with it.\n *\n * A field being edited holds a value the author has not finished with: a\n * draft it writes when it is left, or a run of typing it has already written\n * (`typing-run.ts`), which the history keeps as one step. Either way, Escape\n * in that field puts back the value from before the edit, in the field and\n * on the canvas, and records nothing. That is the innermost thing Escape can\n * close, so it closes that alone; with nothing left to put back, the next\n * Escape leaves the field.\n *\n * One edit at a time, the field's: focus is in one field, and a field's edit\n * ends when its value is stored, when it is put back, or when it unmounts.\n * The edit names the element it is in, so Escape pressed anywhere else never\n * puts back a field the author is not in.\n *\n * Module state rather than context, as `typing-run.ts` is: every field in\n * the inspectors passes through `useStoredDraft`, which is called with a value\n * and nothing else, and the keyboard layer that answers Escape is mounted\n * apart from every panel.\n *\n * A draft in a field of the document is also work the page has not saved:\n * the page says so from the draft's first keystroke ({@link\n * useFieldDraftHeld}), and a store of the page writes it first ({@link\n * finishFieldEdit}), so Save pressed from the keyboard, with focus still in\n * the field, saves what the author typed.\n *\n * @module field-edit\n */\n\nimport * as React from \"react\";\nimport { flushSync } from \"react-dom\";\n\n/** An edit in progress: where it is, and how to put it back. */\ninterface FieldEdit {\n  /** The field it is in: the element focus was in when it began. */\n  readonly element: Element | null;\n  /** Put back the value from before the edit, recording nothing. */\n  readonly cancel: () => void;\n  /**\n   * Whether it is a draft of the document's that the field writes only when\n   * it is left: unsaved work until then. A field that writes as it is typed\n   * has its keystrokes in the document already.\n   */\n  readonly draft: boolean;\n}\n\n/**\n * Whether the fields drawn here edit the document: provided by the block\n * settings panel. A field elsewhere, such as a site variable's, holds a\n * draft the page does not contain, so the page neither waits for it nor\n * counts it.\n */\nexport const FieldsOfDocument: React.Context<boolean> =\n  React.createContext<boolean>(false);\n\n/** The edit in progress, or `null` for none. */\nlet current: FieldEdit | null = null;\n\n/** Told whenever the edit in progress changes. */\nconst listeners = new Set<() => void>();\n\n/** Make `next` the edit in progress, telling whoever is listening. */\nfunction setCurrent(next: FieldEdit | null): void {\n  if (current === next) return;\n  current = next;\n  for (const listener of listeners) listener();\n}\n\n/** Fields an edit has been put back in, which the next Escape leaves. */\nconst putBack = new WeakSet<Element>();\n\n/** A field's hold on the edit in progress. */\ninterface FieldEditHandle {\n  /** End the edit without putting anything back: stored, or the field gone. */\n  readonly end: () => void;\n  /** Whether this is still the edit in progress: another field's displaces it. */\n  readonly held: () => boolean;\n}\n\n/**\n * Begin an edit, displacing any other field's.\n *\n * It also ends when focus leaves the field it began in, by a blur or by\n * {@link finishFieldEdit}: the field has written what it will on the way\n * out. A draft whose commit wrote nothing (`2px ` trimmed back to the `2px`\n * stored, or a value refused) moves no stored value, so without this its\n * record would stay, and the page would report unsaved work it does not have.\n */\nfunction beginFieldEdit(edit: FieldEdit): FieldEditHandle {\n  setCurrent(edit);\n  const { element } = edit;\n  const end = (): void => {\n    element?.removeEventListener(\"focusout\", end);\n    if (current === edit) setCurrent(null);\n  };\n  if (element !== null) {\n    putBack.delete(element);\n    element.addEventListener(\"focusout\", end);\n  }\n  return { end, held: () => current === edit };\n}\n\n/**\n * A draft field's edit in progress, kept with its draft: the one rule every\n * field that holds a draft over a stored value follows, so each has the same\n * Escape.\n *\n * Answers the draft's setter. A draft set away from `stored` begins an edit\n * in the element focus is in (the field being typed into), unless this field\n * already holds the edit in progress; one displaced by another field's begins\n * again. The edit ends when `stored` moves (the draft was written, or an undo\n * or another surface replaced it), when the draft comes back to `stored`, and\n * when the field goes. Escape's put-back sets the draft to `stored`, so the\n * field then writes nothing when it is left.\n */\nexport function useFieldEdit(\n  stored: string,\n  setDraft: (next: string) => void\n): (next: string) => void {\n  const ofDocument = React.useContext(FieldsOfDocument);\n  // Read when Escape lands, so the value put back is the one stored now.\n  const latestStored = React.useRef(stored);\n  latestStored.current = stored;\n  const handle = React.useRef<FieldEditHandle | null>(null);\n  const end = React.useCallback(() => {\n    handle.current?.end();\n    handle.current = null;\n  }, []);\n  React.useEffect(end, [stored, end]);\n  React.useEffect(() => end, [end]);\n  return React.useCallback(\n    (next: string) => {\n      setDraft(next);\n      if (next === latestStored.current) {\n        end();\n        return;\n      }\n      if (handle.current?.held() === true) return;\n      handle.current = beginFieldEdit({\n        element:\n          typeof document === \"undefined\" ? null : document.activeElement,\n        cancel: () => {\n          handle.current = null;\n          setDraft(latestStored.current);\n        },\n        draft: ofDocument,\n      });\n    },\n    [setDraft, end, ofDocument]\n  );\n}\n\n/** A field's own begin and end of its edit, for a field that says when. */\ninterface HeldFieldEdit {\n  /** Begin the edit, unless this field holds it; `cancel` is Escape's put-back. */\n  readonly begin: (cancel: () => void) => void;\n  /** End it without putting anything back. */\n  readonly end: () => void;\n}\n\n/**\n * An edit the field begins and ends itself, of the kind `draft` says. Begun\n * in the element focus is in, unless this field already holds the edit in\n * progress; ended by the field, by focus leaving it and when it goes.\n */\nfunction useHeldFieldEdit(draft: boolean): HeldFieldEdit {\n  const handle = React.useRef<FieldEditHandle | null>(null);\n  const end = React.useCallback(() => {\n    handle.current?.end();\n    handle.current = null;\n  }, []);\n  React.useEffect(() => end, [end]);\n  return React.useMemo(\n    () => ({\n      begin: (cancel: () => void) => {\n        if (handle.current?.held() === true) return;\n        handle.current = beginFieldEdit({\n          element:\n            typeof document === \"undefined\" ? null : document.activeElement,\n          cancel: () => {\n            handle.current = null;\n            cancel();\n          },\n          draft,\n        });\n      },\n      end,\n    }),\n    [end, draft]\n  );\n}\n\n/**\n * The edit of a field that writes as it is typed (`live-draft.ts`), whose own\n * writes move the stored value as it goes, so the edit cannot end when the\n * stored value moves, as a draft's does. Begun at the first keystroke in the\n * element focus is in, unless this field already holds the edit in progress;\n * ended by the field when its edit ends (blur, Enter, the value moved by\n * something else) and when it goes. Escape's put-back runs `cancel`.\n */\nexport function useTypedFieldEdit(): HeldFieldEdit {\n  return useHeldFieldEdit(false);\n}\n\n/**\n * The edit of a field whose draft is not one text following one stored\n * value, so {@link useFieldEdit} cannot tell when it begins and ends: the\n * Advanced tab's anchor and attribute rows, held as one draft, or a field\n * whose text lives in the input itself, as a Layers rename's does. The field\n * begins it at each keystroke and says how Escape puts its value back; it\n * ends when focus leaves the field, as the field writes its draft, and when\n * the field goes.\n *\n * A draft of the document's where the fields drawn here edit the document\n * ({@link FieldsOfDocument}), so the page counts it as unsaved work and a\n * store of the page writes it first ({@link finishFieldEdit}).\n */\nexport function useDraftFieldEdit(): HeldFieldEdit {\n  return useHeldFieldEdit(React.useContext(FieldsOfDocument));\n}\n\n/** Whether `edit` was begun in `origin`, or in a field holding it. */\nfunction inField(edit: FieldEdit, origin: Element): boolean {\n  return edit.element !== null && edit.element.contains(origin);\n}\n\n/** What Escape pressed in a field does. */\ntype FieldEscape =\n  /** The field's edit was put back; the field keeps focus. */\n  | \"put-back\"\n  /** Nothing to put back in a field whose edit just was: leave the field. */\n  | \"leave-field\"\n  /** Not a field with an edit: the key does what it did before. */\n  | \"none\";\n\n/**\n * Escape pressed in `origin`: put back the edit in progress there, or, in a\n * field whose edit Escape has just put back, leave it.\n */\nexport function escapeFieldEdit(origin: Element | null): FieldEscape {\n  if (origin === null) return \"none\";\n  const edit = current;\n  if (edit !== null && inField(edit, origin)) {\n    setCurrent(null);\n    edit.cancel();\n    if (edit.element !== null) putBack.add(edit.element);\n    return \"put-back\";\n  }\n  for (let at: Element | null = origin; at !== null; at = at.parentElement) {\n    if (putBack.has(at)) {\n      putBack.delete(at);\n      return \"leave-field\";\n    }\n  }\n  return \"none\";\n}\n\n/** Subscribe to the edit in progress. */\nfunction subscribe(listener: () => void): () => void {\n  listeners.add(listener);\n  return () => {\n    listeners.delete(listener);\n  };\n}\n\n/** Whether a field of the document holds a draft it has not written yet. */\nfunction draftHeld(): boolean {\n  return current?.draft === true;\n}\n\n/**\n * Whether a field of the document holds a draft it has not written yet:\n * work the page has not saved, from the draft's first keystroke.\n *\n * @experimental\n */\nexport function useFieldDraftHeld(): boolean {\n  return React.useSyncExternalStore(subscribe, draftHeld, () => false);\n}\n\n/**\n * Write the draft a field of the document holds, as leaving the field would,\n * without the author leaving it: for a store of the page made while focus is\n * still in the field, as Save from the keyboard is. The field's own blur\n * writes it, with every rule that field applies on the way out, and focus\n * and the caret stay where they are. The editor has drawn what it wrote by\n * the time this returns.\n *\n * Nothing for a field that writes as it is typed: its keystrokes are in the\n * document already.\n *\n * @experimental\n */\nexport function finishFieldEdit(): void {\n  const edit = current;\n  if (edit === null || !edit.draft) return;\n  const { element } = edit;\n  if (element === null || !element.isConnected) return;\n  flushSync(() => {\n    element.dispatchEvent(new FocusEvent(\"focusout\", { bubbles: true }));\n  });\n}\n","/**\n * A field's draft, which follows the stored value whenever that changes\n * underneath it.\n *\n * Every text field in the inspectors holds its own value while focused so\n * typing is responsive, and reports it on blur so one undo takes back one\n * edit. Each also has to give way to the document: an undo, an edit from the\n * canvas, a reset, or a different node selected into the same slot replaces\n * the stored value, and a field that kept its draft would go on showing a\n * value the document no longer has.\n *\n * One hook rather than the same three lines in every field, because the\n * three lines were drifting: one copy's comment listed the reasons a value\n * changes underneath a field and another's listed different ones, and the\n * next copy would have carried whichever it was pasted from.\n *\n * @module stored-draft\n */\n\nimport * as React from \"react\";\n\nimport { useFieldEdit } from \"./field-edit\";\n\n/**\n * @param stored - the value the document holds, as the field shows it\n * @returns the draft and its setter, the draft reset whenever `stored` moves\n *\n * A draft that differs from `stored` is an edit in progress, which Escape in\n * the field puts back (`field-edit.ts`).\n */\nexport function useStoredDraft(\n  stored: string\n): [string, (next: string) => void] {\n  const [draft, setDraftState] = React.useState(stored);\n  React.useEffect(() => {\n    setDraftState(stored);\n  }, [stored]);\n  const setDraft = useFieldEdit(stored, setDraftState);\n  return [draft, setDraft];\n}\n","/**\n * A run of typing: the writes one field makes while an author types into it,\n * joined into ONE step of the editor's history.\n *\n * A field that writes as the author types — so the canvas shows the words as\n * they go in, rather than when the field is left — would otherwise put a step\n * on the history per keystroke, and undo would take a sentence back a letter\n * at a time. Inside {@link joinTyping}, every write the same run makes after\n * its first moves the document without a new step: undo takes the run back\n * whole, to what the value was before the author started.\n *\n * Ambient rather than passed through the write path, because the write path is\n * every field's: the run is named around the call that writes, and the\n * history asks for it when that write is applied, synchronously, inside it.\n *\n * @module typing-run\n */\n\n/** The run the write being applied belongs to, or `null` for none. */\nlet ambient: object | null = null;\n\n/**\n * Run `write` as part of the typing run `run`: a run is any object a field\n * keeps for as long as one stretch of typing lasts, and a new object starts a\n * new step.\n */\nexport function joinTyping<T>(run: object, write: () => T): T {\n  const outer = ambient;\n  ambient = run;\n  try {\n    return write();\n  } finally {\n    ambient = outer;\n  }\n}\n\n/** The typing run the write being applied belongs to, or `null`. */\nexport function typingRunNow(): object | null {\n  return ambient;\n}\n\n/**\n * Which stretch of typing the editor is in. Moved on by {@link endTypingRuns},\n * so every run open before it is over: its next write is a step of its own.\n */\nlet epoch = 0;\n\n/**\n * End every run of typing now, as leaving the field would, without the author\n * leaving it. For a save made while a field is still being typed in: what was\n * saved is one step, and typing on is the next, so undo after the save takes\n * back only what came after it and the count of unsaved work stays right.\n *\n * @experimental\n */\nexport function endTypingRuns(): void {\n  epoch += 1;\n}\n\n/** The current stretch, for a step or a field to note when its run began. */\nexport function typingEpoch(): number {\n  return epoch;\n}\n\n/** The run of typing a step of the history was pushed for, and the step. */\nexport interface TypingStep<Entry> {\n  readonly run: object;\n  readonly entry: Entry;\n  /** The stretch the step began in: a later one ({@link endTypingRuns}) ends it. */\n  readonly epoch: number;\n}\n\n/**\n * Whether a write of `run` joins the step `last` was pushed for: the same\n * run, while that step is still the newest of the history. Any other step\n * since, and the run's next write is a step of its own.\n */\nexport function joinsTyping<Entry>(\n  last: TypingStep<Entry> | null,\n  newest: Entry | undefined,\n  run: object | null\n): boolean {\n  return (\n    run !== null &&\n    last?.run === run &&\n    newest === last.entry &&\n    last.epoch === epoch\n  );\n}\n","/**\n * A field's draft that writes as it is typed, so the canvas follows the\n * author's keystrokes instead of waiting for them to leave the field.\n *\n * Each keystroke is handed to the field's own write inside one run of typing\n * (`typing-run.ts`), so the history keeps the whole stretch as ONE step: undo\n * takes it back to the value from before the author started, not a letter at\n * a time. The run ends when the edit does, on blur or Enter, and the next\n * keystroke starts a new step.\n *\n * Two rules make it safe to write while the value is still being typed:\n *\n * - **The last valid value stays on the canvas.** A keystroke whose text is\n *   not a value yet (`12p`, half a hex colour, an emptied field) writes\n *   nothing, so the document and the canvas keep the last value that was one.\n *   The field shows its own message as it does on blur, and leaving the field\n *   settles the text as before.\n * - **The field's own writes leave its text alone.** The document answers a\n *   write in its own spelling (`24` is stored as `24px`), and a draft that\n *   followed it would move the caret and the text under the author's fingers.\n *   A value moved by anything else, such as an undo or an edit from the\n *   canvas, still replaces the draft.\n *\n * @module live-draft\n */\n\nimport { trimCssWhitespace } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { useFieldEdit, useTypedFieldEdit } from \"./field-edit\";\nimport { joinTyping, typingEpoch } from \"./typing-run\";\n\n/** A field's draft over the stored value, written as it is typed. */\nexport interface LiveDraft {\n  /** The text the field shows. */\n  readonly draft: string;\n  /** Show `next`, writing nothing: a step, a reset or a pick. */\n  readonly setDraft: (next: string) => void;\n  /**\n   * The author typed `next`: shown at once, and handed to `write` inside this\n   * edit's run of typing. `write` answers whether it moved the document:\n   * `false` for a value it did not write (not one yet, refused, the same).\n   */\n  readonly type: (next: string, write: (text: string) => boolean) => void;\n  /**\n   * Run `write` in this edit's run of typing, while one is open, so a write\n   * that finishes the edit (a unit picked after the number, the tidy-up on\n   * blur) is part of the same step.\n   */\n  readonly join: <T>(write: () => T) => T;\n  /**\n   * Whether `text` is what the last keystroke wrote, so the edit ending on it\n   * has nothing left to write.\n   */\n  readonly written: (text: string) => boolean;\n  /**\n   * The edit is over: the next keystroke starts a new step, and a draft the\n   * last keystroke wrote takes the stored spelling (\"24\" shows as stored).\n   */\n  readonly end: () => void;\n}\n\n/**\n * Put back what a run of typing wrote, recording nothing: the editor's\n * `cancelTyping`, provided where the fields are drawn over an editor. Escape\n * in a field being typed uses it; without it, Escape puts back the field's\n * text alone.\n */\nexport const TypingCancel: React.Context<\n  ((run: object) => boolean) | undefined\n> = React.createContext<((run: object) => boolean) | undefined>(undefined);\n\n/** What one stretch of typing holds between its keystrokes. */\ninterface Stretch {\n  /** The run it writes in, from its first keystroke. */\n  run: object | null;\n  /** The stretch of typing the run began in (`typingEpoch`). */\n  epoch: number;\n  /** The stored text before its first keystroke, which Escape puts back. */\n  before: string;\n  /** Whether the stored value is about to move for a keystroke's own write. */\n  own: boolean;\n  /** The text the last keystroke wrote, while the document still holds it. */\n  wrote: string | null;\n  /** The stored spelling that text came back as, once it has. */\n  answered: string | null;\n}\n\n/** A stretch with nothing typed. */\nfunction idle(stretch: Stretch): void {\n  stretch.run = null;\n  stretch.own = false;\n  stretch.wrote = null;\n  stretch.answered = null;\n}\n\n/**\n * @param stored - the value the document holds, as the field shows it\n * @param putBackDone - told after Escape puts the draft back, for a field\n *   that keeps state of its own about the typing\n * @returns the draft, reset whenever `stored` moves for any reason but the\n *   field's own typing. A draft set away from `stored` without typing, and a\n *   stretch of typing, are both an edit Escape puts back (`field-edit.ts`).\n */\nexport function useLiveDraft(\n  stored: string,\n  putBackDone?: () => void\n): LiveDraft {\n  const [draft, show] = React.useState(stored);\n  // Read when Escape puts the draft back, so a field showing typing as typed\n  // (a unit kept in the text) shows the value as stored again.\n  const onPutBack = React.useRef(putBackDone);\n  onPutBack.current = putBackDone;\n  // Escape runs the put-back registered by the first keystroke's render, so\n  // the stored value it falls back on is read from here, never from then.\n  const storedNow = React.useRef(stored);\n  storedNow.current = stored;\n  // Set without typing: a draft over the stored value, as every field's is.\n  const setDraft = useFieldEdit(stored, show);\n  const edit = useTypedFieldEdit();\n  const cancelTyping = React.useContext(TypingCancel);\n  const stretch = React.useRef<Stretch>({\n    run: null,\n    epoch: typingEpoch(),\n    before: stored,\n    own: false,\n    wrote: null,\n    answered: null,\n  }).current;\n  React.useEffect(() => {\n    if (stretch.own) {\n      stretch.own = false;\n      stretch.answered = stored;\n      return;\n    }\n    // Moved underneath the field, so what it was typing no longer applies.\n    idle(stretch);\n    edit.end();\n    show(stored);\n  }, [stored, stretch, edit]);\n  return React.useMemo(() => {\n    // Escape mid-stretch: the document as it was before the first keystroke,\n    // with nothing recorded, and the field showing it again.\n    const putBack = () => {\n      const { run, before } = stretch;\n      idle(stretch);\n      // The text from before only where the canvas went back to it too. A run\n      // another edit has since followed, or one with no editor to cancel it,\n      // stays on the canvas, and the field shows what the document holds.\n      const cancelled = run === null || cancelTyping?.(run) === true;\n      show(cancelled ? before : storedNow.current);\n      onPutBack.current?.();\n    };\n    return {\n      draft,\n      setDraft,\n      type: (next, write) => {\n        show(next);\n        // A new run from the first keystroke, and again after a save ended\n        // every run (`endTypingRuns`): what was saved is its own step, and\n        // Escape puts back the saved text, not the text before the save.\n        if (stretch.run === null || stretch.epoch !== typingEpoch()) {\n          stretch.run = {};\n          stretch.epoch = typingEpoch();\n          stretch.before = stored;\n        }\n        edit.begin(putBack);\n        if (joinTyping(stretch.run, () => write(next))) {\n          stretch.own = true;\n          stretch.wrote = next;\n          stretch.answered = null;\n        }\n      },\n      join: write =>\n        stretch.run === null ? write() : joinTyping(stretch.run, write),\n      written: text => stretch.wrote === text,\n      end: () => {\n        if (stretch.wrote === draft && stretch.answered !== null) {\n          show(stretch.answered);\n        }\n        idle(stretch);\n        edit.end();\n      },\n    };\n  }, [draft, setDraft, stored, stretch, edit, cancelTyping]);\n}\n\n/**\n * A number typed so far, or `undefined` while the text is not one yet: empty,\n * a lone sign, an exponent or a unit on its way in.\n */\nexport function typedNumber(text: string): number | undefined {\n  if (text.trim() === \"\") return undefined;\n  const parsed = Number(text);\n  return Number.isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * A style field's text as typed, or `undefined` for an emptied field, which\n * clears the value only when the field is left: mid-edit, emptied is the\n * author deleting on the way to the next value.\n */\nexport function typedStyleText(text: string): string | undefined {\n  return trimCssWhitespace(text) === \"\" ? undefined : text;\n}\n","/**\n * The words a style keyword is offered in.\n *\n * The catalog's keywords are CSS spellings (\"inline-flex\", \"no-repeat\",\n * \"scale-down\"), and the panel printed them as they are. An author reads the\n * words here instead, in every menu, segmented choice and icon tooltip, and\n * the CSS spelling is kept for the tooltip of whoever wants it.\n *\n * ONE map, keyed by the CSS property and then the keyword, because a keyword's\n * meaning depends on its property: `none` is \"Hidden\" for `display` and \"None\"\n * for `border-style`. A keyword this map does not name falls back to the words\n * many properties share (`auto`, `normal`), and then to the keyword itself in\n * words, so a keyword the catalog gains later still reads as words.\n *\n * @module style-keyword-labels\n */\nimport {\n  APPEAR_EFFECT_PROPERTY,\n  APPEAR_START_PROPERTY,\n  asciiLower,\n  decodeIdentifier,\n  DISCLOSURE_ICON_PROPERTY,\n  DISCLOSURE_POSITION_PROPERTY,\n  trimCssWhitespace,\n} from \"@nextlyhq/blocks-engine\";\n\nconst SIZE_KEYWORDS: Readonly<Record<string, string>> = {\n  auto: \"Auto\",\n  none: \"None\",\n  \"min-content\": \"Shrink to content\",\n  \"max-content\": \"Widest content\",\n  \"fit-content\": \"Fit content\",\n  stretch: \"Fill\",\n  contain: \"Contain\",\n};\n\nconst KEYWORD_LABELS: Readonly<\n  Record<string, Readonly<Record<string, string>>>\n> = {\n  display: {\n    block: \"Block\",\n    flex: \"Flex\",\n    grid: \"Grid\",\n    inline: \"Inline\",\n    \"inline-block\": \"Inline block\",\n    \"inline-flex\": \"Inline flex\",\n    \"inline-grid\": \"Inline grid\",\n    \"flow-root\": \"Contain floats\",\n    contents: \"Contents only\",\n    none: \"Hidden\",\n    \"list-item\": \"List item\",\n    table: \"Table\",\n  },\n  position: {\n    static: \"Normal flow\",\n    relative: \"Relative\",\n    absolute: \"Absolute\",\n    fixed: \"Fixed to the window\",\n    sticky: \"Sticky\",\n  },\n  \"box-sizing\": {\n    \"content-box\": \"Content only\",\n    \"border-box\": \"Include padding and border\",\n  },\n  \"flex-direction\": {\n    row: \"Row\",\n    \"row-reverse\": \"Row, reversed\",\n    column: \"Column\",\n    \"column-reverse\": \"Column, reversed\",\n  },\n  \"flex-wrap\": {\n    nowrap: \"No wrap\",\n    wrap: \"Wrap\",\n    \"wrap-reverse\": \"Wrap, reversed\",\n  },\n  \"grid-auto-flow\": {\n    row: \"Row\",\n    column: \"Column\",\n    dense: \"Fill gaps\",\n    \"row dense\": \"Row, fill gaps\",\n    \"dense row\": \"Row, fill gaps\",\n    \"column dense\": \"Column, fill gaps\",\n    \"dense column\": \"Column, fill gaps\",\n  },\n  width: SIZE_KEYWORDS,\n  height: SIZE_KEYWORDS,\n  \"min-width\": SIZE_KEYWORDS,\n  \"min-height\": SIZE_KEYWORDS,\n  \"max-width\": SIZE_KEYWORDS,\n  \"max-height\": SIZE_KEYWORDS,\n  // Strikethrough is what an author calls a line through text.\n  \"text-decoration-line\": {\n    none: \"None\",\n    underline: \"Underline\",\n    \"line-through\": \"Strikethrough\",\n    overline: \"Overline\",\n  },\n  \"object-fit\": {\n    fill: \"Stretch to fill\",\n    contain: \"Fit inside\",\n    cover: \"Cover\",\n    none: \"Original size\",\n    \"scale-down\": \"Shrink to fit\",\n  },\n  overflow: {\n    visible: \"Visible\",\n    hidden: \"Hidden\",\n    clip: \"Clip\",\n    scroll: \"Scroll\",\n    auto: \"Scroll when needed\",\n  },\n  \"font-size\": {\n    \"xx-small\": \"XX small\",\n    \"x-small\": \"X small\",\n    small: \"Small\",\n    medium: \"Medium\",\n    large: \"Large\",\n    \"x-large\": \"X large\",\n    \"xx-large\": \"XX large\",\n    \"xxx-large\": \"XXX large\",\n    smaller: \"Smaller\",\n    larger: \"Larger\",\n    math: \"Math\",\n  },\n  \"font-weight\": {\n    normal: \"Normal\",\n    bold: \"Bold\",\n    lighter: \"Lighter\",\n    bolder: \"Bolder\",\n  },\n  \"font-style\": { normal: \"Normal\", italic: \"Italic\", oblique: \"Oblique\" },\n  \"text-align\": {\n    start: \"Start\",\n    center: \"Center\",\n    end: \"End\",\n    justify: \"Justify\",\n    \"justify-all\": \"Justify every line\",\n    \"match-parent\": \"Match the parent\",\n  },\n  \"text-transform\": {\n    none: \"None\",\n    uppercase: \"Uppercase\",\n    lowercase: \"Lowercase\",\n    capitalize: \"Capitalize words\",\n  },\n  // An Accordion's icon choices, traced on their own custom properties, as\n  // the Content tab names them. A stored Browser default draws the plus.\n  [DISCLOSURE_ICON_PROPERTY]: {\n    plus: \"+ / −\",\n    chevron: \"Chevron\",\n    none: \"None\",\n    browser: \"+ / −\",\n  },\n  [DISCLOSURE_POSITION_PROPERTY]: {\n    before: \"Before\",\n    after: \"After\",\n  },\n  \"list-style-type\": {\n    none: \"None\",\n    revert: \"Default\",\n    disc: \"Bullet\",\n    circle: \"Circle\",\n    square: \"Square\",\n    decimal: \"1, 2, 3\",\n    \"decimal-leading-zero\": \"01, 02, 03\",\n    \"lower-alpha\": \"a, b, c\",\n    \"upper-alpha\": \"A, B, C\",\n    \"lower-roman\": \"i, ii, iii\",\n    \"upper-roman\": \"I, II, III\",\n  },\n  \"background-repeat\": {\n    repeat: \"Tile\",\n    \"repeat-x\": \"Tile across\",\n    \"repeat-y\": \"Tile down\",\n    \"no-repeat\": \"Don't repeat\",\n    space: \"Tile with space\",\n    round: \"Tile and stretch\",\n  },\n  \"background-attachment\": {\n    scroll: \"Scroll with the page\",\n    fixed: \"Fixed\",\n    local: \"Scroll with the content\",\n  },\n  \"border-style\": {\n    none: \"None\",\n    hidden: \"Hidden\",\n    solid: \"Solid\",\n    dashed: \"Dashed\",\n    dotted: \"Dotted\",\n    double: \"Double\",\n    groove: \"Groove\",\n    ridge: \"Ridge\",\n    inset: \"Inset\",\n    outset: \"Outset\",\n  },\n  \"outline-style\": {\n    auto: \"Browser's focus ring\",\n    none: \"None\",\n    solid: \"Solid\",\n    dashed: \"Dashed\",\n    dotted: \"Dotted\",\n    double: \"Double\",\n    groove: \"Groove\",\n    ridge: \"Ridge\",\n    inset: \"Inset\",\n    outset: \"Outset\",\n  },\n  \"container-type\": {\n    normal: \"None\",\n    \"inline-size\": \"Width\",\n    size: \"Width and height\",\n    \"scroll-state\": \"Scroll state\",\n  },\n  // \"Animation when it appears\", traced on its own custom properties.\n  [APPEAR_EFFECT_PROPERTY]: {\n    none: \"None\",\n    \"fade-in\": \"Fade in\",\n    rise: \"Rise\",\n    \"slide-in-left\": \"Slide in from the left\",\n    \"slide-in-right\": \"Slide in from the right\",\n    \"zoom-in\": \"Zoom in\",\n  },\n  [APPEAR_START_PROPERTY]: {\n    scroll: \"When scrolled into view\",\n    load: \"When the page loads\",\n  },\n};\n\n/** Words many properties share for the same keyword. */\nconst SHARED_LABELS: Readonly<Record<string, string>> = {\n  auto: \"Auto\",\n  normal: \"Default\",\n  none: \"None\",\n};\n\n/**\n * The words for one keyword of one CSS property: this property's own, else\n * the shared ones, else the keyword in words (\"space-between\" reads \"Space\n * between\"), so no keyword is ever shown in its CSS spelling.\n */\nexport function keywordLabel(cssProperty: string, keyword: string): string {\n  // Looked up as CSS reads a keyword; only the lookup is folded, and the\n  // stored value and its tooltip keep the spelling they were given.\n  const folded = foldKeyword(keyword);\n  return (\n    KEYWORD_LABELS[cssProperty]?.[folded] ??\n    SHARED_LABELS[folded] ??\n    inWords(folded)\n  );\n}\n\n/**\n * A keyword as CSS reads it: its escapes decoded, case-folded the ASCII way,\n * with its CSS whitespace trimmed and collapsed, since the validator stores\n * `INLINE-FLEX`, `inline\\2d flex` and `row  dense` as the keywords they\n * spell. For comparing a stored value with the keywords a control offers.\n */\nexport function foldKeyword(keyword: string): string {\n  return asciiLower(decodeIdentifier(trimCssWhitespace(keyword))).replace(\n    /[ \\t\\n\\r\\f]+/g,\n    \" \"\n  );\n}\n\n/**\n * The keywords a menu offers, one item per choice.\n *\n * Two spellings of one value read the same in words (`row dense` and `dense\n * row`), and a menu holding both shows two items an author cannot tell apart,\n * the second recording an edit that changes nothing. So a menu keeps the\n * first spelling of each, or the stored one in its place. A stored keyword the\n * list lacks (`inherit`) is offered first, so the menu never shows empty over\n * a value that is doing something.\n */\nexport function menuKeywords(\n  cssProperty: string,\n  values: readonly string[],\n  stored: string\n): readonly string[] {\n  const words = (keyword: string): string => keywordLabel(cssProperty, keyword);\n  const storedWords = stored === \"\" ? undefined : words(stored);\n  const placed = values.map(value =>\n    storedWords !== undefined && words(value) === storedWords ? stored : value\n  );\n  const all =\n    stored !== \"\" && !placed.includes(stored) ? [stored, ...placed] : placed;\n  const seen = new Set<string>();\n  return all.filter(keyword => {\n    const said = words(keyword);\n    if (seen.has(said)) return false;\n    seen.add(said);\n    return true;\n  });\n}\n\n/** A CSS keyword as words: its hyphens as spaces, its first letter capital. */\nfunction inWords(keyword: string): string {\n  const words = keyword.replace(/-/g, \" \").replace(/\\s+/g, \" \").trim();\n  return words.charAt(0).toUpperCase() + words.slice(1);\n}\n","/**\n * The numeric view of a stored style value, and the choices a control may offer\n * over it.\n *\n * Pure, for the reason `style-controls.ts` is: what a value decomposes into,\n * whether it may be stepped, and which units are worth offering 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 an input with a number in it.\n *\n * ## A measurement is a PROJECTION over the string, never a model of it\n *\n * A `dimension` is stored as a string, and the catalog lets one hold far more\n * than a number and a unit: per-property `keywords` (`auto` centres a margin\n * and is discarded on padding), `maxParts` (four corners, or a row and a column\n * gap), `functions` (`clamp()`, `fit-content()`), a unitless number where the\n * property says so, the CSS-wide keywords everywhere, and a `{ $token }`\n * reference that is a record and nonetheless a scalar.\n *\n * So `16px`, `auto`, `10px 20px`, `clamp(1rem, 2vw, 3rem)`, `inherit` and a\n * token are all legal in one position. A control that MODELLED the value as a\n * number plus a unit could represent one of those six, and would write the\n * other five away the moment a field was focused and blurred — the author's\n * `clamp()` replaced by `0px`, with nothing to say it happened.\n *\n * Everything here therefore answers with `undefined` rather than with a guess.\n * A caller that gets `undefined` keeps the plain text field it already had,\n * which accepts every one of those spellings; a caller that gets a measurement\n * may additionally offer stepping and a unit. Nothing here ever rewrites a\n * value it could not decompose.\n *\n * ## The engine decides, and this asks it\n *\n * No grammar is restated here. Whether a composed string is a legal value for a\n * property is `checkDimensionValue`'s question, asked with the leaf's own rules,\n * and a step or a unit swap that would produce something the engine refuses is\n * answered `undefined` instead of being offered. Predicting it here would mean\n * a second copy of the rules for negatives, percentages, functions and unitless\n * numbers — the copy that keeps compiling while the two drift apart, which is\n * invisible because a refused value and an unoffered one look identical.\n *\n * @module style-numeric\n */\n\nimport {\n  checkDimensionValue,\n  trimCssWhitespace,\n  type StyleLeaf,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { keywordLabel } from \"../inspector/style-inspector/style-keyword-labels\";\n\n/**\n * The grammar CSS calls a `<number>`: an optional sign, digits with an optional\n * decimal part, and an optional exponent.\n *\n * Deliberately narrower than `Number` in both directions. `Number` reads\n * spellings CSS does not (`0x10`, `0b10`, `0o10`), and it also accepts a\n * trailing point: CSS requires at least one digit AFTER a decimal point, so\n * `1.` is a number followed by a stray delimiter rather than a number, and\n * `Number(\"1.\")` quietly answering `1` would store a value the author never\n * wrote a valid spelling of.\n */\nexport const CSS_NUMBER: RegExp =\n  /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/;\n\n/**\n * One measurement split into the parts a control edits separately.\n *\n * A unit can be absent — `line-height: 1.5` is unitless and `0` is legal\n * everywhere — so the empty string means \"no unit\" rather than \"unknown\", and a\n * caller composing a new value joins the two with nothing between them.\n */\nexport interface Measurement {\n  /** The numeric part, as CSS reads it. */\n  readonly number: number;\n  /** The unit as WRITTEN, or `\"\"` for a unitless value. */\n  readonly unit: string;\n  /**\n   * How many digits followed the decimal point, so a step ROUNDS at the\n   * author's own precision.\n   *\n   * Carried rather than recovered from {@link number}, which has already lost\n   * it: `1.50` and `1.5` parse to the same double, so without this a step of\n   * `0.25` on `1.50rem` would round to the value's apparent one decimal and\n   * answer `1.8rem` instead of `1.75rem`.\n   *\n   * It governs ROUNDING and not spelling. A trailing zero is not preserved\n   * through a step — `1.50` stepped by `0.1` answers `1.6`, not `1.60` —\n   * because the composed text is re-parsed to drop the zeros that rounding\n   * introduces. Stated because the two are easy to conflate, and a reader\n   * expecting the spelling back would find the value correct and the text\n   * changed.\n   */\n  readonly decimals: number;\n}\n\n/**\n * The most fractional digits `Number.prototype.toFixed` accepts.\n *\n * Named rather than inlined because it is a limit of the FORMATTER and not a\n * judgement about how precise a length may be: the engine accepts more, and\n * anything beyond this is declined rather than truncated for that reason.\n */\nconst MAX_FRACTION_DIGITS = 100;\n\n/**\n * A number followed by an optional unit, and nothing else.\n *\n * The unit is matched as letters or a single `%` rather than by a list, because\n * a list here would be a second copy of the engine's — this only has to SPLIT\n * the string; whether the unit means anything is decided by asking. Anchored at\n * both ends so a value with a second term (`10px 20px`), a function, or any\n * trailing text fails to match rather than matching its first part and\n * presenting a shorthand as though it were one measurement.\n */\nconst MEASUREMENT = new RegExp(\n  // Composed from the one grammar rather than spelled again: a second copy of\n  // the number rule would let a draft this accepts and `committedValue`\n  // rejects — or the reverse — pass every test either side owns.\n  `^(${CSS_NUMBER.source.replace(/^\\^|\\$$/g, \"\")})([a-zA-Z]+|%)?$`\n);\n\n/**\n * The measurement a stored value holds, when it holds exactly one.\n *\n * Answers `undefined` for everything a numeric affordance cannot represent —\n * a keyword, a shorthand, a function, a token reference, an object at a scalar\n * position — so the caller keeps its text field rather than narrowing what the\n * author can express.\n *\n * A stored NUMBER is a measurement with no unit. `number` leaves store numbers\n * rather than strings, so reading only strings would leave every `opacity` and\n * `line-height` unsteppable while looking supported.\n */\nexport function measurementOf(\n  value: StyleValue | undefined\n): Measurement | undefined {\n  if (typeof value === \"number\") {\n    // DELEGATED to the text path rather than decomposed here, so the\n    // round-trip guard applies to a stored number too. Read directly, this\n    // branch answered `{ number: 1e-7, decimals: 0 }` for a value the text path\n    // declines — and `line-height: 1e-7` then stepped to `1`, discarding the\n    // quantity. Two paths to one answer is the defect this module keeps\n    // producing; the number branch simply prints its value and asks the same\n    // question of it.\n    return Number.isFinite(value)\n      ? measurementOfText(String(value))\n      : undefined;\n  }\n  // Every remaining non-string is refused by the same test, and a token\n  // reference is one of them: `{ $token }` is one value spelled as a record, so\n  // it arrives here as an object and is never decomposed. A control that\n  // offered to step it would be offering to replace the reference with a\n  // literal. Named because the shape is easy to mistake for a composite —\n  // `isTokenRef` is deliberately NOT called, since it could only ever agree\n  // with the test already made.\n  if (typeof value !== \"string\") return undefined;\n  return measurementOfText(value);\n}\n\n/** The measurement a typed draft holds, when it holds exactly one. */\nexport function measurementOfText(text: string): Measurement | undefined {\n  const trimmed = trimCssWhitespace(text);\n  const match = MEASUREMENT.exec(trimmed);\n  if (match === null) return undefined;\n  const [, digits = \"\", unit = \"\"] = match;\n  const number = Number(digits);\n  if (!Number.isFinite(number)) return undefined;\n  const decimals = decimalsOf(digits);\n  // Precision the formatter cannot round to is DECLINED, not truncated. The\n  // engine accepts a length with more fractional digits than `toFixed` takes,\n  // and composing one would throw mid-keystroke. Checked BEFORE the round trip\n  // below, which would be the thing that throws.\n  if (decimals > MAX_FRACTION_DIGITS) return undefined;\n  // THE PROJECTION MUST REPRODUCE ITS OWN INPUT, or it does not get to edit it.\n  //\n  // A `number` is a double and several spellings the engine accepts do not\n  // survive the trip through one: `9007199254740993` comes back smaller than it\n  // started, `1e-7` composes to `0`, `.5` becomes `0.5`. Composing any of them\n  // writes a value the author never typed, which is the silent rewrite this\n  // module exists to prevent, committed by the module itself.\n  //\n  // Asked by CALLING THE COMPOSER rather than by re-deriving what it would do.\n  // That is the whole point of the check and not an implementation detail: a\n  // guard written as its own expression is a second answer to \"what will this\n  // become\", and the two drifted apart at exactly one input — `String(1e-7)` is\n  // `\"1e-7\"` and round-trips, while `toFixed(0)` on the same value is `\"0\"`. So\n  // the guard admitted a value the composer then destroyed. Sharing the\n  // function makes that disagreement unrepresentable.\n  //\n  // Conservative by design: `1.50`, `+5`, `05` and `.5` are all legal and none\n  // reproduces itself, so they lose the affordances too. For an editing aid\n  // that is the cheap direction to be wrong in — the value still works and can\n  // still be typed, which is not true of the alternative.\n  if (composeMeasurement(number, \"\", decimals) !== digits) return undefined;\n  return { number, unit, decimals };\n}\n\n/**\n * How many digits follow the decimal point in a written number.\n *\n * Read from the TEXT rather than from the parsed double, which no longer knows\n * the difference between `1.50` and `1.5` — and the count is what a step rounds\n * at, so losing it coarsens the result rather than merely reformatting it.\n *\n * Exponent notation reaches here and answers 0, which is correct for what this\n * measures: it never survives the round-trip check in {@link measurementOfText}\n * regardless, so no caller sees the count.\n */\nfunction decimalsOf(digits: string): number {\n  const point = digits.indexOf(\".\");\n  return point === -1 ? 0 : digits.length - point - 1;\n}\n\n/**\n * The value written back after a measurement is composed, in the author's own\n * precision.\n *\n * Rounded rather than left to floating point, because the arithmetic is not\n * exact in the base the author is typing in: stepping `0.1` by `0.2` answers\n * `0.30000000000000004`, which is a valid CSS number and a value no one would\n * choose to store.\n */\nfunction composeMeasurement(\n  number: number,\n  unit: string,\n  decimals: number\n): string {\n  // `toFixed` rather than a multiply-round-divide, which reintroduces the error\n  // it was meant to remove at the magnitudes a length actually takes.\n  return `${String(roundedTo(number, decimals))}${unit}`;\n}\n\n/**\n * Whether the engine accepts this text as a value for this leaf.\n *\n * The LEAF is handed over whole rather than having its rule fields copied into\n * a fresh object. A dimension leaf already carries everything\n * `checkDimensionValue` reads, so passing it through means the preflight this\n * module performs and the validation the write path performs are judged by\n * literally the same values — including any the engine adds later, which an\n * enumeration here would silently omit while continuing to compile. A control\n * that offered a unit the write path then refused would be the visible half of\n * that drift; the invisible half is a restriction quietly not applied.\n */\nfunction accepts(\n  leaf: Extract<StyleLeaf, { kind: \"dimension\" }>,\n  text: string\n): boolean {\n  return checkDimensionValue(text, leaf) === null;\n}\n\n/**\n * The units a control may OFFER for this leaf, in the order an author meets\n * them.\n *\n * Every candidate is tried against the engine before being offered, so the list\n * is filtered by the property's own rules rather than by a belief about them: a\n * leaf that refuses percentages never shows `%`, and no offered unit can\n * produce a value the write path then rejects.\n *\n * **The candidate list is a discoverability aid and NOT a grammar, which is the\n * honest description of its limits.** A unit missing from it is still typeable,\n * because the field it sits beside accepts any text the engine does; a unit\n * wrongly present is filtered out by the check above. So the failure mode is a\n * shorter menu, which an author routes around, rather than an offered value the\n * document then refuses. That asymmetry is why a fixed list is acceptable here\n * and would not be in the write path — the engine's own unit sets are private\n * to it, and reaching for them would put a second copy in this package.\n */\nexport function unitChoicesFor(leaf: StyleLeaf): readonly string[] {\n  if (leaf.kind !== \"dimension\") return [];\n  const candidates = SCREEN_HEIGHT_PROPERTIES.has(leaf.cssProperty)\n    ? SCREEN_HEIGHT_CANDIDATES\n    : UNIT_CANDIDATES;\n  return candidates.filter(unit => accepts(leaf, `1${unit}`));\n}\n\n/**\n * Units common enough in authoring to be worth a menu entry.\n *\n * Absolute first, then the two font-relative units, then the viewport pair,\n * then the percentage — the order an author reaches for them rather than\n * alphabetical, which would open the menu on `%`. `ch` and the container-query\n * units are omitted deliberately: they are typeable, and a menu long enough to\n * scroll costs every author to serve a few.\n */\nconst UNIT_CANDIDATES: readonly string[] = [\"px\", \"rem\", \"em\", \"vw\", \"vh\", \"%\"];\n\n/**\n * The properties a screen's own height is offered on: the small, dynamic and\n * large viewport heights, after `vh`.\n *\n * On a phone `100vh` is the height with the browser's toolbar hidden, so a\n * block sized by it runs under the toolbar while it shows. `svh` is the\n * height with it showing (what Full screen writes), `lvh` with it hidden and\n * `dvh` follows it as it moves. Only on the heights, where that matters; on\n * any other length they are typeable, and the menu stays short.\n */\nconst SCREEN_HEIGHT_PROPERTIES: ReadonlySet<string> = new Set([\n  \"height\",\n  \"min-height\",\n  \"max-height\",\n]);\n\nconst SCREEN_HEIGHT_CANDIDATES: readonly string[] = [\n  \"px\",\n  \"rem\",\n  \"em\",\n  \"vw\",\n  \"vh\",\n  \"svh\",\n  \"dvh\",\n  \"lvh\",\n  \"%\",\n];\n\n/**\n * The same value carrying a different unit, or `undefined` when the swap would\n * produce something this property refuses.\n *\n * The NUMBER is carried across unchanged rather than converted. A conversion\n * would have to know the font size and the viewport to be correct, and neither\n * is knowable from here — so `16px` becoming `16rem` is what the author asked\n * for and is what a design tool does; inventing `1rem` instead would be a\n * guess dressed as help.\n */\nexport function withUnit(\n  leaf: StyleLeaf,\n  value: StyleValue | undefined,\n  unit: string\n): string | undefined {\n  if (leaf.kind !== \"dimension\") return undefined;\n  const current = measurementOf(value);\n  if (current === undefined) return undefined;\n  const next = composeMeasurement(current.number, unit, current.decimals);\n  return accepts(leaf, next) ? next : undefined;\n}\n\n/**\n * A length field's value as committed: a bare number takes the unit the field\n * shows (px unless the author chose another), where \"24\" used to be refused\n * as \"not a length\". Anything that already says its own unit, a keyword, an\n * empty field, or a number the property would refuse even with the unit is\n * left exactly as typed, so the write path judges it as before.\n */\nexport function withDefaultUnit(\n  leaf: StyleLeaf,\n  value: StyleValue | null,\n  unit: string\n): StyleValue | null {\n  if (leaf.kind !== \"dimension\" || typeof value !== \"string\") return value;\n  // CSS whitespace only, as every numeric field here reads it.\n  const text = trimCssWhitespace(value);\n  if (!CSS_NUMBER.test(text)) return value;\n  const next = `${text}${unit}`;\n  return accepts(leaf, next) ? next : value;\n}\n\n/**\n * The value one step away, or `undefined` when this value cannot be stepped or\n * the result would be refused.\n *\n * The unit is preserved, so stepping is an edit to the quantity and never a\n * change of kind. A result the property refuses — a negative margin on a\n * padding, a percentage where none resolves — answers `undefined` so the key\n * does nothing visible, rather than writing a value the document then rejects\n * and leaving the field holding text that was never stored.\n */\nexport function steppedValue(\n  leaf: StyleLeaf,\n  value: StyleValue | undefined,\n  delta: number\n): string | number | undefined {\n  if (leaf.kind === \"number\") return steppedNumber(leaf, value, delta);\n  if (leaf.kind !== \"dimension\") return undefined;\n  const current = measurementOf(value);\n  if (current === undefined) return undefined;\n  const decimals = stepDecimals(current.decimals, delta);\n  const stepped = roundedTo(current.number + delta, decimals);\n  if (!movedBy(current.number, stepped, delta, decimals)) return undefined;\n  const next = composeMeasurement(\n    current.number + delta,\n    current.unit,\n    decimals\n  );\n  return accepts(leaf, next) ? next : undefined;\n}\n\n/**\n * Where a drag on a field's label starts, or `undefined` when its value is not\n * one measurement a drag could move.\n *\n * The text in the field, with the unit the field shows given to a bare number,\n * as a commit would give it. An EMPTY field starts from what it shows instead:\n * the value reaching it from another tier when that is a measurement, else\n * zero in the field's unit — dragging an unset padding is the commonest scrub\n * there is, and refusing it would make the label inert exactly where it is\n * reached for. Anything else typed — `auto`, a `clamp()`, a shorthand — is\n * left to the keyboard, as stepping leaves it.\n */\nexport function scrubOrigin(\n  leaf: StyleLeaf,\n  draft: string,\n  unit: string,\n  inherited: string | undefined\n): string | undefined {\n  const text = trimCssWhitespace(draft);\n  const steppable = (value: string): string | undefined =>\n    steppedValue(leaf, value, 0) === undefined ? undefined : value;\n  if (text !== \"\") {\n    const given = withDefaultUnit(leaf, text, unit);\n    return steppable(typeof given === \"string\" ? given : text);\n  }\n  const shown = inherited === undefined ? undefined : steppable(inherited);\n  if (shown !== undefined) return shown;\n  return steppable(leaf.kind === \"dimension\" ? `0${unit}` : \"0\");\n}\n\n/**\n * The value `delta` away, or as far toward it as the property takes, for a\n * drag; `undefined` when not even the smallest step is taken.\n *\n * A drag is not a key press. Dragging a padding from `4px` well past zero\n * must REST at `0px`, where {@link steppedValue} answers `undefined` for the\n * refused `-20px` and the field would freeze at whatever the last accepted\n * move happened to be. So the step is shortened, at the drag's own precision,\n * to the longest one the engine still accepts: the property's bounds are the\n * engine's, and this only asks.\n *\n * The search halves, which assumes what is refused lies beyond a bound — the\n * only refusal a change of quantity can meet, since the unit and the shape of\n * the value are kept.\n */\nexport function scrubbedValue(\n  leaf: StyleLeaf,\n  value: StyleValue | undefined,\n  dragged: number\n): string | number | undefined {\n  // An integer moves by whole steps: a fine drag's tenths are dropped toward\n  // zero, so the value moves once they add up to a whole one.\n  const delta =\n    leaf.kind === \"number\" && leaf.integer === true\n      ? Math.trunc(dragged)\n      : dragged;\n  const whole = steppedValue(leaf, value, delta);\n  if (whole !== undefined || delta === 0) return whole;\n  const current = measurementOf(value);\n  if (current === undefined) return undefined;\n  const decimals = stepDecimals(current.decimals, delta);\n  const quantum = 10 ** -decimals;\n  const sign = Math.sign(delta);\n  // Steps of the smallest unit the drag can move by: `low` is taken, `high`\n  // is not.\n  let low = 0;\n  let high = Math.round(Math.abs(delta) / quantum);\n  let found: string | number | undefined;\n  while (high - low > 1) {\n    const middle = low + Math.floor((high - low) / 2);\n    // Past the safe integers a midpoint can round back onto an end, and the\n    // search would never move again: what it has found is then as close to\n    // the bound as a double can say.\n    if (middle <= low || middle >= high) break;\n    const next = steppedValue(\n      leaf,\n      value,\n      roundedTo(sign * middle * quantum, decimals)\n    );\n    if (next === undefined) {\n      high = middle;\n    } else {\n      low = middle;\n      found = next;\n    }\n  }\n  return found;\n}\n\n/**\n * Whether the composed result actually moved by the step that was asked for.\n *\n * The round-trip guard in {@link measurementOfText} proves the STARTING value\n * survives a double. It says nothing about the step, and near the safe-integer\n * boundary the two come apart: `9007199254740992` plus one is the same double,\n * so the arrow is consumed and nothing happens, and `9007199254740994` plus one\n * lands on `...996` — a silent step of two. Neither is a value the author asked\n * for, and the first is worse than an error because it looks like a dead key.\n *\n * Measured at the composition's own precision rather than exactly, because\n * binary arithmetic does not land on decimal boundaries: `1.25 + 0.1` differs\n * from `1.25` by `0.10000000000000009`, which is the correct step and is not\n * `0.1`. Rounding both sides at the digits the value is written to compares\n * what an author would read rather than what a double holds.\n */\nfunction movedBy(\n  from: number,\n  stepped: number,\n  delta: number,\n  decimals: number\n): boolean {\n  return roundedTo(stepped - from, decimals) === roundedTo(delta, decimals);\n}\n\n/**\n * A number as it reads at a given precision.\n *\n * The one rounding used by both the composer and the check above, so what gets\n * written and what gets verified cannot be two different roundings — which is\n * the disagreement this module has already produced once, between a guard and\n * the composer it was guarding.\n */\nfunction roundedTo(value: number, decimals: number): number {\n  return Number(value.toFixed(decimals));\n}\n\n/**\n * A `number` leaf stepped within its declared bounds.\n *\n * Separate from the dimension path because the two are judged by different\n * things: a number carries `min`, `max` and `integer` on the leaf itself, where\n * a dimension's legality is a question only the engine can answer. Clamped\n * rather than refused at the ends, which is what a spinbutton does — holding an\n * arrow key at the maximum should rest there rather than stop responding.\n */\nfunction steppedNumber(\n  leaf: Extract<StyleLeaf, { kind: \"number\" }>,\n  value: StyleValue | undefined,\n  delta: number\n): number | undefined {\n  const current = measurementOf(value);\n  // A unit on a number leaf is not a number: `opacity: 5px` is stored text the\n  // engine refuses, and stepping it would answer `6px`, which it also refuses.\n  if (current === undefined || current.unit !== \"\") return undefined;\n  // A fine step on an integer has no value to land on: rounded back, it would\n  // be a key claimed and a write attempted for a value that did not move.\n  if (leaf.integer === true && !Number.isInteger(delta)) return undefined;\n  const stepped =\n    leaf.integer === true\n      ? Math.round(current.number + delta)\n      : current.number + delta;\n  const decimals =\n    leaf.integer === true ? 0 : stepDecimals(current.decimals, delta);\n  const rounded = roundedTo(stepped, decimals);\n  // Clamping comes FIRST and is exempt from the check below. Resting at a\n  // declared bound is the correct answer to a step rather than a step that\n  // failed to happen, so requiring movement there would make the arrow go dead\n  // exactly at the ends, which is where a spinbutton is most often held.\n  const bound = boundFor(leaf, rounded);\n  if (bound !== undefined) return bound;\n  // Everywhere else a number leaf is subject to the same arithmetic as a\n  // dimension, and was not asking the same question of it: `z-index` is an\n  // unbounded integer, so `9007199254740992` plus one is the same double and\n  // `9007199254740994` plus one lands two away — a dead key and a doubled step,\n  // in a branch the dimension path's guard never reached.\n  if (!movedBy(current.number, rounded, delta, decimals)) return undefined;\n  return rounded;\n}\n\n/**\n * The bound this leaf holds a value to, when the value has passed one.\n *\n * Its own answer rather than two conditionals inside the step, because \"has\n * this left the declared range\" and \"did this move by what was asked\" are\n * different questions with opposite answers at the ends: one says the value is\n * correct, the other would say the step failed.\n */\nfunction boundFor(\n  leaf: Extract<StyleLeaf, { kind: \"number\" }>,\n  value: number\n): number | undefined {\n  if (leaf.min !== undefined && value < leaf.min) return leaf.min;\n  if (leaf.max !== undefined && value > leaf.max) return leaf.max;\n  return undefined;\n}\n\n/**\n * How many decimals the stepped result keeps.\n *\n * The wider of the value's own precision and the step's, so a fine step off a\n * whole number lands on `0.1` rather than being rounded straight back to `0`,\n * and a coarse step off `1.50` does not drop the trailing zero the author\n * typed.\n */\nfunction stepDecimals(valueDecimals: number, delta: number): number {\n  // Bounded as well as widened. A measurement reaching here is already within\n  // the formatter's range, but the step's own precision is a caller's value and\n  // widening past the limit would throw where the measurement alone would not.\n  return Math.min(\n    MAX_FRACTION_DIGITS,\n    Math.max(valueDecimals, decimalsOf(String(Math.abs(delta))))\n  );\n}\n\n/**\n * How many options a segmented control may offer.\n *\n * Three, not two — the condition was never that two is special, it is that the\n * WHOLE vocabulary fits in the control. A keyword offering three short values\n * fits, and folding it into a menu makes an author open something to read three\n * words that could have been on screen.\n */\nconst MAX_TOGGLE_OPTIONS = 3;\n\n/**\n * The longest a single option may be, and the longest they may be together.\n *\n * Length decides as well as count, because this draws in a rail an author can\n * drag narrow. Three long words do not sit side by side there, and a segmented\n * control that wraps onto three lines is worse than the menu it replaced: it\n * takes MORE height and still has to be read word by word. The bounds are\n * deliberately mean, so the control appears only where it plainly fits and the\n * menu keeps everything else.\n */\nconst MAX_OPTION_LENGTH = 8;\nconst MAX_OPTIONS_LENGTH = 20;\n\n/**\n * The options a keyword leaf offers, when offering all of them at once fits.\n *\n * A toggle is a PROJECTION of a keyword leaf and not a shape of its own — the\n * engine has no boolean — so it is offered only where the whole vocabulary fits\n * in it: at most three values, each short, and one keyword per value. A leaf\n * taking a shorthand of two keywords (`overflow: hidden auto`) has more to say\n * than a row of buttons can, and drawing one would hide the second axis\n * entirely.\n *\n * Returned whole or not at all. Offering the first three of a longer vocabulary\n * would be a control that silently cannot reach the values it does not show.\n */\nexport function toggleOptionsFor(\n  leaf: StyleLeaf\n): readonly string[] | undefined {\n  if (leaf.kind !== \"keyword\") return undefined;\n  if ((leaf.maxParts ?? 1) !== 1) return undefined;\n\n  const values = leaf.values;\n  // By the words the buttons show, which can be far longer than the keyword:\n  // `scroll` reads \"When scrolled into view\".\n  return fitsSideBySide(\n    values.map(value => keywordLabel(leaf.cssProperty, value)),\n    STYLE_ROW\n  )\n    ? values\n    : undefined;\n}\n\n/** How much room a row of options has: how many, how long each and together. */\nexport interface SideBySideRoom {\n  readonly maxCount: number;\n  readonly maxEach: number;\n  readonly maxTotal: number;\n}\n\n/** A style row's room, beside its label in a rail an author can drag narrow. */\nconst STYLE_ROW: SideBySideRoom = {\n  maxCount: MAX_TOGGLE_OPTIONS,\n  maxEach: MAX_OPTION_LENGTH,\n  maxTotal: MAX_OPTIONS_LENGTH,\n};\n\n/**\n * Whether a whole set of options, by the words that show, fits side by side\n * in the room given: at least two, and none of the bounds exceeded.\n *\n * ONE rule for every surface that draws options as a row of buttons; each\n * says only how much room it has.\n */\nexport function fitsSideBySide(\n  labels: readonly string[],\n  room: SideBySideRoom\n): boolean {\n  if (labels.length < 2 || labels.length > room.maxCount) return false;\n  if (labels.some(label => label.length > room.maxEach)) return false;\n  const together = labels.reduce((sum, label) => sum + label.length, 0);\n  return together <= room.maxTotal;\n}\n\n/**\n * Whether a toggle may show this stored value as one of its two options.\n *\n * A stored value outside the pair — a CSS-wide keyword, a token, a spelling the\n * validator folds — is live and compiles while matching neither button, and a\n * toggle rendered over it would show one side selected and silently replace the\n * value on the first click. Answering `false` keeps the text field, which can\n * show what is actually stored.\n */\nexport function toggleShows(\n  options: readonly string[],\n  value: StyleValue | undefined\n): boolean {\n  if (value === undefined) return true;\n  return typeof value === \"string\" && options.includes(value);\n}\n\n/**\n * Above this, a bare line height reads as pixels typed without their unit:\n * `20` is twenty times the text size, which no text is set at, where `1.5`\n * or `2` is an ordinary multiple.\n */\nconst LINE_HEIGHT_PIXELS_ABOVE = 4;\n\n/**\n * The pixels a bare line height was probably meant as (`20` gives `20px`), or\n * nothing for a multiple an author would choose, or for any value that\n * already says its unit.\n */\nexport function lineHeightAsPixels(text: string): string | undefined {\n  const number = trimCssWhitespace(text);\n  if (!CSS_NUMBER.test(number)) return undefined;\n  return Number(number) > LINE_HEIGHT_PIXELS_ABOVE ? `${number}px` : undefined;\n}\n","/**\n * The plain layout layer: a container's Arrange (Stack, Row or Grid) and its\n * rows, mapped to the catalog values they write and read back from the values\n * in force at the device being edited.\n *\n * Pure. It is handed what is in force at each device, widest first, and\n * answers with a plain state, or with the writes one plain change makes, so\n * the panel draws and writes through the same rules a test asserts.\n *\n * Read back by the display and direction IN FORCE at the edited device, never\n * by a plain choice alone: a Row that stacks on Mobile reads as a Row there,\n * with \"Stack on: Mobile\", and its Align, Spread and Reverse order go by the\n * column in force there.\n *\n * @module plain-layout\n */\n\nimport { applies } from \"@nextlyhq/blocks-engine\";\n\n/** The catalog properties the layer reads and writes. */\nexport const LAYOUT_PROPERTIES = [\n  \"display\",\n  \"flexDirection\",\n  \"flexWrap\",\n  \"justifyContent\",\n  \"alignItems\",\n  \"justifyItems\",\n  \"gap\",\n  \"rowGap\",\n  \"columnGap\",\n  \"gridTemplateColumns\",\n  \"gridTemplateRows\",\n  // How the block sits in its parent: \"Inside its parent\".\n  \"width\",\n  \"height\",\n  \"minWidth\",\n  \"minHeight\",\n  \"flexGrow\",\n  \"flexShrink\",\n  \"flexBasis\",\n  \"alignSelf\",\n  \"justifySelf\",\n] as const;\n\n/** Each layout property's CSS name, as a declaration spells it. */\nexport const LAYOUT_CSS_NAMES: Readonly<Record<string, string>> = {\n  display: \"display\",\n  flexDirection: \"flex-direction\",\n  flexWrap: \"flex-wrap\",\n  justifyContent: \"justify-content\",\n  alignItems: \"align-items\",\n  justifyItems: \"justify-items\",\n  gap: \"gap\",\n  rowGap: \"row-gap\",\n  columnGap: \"column-gap\",\n  gridTemplateColumns: \"grid-template-columns\",\n  gridTemplateRows: \"grid-template-rows\",\n  width: \"width\",\n  height: \"height\",\n  minWidth: \"min-width\",\n  minHeight: \"min-height\",\n  flexGrow: \"flex-grow\",\n  flexShrink: \"flex-shrink\",\n  flexBasis: \"flex-basis\",\n  alignSelf: \"align-self\",\n  justifySelf: \"justify-self\",\n};\n\n/** One of {@link LAYOUT_PROPERTIES}. */\nexport type LayoutProperty = (typeof LAYOUT_PROPERTIES)[number];\n\n/** Layout values, by catalog property, as text. */\nexport type LayoutValues = Readonly<Partial<Record<LayoutProperty, string>>>;\n\n/** What is in force, and what is stored, at each device. */\nexport interface LayoutTiers {\n  /** The devices along the viewport axis, widest (the base) first. */\n  readonly order: readonly string[];\n  /** The values in force at a device: its own, else what reaches it. */\n  readonly inForce: (device: string) => LayoutValues;\n  /** The values the edited target stores at a device itself. */\n  readonly own: (device: string) => LayoutValues;\n  /**\n   * Every tier the page's styles are written for, in their order, where it\n   * holds more than {@link order} (two tiers at one width): what survives a\n   * clear is read through all of them.\n   */\n  readonly cascadeOrder?: readonly string[];\n  /**\n   * What is in force at a device beneath the target's own values there: a\n   * shared style it wears, its block's defaults. Absent where nothing but the\n   * target is read, as for a shared style edited on its own.\n   */\n  readonly beneath?: (device: string) => LayoutValues;\n  /** Which way the container's lines run, so a point is placed on screen. */\n  readonly flow?: PlainFlow;\n}\n\n/** A container's writing mode and inline direction. */\nexport interface PlainFlow {\n  readonly writingMode: string;\n  readonly rtl: boolean;\n}\n\n/**\n * What a target's own values put in force at a device, in the order the\n * page's styles are written: state outside, device inside. Its Normal values\n * cascade widest first, and the edited state's values, cascading the same\n * way, go over all of them, so a Hover value set at any wider device beats a\n * Normal one at this device. A shared style edited on its own is read so.\n */\nexport function ownCascade(\n  order: readonly string[],\n  own: (device: string) => LayoutValues,\n  normal: (device: string) => LayoutValues\n): (device: string) => LayoutValues {\n  const upTo = (\n    device: string,\n    read: (device: string) => LayoutValues\n  ): Partial<Record<LayoutProperty, string>> => {\n    const merged: Partial<Record<LayoutProperty, string>> = {};\n    for (const each of order) {\n      Object.assign(merged, read(each));\n      if (each === device) break;\n    }\n    return merged;\n  };\n  return device => ({ ...upTo(device, normal), ...upTo(device, own) });\n}\n\n/**\n * At an interaction state, what is in force beneath the state's own values:\n * the target's Normal values, cascading widest first, which a value cleared\n * at the state leaves in force. Nothing at Normal itself.\n */\nexport function normalBeneath(\n  order: readonly string[],\n  normal: (device: string) => LayoutValues\n): (device: string) => LayoutValues {\n  return ownCascade(order, () => ({}), normal);\n}\n\n/** Horizontal lines, left to right: what is assumed where nothing is measured. */\nconst LTR: PlainFlow = { writingMode: \"horizontal-tb\", rtl: false };\n\n/** One point of the 3×3 Align. */\nexport type AlignX = \"left\" | \"center\" | \"right\";\nexport type AlignY = \"top\" | \"middle\" | \"bottom\";\nexport interface AlignPoint {\n  readonly x: AlignX;\n  readonly y: AlignY;\n}\n\n/** How a Row spreads its blocks along its main axis. */\nexport type Spread = \"packed\" | \"between\" | \"around\" | \"even\";\n\n/** A Grid's columns: a count per device, or as many as fit a width. */\nexport type GridColumns =\n  | { readonly kind: \"count\"; readonly count: number }\n  | { readonly kind: \"fit\"; readonly min: string };\n\n/** What a container's Arrange reads as at the edited device. */\nexport type PlainArrange =\n  | {\n      readonly mode: \"stack\";\n      /** Whether it is a flex column, written by its own settings. */\n      readonly flex: boolean;\n      readonly align: AlignPoint | undefined;\n      readonly reverse: boolean;\n    }\n  | {\n      readonly mode: \"row\";\n      /** The widest device it stacks at, where it does. */\n      readonly stackOn: string | undefined;\n      /** Whether it is stacked at the edited device. */\n      readonly stacked: boolean;\n      readonly align: AlignPoint | undefined;\n      readonly spread: Spread;\n      readonly wrap: boolean;\n      readonly reverse: boolean;\n    }\n  | {\n      readonly mode: \"grid\";\n      readonly columns: GridColumns | undefined;\n      readonly rows: number | undefined;\n      readonly align: AlignPoint | undefined;\n    }\n  | { readonly mode: \"custom\" };\n\n/** One value to write at one device; `null` clears it there. */\nexport interface LayoutWrite {\n  readonly device: string;\n  readonly property: LayoutProperty;\n  readonly value: string | null;\n}\n\nconst COLUMN_DIRECTIONS = new Set([\"column\", \"column-reverse\"]);\n\n/** The directions a Row or Stack reads: across or down, either way. */\nconst PLAIN_DIRECTIONS: ReadonlySet<string> = new Set([\n  \"row\",\n  \"row-reverse\",\n  \"column\",\n  \"column-reverse\",\n]);\n\n/** The wraps Wrap onto new lines says: on, or off. */\nconst PLAIN_WRAPS: ReadonlySet<string> = new Set([\"wrap\", \"nowrap\"]);\nconst ROW_DIRECTIONS = new Set([\"row\", \"row-reverse\"]);\n\n/** Whether a device's values make the block a flex row. */\nfunction isRow(values: LayoutValues): boolean {\n  return (\n    values.display === \"flex\" &&\n    ROW_DIRECTIONS.has(values.flexDirection ?? \"row\")\n  );\n}\n\n/** Whether a device's values make the block a flex column. */\nfunction isColumn(values: LayoutValues): boolean {\n  return (\n    values.display === \"flex\" &&\n    COLUMN_DIRECTIONS.has(values.flexDirection ?? \"row\")\n  );\n}\n\n/** Each keyword's place on its axis: start, centre or end. */\nconst AXIS_PLACES: Readonly<Record<string, 0 | 1 | 2>> = {\n  start: 0,\n  center: 1,\n  end: 2,\n};\n\n/**\n * The flex-relative keywords, read as the logical edge they name only where\n * the main axis runs its own way: reversed, `flex-start` is the far edge.\n * Physical `left` and `right` name no logical edge at all, so with these\n * anything else reads as Custom rather than as a point it doesn't make.\n */\nconst FLEX_PLACES: Readonly<Record<string, 0 | 2>> = {\n  \"flex-start\": 0,\n  \"flex-end\": 2,\n};\n\n/** A keyword's place on its axis, or `undefined` for one with none. */\nfunction axisPlace(value: string | undefined): 0 | 1 | 2 | undefined {\n  return value === undefined ? undefined : AXIS_PLACES[value];\n}\n\nconst X_POINTS: readonly AlignX[] = [\"left\", \"center\", \"right\"];\nconst Y_POINTS: readonly AlignY[] = [\"top\", \"middle\", \"bottom\"];\nconst PLACE_KEYWORDS = [\"start\", \"center\", \"end\"] as const;\n\n/** The properties a point's x and y are written to, by arrangement. */\nfunction alignAxes(kind: \"row\" | \"column\" | \"grid\"): {\n  readonly inline: LayoutProperty;\n  readonly block: LayoutProperty;\n} {\n  // A row's main axis runs along the lines, a column's across them.\n  if (kind === \"row\") return { inline: \"justifyContent\", block: \"alignItems\" };\n  if (kind === \"column\") {\n    return { inline: \"alignItems\", block: \"justifyContent\" };\n  }\n  return { inline: \"justifyItems\", block: \"alignItems\" };\n}\n\n/** Whether the lines run down the screen rather than across it. */\nfunction vertical(flow: PlainFlow): boolean {\n  return (\n    flow.writingMode.startsWith(\"vertical\") ||\n    flow.writingMode.startsWith(\"sideways\")\n  );\n}\n\n/** Whether a vertical flow's lines stack from the right. */\nfunction blockFromRight(flow: PlainFlow): boolean {\n  return flow.writingMode.endsWith(\"-rl\");\n}\n\n/** Whether a flow's inline axis runs up or leftward rather than its default. */\nfunction inlineReversed(flow: PlainFlow): boolean {\n  // sideways-lr runs its lines bottom to top; direction rtl flips any.\n  return flow.rtl !== (flow.writingMode === \"sideways-lr\");\n}\n\n/** A place 0, 1 or 2, counted from the other end. */\nfunction flipped(place: 0 | 1 | 2, flip: boolean): 0 | 1 | 2 {\n  return flip ? ((2 - place) as 0 | 1 | 2) : place;\n}\n\n/**\n * A point on screen as places along the inline and block axes, which are\n * what `start`, `center` and `end` are measured on.\n */\nfunction logicalPlaces(\n  point: AlignPoint,\n  flow: PlainFlow\n): { inline: 0 | 1 | 2; block: 0 | 1 | 2 } {\n  const x = X_POINTS.indexOf(point.x) as 0 | 1 | 2;\n  const y = Y_POINTS.indexOf(point.y) as 0 | 1 | 2;\n  if (!vertical(flow)) {\n    return { inline: flipped(x, flow.rtl), block: y };\n  }\n  return {\n    inline: flipped(y, inlineReversed(flow)),\n    block: flipped(x, blockFromRight(flow)),\n  };\n}\n\n/** Places along the inline and block axes as the point on screen. */\nfunction physicalPoint(\n  inline: 0 | 1 | 2,\n  block: 0 | 1 | 2,\n  flow: PlainFlow\n): AlignPoint {\n  if (!vertical(flow)) {\n    return {\n      x: X_POINTS[flipped(inline, flow.rtl)] ?? \"left\",\n      y: Y_POINTS[block] ?? \"top\",\n    };\n  }\n  return {\n    x: X_POINTS[flipped(block, blockFromRight(flow))] ?? \"left\",\n    y: Y_POINTS[flipped(inline, inlineReversed(flow))] ?? \"top\",\n  };\n}\n\n/**\n * The screen axis Spread takes while it is on: the main axis, along the lines\n * for a Row and across them for a stacked one.\n */\nexport function spreadAxis(stacked: boolean, flow: PlainFlow = LTR): \"x\" | \"y\" {\n  const alongLines = !stacked;\n  return alongLines === vertical(flow) ? \"y\" : \"x\";\n}\n\n/**\n * One axis of a point read from its value: its place, the start where it\n * holds none, a spread left to Spread (read as the start), or `\"custom\"`.\n */\nfunction axisRead(\n  value: string | undefined,\n  spreadHere: boolean,\n  flexRelative = false\n): 0 | 1 | 2 | \"custom\" {\n  if (value === undefined || value === \"normal\" || value === \"stretch\") {\n    return 0;\n  }\n  const place =\n    axisPlace(value) ?? (flexRelative ? FLEX_PLACES[value] : undefined);\n  if (place !== undefined) return place;\n  return spreadHere && SPREADS.has(value) ? 0 : \"custom\";\n}\n\n/**\n * A 3×3 point read from the values in force, or `undefined` for none chosen\n * (the default stretch). A spread, not a place, leaves the main axis unread.\n */\nfunction readAlign(\n  values: LayoutValues,\n  kind: \"row\" | \"column\" | \"grid\",\n  flow: PlainFlow = LTR\n): AlignPoint | undefined | \"custom\" {\n  const axes = alignAxes(kind);\n  const inlineValue = values[axes.inline];\n  const blockValue = values[axes.block];\n  // Nothing chosen, or only the reset a narrower device writes: the default\n  // stretch.\n  if (isDefaultPlace(inlineValue) && isDefaultPlace(blockValue)) {\n    return undefined;\n  }\n  // A spread on the main axis is Spread's, not Align's.\n  // Flex-relative keywords read as their edge only while the main axis\n  // isn't reversed; a grid has none.\n  const forward =\n    kind !== \"grid\" && !(values.flexDirection ?? \"\").endsWith(\"-reverse\");\n  const inline = axisRead(inlineValue, kind === \"row\", forward);\n  const block = axisRead(blockValue, kind === \"column\", forward);\n  if (inline === \"custom\" || block === \"custom\") return \"custom\";\n  return physicalPoint(inline, block, flow);\n}\n\n/** Whether a value leaves an axis at its default stretch. */\nfunction isDefaultPlace(value: string | undefined): boolean {\n  return value === undefined || value === \"normal\" || value === \"stretch\";\n}\n\nconst SPREAD_OF: Readonly<Record<string, Spread>> = {\n  \"space-between\": \"between\",\n  \"space-around\": \"around\",\n  \"space-evenly\": \"even\",\n};\nconst SPREADS: ReadonlySet<string> = new Set(Object.keys(SPREAD_OF));\n\n/** The keyword a Spread writes; Packed writes none. */\nconst SPREAD_KEYWORDS: Readonly<Record<Spread, string | null>> = {\n  packed: null,\n  between: \"space-between\",\n  around: \"space-around\",\n  even: \"space-evenly\",\n};\n\nconst COUNT_TEMPLATE = /^repeat\\((\\d+),\\s*minmax\\(0,\\s*1fr\\)\\)$/;\n// The minimum may itself hold commas, as `min(12rem, 100%)` does: the last\n// `, 1fr))` closes the template.\nconst FIT_TEMPLATE = /^repeat\\(auto-fill,\\s*minmax\\((.+),\\s*1fr\\)\\)$/;\nconst ROWS_TEMPLATE = /^repeat\\((\\d+),\\s*auto\\)$/;\n\n/** A Grid's columns read from its template, or `\"custom\"` for another. */\nfunction readColumns(\n  template: string | undefined\n): GridColumns | undefined | \"custom\" {\n  if (template === undefined || template === \"none\") return undefined;\n  const count = COUNT_TEMPLATE.exec(template);\n  if (count !== null) return { kind: \"count\", count: Number(count[1]) };\n  const fit = FIT_TEMPLATE.exec(template);\n  if (fit !== null) return { kind: \"fit\", min: (fit[1] ?? \"\").trim() };\n  return \"custom\";\n}\n\n/** A Grid's rows read from its template, or `\"custom\"` for another. */\nfunction readRows(template: string | undefined): number | undefined | \"custom\" {\n  if (template === undefined || template === \"none\") return undefined;\n  const rows = ROWS_TEMPLATE.exec(template);\n  return rows === null ? \"custom\" : Number(rows[1]);\n}\n\n/**\n * The widest device at or below `from` (by index) that sets the column of a\n * Row: one where the block is a flex column while a wider one is a Row.\n */\nfunction stackDevice(tiers: LayoutTiers): string | undefined {\n  let rowSeen = false;\n  for (const device of tiers.order) {\n    const values = tiers.inForce(device);\n    if (isRow(values)) rowSeen = true;\n    else if (rowSeen && isColumn(values)) return device;\n  }\n  return undefined;\n}\n\n/** Whether a column at a device is a Row stacked there, not a Stack. */\nfunction stackedRowAt(tiers: LayoutTiers, device: string): boolean {\n  const stackOn = stackDevice(tiers);\n  return (\n    stackOn !== undefined &&\n    tiers.order.indexOf(device) >= tiers.order.indexOf(stackOn)\n  );\n}\n\n/**\n * Whether a flex container's direction and wrap have plain words: a\n * direction such as `inherit`, or wrapping in reverse, is the raw rows'.\n */\nfunction plainFlex(values: LayoutValues): boolean {\n  return (\n    PLAIN_DIRECTIONS.has(values.flexDirection ?? \"row\") &&\n    PLAIN_WRAPS.has(values.flexWrap ?? \"nowrap\")\n  );\n}\n\n/** What a container's Arrange reads as at the edited device. */\nexport function readArrange(tiers: LayoutTiers, editing: string): PlainArrange {\n  const values = tiers.inForce(editing);\n  const display = values.display;\n  if (display === undefined || display === \"block\") {\n    return { mode: \"stack\", flex: false, align: undefined, reverse: false };\n  }\n  if (display === \"grid\") return readGrid(values, tiers.flow);\n  if (display !== \"flex\") return { mode: \"custom\" };\n  const stackOn = stackDevice(tiers);\n  const column = isColumn(values);\n  const index = tiers.order.indexOf(editing);\n  const stackIndex = stackOn === undefined ? -1 : tiers.order.indexOf(stackOn);\n  // A column below a Row is that Row stacked; any other column is a Stack.\n  const stacked = column && stackIndex !== -1 && index >= stackIndex;\n  if (column && !stacked) return readStack(values, tiers.flow);\n  if (!plainFlex(values)) return { mode: \"custom\" };\n  const align = readAlign(values, column ? \"column\" : \"row\", tiers.flow);\n  if (align === \"custom\") return { mode: \"custom\" };\n  const main = values.justifyContent;\n  return {\n    mode: \"row\",\n    stackOn,\n    stacked,\n    align,\n    spread: SPREAD_OF[main ?? \"\"] ?? \"packed\",\n    wrap: values.flexWrap === \"wrap\",\n    reverse:\n      values.flexDirection === \"row-reverse\" ||\n      values.flexDirection === \"column-reverse\",\n  };\n}\n\n/** A flex column that is a Stack, with its own settings. */\nfunction readStack(values: LayoutValues, flow?: PlainFlow): PlainArrange {\n  // A Stack has no Spread: a distribution on its main axis is Custom's.\n  if (SPREADS.has(values.justifyContent ?? \"\")) return { mode: \"custom\" };\n  const align = readAlign(values, \"column\", flow);\n  if (align === \"custom\") return { mode: \"custom\" };\n  return {\n    mode: \"stack\",\n    flex: true,\n    align,\n    reverse: values.flexDirection === \"column-reverse\",\n  };\n}\n\n/** A Grid, with its columns, rows and Align. */\nfunction readGrid(values: LayoutValues, flow?: PlainFlow): PlainArrange {\n  const columns = readColumns(values.gridTemplateColumns);\n  const rows = readRows(values.gridTemplateRows);\n  const align = readAlign(values, \"grid\", flow);\n  if (columns === \"custom\" || rows === \"custom\" || align === \"custom\") {\n    return { mode: \"custom\" };\n  }\n  return { mode: \"grid\", columns, rows, align };\n}\n\n/** The template a Grid's columns write. */\nfunction columnsTemplate(columns: GridColumns): string {\n  return columns.kind === \"count\"\n    ? `repeat(${String(columns.count)}, minmax(0, 1fr))`\n    : `repeat(auto-fill, minmax(${columns.min}, 1fr))`;\n}\n\n/** The template a Grid's rows write, or `null` for Auto. */\nfunction rowsTemplate(rows: number | undefined): string | null {\n  return rows === undefined ? null : `repeat(${String(rows)}, auto)`;\n}\n\n/**\n * The value to write at the edited device so a property reads `value` there:\n * nothing stored where nothing else would be in force (no wider device's\n * value, nothing beneath the target's own) and the value is the default, else\n * the value itself or the default spelled out, so what lies beneath cannot\n * stay in force under the one shown.\n */\nfunction settled(\n  tiers: LayoutTiers,\n  device: string,\n  property: LayoutProperty,\n  value: string | null\n): LayoutWrite {\n  if (value !== null) return { device, property, value };\n  const reaching = surviving(tiers, device)[property];\n  return {\n    device,\n    property,\n    // Nothing left in force but the default: the clear is enough.\n    value:\n      reaching === undefined || reaching === RESET[property]\n        ? null\n        : RESET[property],\n  };\n}\n\n/**\n * What stays in force at a device once the target's own value there is gone:\n * what lies beneath the target (a shared style it wears, its Normal values at\n * an interaction state), with the target's own values at wider devices, at\n * the edited state, over it, as the page applies them.\n */\nfunction surviving(tiers: LayoutTiers, device: string): LayoutValues {\n  const merged: Partial<Record<LayoutProperty, string>> = {\n    ...(tiers.beneath?.(device) ?? {}),\n  };\n  for (const each of tiers.cascadeOrder ?? tiers.order) {\n    if (each === device) break;\n    Object.assign(merged, tiers.own(each));\n  }\n  return merged;\n}\n\n/** The value that undoes a property reaching from a wider device. */\nconst RESET: Readonly<Record<LayoutProperty, string>> = {\n  display: \"block\",\n  flexDirection: \"row\",\n  flexWrap: \"nowrap\",\n  justifyContent: \"normal\",\n  alignItems: \"normal\",\n  justifyItems: \"normal\",\n  gap: \"normal\",\n  rowGap: \"normal\",\n  columnGap: \"normal\",\n  gridTemplateColumns: \"none\",\n  gridTemplateRows: \"none\",\n  width: \"auto\",\n  height: \"auto\",\n  minWidth: \"auto\",\n  minHeight: \"auto\",\n  flexGrow: \"0\",\n  flexShrink: \"1\",\n  flexBasis: \"auto\",\n  alignSelf: \"auto\",\n  justifySelf: \"auto\",\n};\n\n/** The writes choosing an Arrange mode makes at the edited device. */\nexport function planArrange(\n  tiers: LayoutTiers,\n  editing: string,\n  mode: \"stack\" | \"row\" | \"grid\"\n): LayoutWrite[] {\n  const current = readArrange(tiers, editing);\n  if (mode === \"stack\") {\n    // Below a Row, Stack is that Row stacked here: the same writes.\n    if (current.mode === \"row\" && tiers.order.indexOf(editing) > 0) {\n      const wider = tiers.order[tiers.order.indexOf(editing) - 1];\n      if (wider !== undefined && isRow(tiers.inForce(wider))) {\n        return planStackOn(tiers, editing);\n      }\n    }\n    return [\n      settled(tiers, editing, \"display\", null),\n      settled(tiers, editing, \"flexDirection\", null),\n    ];\n  }\n  if (mode === \"row\") {\n    return [\n      { device: editing, property: \"display\", value: \"flex\" },\n      settled(tiers, editing, \"flexDirection\", null),\n    ];\n  }\n  return [{ device: editing, property: \"display\", value: \"grid\" }];\n}\n\n/** The writes a Row's \"Stack on\" makes: its column at that device. */\nexport function planStackOn(\n  tiers: LayoutTiers,\n  device: string | null\n): LayoutWrite[] {\n  const current = stackDevice(tiers);\n  const writes: LayoutWrite[] = [];\n  // The old stack device gives up its column, undone there where a shared\n  // style or a wider device would keep it.\n  if (current !== undefined && current !== device) {\n    // Moved to a wider device, whose column reaches the old one: only the old\n    // one's own column goes. Otherwise it is undone there.\n    const wider =\n      device !== null &&\n      tiers.order.indexOf(device) < tiers.order.indexOf(current);\n    writes.push(\n      wider\n        ? { device: current, property: \"flexDirection\", value: null }\n        : settled(tiers, current, \"flexDirection\", null)\n    );\n  }\n  if (device === null) writes.push(...narrowerColumns(tiers, current));\n  if (device !== null) writes.push(...narrowerRows(tiers, device));\n  if (device !== null) {\n    const reversed =\n      tiers.inForce(device).flexDirection === \"row-reverse\" ||\n      tiers.own(device).flexDirection === \"column-reverse\";\n    writes.push({\n      device,\n      property: \"flexDirection\",\n      value: reversed ? \"column-reverse\" : \"column\",\n    });\n  }\n  return writes;\n}\n\n/**\n * Stack on a device also stacks the narrower ones that hold a row of their\n * own (a Reverse order turned off there), keeping each one's order: a row\n * becomes a column, a reversed row a reversed column.\n */\nfunction narrowerRows(tiers: LayoutTiers, from: string): LayoutWrite[] {\n  return tiers.order\n    .slice(tiers.order.indexOf(from) + 1)\n    .flatMap((device): LayoutWrite[] => {\n      const own = tiers.own(device).flexDirection;\n      if (own === \"row\") {\n        return [{ device, property: \"flexDirection\", value: \"column\" }];\n      }\n      if (own === \"row-reverse\") {\n        return [{ device, property: \"flexDirection\", value: \"column-reverse\" }];\n      }\n      return [];\n    });\n}\n\n/**\n * Stack on: Never also takes back the columns written below the stack device\n * (a Reverse order set at a narrower one), keeping a reversed one reversed as\n * a row, so no device is left stacked.\n */\nfunction narrowerColumns(\n  tiers: LayoutTiers,\n  from: string | undefined\n): LayoutWrite[] {\n  if (from === undefined) return [];\n  return tiers.order\n    .slice(tiers.order.indexOf(from) + 1)\n    .flatMap((device): LayoutWrite[] => {\n      const own = tiers.own(device).flexDirection;\n      if (own === \"column\") {\n        return [{ device, property: \"flexDirection\", value: null }];\n      }\n      if (own === \"column-reverse\") {\n        return [{ device, property: \"flexDirection\", value: \"row-reverse\" }];\n      }\n      return [];\n    });\n}\n\n/**\n * The writes a 3×3 point makes, by the direction in force at the edited\n * device; `null` clears both axes back to the default stretch.\n */\nexport function planAlign(\n  tiers: LayoutTiers,\n  editing: string,\n  point: AlignPoint | null\n): LayoutWrite[] {\n  const current = readArrange(tiers, editing);\n  const kind =\n    current.mode === \"grid\"\n      ? \"grid\"\n      : current.mode === \"row\" && !current.stacked\n        ? \"row\"\n        : \"column\";\n  const axes = alignAxes(kind);\n  const places =\n    point === null ? undefined : logicalPlaces(point, tiers.flow ?? LTR);\n  const writes: LayoutWrite[] = [];\n  // A Stack in block flow becomes a flex column to align.\n  if (current.mode === \"stack\" && !current.flex && point !== null) {\n    writes.push(\n      { device: editing, property: \"display\", value: \"flex\" },\n      { device: editing, property: \"flexDirection\", value: \"column\" }\n    );\n  }\n  // While a Row spreads its blocks, the axis Spread holds is its: a point\n  // places them on the other axis alone.\n  const spreading = current.mode === \"row\" && current.spread !== \"packed\";\n  const write = (property: LayoutProperty, place: 0 | 1 | 2 | undefined) =>\n    spreading && property === \"justifyContent\"\n      ? []\n      : [\n          settled(\n            tiers,\n            editing,\n            property,\n            place === undefined ? null : (PLACE_KEYWORDS[place] ?? \"start\")\n          ),\n        ];\n  writes.push(\n    ...write(axes.inline, places?.inline),\n    ...write(axes.block, places?.block)\n  );\n  return writes;\n}\n\n/** The writes a Row's Spread makes on the main axis in force. */\nexport function planSpread(\n  tiers: LayoutTiers,\n  editing: string,\n  spread: Spread\n): LayoutWrite[] {\n  return [settled(tiers, editing, \"justifyContent\", SPREAD_KEYWORDS[spread])];\n}\n\n/** The writes Reverse order makes, by the direction in force. */\nexport function planReverse(\n  tiers: LayoutTiers,\n  editing: string,\n  reverse: boolean\n): LayoutWrite[] {\n  const column = isColumn(tiers.inForce(editing));\n  const current = readArrange(tiers, editing);\n  if (current.mode === \"stack\") {\n    return [\n      { device: editing, property: \"display\", value: \"flex\" },\n      {\n        device: editing,\n        property: \"flexDirection\",\n        value: reverse ? \"column-reverse\" : \"column\",\n      },\n    ];\n  }\n  const writes: LayoutWrite[] = [\n    column\n      ? {\n          device: editing,\n          property: \"flexDirection\",\n          value: reverse ? \"column-reverse\" : \"column\",\n        }\n      : // Off, a reverse reaching from a wider device is undone here.\n        settled(\n          tiers,\n          editing,\n          \"flexDirection\",\n          reverse ? \"row-reverse\" : null\n        ),\n  ];\n  // Turned on at a wider device, it holds at the stacked one too.\n  const stackOn = current.mode === \"row\" ? current.stackOn : undefined;\n  if (\n    !column &&\n    stackOn !== undefined &&\n    tiers.order.indexOf(stackOn) > tiers.order.indexOf(editing)\n  ) {\n    writes.push({\n      device: stackOn,\n      property: \"flexDirection\",\n      value: reverse ? \"column-reverse\" : \"column\",\n    });\n  }\n  return writes;\n}\n\n/** The writes Wrap onto new lines makes. */\nexport function planWrap(\n  tiers: LayoutTiers,\n  editing: string,\n  wrap: boolean\n): LayoutWrite[] {\n  return [settled(tiers, editing, \"flexWrap\", wrap ? \"wrap\" : null)];\n}\n\n/** The writes a Grid's columns make at the edited device. */\nexport function planColumns(\n  tiers: LayoutTiers,\n  editing: string,\n  columns: GridColumns | undefined\n): LayoutWrite[] {\n  // None given is Auto: cleared, or undone where a wider device sets one.\n  return [\n    settled(\n      tiers,\n      editing,\n      \"gridTemplateColumns\",\n      columns === undefined ? null : columnsTemplate(columns)\n    ),\n  ];\n}\n\n/** The writes a Grid's rows make at the edited device. */\nexport function planRows(\n  tiers: LayoutTiers,\n  editing: string,\n  rows: number | undefined\n): LayoutWrite[] {\n  return [settled(tiers, editing, \"gridTemplateRows\", rowsTemplate(rows))];\n}\n\n/**\n * The values stored at the edited device that do nothing there: kept, but not\n * to be listed as if they applied. Judged by the engine's `applies`, against\n * the display and wrap in force, so this line and every other reader agree.\n * A wrap on a Row stacked here still applies to a flex container, so it is\n * not listed; the Row's own controls just don't show it there.\n */\nexport function unusedSettings(\n  tiers: LayoutTiers,\n  editing: string\n): LayoutProperty[] {\n  const values = tiers.inForce(editing);\n  const context = {\n    display: values.display ?? \"block\",\n    flexWrap: values.flexWrap ?? \"nowrap\",\n  };\n  const own = tiers.own(editing);\n  return LAYOUT_PROPERTIES.filter(\n    property => own[property] !== undefined && !applies(property, context)\n  );\n}\n\n/** A container's Space between: one gap, or rows and columns set apart. */\nexport interface PlainSpace {\n  readonly gap?: string;\n  readonly rowGap?: string;\n  readonly columnGap?: string;\n}\n\n/** The Space between in force at the edited device. */\nexport function readSpace(tiers: LayoutTiers, editing: string): PlainSpace {\n  const values = tiers.inForce(editing);\n  return {\n    ...(values.gap === undefined ? {} : { gap: values.gap }),\n    ...(values.rowGap === undefined ? {} : { rowGap: values.rowGap }),\n    ...(values.columnGap === undefined ? {} : { columnGap: values.columnGap }),\n  };\n}\n\n/** The display a Custom arrangement's plain rewrite keeps. */\nconst PLAIN_DISPLAY: Readonly<Record<string, \"flex\" | \"grid\">> = {\n  flex: \"flex\",\n  \"inline-flex\": \"flex\",\n  grid: \"grid\",\n  \"inline-grid\": \"grid\",\n};\n\n/** The alignment values a plain rewrite clears: those with no 3×3 point. */\nfunction unplainAlign(\n  values: LayoutValues,\n  kind: \"row\" | \"column\" | \"grid\",\n  spreads: boolean\n): LayoutProperty[] {\n  const axes = alignAxes(kind);\n  const forward =\n    kind !== \"grid\" && !(values.flexDirection ?? \"\").endsWith(\"-reverse\");\n  return [axes.inline, axes.block].filter(property => {\n    const spreadHere =\n      spreads && property === \"justifyContent\" && kind !== \"grid\";\n    return axisRead(values[property], spreadHere, forward) === \"custom\";\n  });\n}\n\n/** The Grid templates a plain rewrite clears: those with no plain form. */\nfunction unplainTemplates(values: LayoutValues): LayoutProperty[] {\n  const cleared: LayoutProperty[] = [];\n  if (readColumns(values.gridTemplateColumns) === \"custom\") {\n    cleared.push(\"gridTemplateColumns\");\n  }\n  if (readRows(values.gridTemplateRows) === \"custom\") {\n    cleared.push(\"gridTemplateRows\");\n  }\n  return cleared;\n}\n\n/** The arrangement a plain rewrite's alignment is read by. */\nfunction plainKind(\n  display: \"flex\" | \"grid\" | undefined,\n  values: LayoutValues\n): \"row\" | \"column\" | \"grid\" {\n  if (display === \"grid\") return \"grid\";\n  return display === \"flex\" && isColumn({ ...values, display: \"flex\" })\n    ? \"column\"\n    : \"row\";\n}\n\n/**\n * \"Use plain controls\": the writes that turn a Custom arrangement into the\n * nearest plain one at the edited device, as one step. An inline flex or grid\n * becomes its block form; any other display becomes a Stack; each value the\n * plain controls can't say (an alignment keyword with no 3×3 point, a\n * template with no plain form) is cleared, and every other value is kept.\n */\nexport function planPlain(tiers: LayoutTiers, editing: string): LayoutWrite[] {\n  if (readArrange(tiers, editing).mode !== \"custom\") return [];\n  const values = tiers.inForce(editing);\n  const display = PLAIN_DISPLAY[values.display ?? \"\"];\n  const kind = plainKind(display, values);\n  // Only a Row stacked here offers Spread; a Stack's distribution goes.\n  const spreads = kind !== \"column\" || stackedRowAt(tiers, editing);\n  const cleared: LayoutProperty[] = [\n    ...(display === undefined ? ([\"flexDirection\"] as const) : []),\n    ...unplainAlign(values, kind, spreads),\n    ...(display === \"grid\" ? unplainTemplates(values) : []),\n    ...(PLAIN_WRAPS.has(values.flexWrap ?? \"nowrap\")\n      ? []\n      : ([\"flexWrap\"] as const)),\n    ...(display !== undefined &&\n    !PLAIN_DIRECTIONS.has(values.flexDirection ?? \"row\")\n      ? ([\"flexDirection\"] as const)\n      : []),\n  ];\n  return [\n    settled(tiers, editing, \"display\", display ?? null),\n    ...cleared.map(property => settled(tiers, editing, property, null)),\n  ];\n}\n\n// --- Inside its parent: Fill, Fit or Fixed\n\n/** How a block's parent lays it out at the edited device. */\nexport type ParentArrangement = \"flow\" | \"column\" | \"row\" | \"grid\";\n\n/** A child's size choice: fill what it's given, fit its content, or set. */\nexport type ChildFit = \"fill\" | \"fit\" | \"fixed\";\n\n/** A child's size as read back: a choice (Fixed with its size), or Custom. */\nexport type ChildSize =\n  | { readonly choice: \"fill\" | \"fit\" }\n  | { readonly choice: \"fixed\"; readonly size: string }\n  | { readonly choice: \"custom\" };\n\n/** One of a block's two sizes on screen. */\nexport type ChildAxis = \"width\" | \"height\";\n\n/**\n * What a size is to the parent's layout: a flex container's main or cross\n * axis, a Grid's inline or block axis, or a width in flow. Lines running down\n * the screen turn a Row's main axis into the height, a Grid's inline axis\n * too, as Align's points turn with them.\n */\ntype AxisRole = \"flow\" | \"main\" | \"cross\" | \"inline\" | \"block\";\n\n/** The role each size plays in each arrangement, lines across or down. */\nconst ROLES: Readonly<\n  Record<\n    ParentArrangement,\n    Readonly<\n      Record<\"across\" | \"down\", Readonly<Record<ChildAxis, AxisRole | null>>>\n    >\n  >\n> = {\n  flow: {\n    across: { width: \"flow\", height: null },\n    down: { width: \"flow\", height: null },\n  },\n  column: {\n    across: { width: \"cross\", height: null },\n    down: { width: \"main\", height: null },\n  },\n  row: {\n    across: { width: \"main\", height: \"block\" },\n    down: { width: \"block\", height: \"main\" },\n  },\n  grid: {\n    across: { width: \"inline\", height: \"block\" },\n    down: { width: \"block\", height: \"inline\" },\n  },\n};\n\n/**\n * What a size is to the parent at the edited device; `null` where the\n * parent offers no choice for it (a height under a Stack, set in Size).\n */\nfunction roleOf(\n  parent: ParentArrangement,\n  axis: ChildAxis,\n  flow: PlainFlow = LTR\n): AxisRole | null {\n  return ROLES[parent][vertical(flow) ? \"down\" : \"across\"][axis];\n}\n\n/** Whether the parent offers a choice for a size at the edited device. */\nexport function offersChildAxis(\n  parent: ParentArrangement,\n  axis: ChildAxis,\n  flow?: PlainFlow\n): boolean {\n  return roleOf(parent, axis, flow) !== null;\n}\n\n/** The size a Fixed choice writes, filled in when it is planned. */\nconst SIZE = \"\\u0000size\";\n\n/** What a choice writes, by property; `null` leaves it at its default. */\ntype ChoiceWrites = Readonly<Partial<Record<LayoutProperty, string | null>>>;\n\n/** A size's own property, and its minimum. */\nconst SIZE_OF: Readonly<\n  Record<\n    ChildAxis,\n    { readonly size: LayoutProperty; readonly min: LayoutProperty }\n  >\n> = {\n  width: { size: \"width\", min: \"minWidth\" },\n  height: { size: \"height\", min: \"minHeight\" },\n};\n\n/**\n * What each choice writes, by the role a size plays. Each choice of a role\n * says every property the others write, so switching from one to another\n * leaves nothing of the last behind.\n */\nfunction roleWrites(\n  role: AxisRole,\n  axis: ChildAxis\n): Readonly<Record<ChildFit, ChoiceWrites>> {\n  const { size, min } = SIZE_OF[axis];\n  switch (role) {\n    case \"flow\":\n      return {\n        fill: { [size]: null },\n        fit: { [size]: \"fit-content\" },\n        fixed: { [size]: SIZE },\n      };\n    case \"main\":\n      return {\n        fill: {\n          flexGrow: \"1\",\n          flexShrink: \"1\",\n          flexBasis: \"0\",\n          [min]: \"0\",\n          [size]: null,\n        },\n        fit: {\n          flexGrow: null,\n          flexShrink: null,\n          flexBasis: null,\n          [min]: null,\n          [size]: null,\n        },\n        fixed: {\n          [size]: SIZE,\n          flexShrink: \"0\",\n          flexGrow: null,\n          flexBasis: null,\n          [min]: null,\n        },\n      };\n    // A flex column's cross axis: an automatic size is what stretching sizes.\n    case \"cross\":\n      return {\n        fill: { [size]: null, alignSelf: \"stretch\" },\n        fit: { [size]: null, alignSelf: \"flex-start\" },\n        fixed: { [size]: SIZE, alignSelf: \"flex-start\" },\n      };\n    // Stretched itself, so the parent's own Align can't keep it to its\n    // content.\n    case \"inline\":\n      return {\n        fill: { justifySelf: \"stretch\", [size]: null },\n        fit: { justifySelf: \"start\", [size]: null },\n        fixed: { [size]: SIZE, justifySelf: null },\n      };\n    case \"block\":\n      return {\n        fill: { alignSelf: \"stretch\", [size]: null },\n        fit: { alignSelf: \"start\", [size]: null },\n        fixed: { [size]: SIZE, alignSelf: null },\n      };\n  }\n}\n\n/** The properties a size's choices write, beside its own size. */\nexport function childAxisRows(\n  parent: ParentArrangement,\n  axis: ChildAxis,\n  flow?: PlainFlow\n): LayoutProperty[] {\n  const role = roleOf(parent, axis, flow);\n  if (role === null) return [];\n  const { size } = SIZE_OF[axis];\n  const written = new Set<LayoutProperty>();\n  for (const writes of Object.values(roleWrites(role, axis))) {\n    for (const property of Object.keys(writes) as LayoutProperty[]) {\n      if (property !== size) written.add(property);\n    }\n  }\n  return [...written];\n}\n\n/** A choice's writes at the edited device, its size filled in. */\nfunction childWrites(\n  tiers: LayoutTiers,\n  editing: string,\n  writes: ChoiceWrites,\n  size: string | undefined\n): LayoutWrite[] {\n  return (Object.keys(writes) as LayoutProperty[]).map(property => {\n    const value = writes[property] ?? null;\n    return settled(\n      tiers,\n      editing,\n      property,\n      value === SIZE ? (size ?? null) : value\n    );\n  });\n}\n\n/** Whether the block lays out inline: its display in force is inline-level. */\nfunction inlineLevel(tiers: LayoutTiers, editing: string): boolean {\n  return tiers.inForce(editing).display?.startsWith(\"inline\") === true;\n}\n\n/**\n * Whether a flowing block's automatic width is its content's: an inline-level\n * box's is, and so is any block's where lines run down the screen, the width\n * being its block size there.\n */\nfunction contentSized(tiers: LayoutTiers, editing: string): boolean {\n  return inlineLevel(tiers, editing) || vertical(tiers.flow ?? LTR);\n}\n\n/**\n * The writes a size's choice makes at the edited device, by the role it\n * plays in the parent's arrangement there. Defaults are written only where a\n * wider device's value would stay in force under the one chosen.\n */\nexport function planChildSize(\n  tiers: LayoutTiers,\n  editing: string,\n  parent: ParentArrangement,\n  axis: ChildAxis,\n  choice: ChildFit,\n  size?: string\n): LayoutWrite[] {\n  const role = roleOf(parent, axis, tiers.flow);\n  if (role === null) return [];\n  // In flow an inline-level block (a Button) is as wide as its content at\n  // an automatic width: Fill gives it the line's.\n  if (role === \"flow\" && choice === \"fill\" && contentSized(tiers, editing)) {\n    return childWrites(tiers, editing, { [SIZE_OF[axis].size]: \"100%\" }, size);\n  }\n  return childWrites(tiers, editing, roleWrites(role, axis)[choice], size);\n}\n\n/** Whether a length is the automatic one, which no choice sets. */\nfunction automatic(value: string | undefined): boolean {\n  return value === undefined || value === \"auto\";\n}\n\n/** Whether a self-alignment leaves the block stretched, as by default. */\nfunction stretched(value: string | undefined): boolean {\n  return (\n    value === undefined ||\n    value === \"auto\" ||\n    value === \"normal\" ||\n    value === \"stretch\"\n  );\n}\n\n/** Whether a self-alignment puts the block at its start. */\nfunction atStart(value: string | undefined): boolean {\n  return value === \"start\" || value === \"flex-start\" || value === \"self-start\";\n}\n\n/**\n * A size across the parent's axis: set, at the start, or stretched. An\n * automatic self-alignment takes the parent's for its items: under one that\n * doesn't stretch (centred, at the end) an automatic size is neither filled\n * nor at its start, so it reads as Custom. A size of its own is Fixed there\n * still: Fixed leaves the alignment to the parent.\n */\nfunction crossSize(\n  size: string | undefined,\n  ownSelf: string | undefined,\n  items?: string\n): ChildSize {\n  const deferred = automaticSelf(ownSelf);\n  const self = deferred ? itemsSelf(items) : ownSelf;\n  const chosen = atStart(self) || stretched(self);\n  if (!automatic(size) && (chosen || deferred)) {\n    return { choice: \"fixed\", size: size ?? \"\" };\n  }\n  // A self-alignment no choice writes (centred, at the end) is Custom, so\n  // its row stays drawn to say it.\n  if (!chosen) return { choice: \"custom\" };\n  return atStart(self) ? { choice: \"fit\" } : { choice: \"fill\" };\n}\n\n/** Whether a self-alignment defers to the parent's for its items. */\nfunction automaticSelf(value: string | undefined): boolean {\n  return value === undefined || value === \"auto\";\n}\n\n/** The parent's alignment for its items, as a self-alignment reads it. */\nfunction itemsSelf(items: string | undefined): string | undefined {\n  return items === undefined || items === \"normal\" || items === \"legacy\"\n    ? undefined\n    : items;\n}\n\n/** A basis of nothing, as Fill writes it and as it may be spelled. */\nconst ZERO_BASES: ReadonlySet<string> = new Set([\"0\", \"0%\", \"0px\"]);\n\n/**\n * A size along a flex container's main axis: grown from nothing, its\n * content's, or set. Anything a choice doesn't write (a basis of its own, a\n * grow of 2) is Custom, so its rows stay drawn to say it.\n */\nfunction mainSize(size: string | undefined, values: LayoutValues): ChildSize {\n  const grow = values.flexGrow ?? \"0\";\n  const basis = values.flexBasis ?? \"auto\";\n  const natural = grow === \"0\" && basis === \"auto\";\n  if (grow === \"1\" && ZERO_BASES.has(basis) && automatic(size)) {\n    return { choice: \"fill\" };\n  }\n  if (!natural) return { choice: \"custom\" };\n  return automatic(size)\n    ? { choice: \"fit\" }\n    : { choice: \"fixed\", size: size ?? \"\" };\n}\n\n/**\n * A flowing block's width: an automatic one fills the line for a block-level\n * box and fits the content of an inline-level one; 100% fills either.\n */\nfunction flowSize(size: string | undefined, inline: boolean): ChildSize {\n  if (size === \"100%\") return { choice: \"fill\" };\n  if (automatic(size)) return { choice: inline ? \"fit\" : \"fill\" };\n  return size === \"fit-content\"\n    ? { choice: \"fit\" }\n    : { choice: \"fixed\", size: size ?? \"\" };\n}\n\n/**\n * The choice a size reads as at the edited device, by the role it plays in\n * the parent's arrangement there. Under a Row stacked here, values a wider\n * device's Row choice wrote on the main axis (grow, shrink, a minimum) act\n * on the column's height and change nothing shown.\n */\nexport function readChildSize(\n  tiers: LayoutTiers,\n  editing: string,\n  parent: ParentArrangement,\n  axis: ChildAxis,\n  items?: ParentItems\n): ChildSize {\n  const role = roleOf(parent, axis, tiers.flow);\n  const values = tiers.inForce(editing);\n  const size = values[SIZE_OF[axis].size];\n  switch (role) {\n    case null:\n      return { choice: \"custom\" };\n    case \"flow\":\n      return flowSize(size, contentSized(tiers, editing));\n    case \"main\":\n      return mainSize(size, values);\n    case \"cross\":\n    case \"block\":\n      return crossSize(size, values.alignSelf, items?.alignItems);\n    case \"inline\":\n      return crossSize(size, values.justifySelf, items?.justifyItems);\n  }\n}\n\n/** The alignment a parent gives its items, which its children defer to. */\nexport interface ParentItems {\n  readonly alignItems?: string | undefined;\n  readonly justifyItems?: string | undefined;\n}\n\n/** The writes a Width choice makes: {@link planChildSize} for the width. */\nexport function planChildWidth(\n  tiers: LayoutTiers,\n  editing: string,\n  parent: ParentArrangement,\n  choice: ChildFit,\n  size?: string\n): LayoutWrite[] {\n  return planChildSize(tiers, editing, parent, \"width\", choice, size);\n}\n\n/** The writes a Height choice makes, under a Row or a Grid. */\nexport function planChildHeight(\n  tiers: LayoutTiers,\n  editing: string,\n  choice: ChildFit,\n  size?: string,\n  parent: ParentArrangement = \"row\"\n): LayoutWrite[] {\n  return planChildSize(tiers, editing, parent, \"height\", choice, size);\n}\n\n/** The Width choice the block's values read as at the edited device. */\nexport function readChildWidth(\n  tiers: LayoutTiers,\n  editing: string,\n  parent: ParentArrangement\n): ChildSize {\n  return readChildSize(tiers, editing, parent, \"width\");\n}\n\n/** The Height choice the block's values read as, under a Row or a Grid. */\nexport function readChildHeight(\n  tiers: LayoutTiers,\n  editing: string,\n  parent: ParentArrangement = \"row\"\n): ChildSize {\n  return readChildSize(tiers, editing, parent, \"height\");\n}\n","/**\n * What a panel control writes, in the words a developer reads: CSS as\n * `property: value` declarations joined by `; `, HTML as the tag or the\n * attribute. One function per kind of control, so a tooltip and the \"Show\n * CSS names\" line say the same thing for the same control.\n *\n * @module code-hints\n */\nimport {\n  compileStyleValues,\n  type PropSchema,\n  type StyleLeaf,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { LAYOUT_CSS_NAMES, type LayoutWrite } from \"../styles/plain-layout\";\n\n/** One declaration: its property, and its value where one is known. */\nexport interface WrittenDeclaration {\n  readonly property: string;\n  readonly value?: string | undefined;\n}\n\n/** Declarations as a developer writes them: `a: b; c: d`. */\nexport function declarationsText(\n  declarations: readonly WrittenDeclaration[]\n): string {\n  return declarations\n    .map(({ property, value }) =>\n      value === undefined || value === \"\" ? property : `${property}: ${value}`\n    )\n    .join(\"; \");\n}\n\n/** A catalog control, as far as saying what it writes goes. */\nexport interface WritingControl {\n  /** The catalog property the control writes. */\n  readonly property: string;\n  /** Where inside the property's value it writes, outermost first. */\n  readonly path: readonly string[];\n  readonly leaf: Pick<StyleLeaf, \"cssProperty\">;\n}\n\n/**\n * What a catalog control writes for a value: the declarations the engine\n * compiles it to, the page's own CSS (a URL wrapped, a keyword expanded, a\n * variable under the site's prefix), or its CSS property alone while it holds\n * nothing the engine writes. \"min-height: 40px\"; \"flex-direction: column\".\n */\nexport function controlWrites(\n  control: WritingControl,\n  value: unknown,\n  tokenPrefix: string\n): string {\n  if (value === undefined || value === null) return control.leaf.cssProperty;\n  const nested = control.path.reduceRight<unknown>(\n    (inner, key) => ({ [key]: inner }),\n    value\n  );\n  const { declarations } = compileStyleValues(\n    { [control.property]: nested },\n    \"\",\n    tokenPrefix\n  );\n  return declarations.length === 0\n    ? control.leaf.cssProperty\n    : declarationsText(declarations);\n}\n\n/**\n * What a block's own setting writes, from its `code` hint: the one string for\n * the setting, or the one for the option it holds. `undefined` where the\n * setting declares none.\n */\nexport function propWrites(\n  schema: Pick<PropSchema, \"code\">,\n  value?: unknown\n): string | undefined {\n  const { code } = schema;\n  if (typeof code === \"string\") return code;\n  if (code === undefined || typeof value !== \"string\") return undefined;\n  return code[value];\n}\n\n/** What a Section's Height shortcut writes, by choice. */\nexport function heightShortcutWrites(fullScreen: string): {\n  readonly auto: string;\n  readonly screen: string;\n} {\n  return {\n    auto: declarationsText([{ property: \"min-height\", value: \"auto\" }]),\n    screen: declarationsText([{ property: \"min-height\", value: fullScreen }]),\n  };\n}\n\n/** What a Button's Size shortcut writes, by choice. */\nexport function sizeShortcutWrites(sizes: {\n  readonly small: { readonly times: number; readonly text: string };\n  readonly large: { readonly times: number; readonly text: string };\n}): {\n  readonly small: string;\n  readonly medium: string;\n  readonly large: string;\n} {\n  const scaled = (size: { times: number; text: string }) =>\n    declarationsText([\n      { property: \"padding\", value: `calc(<padding> * ${String(size.times)})` },\n      { property: \"font-size\", value: size.text },\n    ]);\n  return {\n    small: scaled(sizes.small),\n    medium: declarationsText([\n      { property: \"padding\" },\n      { property: \"font-size\" },\n    ]),\n    large: scaled(sizes.large),\n  };\n}\n\n/** What an Icon's Size shortcut writes: its font size alone, Medium clearing it. */\nexport function iconSizeShortcutWrites(sizes: {\n  readonly small: string;\n  readonly large: string;\n}): {\n  readonly small: string;\n  readonly medium: string;\n  readonly large: string;\n} {\n  return {\n    small: declarationsText([{ property: \"font-size\", value: sizes.small }]),\n    medium: declarationsText([{ property: \"font-size\" }]),\n    large: declarationsText([{ property: \"font-size\", value: sizes.large }]),\n  };\n}\n\n/** What a Button's Full width shortcut writes. */\nexport const FULL_WIDTH_WRITES: string = declarationsText([\n  { property: \"width\", value: \"100%\" },\n]);\n\n/** What the builder's own Advanced rows write, by row. */\nexport const BUILT_IN_WRITES = {\n  /** Anchor (ID): the root element's `id`. */\n  anchor: \"id\",\n  /** CSS classes: names added to the root element's `class`. */\n  cssClasses: \"class\",\n  /** Keep out of search previews. */\n  searchPreviews: \"data-nosnippet\",\n} as const;\n\n/** The widths a device covers: from its lower bound up to its upper one. */\nexport interface DeviceRange {\n  /** Its narrowest width, `undefined` for the narrowest device. */\n  readonly from?: number | undefined;\n  /** Its widest width, `undefined` for the widest device. */\n  readonly to?: number | undefined;\n}\n\n/**\n * What Hide on writes for one device: `display: none` at that device's widths\n * alone. \"display: none at 768–1023px\"; the widest device has no upper bound\n * and the narrowest no lower one.\n */\nexport function hideOnWrites({ from, to }: DeviceRange): string {\n  const hidden = declarationsText([{ property: \"display\", value: \"none\" }]);\n  if (from !== undefined && to !== undefined) {\n    return `${hidden} at ${String(from)}–${String(to)}px`;\n  }\n  if (from !== undefined) return `${hidden} at ${String(from)}px and wider`;\n  if (to !== undefined) return `${hidden} at ${String(to)}px and narrower`;\n  return hidden;\n}\n\n/** What an HTML tag menu writes for a tag: the element, `<section>`. */\nexport function tagWrites(tag: string): string {\n  return `<${tag}>`;\n}\n\n/**\n * What a plain layout choice writes, from the writes it plans, so the hint\n * can't disagree with the write. A cleared value writes nothing; a choice\n * that only clears says the block flow it leaves.\n */\nexport function layoutWritesText(writes: readonly LayoutWrite[]): string {\n  const declarations = writes\n    .filter(write => write.value !== null)\n    .map(write => ({\n      property: LAYOUT_CSS_NAMES[write.property] ?? write.property,\n      value: write.value ?? undefined,\n    }));\n  return declarations.length === 0\n    ? \"display: block\"\n    : declarationsText(declarations);\n}\n","/**\n * Committing a single-line field with Enter, without submitting what contains it.\n *\n * One policy rather than a copy per field. Every builder panel that edits a\n * value in place mounts inside the entry form, where an unprevented Enter\n * submits it — saving or publishing the entry when the author only meant to\n * finish typing. Two fields deciding that separately is two chances to omit the\n * `preventDefault`, and the omission is invisible until the form is what moves.\n *\n * @module commit-on-enter\n */\nimport type * as React from \"react\";\n\n/**\n * Whether this key event was the commit, having performed it. An Enter an\n * input method is composing with is not one.\n *\n * Returns a boolean rather than swallowing the event, because callers have\n * their own keys to handle afterwards — a stepper reads the arrows, a rename\n * reads Escape — and a handler that could not tell whether the commit ran would\n * have to re-test the key it was just given.\n */\nexport function commitOnEnter(\n  event: React.KeyboardEvent,\n  commit: () => void\n): boolean {\n  if (event.key !== \"Enter\") return false;\n  // The Enter that confirms an input method's candidate belongs to the IME:\n  // committing on it would write the characters still being composed. Safari\n  // reports that keydown by keyCode 229 rather than `isComposing`.\n  const native = event.nativeEvent;\n  if (native.isComposing || native.keyCode === 229) return false;\n  event.preventDefault();\n  commit();\n  return true;\n}\n","\"use client\";\n\n/**\n * What a panel control writes, where an author can find it: in a tooltip on\n * hover or keyboard focus, for everyone, and printed small under the label\n * while \"Show CSS names\" is on.\n *\n * The tooltip is the builder's own (`ChromeTooltip`): it opens after a short\n * hover or at once on keyboard focus, stays while the pointer is over it,\n * closes on Escape without that Escape reaching the editor, and is a layer,\n * so nothing in the panel moves while it shows.\n *\n * @module css-hint\n */\nimport { TooltipProvider } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { isElement } from \"../canvas/dom-kind\";\nimport { ChromeTooltip } from \"../chrome-tooltip\";\n\nimport { useCssNames } from \"./css-names-context\";\n\n/**\n * What each option of the field around it writes, as the engine compiles it,\n * for an option's own tooltip; `undefined` outside a field.\n */\nexport const OptionWrites: React.Context<\n  ((option: string) => string) | undefined\n> = React.createContext<((option: string) => string) | undefined>(undefined);\n\n/** A control's tooltip: what it does in words, then what it writes. */\nfunction HintContent({\n  summary,\n  writes,\n}: {\n  summary: string | undefined;\n  writes: string | undefined;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-css-hint\">\n      {summary === undefined ? null : (\n        <span className=\"nx-css-hint__summary\">{summary}</span>\n      )}\n      {writes === undefined ? null : (\n        <code className=\"nx-css-hint__code\">{writes}</code>\n      )}\n    </span>\n  );\n}\n\n/**\n * A control with its \"what it writes\" tooltip. Draws the control alone where\n * there is nothing to say.\n */\nexport function CssHint({\n  writes,\n  summary,\n  children,\n}: {\n  writes: string | undefined;\n  /** What the control does, in words, said above the code. */\n  summary?: string | undefined;\n  /** The control: one element, which becomes the tooltip's trigger. */\n  children: React.ReactElement<TriggerHandlers>;\n}): React.JSX.Element {\n  if (writes === undefined && summary === undefined) return children;\n  return (\n    // Its own provider, so a control drawn outside the panel still has one; a\n    // provider above keeps the shell's shared delay.\n    <TooltipProvider delayDuration={300}>\n      <ChromeTooltip\n        content={<HintContent summary={summary} writes={writes} />}\n        side=\"left\"\n        align=\"start\"\n      >\n        {React.cloneElement(children, {\n          ...ownElementsOnly(children.props),\n          // Noted in the control's own document, which is an iframe's where\n          // the editor is drawn in one.\n          ref: withNavigationNoted(children.props.ref),\n        })}\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/** The handlers the trigger's own element passes on, composed below. */\ninterface TriggerHandlers {\n  onFocus?: (event: React.FocusEvent<HTMLElement>) => void;\n  onPointerMove?: (event: React.PointerEvent<HTMLElement>) => void;\n  ref?: React.Ref<HTMLElement> | undefined;\n}\n\n/**\n * The control's own ref, with its document noted as it mounts: whether the\n * last key pressed there moved between controls is read in that document.\n */\n/** @internal Exported for its tests. */\nexport function withNavigationNoted(\n  own: React.Ref<HTMLElement> | undefined\n): React.RefCallback<HTMLElement> {\n  return node => {\n    if (node !== null) noteNavigation(node.ownerDocument);\n    if (typeof own === \"function\") own(node);\n    else if (own !== null && own !== undefined) {\n      own.current = node;\n    }\n  };\n}\n\n/** The keys that move focus from one control to the next. */\nconst NAVIGATION_KEYS: ReadonlySet<string> = new Set([\n  \"Tab\",\n  \"ArrowUp\",\n  \"ArrowDown\",\n  \"ArrowLeft\",\n  \"ArrowRight\",\n  \"Home\",\n  \"End\",\n]);\n\n/** The documents a key listener is on, so each gets one. */\nconst LISTENING: WeakSet<Document> = new WeakSet();\n\n/** Whether the last key pressed in a document moved focus between controls. */\nconst NAVIGATED: WeakMap<Document, boolean> = new WeakMap();\n\n/** Start noting, for a document, whether its last key press navigated. */\nfunction noteNavigation(at: Document): void {\n  if (LISTENING.has(at)) return;\n  LISTENING.add(at);\n  const note = (event: Event) =>\n    NAVIGATED.set(at, NAVIGATION_KEYS.has((event as KeyboardEvent).key));\n  at.addEventListener(\"keydown\", note, true);\n  // A press of the pointer is not navigation, whatever key came before it.\n  const pressed = () => NAVIGATED.set(at, false);\n  at.addEventListener(\"pointerdown\", pressed, true);\n  at.addEventListener(\"mousedown\", pressed, true);\n}\n\n/**\n * Whether focus arrived by the author moving from control to control with the\n * keyboard. Focus handed back after a menu or picker closes, by pointer or by\n * Escape, opens no tooltip, so the Escape that follows still reaches the\n * editor.\n */\n/** @internal Exported for its tests. */\nexport function keyboardFocus(target: EventTarget): boolean {\n  if (!isElement(target)) return false;\n  const at = target.ownerDocument;\n  const navigated = NAVIGATED.get(at) === true;\n  // Spent on the one focus it moved: a later focus is judged by a later key.\n  NAVIGATED.set(at, false);\n  return navigated;\n}\n\n/**\n * The trigger's focus and hover, answered only for what is inside its own\n * element on the page. A menu or picker it opens is portalled elsewhere in the\n * page but stays inside it in React's tree, where its events bubble through:\n * answered there, the field's tooltip opened over the picker and took the\n * Escape that should close it. Marked handled, the tooltip leaves them.\n */\nfunction ownElementsOnly(props: TriggerHandlers): TriggerHandlers {\n  const outside = (event: React.SyntheticEvent<HTMLElement>) =>\n    !isElement(event.target) || !event.currentTarget.contains(event.target);\n  return {\n    onFocus: event => {\n      props.onFocus?.(event);\n      if (outside(event) || !keyboardFocus(event.target))\n        event.preventDefault();\n    },\n    onPointerMove: event => {\n      props.onPointerMove?.(event);\n      if (outside(event)) event.preventDefault();\n    },\n  };\n}\n\n/**\n * The CSS names a control writes, printed small under its label while \"Show\n * CSS names\" is on, and nothing while it is off. Its `id` joins the control's\n * description, so a screen reader says the names only while they are shown.\n */\nexport function CssNamesLine({\n  id,\n  names,\n}: {\n  id: string;\n  names: readonly string[];\n}): React.JSX.Element | null {\n  const { shown } = useCssNames();\n  if (!shown || names.length === 0) return null;\n  return (\n    <span id={id} className=\"nx-css-names\">\n      {names.join(\", \")}\n    </span>\n  );\n}\n\n/**\n * The id of the CSS names line of the field a control is drawn in, while the\n * names are shown; `undefined` otherwise. Lent by the field, so its controls\n * add it to their description without it ever reading as a refusal.\n */\nexport const FieldNamesId: React.Context<string | undefined> =\n  React.createContext<string | undefined>(undefined);\n\n/**\n * A control's description: its refusal, if any, and its field's CSS names\n * while they are shown. The refusal alone still decides whether the control\n * is invalid, so showing the names never marks a valid field invalid.\n */\nexport function useFieldDescription(\n  describedBy: string | undefined\n): string | undefined {\n  const namesId = React.useContext(FieldNamesId);\n  const { shown } = useCssNames();\n  if (!shown || namesId === undefined) return describedBy;\n  return describedBy === undefined ? namesId : `${describedBy} ${namesId}`;\n}\n","\"use client\";\n\n/**\n * The Entry content block's Content tab: which of the template's collection's\n * top-level blocks fields it draws, and the way to the entry those blocks are\n * edited on.\n *\n * - **Field** is a menu of the collection's top-level blocks fields. A choice\n *   the collection no longer has stays chosen, read \"Body (removed)\" and\n *   marked invalid, so the author sees what the block still names and picks\n *   another; nothing is changed for them.\n * - A line says the content is the entry's own, edited on the entry, in the\n *   collection's words (\"This is the post’s own content, edited on the\n *   post.\").\n * - **Open post** opens the previewed entry's edit screen in a new tab, so\n *   the template stays open with its history. Disabled while no entry is\n *   previewed.\n *\n * The fields and the entry come from the template's editor\n * (`usePreviewedCollection`, `usePreviewedEntry`); outside a template there\n * is no collection, and the menu offers the stored choice alone.\n *\n * @experimental Settles when collection templates ship.\n * @module entry-field-control\n */\nimport {\n  Button,\n  Label,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { ExternalLink } from \"lucide-react\";\nimport type * as React from \"react\";\n\nimport {\n  entryFieldRemoved,\n  fieldName,\n  usePreviewedCollection,\n  usePreviewedEntry,\n  type PreviewedBlocksField,\n  type PreviewedCollection,\n} from \"../../canvas/previewed-entry\";\nimport { propLabel } from \"../inspector\";\n\nimport type { ContentControlProps } from \"./content-controls\";\n\n/** A stored field name, or `undefined` where the block names none as text. */\nfunction storedField(value: unknown): string | undefined {\n  return typeof value === \"string\" && value.trim() !== \"\"\n    ? value.trim()\n    : undefined;\n}\n\n/** Open an entry's edit screen in a new tab, holding no handle on this one. */\nfunction openInNewTab(href: string): void {\n  window.open(href, \"_blank\", \"noopener\");\n}\n\n/** The Field menu, the line about whose content it is, and Open entry. */\n/**\n * The words a chosen field is read by: its label where the collection has\n * it, else its name as the canvas and Layers name it, marked \"(removed)\"\n * where the collection no longer has it. Nothing while none is chosen.\n */\nfunction chosenWords(\n  field: string | undefined,\n  offered: readonly PreviewedBlocksField[],\n  removed: boolean,\n  collection: PreviewedCollection | undefined\n): string | undefined {\n  if (field === undefined) return undefined;\n  const listed = offered.find(each => each.name === field);\n  if (listed !== undefined) return listed.label;\n  const words = fieldName(field, collection);\n  return removed ? `${words} (removed)` : words;\n}\n\nexport function EntryFieldControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  label,\n}: ContentControlProps): React.JSX.Element {\n  const collection = usePreviewedCollection();\n  const previewed = usePreviewedEntry();\n  const name = label ?? propLabel(prop.name, prop.schema);\n  const field = storedField(prop.value);\n  const removed = entryFieldRemoved(field, collection);\n  const offered = collection?.blocksFields ?? [];\n  // The stored choice is always listed, so the menu can say what it is even\n  // where the collection no longer has it or its fields are not known.\n  const listsStored =\n    field !== undefined && !offered.some(each => each.name === field);\n  const singular = collection?.singular ?? \"entry\";\n  // What the trigger shows, in full: its title, where a long name (\"Members\n  // Only (removed)\") is cut to one line with an ellipsis.\n  const chosen = chosenWords(field, offered, removed, collection);\n  const entryId = previewed?.kind === \"entry\" ? previewed.id : undefined;\n  return (\n    <div className=\"nx-inspector__field\" data-content-control=\"entryField\">\n      <Label htmlFor={id}>{name}</Label>\n      <Select\n        disabled={disabled}\n        value={field}\n        onValueChange={next => onCommit(prop.name, next)}\n      >\n        <SelectTrigger\n          id={id}\n          aria-invalid={removed ? true : undefined}\n          title={chosen}\n        >\n          <SelectValue placeholder=\"Choose a field\" />\n        </SelectTrigger>\n        <SelectContent>\n          {offered.map(each => (\n            <SelectItem key={each.name} value={each.name}>\n              {each.label}\n            </SelectItem>\n          ))}\n          {field !== undefined && listsStored ? (\n            <SelectItem value={field}>\n              {/* Named as the canvas and Layers name it. */}\n              {chosen}\n            </SelectItem>\n          ) : null}\n        </SelectContent>\n      </Select>\n      <div className=\"nx-inspector__entry-content\">\n        <p className=\"nx-inspector__note\">\n          This is the {singular}’s own content, edited on the {singular}.\n        </p>\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          // Said as well as shown: it leaves this tab for another.\n          aria-label={`Open ${singular} in a new tab`}\n          disabled={entryId === undefined || collection === undefined}\n          onClick={() => {\n            if (entryId !== undefined && collection !== undefined) {\n              openInNewTab(collection.entryHref(entryId));\n            }\n          }}\n        >\n          <ExternalLink aria-hidden=\"true\" className=\"size-3.5\" />\n          Open {singular}\n        </Button>\n      </div>\n    </div>\n  );\n}\n","/**\n * The Lucide set as the Icon control's source.\n *\n * Reached only through the dynamic `import()` below, so the set (its SVG\n * bodies and search words) is a chunk of its own, fetched the first time an\n * Icon control draws an icon or opens its picker, and never part of the\n * editor's own bundle. The set's source object comes from the set itself\n * (`lucideIconSource`), the one the admin's icon field reads too.\n *\n * @module lucide-icon-source\n */\nimport type { IconSource } from \"@nextlyhq/ui\";\n\n/**\n * Loads the set. A module-level function, so every Icon control hands the\n * picker the same loader and the set is loaded once per editor.\n */\nexport async function loadLucideIcons(): Promise<IconSource> {\n  return (await import(\"@nextlyhq/blocks-react/icons/lucide\")).lucideIconSource;\n}\n","\"use client\";\n\n/**\n * The media control: the chosen file and its summary, and choosing another\n * from the host's media library.\n *\n * @module media-controls\n */\n\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { propLabel } from \"../inspector\";\n\nimport type {\n  ContentControlProps,\n  ContentServices,\n  MediaPickerProps,\n  MediaSummary,\n  PickedMedia,\n} from \"./content-services\";\n\n/**\n * A media item, chosen from the host's library. Only the id is stored: the\n * page resolves it to the file's current address when it draws, so a file\n * moved or renamed in the library stays right on the page.\n */\nexport function MediaControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  services,\n}: ContentControlProps): React.JSX.Element {\n  return (\n    <MediaField\n      id={id}\n      label={propLabel(prop.name, prop.schema)}\n      stored={\n        typeof prop.value === \"string\" && prop.value !== \"\" ? prop.value : null\n      }\n      accept={\n        typeof prop.schema.accept === \"string\" ? prop.schema.accept : undefined\n      }\n      disabled={disabled}\n      services={services}\n      onChange={next => onCommit(prop.name, next)}\n    />\n  );\n}\n\n/**\n * A media field: the chosen file, the button that opens the host's picker,\n * and Remove. Shared by the media control and an image's source, which\n * writes the same id alongside the props it keeps in step.\n */\nexport function MediaField({\n  id,\n  label,\n  stored,\n  accept,\n  disabled,\n  services,\n  showAlt = true,\n  onChange,\n}: {\n  id: string;\n  label: string;\n  /** The stored id, or `null` for none. */\n  stored: string | null;\n  accept: string | undefined;\n  disabled: boolean;\n  services: ContentServices | undefined;\n  /** Whether to show the library's alt text under the file's name. */\n  showAlt?: boolean;\n  /** Store an id, or `undefined` to remove it. */\n  onChange: (mediaId: string | undefined) => void;\n}): React.JSX.Element {\n  // What the last pick was called, for this session; a stored id shows as set.\n  const [picked, setPicked] = React.useState<PickedMedia | null>(null);\n  const Picker = services?.MediaPicker;\n  const name = picked?.id === stored ? picked?.filename : undefined;\n  return (\n    <div className=\"nx-inspector__field\" data-content-control=\"media\">\n      <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n        {label}\n      </p>\n      <div\n        className=\"nx-inspector__media\"\n        role=\"group\"\n        aria-labelledby={`${id}-label`}\n      >\n        <ChosenMedia\n          mediaId={stored}\n          read={services?.readMedia}\n          pickedName={name}\n          fallback=\"A file from the media library.\"\n          showAlt={showAlt}\n        />\n        {Picker === undefined ? (\n          <p className=\"nx-inspector__note\">\n            The media library is not available here.\n          </p>\n        ) : (\n          <MediaChoice\n            Picker={Picker}\n            label={label}\n            stored={stored}\n            accept={accept}\n            disabled={disabled}\n            onChoose={first => {\n              setPicked(first);\n              onChange(first.id);\n            }}\n          />\n        )}\n        {stored === null ? null : (\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"ghost\"\n            disabled={disabled}\n            aria-label={`Remove ${label}`}\n            onClick={() => onChange(undefined)}\n          >\n            Remove\n          </Button>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/**\n * A chosen media item as a field shows it: its thumbnail, its name and its\n * alt text, read by its id. Shared with a placement's exposed image, so a\n * stored file reads the same in both. Until it is read, or where it cannot\n * be, the name of the last pick, else a plain sentence that a file is chosen.\n */\nexport function ChosenMedia({\n  mediaId,\n  read,\n  pickedName,\n  fallback,\n  showAlt = true,\n}: {\n  mediaId: string | null;\n  read: ContentServices[\"readMedia\"];\n  pickedName: string | undefined;\n  fallback: string;\n  /** Whether to show its library alt text, where a row of its own does not. */\n  showAlt?: boolean;\n}): React.JSX.Element {\n  const summary = useMediaSummary(read, mediaId);\n  if (mediaId === null) {\n    return <p className=\"nx-inspector__note\">Nothing chosen.</p>;\n  }\n  const name = summary?.name ?? pickedName ?? fallback;\n  return (\n    <div className=\"nx-inspector__media-chosen\">\n      {summary?.thumbnail === undefined ? null : (\n        // Decorative: the name beside it says which file it is.\n        <img\n          className=\"nx-inspector__media-thumb\"\n          src={summary.thumbnail}\n          alt=\"\"\n        />\n      )}\n      <div className=\"nx-inspector__media-text\">\n        <p className=\"nx-inspector__media-name\" title={name}>\n          {name}\n        </p>\n        {summary?.alt === undefined || !showAlt ? null : (\n          // Named as the library's: a page's own Alt text, where the block\n          // has one, wins over it, and this is only the fallback.\n          <p className=\"nx-inspector__note\">Library alt text: {summary.alt}</p>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/**\n * The summary of `mediaId`, read once per id; `undefined` until it is read,\n * and for the id it was read for only, so a summary never shows beside\n * another file's id.\n */\nexport function useMediaSummary(\n  read: ContentServices[\"readMedia\"],\n  mediaId: string | null\n): MediaSummary | null | undefined {\n  const [found, setFound] = React.useState<{\n    id: string;\n    summary: MediaSummary | null;\n  }>();\n  React.useEffect(() => {\n    if (read === undefined || mediaId === null) return;\n    let live = true;\n    const settle = (summary: MediaSummary | null) => {\n      if (live) setFound({ id: mediaId, summary });\n    };\n    read(mediaId).then(settle, () => settle(null));\n    return () => {\n      live = false;\n    };\n  }, [read, mediaId]);\n  return found?.id === mediaId ? found.summary : undefined;\n}\n\n/**\n * The button that opens the host's media picker, and the picker while open.\n * Shared with a component placement's exposed image, so both choose a file\n * the same way.\n */\nexport function MediaChoice({\n  id,\n  Picker,\n  label,\n  stored,\n  selected = stored,\n  accept,\n  disabled,\n  onChoose,\n}: {\n  /** The button's id, for a field label that names it. */\n  id?: string;\n  Picker: React.ComponentType<MediaPickerProps>;\n  label: string;\n  stored: string | null;\n  /**\n   * The media id the library opens with selected: what `stored` names, unless\n   * a field stores something other than an id (a background's address).\n   */\n  selected?: string | null;\n  accept: string | undefined;\n  disabled: boolean;\n  onChoose: (media: PickedMedia) => void;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  return (\n    <>\n      <Button\n        {...(id === undefined ? {} : { id })}\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        disabled={disabled}\n        aria-label={`Choose ${label}`}\n        onClick={() => setOpen(true)}\n      >\n        {stored === null ? \"Choose\" : \"Replace\"}\n      </Button>\n      {/*\n        Mounted only while open, so each opening starts from what the prop\n        stores now rather than from the picker's last choice, which could\n        belong to another block and be restored by a confirm.\n      */}\n      {open ? (\n        <Picker\n          open\n          onOpenChange={setOpen}\n          title={`Choose ${label.toLowerCase()}`}\n          {...(accept === undefined ? {} : { accept })}\n          initialSelectedIds={new Set(selected === null ? [] : [selected])}\n          onSelect={media => {\n            const first = media[0];\n            // Closed here: the picker leaves closing to whoever opened it,\n            // and left open it would sit over a choice already made.\n            setOpen(false);\n            if (first !== undefined) onChoose(first);\n          }}\n        />\n      ) : null}\n    </>\n  );\n}\n","/**\n * The icons an author chose last, newest first, for the Icon control's\n * \"Recent\" row. Kept by the host's store (one per signed-in author), read\n * and written here, so the picker itself remembers nothing.\n *\n * @module recent-icons\n */\nimport * as React from \"react\";\n\nimport type { PreferenceStore } from \"../../shell-state\";\n\n/** How many icons are remembered: the picker's one Recent row. */\nconst REMEMBERED = 8;\n\n/** The stored text as it is read, or `null` for none or a store that refuses. */\nfunction storedText(store: PreferenceStore | undefined): string | null {\n  if (store === undefined) return null;\n  try {\n    return store.read();\n  } catch {\n    return null;\n  }\n}\n\n/** The ids a stored text holds, newest first; empty for none or anything else. */\nfunction idsIn(raw: string | null): readonly string[] {\n  if (raw === null) return [];\n  try {\n    const parsed: unknown = JSON.parse(raw);\n    return Array.isArray(parsed)\n      ? parsed\n          .filter((id): id is string => typeof id === \"string\")\n          .slice(0, REMEMBERED)\n      : [];\n  } catch {\n    return [];\n  }\n}\n\n/** The remembered ids, newest first; empty when there are none or they are unreadable. */\nexport function readRecentIcons(\n  store: PreferenceStore | undefined\n): readonly string[] {\n  return idsIn(storedText(store));\n}\n\n/**\n * Remembers `id` as the newest, an earlier mention of it removed, and answers\n * the list now kept. A store that refuses the write (private browsing, a full\n * quota) still answers the list, so this session's Recent row is right.\n */\nexport function rememberIcon(\n  store: PreferenceStore | undefined,\n  list: readonly string[],\n  id: string\n): readonly string[] {\n  const next = [id, ...list.filter(other => other !== id)].slice(0, REMEMBERED);\n  try {\n    store?.write(JSON.stringify(next));\n  } catch {\n    // Nothing to do: the row is remembered for this session only.\n  }\n  return next;\n}\n\n/*\n * Who is drawing each store's list, so a choice made in one Icon control\n * reaches every other one on screen at once: one list, read from the store,\n * rather than one copy per control.\n */\nconst watchers = new WeakMap<PreferenceStore, Set<() => void>>();\n\n/*\n * The list each store holds for this session, as last remembered: what the\n * controls draw. Kept beside the store rather than read back from it, so a\n * store that refuses the write (private browsing, a full quota) still shows\n * the choice under Recent for the rest of the session, in every control.\n */\nconst sessionLists = new WeakMap<PreferenceStore, string>();\n\nfunction watch(store: PreferenceStore, onChange: () => void): () => void {\n  const set = watchers.get(store) ?? new Set<() => void>();\n  watchers.set(store, set);\n  set.add(onChange);\n  return () => {\n    set.delete(onChange);\n  };\n}\n\n/**\n * The author's recent icons from the host's store, and a way to remember a\n * choice. Every control drawing the same store reads the same list: a\n * choice in one is remembered in the store and redraws them all.\n */\nexport function useRecentIcons(\n  store: PreferenceStore | undefined\n): readonly [readonly string[], (id: string) => void] {\n  // The stored text is the snapshot: a string compares by value, so React\n  // redraws only when the list changed.\n  const raw = React.useSyncExternalStore(\n    React.useCallback(\n      (onChange: () => void) =>\n        store === undefined ? () => undefined : watch(store, onChange),\n      [store]\n    ),\n    () =>\n      store === undefined\n        ? null\n        : (sessionLists.get(store) ?? storedText(store)),\n    () => null\n  );\n  const list = React.useMemo(() => idsIn(raw), [raw]);\n  const remember = React.useCallback(\n    (id: string) => {\n      if (store === undefined) return;\n      const current = sessionLists.get(store) ?? storedText(store);\n      const next = rememberIcon(store, idsIn(current), id);\n      sessionLists.set(store, JSON.stringify(next));\n      for (const onChange of watchers.get(store) ?? []) onChange();\n    },\n    [store]\n  );\n  return [list, remember] as const;\n}\n","\"use client\";\n\n/**\n * The Content tab's control for a prop that points at one entry of a\n * collection: `{ type: \"relation\", relationTo: \"<collection>\" }`.\n *\n * Only the entry's id is stored, as a media prop stores only the file's: the\n * page resolves it when it draws, so an entry renamed in its collection stays\n * right on the page. The title shown here is read back through the host's\n * `findEntries`, which reads with the signed-in author's own access, so the\n * control never shows an entry the author could not open in the admin.\n *\n * Searching is a field and a list of matches, each a button that chooses it.\n * The list is read when the field is first focused and again as the author\n * types, a short pause after the last key, and a newer read cancels the one in\n * flight so a slow answer cannot replace a later one.\n *\n * @module relation-control\n */\n\nimport { Button, Input } from \"@nextlyhq/ui\";\nimport { Check } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { propLabel } from \"../inspector\";\n\nimport type { ContentControlProps, FoundEntry } from \"./content-controls\";\n\n/** How long typing pauses before the matches are read again. */\nconst SEARCH_PAUSE_MS = 200;\n\n/** How many matches one read asks for. */\nconst MATCHES_SHOWN = 10;\n\ntype FindEntries = NonNullable<\n  NonNullable<ContentControlProps[\"services\"]>[\"findEntries\"]\n>;\n\n/** The matches for what is typed, while the field has been focused. */\ntype Matches =\n  | { readonly kind: \"idle\" }\n  | { readonly kind: \"loading\" }\n  | { readonly kind: \"found\"; readonly entries: readonly FoundEntry[] }\n  | { readonly kind: \"failed\" };\n\n/**\n * Read the matches for `search` in `collection`, once `active`, a pause after\n * the last change, cancelling a read a newer one replaces.\n */\nfunction useMatches(\n  find: FindEntries | undefined,\n  collection: string | undefined,\n  search: string,\n  active: boolean\n): Matches {\n  const [matches, setMatches] = React.useState<Matches>({ kind: \"idle\" });\n  React.useEffect(() => {\n    if (!active || find === undefined || collection === undefined) return;\n    const controller = new AbortController();\n    setMatches({ kind: \"loading\" });\n    const timer = setTimeout(() => {\n      find({\n        collection,\n        search: search.trim(),\n        limit: MATCHES_SHOWN,\n        signal: controller.signal,\n      }).then(\n        entries => {\n          if (!controller.signal.aborted) {\n            setMatches({ kind: \"found\", entries });\n          }\n        },\n        () => {\n          if (!controller.signal.aborted) setMatches({ kind: \"failed\" });\n        }\n      );\n    }, SEARCH_PAUSE_MS);\n    return () => {\n      clearTimeout(timer);\n      controller.abort();\n    };\n  }, [find, collection, search, active]);\n  return matches;\n}\n\n/**\n * The stored entry's title, read once per id. `undefined` while it is read\n * or when nothing is stored; `null` when the author can't read the entry or\n * it is gone, which the control says rather than showing a bare id.\n */\nfunction useChosenTitle(\n  find: FindEntries | undefined,\n  collection: string | undefined,\n  stored: string | null,\n  known: FoundEntry | null\n): string | null | undefined {\n  const [title, setTitle] = React.useState<{\n    id: string;\n    title: string | null;\n  } | null>(null);\n  const knownTitle = known?.id === stored ? known?.title : undefined;\n  React.useEffect(() => {\n    if (stored === null || knownTitle !== undefined) return;\n    if (find === undefined || collection === undefined) return;\n    const controller = new AbortController();\n    // A failed read names nothing: the entry is said to be unreadable rather\n    // than the read's error being shown where a title belongs.\n    const titleOf = async (): Promise<string | null> => {\n      try {\n        const entries = await find({\n          collection,\n          ids: [stored],\n          limit: 1,\n          signal: controller.signal,\n        });\n        return entries.find(entry => entry.id === stored)?.title ?? null;\n      } catch {\n        return null;\n      }\n    };\n    void titleOf().then(found => {\n      if (!controller.signal.aborted) setTitle({ id: stored, title: found });\n    });\n    return () => controller.abort();\n  }, [find, collection, stored, knownTitle]);\n  if (stored === null) return undefined;\n  if (knownTitle !== undefined) return knownTitle;\n  return title?.id === stored ? title.title : undefined;\n}\n\n/** What the control says about the stored entry. */\nfunction chosenWords(\n  stored: string | null,\n  title: string | null | undefined,\n  emptyWords: string | undefined\n): string {\n  // What an empty choice means where the caller says so (\"Any venue\"), and\n  // otherwise that nothing is chosen.\n  if (stored === null) return emptyWords ?? \"Nothing chosen.\";\n  if (title === undefined) return \"Loading the chosen entry…\";\n  if (title === null)\n    return \"An entry you can't open here, or one that was removed.\";\n  return title;\n}\n\n/** Why no entry can be chosen here, or nothing when one can. */\nfunction unavailableWords(\n  collection: string | undefined,\n  find: FindEntries | undefined\n): string | undefined {\n  if (collection === undefined) {\n    return \"This field names no collection to choose from.\";\n  }\n  return find === undefined ? \"Entries can't be searched here.\" : undefined;\n}\n\nexport function RelationControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  services,\n  label: labelOverride,\n  emptyWords,\n}: ContentControlProps & {\n  /** What the control says while nothing is chosen, where that means something. */\n  readonly emptyWords?: string | undefined;\n}): React.JSX.Element {\n  const label = labelOverride ?? propLabel(prop.name, prop.schema);\n  const collection =\n    typeof prop.schema.relationTo === \"string\" && prop.schema.relationTo !== \"\"\n      ? prop.schema.relationTo\n      : undefined;\n  const stored =\n    typeof prop.value === \"string\" && prop.value !== \"\" ? prop.value : null;\n  const find = services?.findEntries;\n  const [search, setSearch] = React.useState(\"\");\n  const [active, setActive] = React.useState(false);\n  // The last entry chosen here, so its title shows at once rather than after\n  // a read of what was just picked.\n  const [chosen, setChosen] = React.useState<FoundEntry | null>(null);\n  const matches = useMatches(find, collection, search, active && !disabled);\n  const title = useChosenTitle(find, collection, stored, chosen);\n  const unavailable = unavailableWords(collection, find);\n  return (\n    <div\n      className=\"nx-inspector__field nx-inspector__field--stacked\"\n      data-content-control=\"relation\"\n    >\n      <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n        {label}\n      </p>\n      <div\n        className=\"nx-inspector__relation\"\n        role=\"group\"\n        aria-labelledby={`${id}-label`}\n      >\n        <div className=\"nx-inspector__relation-chosen\">\n          <p className=\"nx-inspector__note\" data-relation-chosen=\"\">\n            {chosenWords(stored, title, emptyWords)}\n          </p>\n          {stored === null ? null : (\n            <Button\n              type=\"button\"\n              size=\"sm\"\n              variant=\"ghost\"\n              disabled={disabled}\n              aria-label={`Clear ${label}`}\n              onClick={() => onCommit(prop.name, undefined)}\n            >\n              Clear\n            </Button>\n          )}\n        </div>\n        {unavailable === undefined ? (\n          <>\n            <Input\n              id={id}\n              type=\"search\"\n              value={search}\n              disabled={disabled}\n              aria-label={`Search ${label}`}\n              placeholder=\"Search\"\n              onFocus={() => setActive(true)}\n              onChange={event => setSearch(event.target.value)}\n            />\n            <MatchList\n              matches={matches}\n              stored={stored}\n              disabled={disabled}\n              onChoose={entry => {\n                setChosen(entry);\n                onCommit(prop.name, entry.id);\n              }}\n            />\n          </>\n        ) : (\n          <p className=\"nx-inspector__note\">{unavailable}</p>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/** The matches, each a button choosing it, or what the read came to. */\nfunction MatchList({\n  matches,\n  stored,\n  disabled,\n  onChoose,\n}: {\n  matches: Matches;\n  stored: string | null;\n  disabled: boolean;\n  onChoose: (entry: FoundEntry) => void;\n}): React.JSX.Element | null {\n  if (matches.kind === \"idle\") return null;\n  if (matches.kind === \"loading\") {\n    return (\n      <p className=\"nx-inspector__note\" role=\"status\">\n        Searching…\n      </p>\n    );\n  }\n  if (matches.kind === \"failed\") {\n    return (\n      <p className=\"nx-inspector__note\" role=\"alert\">\n        The entries couldn&apos;t be loaded. Try again in a moment.\n      </p>\n    );\n  }\n  if (matches.entries.length === 0) {\n    return (\n      <p className=\"nx-inspector__note\" role=\"status\">\n        No entries match.\n      </p>\n    );\n  }\n  return (\n    <ul className=\"nx-inspector__relation-matches\">\n      {matches.entries.map(entry => (\n        <li key={entry.id}>\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"ghost\"\n            disabled={disabled}\n            aria-pressed={entry.id === stored}\n            // The whole title on hover, since a long one is cut to the row.\n            title={entry.title}\n            onClick={() => onChoose(entry)}\n          >\n            <span className=\"nx-inspector__relation-title\">{entry.title}</span>\n            {entry.id === stored ? (\n              <Check\n                aria-hidden=\"true\"\n                className=\"nx-inspector__relation-tick\"\n              />\n            ) : null}\n          </Button>\n        </li>\n      ))}\n    </ul>\n  );\n}\n","/**\n * What the format bar's actions say and do, shared by the floating bar over\n * the canvas and the full editor a Rich text opens from the panel, so the\n * two offer the same buttons in the same words and cannot drift apart.\n *\n * Kept apart from the bar itself, which is drawn in the canvas overlay and\n * reads the canvas's own modules: the panel's full editor reads these\n * without them.\n *\n * @module format-actions\n */\n\nimport { isLinkableUrl } from \"@nextlyhq/blocks-engine\";\nimport { List, ListOrdered, Quote } from \"lucide-react\";\nimport type * as React from \"react\";\n\nimport type {\n  FormatBlockAction,\n  FormatSelection,\n  FormatSession,\n} from \"./format-bar-state\";\n\n/** The words the bar and its notice say, in one place. */\nexport const FORMAT_BAR_WORDS = {\n  bar: \"Text formatting\",\n  bold: \"B\",\n  boldName: \"Bold\",\n  italic: \"I\",\n  italicName: \"Italic\",\n  link: \"Link\",\n  h2: \"H2\",\n  h2Name: \"Heading 2\",\n  h3: \"H3\",\n  h3Name: \"Heading 3\",\n  bullet: \"Bullets\",\n  number: \"Numbers\",\n  quote: \"Quote\",\n  turnInto: \"Turn into\",\n  address: \"Link address\",\n  addressHint: \"Paste or type an address\",\n  newTab: \"Open in a new tab\",\n  apply: \"Apply\",\n  removeLink: \"Remove link\",\n  badAddress: \"This address can't be used for a link.\",\n  dropped:\n    \"Text keeps words, bold, italic and links. Use Rich text for headings and lists\",\n  toRichText: \"Turn into Rich text\",\n  dismiss: \"Dismiss\",\n} as const;\n\n/**\n * Link the selected words to `address`, answering whether it was taken: an\n * empty address takes a link off (or does nothing), and one this format\n * cannot express — `javascript:`, `data:` — is refused.\n */\nexport function linkTo(\n  session: Pick<FormatSession, \"link\">,\n  address: string,\n  newTab: boolean,\n  linked: boolean\n): boolean {\n  const url = address.trim();\n  if (url === \"\") {\n    if (linked) session.link(null);\n    return true;\n  }\n  if (!isLinkableUrl(url)) return false;\n  session.link(url, { newTab });\n  return true;\n}\n\n/**\n * What a block button shows and is named: H2 and H3 by their words, the\n * lists and the quote by their marks, each named in words. Shared with the\n * full editor, so its buttons say what the bar's say.\n */\nexport const BLOCK_BUTTON_FACES: Record<\n  FormatBlockAction,\n  { readonly face: React.ReactNode; readonly name: string }\n> = {\n  h2: { face: FORMAT_BAR_WORDS.h2, name: FORMAT_BAR_WORDS.h2Name },\n  h3: { face: FORMAT_BAR_WORDS.h3, name: FORMAT_BAR_WORDS.h3Name },\n  bullet: {\n    face: <List aria-hidden=\"true\" size={14} />,\n    name: FORMAT_BAR_WORDS.bullet,\n  },\n  number: {\n    face: <ListOrdered aria-hidden=\"true\" size={14} />,\n    name: FORMAT_BAR_WORDS.number,\n  },\n  quote: {\n    face: <Quote aria-hidden=\"true\" size={14} />,\n    name: FORMAT_BAR_WORDS.quote,\n  },\n};\n\n/** Whether the caret's block is the one `action` makes, so its button is on. */\nexport function blockIsOn(\n  selection: FormatSelection | null | undefined,\n  action: FormatBlockAction\n): boolean {\n  return selection?.block === action;\n}\n","/**\n * What the floating format bar shows, and what it acts on: the one passage\n * being edited in the shared rich-text editor, while that passage is one the\n * bar serves.\n *\n * ONE store for the admin, because there is one editor: a caret is in one\n * place, so at most one passage has a bar. The surface that opens a passage\n * publishes it here; the bar, drawn over the canvas, reads it. Neither holds\n * the other.\n *\n * Plain state and a subscription, no React, so the rules are asserted without\n * a browser and the bar reads it with `useSyncExternalStore`.\n *\n * @module format-bar-state\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\n\n/**\n * A block the bar makes the one the caret is in: a heading, a list or a\n * quote, and the paragraph pressing one of them again goes back to.\n */\nexport type FormatBlock =\n  | \"paragraph\"\n  | \"h2\"\n  | \"h3\"\n  | \"bullet\"\n  | \"number\"\n  | \"quote\";\n\n/** The bar's block buttons, each making its block. */\nexport type FormatBlockAction = Exclude<FormatBlock, \"paragraph\">;\n\n/** One thing the bar offers. */\nexport type FormatAction =\n  | \"bold\"\n  | \"italic\"\n  | \"link\"\n  | FormatBlockAction\n  | \"turnInto\";\n\n/** Whether an action is one of the bar's block buttons. */\nexport function isBlockAction(\n  action: FormatAction\n): action is FormatBlockAction {\n  return (\n    action === \"h2\" ||\n    action === \"h3\" ||\n    action === \"bullet\" ||\n    action === \"number\" ||\n    action === \"quote\"\n  );\n}\n\n/**\n * What the bar offers a Text: bold, italic, a link, and \"Turn into\".\n *\n * Configured per block rather than drawn as one fixed row, so a passage that\n * holds more (headings, lists) is offered more by the same bar. \"Turn into\"\n * keeps its place in the list and is drawn only once a host can turn a block\n * into another.\n */\nexport const TEXT_FORMAT_ACTIONS: readonly FormatAction[] = [\n  \"bold\",\n  \"italic\",\n  \"link\",\n  \"turnInto\",\n];\n\n/**\n * What the bar offers a whole passage, as a Rich text holds: a Text's marks\n * and link, then H2, H3, bullets, numbers and quote, then \"Turn into\".\n */\nexport const RICH_TEXT_FORMAT_ACTIONS: readonly FormatAction[] = [\n  \"bold\",\n  \"italic\",\n  \"link\",\n  \"h2\",\n  \"h3\",\n  \"bullet\",\n  \"number\",\n  \"quote\",\n  \"turnInto\",\n];\n\n/** What the selection in the passage holds. */\nexport interface FormatSelection {\n  readonly collapsed: boolean;\n  readonly bold: boolean;\n  readonly italic: boolean;\n  readonly link: { readonly url: string; readonly newTab: boolean } | null;\n  /**\n   * The block the caret is in, for a whole passage; `other` for one the bar\n   * has no button for. Absent for a one-paragraph passage, which has one.\n   */\n  readonly block?: FormatBlock | \"other\";\n}\n\n/** The editor's hold on the passage, as the bar uses it. */\nexport interface FormatSession {\n  format(mark: \"bold\" | \"italic\"): void;\n  link(url: string | null, options?: { readonly newTab?: boolean }): void;\n  /**\n   * Make the caret's block `kind`, or a paragraph where it already is one;\n   * offered for a whole passage only.\n   */\n  block?(kind: FormatBlockAction): void;\n  selection(): FormatSelection | undefined;\n  /** Put the caret back in the passage, where it was. */\n  focus(): void;\n}\n\n/** The passage the bar serves. */\nexport interface FormatTarget {\n  /** The element being edited, which the bar is placed against. */\n  readonly element: HTMLElement;\n  readonly session: FormatSession;\n  readonly actions: readonly FormatAction[];\n  /** Finish the edit, as leaving the passage does. */\n  readonly finish: () => void;\n  /** Turn the block into another; absent where the host cannot. */\n  readonly turnInto?: FormatTurnInto;\n}\n\n/**\n * What \"Turn into\" needs from the passage being edited: the block, the page\n * as it would stand with the words typed so far (what the choices are judged\n * on), and a way to finish the edit, answering the page it left, or `null`\n * when the words could not be written. The choices and the turn are the\n * editor's own verbs (`BlockActions.turnIntoIn`).\n */\nexport interface FormatTurnInto {\n  readonly nodeId: string;\n  readonly typedPage: () => BlockDocument;\n  readonly finish: () => BlockDocument | null;\n}\n\n/** Everything the bar draws from. */\nexport interface FormatBarSnapshot {\n  readonly target: FormatTarget | null;\n  readonly selection: FormatSelection | null;\n  /** The address field is open, by the Link button or ⌘K. */\n  readonly linking: boolean;\n  /** The \"Turn into\" choices are open, by the Turn into button. */\n  readonly turning: boolean;\n  /** A change (a paste) lost what the passage cannot hold. */\n  readonly dropped: boolean;\n  /** Raised to ask the bar to take the focus, as Alt+F10 does. */\n  readonly focusRequest: number;\n}\n\nconst EMPTY: FormatBarSnapshot = {\n  target: null,\n  selection: null,\n  linking: false,\n  turning: false,\n  dropped: false,\n  focusRequest: 0,\n};\n\n/** The store's surface. */\nexport interface FormatBarStore {\n  readonly get: () => FormatBarSnapshot;\n  readonly subscribe: (listener: () => void) => () => void;\n  /** Serve a passage, replacing whichever was served. */\n  readonly open: (target: FormatTarget) => void;\n  /** Stop serving this passage; a later one already served is kept. */\n  readonly close: (element: HTMLElement) => void;\n  readonly selected: (selection: FormatSelection) => void;\n  readonly setLinking: (open: boolean) => void;\n  readonly setTurning: (open: boolean) => void;\n  readonly setDropped: (dropped: boolean) => void;\n  readonly requestFocus: () => void;\n  /**\n   * Whether the focus is in the bar on the passage's behalf, so the\n   * passage's blur does not finish the edit: an author moving to a button or\n   * the address field is still editing.\n   */\n  readonly holdsFocus: () => boolean;\n  readonly setHoldsFocus: (held: boolean) => void;\n}\n\n/** A fresh store; the admin's one is {@link formatBar}. */\nexport function createFormatBarStore(): FormatBarStore {\n  let snapshot = EMPTY;\n  let focusHeld = false;\n  const listeners = new Set<() => void>();\n  const set = (next: Partial<FormatBarSnapshot>): void => {\n    snapshot = { ...snapshot, ...next };\n    for (const listener of [...listeners]) listener();\n  };\n  return {\n    get: () => snapshot,\n    subscribe: listener => {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n    open: target => {\n      focusHeld = false;\n      set({ ...EMPTY, target, focusRequest: snapshot.focusRequest });\n    },\n    close: element => {\n      if (snapshot.target?.element !== element) return;\n      focusHeld = false;\n      set({ ...EMPTY, focusRequest: snapshot.focusRequest });\n    },\n    selected: selection => {\n      if (snapshot.target === null) return;\n      set({ selection });\n    },\n    setLinking: linking => {\n      if (snapshot.target === null || snapshot.linking === linking) return;\n      set({ linking });\n    },\n    setTurning: turning => {\n      if (snapshot.target === null || snapshot.turning === turning) return;\n      set({ turning });\n    },\n    setDropped: dropped => {\n      if (snapshot.target === null || snapshot.dropped === dropped) return;\n      set({ dropped });\n    },\n    requestFocus: () => {\n      if (snapshot.target === null) return;\n      set({ focusRequest: snapshot.focusRequest + 1 });\n    },\n    holdsFocus: () => focusHeld,\n    setHoldsFocus: held => {\n      focusHeld = held;\n    },\n  };\n}\n\n/** The admin's one bar, for its one editor. */\nexport const formatBar: FormatBarStore = createFormatBarStore();\n\n/**\n * Whether the bar is shown: words are selected, or the address field or the\n * \"Turn into\" choices are open, or the bar holds the focus.\n */\nexport function formatBarShown(state: FormatBarSnapshot): boolean {\n  if (state.target === null) return false;\n  return state.linking || state.turning || state.selection?.collapsed === false;\n}\n","/**\n * Which kind of in-place editing a prop asks for, asked once.\n *\n * A block opts a value into editing on the canvas with `inline`, and what that\n * MEANS depends on the value: a line of text is handed to a `contenteditable`\n * element and read back as a string, while a passage is handed to a rich-text\n * editor and read back as a tree. The two surfaces cannot serve each other —\n * reading a tree as text yields an empty string, and writing a string where a\n * tree belongs breaks every reader of the format.\n *\n * So the question is not \"is this inline\" but \"inline as WHAT\", and it is asked\n * here rather than answered separately by each surface. Two predicates —\n * `inline && type !== rich` on one side and `inline && type === rich` on the\n * other — agree today and are one edit apart from disagreeing: the day a third\n * kind arrives, whichever surface was not updated silently claims it, and the\n * failure is a value handed to the wrong editor rather than an error.\n *\n * @module inline-prop-kind\n */\n\nimport {\n  isInlineItemsProp,\n  isOneParagraphProp,\n  itemOfPropName,\n  RICH_TEXT_PROP_TYPE,\n  type PropSchema,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * How a value may be edited on the canvas, or `null` when it may not be.\n *\n * `\"plain\"` is the default for anything that opted in without saying otherwise,\n * because that is what every prop type other than rich text is: a scalar an\n * element can hold as its text.\n *\n * `\"line\"` is a value restricted to one paragraph of words with bold, italic,\n * links and line breaks (`oneParagraph`, as `core/text` declares it): edited\n * by the same rich-text editor as a passage, held to that restriction, and\n * still TEXT to everything else — a component exposes it as text, so a\n * placement edits its exposed copy as a line of text.\n */\nexport type InlinePropKind = \"plain\" | \"rich\" | \"line\";\n\n/** Whether a kind is edited by the shared rich-text editor. */\nexport function editedAsRichText(kind: InlinePropKind | null): boolean {\n  return kind === \"rich\" || kind === \"line\";\n}\n\n/**\n * The kind of in-place editing this schema opted into, or `null` for none.\n *\n * Decided from the declared TYPE, never from the value a node happens to hold.\n * A passage the author has not written yet is still a passage, and asking the\n * value would offer an empty one to the plain-text surface — which would read\n * nothing out of it and write an empty string back over it.\n *\n * @param schema - the prop's schema, or nothing for a prop the block never declared\n * @returns the kind, or `null` when the value is not editable on the canvas\n */\nexport function inlinePropKind(\n  schema: PropSchema | undefined\n): InlinePropKind | null {\n  // An array is not a line anyone can type: a list of words offers its items\n  // one by one instead, each under its own address (`inlineSchemaAt`).\n  if (schema?.inline !== true || schema.type === \"array\") return null;\n  if (schema.type === RICH_TEXT_PROP_TYPE) return \"rich\";\n  return isOneParagraphProp(schema) ? \"line\" : \"plain\";\n}\n\n/**\n * What one item of a list of words is to the canvas: a line of plain text.\n * Its own schema, rather than the array's, so every surface that asks what a\n * value is asks it the same way for an item as for any other value.\n */\nconst ITEM_SCHEMA: PropSchema = { type: \"text\", inline: true };\n\n/**\n * The schema a canvas value goes by: the declared prop's own, or, for an item\n * of a list of words (`items.2`), a line of text when its array is declared\n * inline. `undefined` for a name the block does not declare.\n *\n * @param props - the block's declared props\n * @param name - the value's name, as the element carrying it is marked\n */\nexport function inlineSchemaAt(\n  props: Partial<Record<string, PropSchema>> | undefined,\n  name: string\n): PropSchema | undefined {\n  const item = itemOfPropName(name);\n  if (item === null) return props?.[name];\n  return isInlineItemsProp(props?.[item.prop]) ? ITEM_SCHEMA : undefined;\n}\n\n/**\n * The kind of in-place editing a value asks for, by its name: an ordinary\n * prop's or an item's. Derived from {@link inlineSchemaAt} and\n * {@link inlinePropKind}, so an item is routed as the line it is.\n */\nexport function inlinePropKindAt(\n  props: Partial<Record<string, PropSchema>> | undefined,\n  name: string\n): InlinePropKind | null {\n  return inlinePropKind(inlineSchemaAt(props, name));\n}\n","/**\n * Finding a block's values that may be edited in place, and choosing among them.\n *\n * Shared by the plain and rich surfaces because both are asked the same\n * question in the same two ways: a pointer names the value it landed on, and a\n * keyboard names none — it has a selected block and expects the block's first.\n *\n * One statement of \"first\" is the point. Two would agree until one of them\n * started sorting, filtering or preferring differently, and the disagreement\n * would show as a keyboard shortcut opening a different value from the one a\n * double-click opens on the same block.\n *\n * The walk that finds them is here for the same reason. Both surfaces ask the\n * same node the same three questions — is it there, is it locked, is its block\n * registered — and a second copy of that is a second place for a lock to stop\n * being honoured. A lock honoured at one entry point and not another is the\n * state where an author believes a block is protected and it is not.\n *\n * @module inline-target\n */\n\nimport {\n  findNode,\n  getBlock,\n  isInlineItemsProp,\n  itemPropName,\n  type BlockDocument,\n  type BlockNode,\n  type PropSchema,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { lockBlockingEdit } from \"../locking\";\n\nimport {\n  inlinePropKindAt,\n  inlineSchemaAt,\n  type InlinePropKind,\n} from \"./inline-prop-kind\";\n\n/** A node and the values on it a given surface may edit. */\nexport interface InlineProps {\n  readonly node: BlockNode;\n  /** The matching names with their schemas, in the order the block declared them. */\n  readonly entries: readonly (readonly [string, PropSchema | undefined])[];\n}\n\n/**\n * The values on this node that may be edited in place AS ONE KIND, or `null`\n * when the node cannot be edited at all.\n *\n * `null` rather than an empty list for a node that is missing, locked or of an\n * unregistered type, so a caller can tell \"this block offers none of yours\"\n * from \"this block is not editable\" — the first is ordinary and the second is\n * what a lock means.\n *\n * @param document - the document being edited\n * @param nodeId - the node to ask about\n * @param kind - which surface is asking\n * @returns the node and its matching values, or `null`\n */\nexport function inlinePropsOfKind(\n  document: BlockDocument,\n  nodeId: string,\n  kind: InlinePropKind | readonly InlinePropKind[]\n): InlineProps | null {\n  const found = editableNode(document, nodeId);\n  if (found === null) return null;\n  const { props } = found;\n  const kinds: readonly InlinePropKind[] =\n    typeof kind === \"string\" ? [kind] : kind;\n  return {\n    node: found.node,\n    entries: inlineNamesOf(found.node, props)\n      .filter(name => {\n        const own = inlinePropKindAt(props, name);\n        return own !== null && kinds.includes(own);\n      })\n      .map(name => [name, inlineSchemaAt(props, name)] as const),\n  };\n}\n\n/**\n * The names a node's canvas values go by, in the order the block declared its\n * props: each prop's own, and for a list of words each item it holds now\n * (`items.0`, `items.1`), so every item is a line of its own.\n */\nfunction inlineNamesOf(\n  node: BlockNode,\n  props: Partial<Record<string, PropSchema>>\n): string[] {\n  const names: string[] = [];\n  for (const name of Object.keys(props)) {\n    if (!isInlineItemsProp(props[name])) {\n      names.push(name);\n      continue;\n    }\n    const stored = (node.props as Record<string, unknown> | undefined)?.[name];\n    const count = Array.isArray(stored) ? stored.length : 0;\n    for (let index = 0; index < count; index++) {\n      names.push(itemPropName(name, index));\n    }\n  }\n  return names;\n}\n\n/**\n * The node and the prop schemas to ask about it, or `null` when it cannot be\n * edited at all.\n *\n * The three refusals every question here shares — the node is gone, it is\n * locked, its block is not registered — asked once. A lock in particular has to\n * be honoured at every entry point or it is honoured at none, and that is the\n * state where an author believes a block is protected and it is not.\n */\nfunction editableNode(\n  document: BlockDocument,\n  nodeId: string\n): { node: BlockNode; props: Partial<Record<string, PropSchema>> } | null {\n  const node = findNode(document.nodes, nodeId);\n  // Locked itself or inside a locked block: the lock covers its subtree.\n  if (node === undefined || lockBlockingEdit(document, nodeId) !== undefined) {\n    return null;\n  }\n  const definition = getBlock(node.type);\n  if (definition === undefined) return null;\n  return { node, props: definition.props ?? {} };\n}\n\n/** A value editable on the canvas, and which surface edits it. */\nexport interface FirstInlineProp {\n  readonly prop: string;\n  readonly kind: InlinePropKind;\n}\n\n/**\n * The FIRST value on this node editable in place, of whichever kind, or `null`.\n *\n * In the order the block declared its props, and across both kinds together.\n * Asking one surface and then the other instead answers with that surface's\n * first, which is a different value whenever a block declares a passage after a\n * line of text — and the caller that wants this is the keyboard, which has a\n * selected block and no element, so the answer it gets is the only one an\n * author sees.\n *\n * `null` for a node that is missing, locked or of an unregistered type, which\n * is the same refusal {@link inlinePropsOfKind} makes and for the same reason.\n *\n * @param document - the document being edited\n * @param nodeId - the node to ask about\n * @returns the first editable value and its kind, or `null`\n */\nexport function firstInlineProp(\n  document: BlockDocument,\n  nodeId: string\n): FirstInlineProp | null {\n  const found = editableNode(document, nodeId);\n  if (found === null) return null;\n  const { props } = found;\n  for (const prop of inlineNamesOf(found.node, props)) {\n    const kind = inlinePropKindAt(props, prop);\n    if (kind !== null) return { prop, kind };\n  }\n  return null;\n}\n\n/**\n * The value a caller asked for, or the block's first when it named none.\n *\n * `undefined` when the block offers nothing, and when it offers something other\n * than the name asked for — the caller decides what that means, because for one\n * surface it means \"not mine\" and for the other it means \"not editable\".\n *\n * @param targets - the block's editable values, in the order it declared them\n * @param prop - the value's name, or nothing to take the first\n * @returns the chosen value, or `undefined`\n */\nexport function namedTarget<T extends { readonly prop: string }>(\n  targets: readonly T[],\n  prop: string | undefined\n): T | undefined {\n  return prop === undefined ? targets[0] : targets.find(t => t.prop === prop);\n}\n","/**\n * Which of a block's passages an author may edit on the canvas, and the op a\n * finished edit produces.\n *\n * The rich half of {@link module:inline-text}, and pure for the same reason:\n * whether a value is editable in place, and whether a finished edit changed\n * anything, are derivations — and a component test cannot separate a correct\n * answer from a plausible wrong one, because both render a caret.\n *\n * **The block decides, not this module.** A prop is offered here only when its\n * schema declares itself rich AND inline, which is the same pair the renderer\n * reads when it marks the element holding the value. Both halves must agree or\n * the value is simply not editable in place, which is the safe direction.\n *\n * @module inline-rich-text\n */\n\nimport {\n  findNode,\n  isOneParagraphProp,\n  isRichTextValue,\n  toOneParagraph,\n  type BlockDocument,\n  type BlockNode,\n  type PropSchema,\n  type RichTextValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { propPatch } from \"../inspector/inspector\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport { inlinePropsOfKind } from \"./inline-target\";\n\n/** One passage a canvas may let an author edit in place. */\nexport interface InlineRichTextTarget {\n  readonly nodeId: string;\n  readonly prop: string;\n  /**\n   * The passage EXACTLY as the document holds it, before any narrowing.\n   *\n   * Kept beside {@link InlineRichTextTarget.value} because the narrowing loses\n   * the difference between two unusable values: a prop holding the string \"A\"\n   * and one holding the string \"B\" both read as `undefined`, so a comparison\n   * over the narrowed form reports no change between them. A passage opened on\n   * one and committed after another surface stored the other would overwrite it\n   * silently.\n   */\n  readonly stored: unknown;\n  /**\n   * The passage as the document holds it, or `undefined` when it holds nothing\n   * usable.\n   *\n   * Undefined rather than an empty passage, because what an EMPTY passage looks\n   * like is the editor's answer and not this module's: inventing one here would\n   * be a second statement of that shape, and the two would drift.\n   */\n  readonly value: RichTextValue | undefined;\n  /**\n   * Whether the value is restricted to ONE paragraph of words with bold,\n   * italic, links and line breaks (`oneParagraph`): edited with only those,\n   * and written only as that.\n   */\n  readonly oneParagraph?: true;\n}\n\nfunction targetFor(\n  node: BlockNode,\n  prop: string,\n  schema: PropSchema | undefined\n): InlineRichTextTarget {\n  const stored = (node.props as Record<string, unknown> | undefined)?.[prop];\n  if (isOneParagraphProp(schema)) {\n    // Read through the restriction the page is drawn by, so an older string\n    // opens as its words and line breaks, and a value holding more opens as\n    // what the page shows of it.\n    return {\n      nodeId: node.id,\n      prop,\n      stored,\n      value: toOneParagraph(stored).value,\n      oneParagraph: true,\n    };\n  }\n  return {\n    nodeId: node.id,\n    prop,\n    stored,\n    // Narrowed with the engine's own predicate rather than trusted from the\n    // schema: the schema says what an editor OFFERS, and the document holds\n    // whatever a migration, an import or a hand-edited row left there.\n    value: isRichTextValue(stored) ? stored : undefined,\n  };\n}\n\n/**\n * A finished edit of a target as it is written: restricted to one paragraph\n * for a target that is (the save half of the restriction the renderer applies\n * when it reads), and as the editor gave it otherwise.\n */\nfunction writtenValue(\n  target: Pick<InlineRichTextTarget, \"oneParagraph\">,\n  value: unknown\n): unknown {\n  return target.oneParagraph === true ? toOneParagraph(value).value : value;\n}\n\n/**\n * Every passage on this node that may be edited on the canvas, in the order the\n * block declared them.\n *\n * Empty for a LOCKED block, and for a node whose type is not registered. A lock\n * is what an author set to stop the block changing, and editing is a change —\n * honoured at every entry point or it is honoured at none, which is the state\n * where an author believes a block is protected.\n *\n * @param document - the document being edited\n * @param nodeId - the node to ask about\n * @returns the editable passages, empty when there are none\n */\nexport function richInlineTargets(\n  document: BlockDocument,\n  nodeId: string\n): readonly InlineRichTextTarget[] {\n  const found = inlinePropsOfKind(document, nodeId, [\"rich\", \"line\"]);\n  if (found === null) return [];\n  return found.entries.map(([name, schema]) =>\n    targetFor(found.node, name, schema)\n  );\n}\n\n/**\n * One named passage, or `null` when it is not editable on the canvas.\n *\n * Derived from {@link richInlineTargets} rather than repeating its rules, so a\n * block that is locked, unregistered or has not declared the prop answers the\n * same way to both.\n *\n * @param document - the document being edited\n * @param nodeId - the node to ask about\n * @param prop - the passage's name\n * @returns the target, or `null`\n */\nexport function richInlineTarget(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string\n): InlineRichTextTarget | null {\n  return richInlineTargets(document, nodeId).find(t => t.prop === prop) ?? null;\n}\n\n/**\n * Whether a finished edit actually changed the passage.\n *\n * Both sides must come from the SAME producer — the editor's own reading of the\n * passage when it opened, against its reading when it closed. Comparing what\n * the editor produced against what the DOCUMENT stored would report a change\n * for every passage merely opened and closed, because an editor normalises what\n * it loads: it fills in the version, direction and format fields its own\n * serializer always writes, and a value that reached storage from another\n * surface, an import or an older schema will not carry them identically.\n *\n * That difference is invisible to an author and would put an entry on the undo\n * stack that appears to do nothing — which reads as the history being broken\n * rather than as an empty change.\n *\n * Compared as serialized JSON, which is sound only because of that same\n * constraint: one producer emits one key order for one state, so two readings\n * of an untouched passage are identical strings.\n *\n * @param before - what the editor read when it opened the passage\n * @param after - what it read when the edit finished\n * @returns whether anything about the passage differs\n */\nexport function richTextChanged(before: unknown, after: unknown): boolean {\n  return JSON.stringify(before) !== JSON.stringify(after);\n}\n\n/**\n * Whether the document's copy of this passage changed since a session opened\n * it.\n *\n * Asked separately from the write because the two `null`s a commit can produce\n * mean opposite things to an author. \"Nothing to write\" is an edit that changed\n * nothing, and letting go is right. \"The document moved on\" is an edit that\n * cannot be written — and letting go there discards words the author typed,\n * with the surface they were typing into gone before they could copy them.\n *\n * @param document - the document as it stands NOW\n * @param nodeId - the node being edited\n * @param prop - the passage being edited\n * @param opened - the RAW stored value the session was handed\n * @returns whether the stored value is no longer the one that was opened\n */\nexport function richTextMovedOn(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string,\n  opened: unknown\n): boolean {\n  const target = richInlineTarget(document, nodeId, prop);\n  // A passage that stopped being editable is refused by the write for its own\n  // reasons; it has not \"moved on\" in the sense this question asks about.\n  if (target === null) return false;\n  return richTextChanged(opened, target.stored);\n}\n\n/**\n * The op a finished edit produces, or `null` when there is nothing to write.\n *\n * `null` for an unchanged passage, for one the editor did not return as rich\n * text at all, and for a value that stopped being editable while the edit was\n * open — a node can be deleted or locked from the layers panel, from a keyboard\n * action, or by another surface entirely, and writing then would either address\n * a node that is gone or defeat a lock applied after the caret went in.\n *\n * `null` too when the STORED passage changed while the caret was open. Another\n * surface, an undo, or an op applied from anywhere else can rewrite the same\n * prop, and this editor has been holding a copy taken before that happened —\n * writing it back would patch the older passage over the newer one and lose the\n * intervening change with nothing raised. Refusing keeps what is in the\n * document; the author's own edit is the one lost, but it is the one still on\n * their screen.\n *\n * @param document - the document as it stands NOW, not when the edit began\n * @param nodeId - the node being edited\n * @param prop - the passage being edited\n * @param next - what the editor read when the edit finished\n * @param before - what it read when the passage opened\n * @param opened - the RAW stored value the session was handed, before narrowing\n * @returns one op, or `null`\n */\nexport function richInlineTextOp(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string,\n  next: unknown,\n  before: unknown,\n  opened: unknown\n): BuilderOp | null {\n  const target = richInlineTarget(document, nodeId, prop);\n  if (target === null) return null;\n  // Compared RAW against raw: both sides come from the document untouched, so a\n  // difference is a real change rather than one serializer's normalisation\n  // against another's — and two values that merely fail to be passages stay\n  // distinguishable, which the narrowed form cannot manage.\n  if (richTextChanged(opened, target.stored)) return null;\n  // Refused rather than stored. A value the editor could not produce as a\n  // passage is not one, and writing it would put a shape into the document that\n  // every reader of the format would then have to survive.\n  if (!isRichTextValue(next)) return null;\n  // Both readings through the restriction, for a one-paragraph value: the\n  // editor's raw state carries fields its serializer adds, and only the\n  // restricted form is what is stored.\n  const written = writtenValue(target, next);\n  if (!richTextChanged(writtenValue(target, before), written)) return null;\n  const node = findNode(document.nodes, nodeId);\n  if (node === undefined) return null;\n  return { kind: \"update\", id: nodeId, patch: propPatch(node, prop, written) };\n}\n","\"use client\";\n\n/**\n * The full editor for a Rich text: a large editor in a dialog, opened from the\n * panel's \"Open the full editor\", for longer work than the canvas suits.\n *\n * ## The same editor and the same actions as the canvas\n *\n * The passage is attached to the admin's one rich-text editor, the one the\n * canvas and every rich-text field use, and its toolbar offers exactly what\n * the canvas's floating bar offers a Rich text: \"B\", \"I\", \"Link\", \"H2\", \"H3\",\n * bullets, numbers and quote, with the bar's words and faces. Nothing here can\n * make a passage the canvas could not then edit.\n *\n * ## Done keeps, Cancel discards\n *\n * The words reach the page only on Done, as one write and so one undo step.\n * Cancel lets them go. Escape and a click outside cancel too, but only while\n * nothing has changed: with changes, they say how to keep or discard them\n * instead of throwing the work away. Closing, either way, puts the focus back\n * on the button that opened it, beside the block still selected.\n *\n * @module rich-text-full-editor\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  BLOCK_BUTTON_FACES,\n  blockIsOn,\n  FORMAT_BAR_WORDS,\n  linkTo,\n} from \"../../canvas/format-actions\";\nimport {\n  isBlockAction,\n  RICH_TEXT_FORMAT_ACTIONS,\n  type FormatAction,\n  type FormatSelection,\n} from \"../../canvas/format-bar-state\";\nimport { richTextChanged } from \"../../canvas/inline-rich-text\";\nimport { useModalKeyboardHold } from \"../../shell/modal-keyboard-hold\";\nimport { BUILDER_TOKENS_CLASS } from \"../../shell-state\";\n\nimport type { ContentServices } from \"./content-services\";\n\n/** The words the full editor and the panel line say, in one place. */\nexport const FULL_EDITOR_WORDS = {\n  line: \"Edit on the canvas. Select text for bold, links, headings and lists.\",\n  open: \"Open the full editor\",\n  description: \"Bold, italic, links, headings, lists and quotes.\",\n  done: \"Done\",\n  cancel: \"Cancel\",\n  unsaved: \"Press Done to keep your changes, or Cancel to discard them.\",\n  held: \"This passage is being edited on the canvas. Finish there first.\",\n  unsupported: \"This passage can't be edited here.\",\n  refused:\n    \"This change could not be saved, perhaps because the page is at its size limit. Shorten it, or press Cancel to discard it.\",\n} as const;\n\n/**\n * What the full editor offers: the canvas bar's Rich text actions, less\n * \"Turn into\", which changes the block rather than its words.\n */\nconst FULL_EDITOR_ACTIONS: readonly FormatAction[] =\n  RICH_TEXT_FORMAT_ACTIONS.filter(action => action !== \"turnInto\");\n\n/** The shared editor, as the services hand it over. */\ntype LoadedEditor = Awaited<\n  ReturnType<NonNullable<ContentServices[\"loadRichTextEditor\"]>>\n>;\n\n/** One attachment of it to the full editor's page. */\ntype Attached = Extract<\n  ReturnType<LoadedEditor[\"attach\"]>,\n  { status: \"attached\" }\n>[\"session\"];\n\n/** Why the editor could not be used here, or why Done did not close. */\ntype Note = \"held\" | \"unsupported\" | \"refused\" | \"unsaved\" | null;\n\nconst NOTES: Record<Exclude<Note, null>, string> = {\n  held: FULL_EDITOR_WORDS.held,\n  unsupported: FULL_EDITOR_WORDS.unsupported,\n  refused: FULL_EDITOR_WORDS.refused,\n  unsaved: FULL_EDITOR_WORDS.unsaved,\n};\n\nexport interface RichTextFullEditorProps {\n  /** The field's name, the dialog's title. */\n  readonly label: string;\n  /** The passage stored. */\n  readonly value: unknown;\n  /**\n   * Write the passage; `null` when the write was refused, which keeps the\n   * dialog open with the author's words.\n   */\n  readonly onCommit: (value: unknown) => BlockDocument | null | void;\n  readonly services: ContentServices | undefined;\n  /** Closed, by Done or Cancel. */\n  readonly onClose: () => void;\n  /** Where the focus goes back to on closing: the button that opened it. */\n  readonly returnFocus: () => HTMLElement | null;\n}\n\n/** The full editor, open. Its parent mounts it while it is wanted. */\nexport function RichTextFullEditor({\n  label,\n  value,\n  onCommit,\n  services,\n  onClose,\n  returnFocus,\n}: RichTextFullEditorProps): React.JSX.Element {\n  // The page, as state: the dialog draws its content in a portal a render\n  // after it opens, and the editor is attached once the page is there.\n  const [page, setPage] = React.useState<HTMLDivElement | null>(null);\n  const live = React.useRef<{ session: Attached; baseline: unknown } | null>(\n    null\n  );\n  const release = React.useRef<(() => void) | null>(null);\n  const [selection, setSelection] = React.useState<FormatSelection | null>(\n    null\n  );\n  const [ready, setReady] = React.useState<Attached | null>(null);\n  const [note, setNote] = React.useState<Note>(null);\n  // The passage and the services it opened with, read once by the effect\n  // that attaches it: a later stored value does not re-open the editor over\n  // the words being typed.\n  const opened = React.useRef({ value, services });\n  useModalKeyboardHold(\"rich-text-full-editor\", true);\n\n  /** Let the editor go, writing nothing. */\n  const letGo = React.useCallback(() => {\n    release.current?.();\n    release.current = null;\n    const held = live.current;\n    live.current = null;\n    held?.session.detach();\n  }, []);\n\n  /**\n   * Write the words. Answers the document the write produced, `null` when\n   * there was nothing to write, or `false` when the page refused it, which\n   * keeps the dialog open.\n   */\n  const keep = (): BlockDocument | null | false => {\n    const held = live.current;\n    if (held === null) return null;\n    const words = held.session.read();\n    if (!richTextChanged(held.baseline, words)) return null;\n    const written = onCommit(words);\n    if (written === null) {\n      // Refused (a size cap, a lock that arrived): the words stay here, held\n      // against anything else taking the editor, until shortened or let go.\n      held.session.hold();\n      setNote(\"refused\");\n      return false;\n    }\n    return written ?? null;\n  };\n\n  /**\n   * Finish as Done does: write, let the editor go and close, answering the\n   * document written, or `null` for none or for a refusal that keeps it open.\n   */\n  const finish = (): BlockDocument | null => {\n    const written = keep();\n    if (written === false) return null;\n    letGo();\n    onClose();\n    return written;\n  };\n  // Read by the open passages' hold, which outlives this render.\n  const latestFinish = React.useRef(finish);\n  latestFinish.current = finish;\n\n  const done = (): void => {\n    finish();\n  };\n  const cancel = (): void => {\n    letGo();\n    onClose();\n  };\n\n  /** Escape or a click outside: a cancel while nothing has changed. */\n  const dismiss = (event: Event): void => {\n    const held = live.current;\n    if (held !== null && richTextChanged(held.baseline, held.session.read())) {\n      event.preventDefault();\n      setNote(\"unsaved\");\n      return;\n    }\n    cancel();\n  };\n\n  // The passage is handed to the shared editor once the page is drawn, and\n  // taken back however the dialog goes.\n  React.useEffect(() => {\n    const { value: passage, services: host } = opened.current;\n    const load = host?.loadRichTextEditor;\n    const element = page;\n    if (load === undefined || element === null) return;\n    let gone = false;\n    void load().then(\n      editor => {\n        if (gone) return;\n        const attachment = editor.attach(element, passage, {\n          onSelection: setSelection,\n        });\n        if (attachment.status === \"refused\") {\n          setNote(attachment.reason);\n          return;\n        }\n        const session = attachment.session;\n        live.current = { session, baseline: session.read() };\n        // Held while open, so a Save finishes it as Done does, and is handed\n        // the document the write produced to store, as every open passage's\n        // finish hands it.\n        release.current =\n          host?.openPassages?.hold(() => latestFinish.current()) ?? null;\n        setReady(session);\n        session.focus();\n      },\n      () => {\n        if (!gone) setNote(\"unsupported\");\n      }\n    );\n    return () => {\n      gone = true;\n      letGo();\n    };\n  }, [page, letGo]);\n\n  return (\n    <Dialog\n      open\n      onOpenChange={open => {\n        if (!open) cancel();\n      }}\n    >\n      <DialogContent\n        className={`${BUILDER_TOKENS_CLASS} nx-rich-text-editor`}\n        onEscapeKeyDown={dismiss}\n        onInteractOutside={dismiss}\n        onCloseAutoFocus={event => {\n          const target = returnFocus();\n          if (target === null) return;\n          event.preventDefault();\n          target.focus();\n        }}\n      >\n        <DialogHeader>\n          <DialogTitle>{label}</DialogTitle>\n          <DialogDescription>{FULL_EDITOR_WORDS.description}</DialogDescription>\n        </DialogHeader>\n        <FullEditorToolbar session={ready} selection={selection} />\n        <div\n          ref={setPage}\n          className=\"nx-rich-text-editor__page\"\n          role=\"textbox\"\n          aria-multiline=\"true\"\n          aria-label={label}\n          aria-busy={ready === null && note === null}\n        />\n        {note === null ? null : (\n          <p className=\"nx-rich-text-editor__note\" role=\"status\">\n            {NOTES[note]}\n          </p>\n        )}\n        <DialogFooter>\n          <Button type=\"button\" variant=\"outline\" onClick={cancel}>\n            {FULL_EDITOR_WORDS.cancel}\n          </Button>\n          <Button type=\"button\" onClick={done}>\n            {FULL_EDITOR_WORDS.done}\n          </Button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n\n/** A press on the toolbar keeps the focus, and the selection, in the page. */\nfunction keepFocus(event: React.MouseEvent): void {\n  event.preventDefault();\n}\n\n/**\n * Where an arrow, Home or End moves the toolbar's focus from button `at` of\n * `count`, wrapping; `undefined` for any other key.\n */\nfunction movedTo(key: string, at: number, count: number): number | undefined {\n  const moves: Record<string, number> = {\n    ArrowRight: at + 1,\n    ArrowLeft: at - 1,\n    Home: 0,\n    End: count - 1,\n  };\n  const to = moves[key];\n  return to === undefined ? undefined : (to + count) % count;\n}\n\n/**\n * The full editor's toolbar: the canvas bar's Rich text buttons, said on as\n * the bar says them, pressing the same verbs. One tab stop, arrows between.\n */\nfunction FullEditorToolbar({\n  session,\n  selection,\n}: {\n  session: Attached | null;\n  selection: FormatSelection | null;\n}): React.JSX.Element {\n  const [linking, setLinking] = React.useState(false);\n  // The one button Tab reaches; the arrows move it.\n  const [stop, setStop] = React.useState(0);\n  const disabled = session === null;\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {\n    if (linking) return;\n    const to = movedTo(event.key, stop, FULL_EDITOR_ACTIONS.length);\n    if (to === undefined) return;\n    event.preventDefault();\n    setStop(to);\n    event.currentTarget\n      .querySelectorAll<HTMLButtonElement>(\".nx-rich-text-editor__button\")\n      [to]?.focus();\n  };\n  return (\n    <div\n      role=\"toolbar\"\n      aria-orientation=\"horizontal\"\n      aria-label={FORMAT_BAR_WORDS.bar}\n      className=\"nx-rich-text-editor__toolbar\"\n      onKeyDown={onKeyDown}\n    >\n      {FULL_EDITOR_ACTIONS.map((action, index) => (\n        <ToolbarButton\n          key={action}\n          action={action}\n          session={session}\n          selection={selection}\n          disabled={disabled}\n          tabbable={index === stop}\n          onFocus={() => setStop(index)}\n          onLink={() => setLinking(true)}\n        />\n      ))}\n      {linking && session !== null ? (\n        <LinkForm\n          session={session}\n          current={selection?.link ?? null}\n          close={() => {\n            setLinking(false);\n            session.focus();\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/** One of the toolbar's buttons. */\nfunction ToolbarButton({\n  action,\n  session,\n  selection,\n  disabled,\n  tabbable,\n  onFocus,\n  onLink,\n}: {\n  action: FormatAction;\n  session: Attached | null;\n  selection: FormatSelection | null;\n  disabled: boolean;\n  tabbable: boolean;\n  onFocus: () => void;\n  onLink: () => void;\n}): React.JSX.Element | null {\n  const common = {\n    type: \"button\" as const,\n    className: \"nx-rich-text-editor__button\",\n    disabled,\n    tabIndex: tabbable ? 0 : -1,\n    onMouseDown: keepFocus,\n    onFocus,\n    \"data-format-action\": action,\n  };\n  if (action === \"bold\" || action === \"italic\") {\n    const bold = action === \"bold\";\n    return (\n      <button\n        {...common}\n        aria-label={\n          bold ? FORMAT_BAR_WORDS.boldName : FORMAT_BAR_WORDS.italicName\n        }\n        aria-pressed={selection?.[action] === true}\n        aria-keyshortcuts={bold ? \"Meta+B Control+B\" : \"Meta+I Control+I\"}\n        data-mark={action}\n        onClick={() => session?.format?.(action)}\n      >\n        {bold ? FORMAT_BAR_WORDS.bold : FORMAT_BAR_WORDS.italic}\n      </button>\n    );\n  }\n  if (action === \"link\") {\n    return (\n      <button\n        {...common}\n        aria-pressed={selection?.link != null}\n        onClick={onLink}\n      >\n        {FORMAT_BAR_WORDS.link}\n      </button>\n    );\n  }\n  if (!isBlockAction(action)) return null;\n  const { face, name } = BLOCK_BUTTON_FACES[action];\n  return (\n    <button\n      {...common}\n      aria-label={name}\n      aria-pressed={blockIsOn(selection, action)}\n      onClick={() => session?.block?.(action)}\n    >\n      {face}\n    </button>\n  );\n}\n\n/** Where a link goes, for the words selected in the full editor. */\nfunction LinkForm({\n  session,\n  current,\n  close,\n}: {\n  session: Attached;\n  current: FormatSelection[\"link\"];\n  close: () => void;\n}): React.JSX.Element {\n  const [address, setAddress] = React.useState(current?.url ?? \"\");\n  const [newTab, setNewTab] = React.useState(current?.newTab ?? false);\n  const [refused, setRefused] = React.useState(false);\n  const errorId = React.useId();\n  const input = React.useRef<HTMLInputElement>(null);\n  React.useEffect(() => input.current?.focus(), []);\n  const link = {\n    link: (url: string | null, options?: { readonly newTab?: boolean }) =>\n      session.link?.(url, options),\n  };\n  return (\n    <form\n      className=\"nx-rich-text-editor__link\"\n      onSubmit={event => {\n        event.preventDefault();\n        if (linkTo(link, address, newTab, current !== null)) close();\n        else setRefused(true);\n      }}\n      onKeyDown={event => {\n        if (event.key !== \"Escape\") return;\n        // Escape leaves the address, not the dialog.\n        event.preventDefault();\n        event.stopPropagation();\n        close();\n      }}\n    >\n      <input\n        ref={input}\n        type=\"text\"\n        inputMode=\"url\"\n        className=\"nx-rich-text-editor__address\"\n        aria-label={FORMAT_BAR_WORDS.address}\n        placeholder={FORMAT_BAR_WORDS.addressHint}\n        value={address}\n        aria-invalid={refused}\n        {...(refused ? { \"aria-describedby\": errorId } : {})}\n        onChange={event => {\n          setAddress(event.target.value);\n          setRefused(false);\n        }}\n      />\n      <label className=\"nx-rich-text-editor__new-tab\">\n        <input\n          type=\"checkbox\"\n          checked={newTab}\n          onChange={event => setNewTab(event.target.checked)}\n        />\n        {FORMAT_BAR_WORDS.newTab}\n      </label>\n      <Button type=\"submit\" size=\"sm\" variant=\"outline\">\n        {FORMAT_BAR_WORDS.apply}\n      </Button>\n      {current === null ? null : (\n        <Button\n          type=\"button\"\n          size=\"sm\"\n          variant=\"ghost\"\n          onClick={() => {\n            session.link?.(null);\n            close();\n          }}\n        >\n          {FORMAT_BAR_WORDS.removeLink}\n        </Button>\n      )}\n      {refused ? (\n        <p id={errorId} role=\"alert\" className=\"nx-rich-text-editor__error\">\n          {FORMAT_BAR_WORDS.badAddress}\n        </p>\n      ) : null}\n    </form>\n  );\n}\n","\"use client\";\n\n/**\n * The rich text control: the field that edits a passage in place, and the\n * session it keeps while it is open.\n *\n * @module rich-text-control\n */\n\nimport {\n  isOneParagraphProp,\n  isRichTextValue,\n  richTextToPlainText,\n  toOneParagraph,\n  type BlockDocument,\n  type RichTextValue,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { joinTyping } from \"../../typing-run\";\nimport { propLabel } from \"../inspector\";\n\nimport type { ContentControlProps, ContentServices } from \"./content-services\";\nimport { FULL_EDITOR_WORDS, RichTextFullEditor } from \"./rich-text-full-editor\";\n\n/** The live attachment of the shared editor to this field, while focused. */\ninterface RichTextSession {\n  focus(at?: number): void;\n  read(): unknown;\n  detach(): void;\n  /** Keep this attachment against anything else asking for the editor. */\n  hold(): void;\n}\n\n/** Said where the host has no editor for the panel: where it is edited. */\nfunction canvasOnlyNote(oneParagraph: boolean): string {\n  return oneParagraph\n    ? \"Text is edited on the canvas here.\"\n    : \"Rich text is edited on the canvas here.\";\n}\n\n/** What a paste that lost formatting says under a one-paragraph field. */\nexport const ONE_PARAGRAPH_DROPPED =\n  \"Text keeps words, bold, italic and links. Use Rich text for headings and lists\";\n\n/**\n * A passage as one string, to tell one stored passage from another; empty\n * for one that cannot be written out (a cycle), which no stored one is.\n */\nfunction passageKey(value: unknown): string {\n  try {\n    return JSON.stringify(value) ?? \"\";\n  } catch {\n    return \"\";\n  }\n}\n\n/** What the field's editor is attached with, for a one-paragraph value. */\ntype ParagraphMode = Parameters<\n  Awaited<\n    ReturnType<NonNullable<ContentServices[\"loadRichTextEditor\"]>>\n  >[\"attach\"]\n>[2];\n\n/**\n * A one-paragraph value's attachment: held to one paragraph by the engine's\n * restriction, a paste that lost formatting said, and every change written as\n * it is typed, in this attachment's one run of typing.\n */\nfunction typedLive(\n  oneParagraph: boolean,\n  run: object,\n  onDropped: (dropped: boolean) => void,\n  write: (value: unknown) => unknown\n): ParagraphMode | undefined {\n  if (!oneParagraph) return undefined;\n  return {\n    paragraph: {\n      restrict: toOneParagraph,\n      onDropped: () => onDropped(true),\n      onChange: next => {\n        joinTyping(run, () => write(next));\n      },\n    },\n  };\n}\n\n/** Attach the shared editor, with the one-paragraph mode where there is one. */\nfunction attachField(\n  editor: Awaited<\n    ReturnType<NonNullable<ContentServices[\"loadRichTextEditor\"]>>\n  >,\n  element: HTMLElement,\n  value: unknown,\n  mode: ParagraphMode | undefined\n) {\n  return mode === undefined\n    ? editor.attach(element, value)\n    : editor.attach(element, value, mode);\n}\n\n/**\n * Write what the editor read when the field is left: restricted to one\n * paragraph, and joined to the attachment's run of typing, for a value that\n * is one; as read otherwise.\n */\nfunction writeRead(\n  read: unknown,\n  oneParagraph: boolean,\n  run: object | null,\n  write: (value: unknown) => BlockDocument | null | void\n): BlockDocument | null | void {\n  if (!oneParagraph || run === null) return write(read);\n  return joinTyping(run, () => write(toOneParagraph(read).value));\n}\n\n/**\n * The Content tab's rich-text prop: its name, and the passage under it.\n *\n * A whole passage (a Rich text's) also says where it is best edited, on the\n * canvas with the format bar, and offers \"Open the full editor\" for longer\n * work, where the host has an editor to open.\n */\nexport function RichTextControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  services,\n}: ContentControlProps): React.JSX.Element {\n  const oneParagraph = isOneParagraphProp(prop.schema);\n  const label = propLabel(prop.name, prop.schema);\n  const write = (value: unknown) => onCommit(prop.name, value);\n  return (\n    <div\n      className=\"nx-inspector__field\"\n      data-content-control={prop.schema.type}\n    >\n      <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n        {label}\n      </p>\n      <RichTextField\n        id={id}\n        labelledBy={`${id}-label`}\n        value={prop.value}\n        disabled={disabled}\n        onCommit={write}\n        services={services}\n        oneParagraph={oneParagraph}\n      />\n      {oneParagraph || services?.loadRichTextEditor === undefined ? null : (\n        <FullEditorEntry\n          label={label}\n          value={prop.value}\n          disabled={disabled}\n          onCommit={write}\n          services={services}\n        />\n      )}\n    </div>\n  );\n}\n\n/**\n * The panel's line on where a Rich text is edited, and the button that opens\n * the full editor; closing it puts the focus back on the button, beside the\n * block still selected.\n */\nfunction FullEditorEntry({\n  label,\n  value,\n  disabled,\n  onCommit,\n  services,\n}: {\n  label: string;\n  value: unknown;\n  disabled: boolean;\n  onCommit: (value: unknown) => BlockDocument | null | void;\n  services: ContentServices;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const button = React.useRef<HTMLButtonElement>(null);\n  return (\n    <>\n      <p className=\"nx-inspector__note\">{FULL_EDITOR_WORDS.line}</p>\n      <Button\n        ref={button}\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        className=\"nx-inspector__full-editor\"\n        disabled={disabled}\n        aria-haspopup=\"dialog\"\n        onClick={() => setOpen(true)}\n      >\n        {FULL_EDITOR_WORDS.open}\n      </Button>\n      {open ? (\n        <RichTextFullEditor\n          label={label}\n          value={value}\n          onCommit={onCommit}\n          services={services}\n          onClose={() => setOpen(false)}\n          returnFocus={() => button.current}\n        />\n      ) : null}\n    </>\n  );\n}\n\n/**\n * A passage's words for the field while no editor is attached: one line per\n * block, and one per item of a list, as the editor will lay them out, so the\n * field is as tall before it is focused as after.\n */\nexport function passagePreview(passage: RichTextValue): string {\n  const lines: string[] = [];\n  for (const block of passage.root.children) {\n    const items =\n      block.type === \"list\" && Array.isArray(block.children)\n        ? block.children\n        : [block];\n    for (const item of items) {\n      lines.push(\n        richTextToPlainText({\n          root: { ...passage.root, children: [item] },\n        }).trim()\n      );\n    }\n  }\n  return lines.join(\"\\n\");\n}\n\n/**\n * A rich-text passage, edited in the inspector with the admin's one rich-text\n * editor. Shared by every surface that edits one: the Content tab's prop and a\n * placement's exposed field, each with its own label and write path.\n *\n * The editor is attached when the field is focused, loaded with the stored\n * passage, and what it reads is committed once when the field is left, so an\n * edit is one entry in the history. There is one editor for the whole admin:\n * while it is held on the canvas the field says so and writes nothing.\n *\n * Read-only is passed to the element itself: a disabled fieldset does not\n * stop typing in a `contenteditable`.\n */\nexport function RichTextField({\n  id,\n  labelledBy,\n  value,\n  disabled,\n  onCommit,\n  services,\n  oneParagraph = false,\n}: {\n  id: string;\n  /** The id of the element naming the field. */\n  labelledBy: string;\n  /**\n   * The value is one paragraph of words with bold, italic, links and line\n   * breaks (a Text's): edited held to that, and written as it is typed, the\n   * typing joined into one step of the history, so the canvas shows the words\n   * as they go in.\n   */\n  oneParagraph?: boolean;\n  /** The passage stored, or `undefined` for none. */\n  value: unknown;\n  disabled: boolean;\n  /**\n   * Write the passage the editor reads; `null` when the write was refused,\n   * which keeps the passage open with the author's words.\n   */\n  onCommit: (value: unknown) => BlockDocument | null | void;\n  services: ContentServices | undefined;\n}): React.JSX.Element {\n  const field = React.useRef<HTMLDivElement>(null);\n  const session = React.useRef<RichTextSession | null>(null);\n  // Whether the field still has focus, so an editor that finishes loading\n  // after the author has moved on is not attached to a field nobody is in.\n  const focused = React.useRef(false);\n  const [loading, setLoading] = React.useState(false);\n  const [refused, setRefused] = React.useState<\n    \"held\" | \"unsupported\" | \"unsaved\" | null\n  >(null);\n  const load = services?.loadRichTextEditor;\n  const editable = !disabled && load !== undefined;\n  // A one-paragraph value is read through its restriction, so an older\n  // string opens as its words and line breaks.\n  const passage = oneParagraph ? toOneParagraph(value).value : value;\n  // The run of typing this attachment's writes join, one per attachment.\n  const typing = React.useRef<object | null>(null);\n  const [dropped, setDropped] = React.useState(false);\n\n  // Loaded as soon as the field is drawn, so focusing it attaches at once\n  // rather than after a fetch the author would type through.\n  React.useEffect(() => {\n    if (editable) load().catch(() => undefined);\n  }, [editable, load]);\n\n  // The host's hold on this passage while it is open; see `OpenPassages`.\n  const release = React.useRef<(() => void) | null>(null);\n\n  const attach = async (): Promise<void> => {\n    const element = field.current;\n    if (!editable || element === null || session.current !== null) return;\n    setLoading(true);\n    let editor: Awaited<ReturnType<typeof load>>;\n    try {\n      editor = await load();\n    } catch {\n      // The editor could not be loaded: the field stays as it is, read-only.\n      return;\n    } finally {\n      setLoading(false);\n    }\n    if (!focused.current || session.current !== null) return;\n    typing.current = {};\n    const attachment = attachField(\n      editor,\n      element,\n      passage,\n      typedLive(oneParagraph, typing.current, setDropped, next =>\n        latestWrite.current(next)\n      )\n    );\n    if (attachment.status === \"refused\") {\n      setRefused(attachment.reason);\n      return;\n    }\n    setRefused(null);\n    session.current = attachment.session;\n    // Finished through the latest render's `finish`, whose write path is the\n    // current one.\n    release.current =\n      services?.openPassages?.hold(() => latestFinish.current()) ?? null;\n    attachment.session.focus();\n  };\n\n  const finish = (): BlockDocument | null | void => {\n    focused.current = false;\n    const live = session.current;\n    if (live === null) {\n      release.current?.();\n      release.current = null;\n      return null;\n    }\n    // Read and written BEFORE letting go: the words exist in the editor alone.\n    // A one-paragraph value is written restricted, joining its typing run.\n    const written = writeRead(\n      live.read(),\n      oneParagraph,\n      typing.current,\n      onCommit\n    );\n    if (written === null) {\n      // Refused (a size cap, a lock that arrived): the passage stays open with\n      // the author's words, held against anything else taking the editor,\n      // until they shorten it or press Escape, as on the canvas.\n      live.hold();\n      setRefused(\"unsaved\");\n      return null;\n    }\n    letGo(live);\n    return written;\n  };\n\n  /** End the attachment and the host's hold on it. */\n  const letGo = (live: RichTextSession): void => {\n    release.current?.();\n    release.current = null;\n    session.current = null;\n    typing.current = null;\n    live.detach();\n    setRefused(null);\n    setDropped(false);\n  };\n\n  // A write as the author types, through the latest render's write path.\n  const latestWrite = React.useRef(onCommit);\n  latestWrite.current = onCommit;\n\n  // While no editor is attached, the field shows the passage's words, set on\n  // the element rather than rendered as children: the editor takes the\n  // element's contents over once attached, and React must not own them.\n  const preview = isRichTextValue(passage) ? passagePreview(passage) : \"\";\n  // A stored passage that changes under words the document refused (a Reset,\n  // an undo) is what the page now holds: the refused draft is let go and the\n  // field shows the stored one, rather than the draft and its notice sitting\n  // over a value that has moved on. Keyed on the whole passage, so a change\n  // its plain text would not show is still seen.\n  const storedKey = passageKey(value);\n  const refusedNow = React.useRef(refused);\n  refusedNow.current = refused;\n  const latestLetGo = React.useRef(letGo);\n  latestLetGo.current = letGo;\n  React.useEffect(() => {\n    const live = session.current;\n    if (live !== null && refusedNow.current === \"unsaved\") {\n      latestLetGo.current(live);\n    }\n    if (session.current === null && field.current !== null) {\n      field.current.textContent = preview;\n    }\n  }, [storedKey, preview]);\n\n  // A passage left open when the block changes or the panel goes is finished,\n  // so nothing typed is lost and the shared editor is never left held. Read\n  // through a ref so the cleanup commits with this render's write path.\n  const latestFinish = React.useRef(finish);\n  latestFinish.current = finish;\n  React.useEffect(\n    () => () => {\n      latestFinish.current();\n      // A passage the document refused stays open while its field is on\n      // screen, where the author can shorten it or press Escape. Once the\n      // field is gone it has no one to finish it, so it is let go rather\n      // than left holding the shared editor and the unsaved state.\n      const refused = session.current;\n      if (refused !== null) {\n        release.current?.();\n        release.current = null;\n        session.current = null;\n        refused.detach();\n      }\n    },\n    []\n  );\n\n  return (\n    <>\n      <div\n        id={id}\n        ref={field}\n        className=\"nx-inspector__rich-text\"\n        role=\"textbox\"\n        aria-multiline=\"true\"\n        aria-labelledby={labelledBy}\n        aria-readonly={!editable}\n        aria-busy={loading}\n        // Not editable until the shared editor attaches and makes it so:\n        // keys typed into the bare element would be replaced by the stored\n        // passage the moment the editor took the element over.\n        tabIndex={0}\n        onFocus={() => {\n          focused.current = true;\n          void attach();\n        }}\n        onBlur={finish}\n        onKeyDown={event => {\n          // Escape discards a change the document refused, deliberately.\n          if (event.key !== \"Escape\" || refused !== \"unsaved\") return;\n          const live = session.current;\n          if (live === null) return;\n          event.preventDefault();\n          letGo(live);\n        }}\n      />\n      {refused === null ? null : (\n        <p className=\"nx-inspector__note\" role=\"status\">\n          {refused === \"held\"\n            ? \"This passage is being edited on the canvas. Finish there first.\"\n            : refused === \"unsaved\"\n              ? \"This change could not be saved, perhaps because the page is at its size limit. Shorten it, or press Escape to discard it.\"\n              : \"This passage can't be edited here.\"}\n        </p>\n      )}\n      {dropped ? (\n        <p className=\"nx-inspector__note\" role=\"status\">\n          {ONE_PARAGRAPH_DROPPED}\n        </p>\n      ) : null}\n      {load === undefined ? (\n        <p className=\"nx-inspector__note\">{canvasOnlyNote(oneParagraph)}</p>\n      ) : null}\n    </>\n  );\n}\n","\"use client\";\n\n/**\n * What every content control is given: the host's services (the media\n * library, entry and link-target search, the collections a list reads), the\n * context that carries them, and the props each control takes.\n *\n * @module content-services\n */\n\nimport type {\n  BlockDocument,\n  FieldStoragePrimitive,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { BindingServices } from \"../../bindings/binding-services\";\nimport type { OpenPassages } from \"../../canvas/open-passages\";\nimport type { InlineRichTextEditorLoader } from \"../../canvas/use-inline-rich-text\";\nimport type { PreferenceStore } from \"../../shell-state\";\nimport type { EditableProp } from \"../inspector\";\n\nimport type { QueryField } from \"./list-query-model\";\nimport type { CustomSource } from \"./named-query-model\";\n\n/** One item the host's media picker returned. Only its id is ever stored. */\nexport interface PickedMedia {\n  readonly id: string;\n  readonly url?: string | null;\n  readonly filename?: string;\n}\n\n/** What a field shows of a chosen media item, read by its id. */\nexport interface MediaSummary {\n  /** The file's name, as the author uploaded it. */\n  readonly name?: string;\n  /** An address to draw a small picture of it from. */\n  readonly thumbnail?: string;\n  /** Its alt text in the library, when it has one. */\n  readonly alt?: string;\n}\n\n/**\n * One image a library search found: its summary, and the id a pick stores.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport interface FoundMedia extends MediaSummary {\n  readonly id: string;\n}\n\n/**\n * Put one file in the host's media library, through the library's own upload\n * and its checks (the types and size the site accepts, and the author's\n * right to upload), telling `onProgress` how far it is, from 0 to 100.\n * Resolves to the stored item, and rejects with the reason the upload was\n * refused, in words an author can read.\n *\n * @experimental Settles with the canvas's image empty state.\n */\nexport type UploadMedia = (\n  file: File,\n  onProgress?: (percent: number) => void\n) => Promise<PickedMedia>;\n\n/** What the content controls hand the host's media picker. */\nexport interface MediaPickerProps {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  onSelect: (media: PickedMedia[]) => void;\n  title?: string;\n  /** The kinds of file it offers, as an `accept` list: `image/*`. */\n  accept?: string;\n  /** What is chosen when it opens: the file the prop stores, if any. */\n  initialSelectedIds?: Set<string>;\n  /**\n   * One file, or several: `multi` lets the author pick many, handed back in\n   * the order they were picked, as a Gallery's \"Add images\" asks. Unset is\n   * one.\n   *\n   * @experimental Settles with the Gallery's \"Add images\".\n   */\n  mode?: \"single\" | \"multi\";\n}\n\n/** What a relation control asks the host for: one collection's entries. */\nexport interface EntryQuery {\n  readonly collection: string;\n  /** Entries whose title holds this, ignoring case; empty for the first few. */\n  readonly search?: string;\n  /** These entries by id, to name the one a prop stores. */\n  readonly ids?: readonly string[];\n  readonly limit?: number;\n  readonly signal?: AbortSignal;\n}\n\n/** One entry as a relation control shows it: its id and its title, nothing else. */\nexport interface FoundEntry {\n  readonly id: string;\n  readonly title: string;\n}\n\n/** What the link control asks the host for: what a link can point at. */\nexport interface LinkTargetQuery {\n  /** Pages and entries whose title holds this, ignoring case; empty for the first few. */\n  readonly search: string;\n  readonly limit?: number;\n  readonly signal?: AbortSignal;\n}\n\n/** One page or entry the link control offers. */\nexport interface LinkTarget {\n  readonly id: string;\n  /** Its collection's slug, which a link to the entry stores. */\n  readonly collection: string;\n  /** The heading it is listed under: its collection's name (\"Pages\"). */\n  readonly group: string;\n  readonly title: string;\n  /**\n   * Where it is served on the site (`/pricing`), when the host knows. A\n   * heading or a box links by this address; without one, only a block that\n   * can hold an entry reference can link to it.\n   */\n  readonly path?: string;\n}\n\n/**\n * One field a collection list may filter by, and sort by unless it is a\n * relation: a field visitors can see, holding one value.\n */\nexport interface LoopListField extends QueryField {\n  /** A date picked as a day, which a filter compares as that day. */\n  readonly dateOnly?: boolean;\n}\n\n/** A to-many relation a related list can show the entries of. */\nexport interface LoopRelation {\n  /** The relation field a list's `relation.field` stores. */\n  readonly field: string;\n  /** What the author calls it: \"Categories\". */\n  readonly label: string;\n  /** The collection its entries are in. */\n  readonly collection: string;\n}\n\n/** One collection a loop can repeat over, as its controls offer it. */\nexport interface LoopCollection {\n  /** The slug a loop stores. */\n  readonly slug: string;\n  /** Its name, as the admin shows it: \"Blog posts\". */\n  readonly label: string;\n  /** Its name for one entry: \"Post\". Its label where it has none. */\n  readonly singular?: string;\n  /**\n   * The fields a list may filter and sort by, in the collection's order:\n   * only those visitors can see, since the entries shown would otherwise\n   * reveal a field no visitor may read.\n   */\n  readonly fields: readonly LoopListField[];\n  /** Its to-many relations visitors can see, to a listed collection. */\n  readonly relations?: readonly LoopRelation[];\n  /**\n   * Every field name it declares, so a stored filter on a field visitors\n   * can't see is told apart from one on a field it no longer has.\n   */\n  readonly declared?: readonly string[];\n  /**\n   * Every field the public may read, as a save judges a list against them;\n   * {@link fields} is the narrower view of these an author is offered.\n   */\n  readonly readable?: readonly {\n    readonly name: string;\n    /** What the admin calls it: \"Cover image\". */\n    readonly label?: string;\n    readonly type: string;\n    readonly hasMany?: boolean;\n    readonly relationTo?: string | readonly string[];\n    /** A time of day, which no list filters or sorts by. */\n    readonly timeOnly?: boolean;\n    /** The primitive a plugin's field type is stored as, which gives its kind. */\n    readonly storage?: FieldStoragePrimitive;\n    /** For an upload field: whether it takes images, where it says. */\n    readonly takesImages?: boolean;\n  }[];\n  /** The field the admin titles its entries by, where visitors may read it. */\n  readonly titleField?: string;\n  /** Whether its entries are served as pages of their own. */\n  readonly entriesHavePages?: boolean;\n}\n\n/** A list's matching entries, and how many of them it shows. */\nexport interface ListEntriesCount {\n  readonly matching: number;\n  readonly shown: number;\n}\n\n/**\n * One form a provider lists for an author to pick in a Form block.\n *\n * @experimental Settles with the form provider contract.\n */\nexport interface PickableForm {\n  /** The provider's own reference to it, which the block stores. */\n  readonly ref: string;\n  readonly title: string;\n  readonly state: \"draft\" | \"published\" | \"closed\";\n  /** Where the author edits it in the admin, as the provider gives it. */\n  readonly editHref?: string;\n}\n\n/**\n * A source of forms other than the block's own fields (the forms plugin),\n * with the forms the author may pick from it.\n *\n * @experimental Settles with the form provider contract.\n */\nexport interface FormSource {\n  /** The provider's id, which the block stores beside a form's reference. */\n  readonly id: string;\n  /** What authors read: \"Forms\" in \"Fields … come from Forms.\" */\n  readonly label: string;\n  readonly forms: readonly PickableForm[];\n}\n\n/**\n * A picked form's state as its author sees it on the canvas.\n *\n * @experimental Settles with the form provider contract.\n */\nexport type PickedFormState = \"published\" | \"draft\" | \"closed\" | \"missing\";\n\n/**\n * What the host lends the Content tab: the parts of the admin this package\n * cannot reach itself. Each is optional, and a control whose service is absent\n * says so rather than offering a button that does nothing.\n *\n * The binding controls' share is {@link BindingServices}.\n *\n * @experimental Grows with the controls registry.\n */\nexport interface ContentServices extends BindingServices {\n  /** The admin's media library, as a dialog the control opens. */\n  readonly MediaPicker?: React.ComponentType<MediaPickerProps>;\n  /**\n   * The admin's media library upload, for a file an author drops on an\n   * Image or chooses from its empty state. Absent, an Image offers no\n   * Upload and takes no dropped file.\n   *\n   * @experimental Settles with the canvas's image empty state.\n   */\n  readonly uploadMedia?: UploadMedia;\n  /**\n   * Copy the picture a video's provider shows for it into the media library,\n   * once: a second copy for the same video answers the first. Given the\n   * Embed's link as stored; the host fetches only from the provider's fixed\n   * picture host. Absent, an Embed offers no \"Use the video's thumbnail\".\n   *\n   * @experimental Settles with the Embed's poster.\n   */\n  readonly copyEmbedThumbnail?: (link: string) => Promise<PickedMedia>;\n  /** The shared rich-text editor, loaded when a passage is first focused. */\n  readonly loadRichTextEditor?: InlineRichTextEditorLoader;\n  /**\n   * A collection's entries, read with the signed-in author's own access, for\n   * a prop that points at one of them.\n   */\n  readonly findEntries?: (query: EntryQuery) => Promise<readonly FoundEntry[]>;\n  /**\n   * The pages and entries a link can point at, read with the signed-in\n   * author's own access and listed by collection, the site's own pages first.\n   * Absent, a link control takes typed addresses only.\n   */\n  readonly findLinkTargets?: (\n    query: LinkTargetQuery\n  ) => Promise<readonly LinkTarget[]>;\n  /**\n   * The collections a collection loop can repeat over, read with the\n   * signed-in author's own access, each with the fields visitors can see\n   * and its to-many relations. Absent, a loop's collection and sort are\n   * typed as text.\n   */\n  readonly listLoopCollections?: () => Promise<readonly LoopCollection[]>;\n  /**\n   * The custom sources a collection list may show: the named queries the\n   * site registers, each without its run function, with the collections it\n   * reads that visitors can read nothing of. Absent, the Source menu offers\n   * collections and related entries only.\n   */\n  readonly listCustomSources?: () => Promise<readonly CustomSource[]>;\n  /**\n   * How many entries a list's stored query matches as the canvas reads them,\n   * and how many of those its window shows, from one count read. Asked only\n   * for the list selected in the editor. Undefined where one read cannot\n   * count it, such as a list of an entry's related entries.\n   */\n  readonly countListEntries?: (\n    props: Readonly<Record<string, unknown>>\n  ) => Promise<ListEntriesCount | undefined>;\n  /**\n   * The collection the document being edited is an entry of, so a list on\n   * it can show the entry's related entries. `null` where the document is\n   * known to be no collection's entry, such as a Single, so a list there\n   * showing the entry's related entries is refused as the save refuses it;\n   * absent where that is not known.\n   */\n  readonly entryCollection?: string | null;\n  /**\n   * A media item by its id, read with the signed-in author's own access, so a\n   * stored file is shown by its picture and name rather than as \"a file\".\n   */\n  readonly readMedia?: (mediaId: string) => Promise<MediaSummary | null>;\n  /**\n   * The media library's images found by name, read with the signed-in\n   * author's own access: the newest first, a handful at a time, and the\n   * newest of all for an empty search. Rejects where the library cannot be\n   * read, and once `signal` aborts. Absent, an image binding's Fallback\n   * offers the host's `MediaPicker` dialog alone.\n   *\n   * @experimental Settles with the editor's binding controls.\n   */\n  readonly searchMedia?: (\n    search: string,\n    signal?: AbortSignal\n  ) => Promise<readonly FoundMedia[]>;\n  /**\n   * Where a rich-text field holds the passage it has open, so the host\n   * finishes it before the document is stored.\n   */\n  readonly openPassages?: OpenPassages;\n  /**\n   * Where the icons this author chose last are kept, for the Icon control's\n   * Recent row: the host's, so it is one per signed-in author. Absent, the\n   * picker offers no Recent row.\n   */\n  readonly recentIcons?: PreferenceStore;\n  /**\n   * A form a Form block picked from a provider, read with the signed-in\n   * author's own access, for what its own \"After sending\" setting is.\n   * Absent, or answering `undefined`, the panel names the choice without\n   * saying what it is.\n   *\n   * @experimental Settles with the form provider contract.\n   */\n  /**\n   * The site's form sources other than the block's own fields, each with\n   * the forms the signed-in author may pick, for a Form block's \"Form: <pick\n   * a form>\". An empty list is a site with no such source, where the panel\n   * says what installing one adds. Absent, the panel offers neither.\n   *\n   * @experimental Settles with the form provider contract.\n   */\n  readonly listForms?: () => Promise<readonly FormSource[]>;\n  /**\n   * A picked form's state, read with the signed-in author's own access, for\n   * what the canvas says over it: a draft, closed, or deleted. Rejects where\n   * it could not be read, and the canvas then says nothing.\n   *\n   * @experimental Settles with the form provider contract.\n   */\n  readonly pickedFormState?: (form: {\n    readonly provider: string;\n    readonly ref: string;\n  }) => Promise<PickedFormState>;\n  readonly describeForm?: (form: {\n    readonly provider: string;\n    readonly ref: string;\n  }) => Promise<\n    { readonly afterSending: { readonly kind: \"message\" | \"page\" } } | undefined\n  >;\n}\n\n/**\n * The host's content services for a surface below the inspector that is not\n * a Content tab control, such as a component placement's exposed image, so\n * it reaches the same media library without a prop threaded through every\n * surface between.\n */\nexport const ContentServicesContext: React.Context<\n  ContentServices | undefined\n> = React.createContext<ContentServices | undefined>(undefined);\n\n/** What every content control is given. */\nexport interface ContentControlProps {\n  /** The id its field takes, which its label points at. Unique per mount. */\n  readonly id: string;\n  readonly prop: EditableProp;\n  /** Whether the prop may not be changed here: a lock, or a `contentOnly` area. */\n  readonly disabled: boolean;\n  /**\n   * Set the prop, through the editor's one write path; `undefined` removes\n   * it. Answers the document the write produced, when the caller knows it.\n   */\n  readonly onCommit: (\n    name: string,\n    value: unknown\n  ) => BlockDocument | null | void;\n  /** What the host lends, for the controls that need the admin. */\n  readonly services?: ContentServices | undefined;\n  /**\n   * How many lists this control sits inside: 0 at the top of the tab. Lists\n   * nest only as deep as the engine's `ITEM_SCHEMA_MAX_DEPTH`.\n   */\n  readonly depth?: number;\n  /**\n   * The label to show, when it is not the prop's own name: an item of a list\n   * is labelled by its list and its position.\n   */\n  readonly label?: string | undefined;\n  /**\n   * The block's other props as stored, read-only, for a control whose\n   * choices depend on one: a loop's sort offers the fields of the collection\n   * its `collectionProp` names. Absent inside a list's items.\n   */\n  readonly values?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/** A content control: a label and the field it names. */\nexport type ContentControl = (props: ContentControlProps) => React.JSX.Element;\n","\"use client\";\n\n/**\n * The Content tab's controls, one per prop type, looked up by the type a\n * block's prop declares.\n *\n * A registry rather than a switch, so each value type has the control that\n * fits it and a new type is one entry here. The record is typed over\n * `CONTENT_CONTROL_TYPES`, the list the inspection reads to mark a prop\n * supported, so a type cannot be supported without a control or drawn\n * without being supported.\n *\n * **Every control draws its own label and the field the label names.** A\n * label pointing at an element that is not there is announced as a field\n * nobody can reach, so the label and its control are one unit here.\n *\n * **Text writes as it is typed**, so the canvas follows each keystroke. The\n * writes of one stretch of typing are one undo step (`live-draft.ts`), which\n * ends on blur or Enter, so one undo takes back one edit, not one letter.\n * Discrete controls (a checkbox, a select) commit at once: there is no typing\n * to group.\n *\n * This module holds the text, checkbox, select, list, icon and unsupported\n * controls and the lookup, and is the entry for the rest: the host's services\n * and what every control takes are in `content-services.ts`, the media\n * control in `media-controls.tsx`, and the rich text control in\n * `rich-text-control.tsx`.\n *\n * @module content-controls\n */\n\nimport {\n  isOneParagraphProp,\n  ITEM_SCHEMA_MAX_DEPTH,\n  optionLabel,\n  type PropSchema,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  IconField,\n  Input,\n  Label,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n  Switch,\n  Textarea,\n} from \"@nextlyhq/ui\";\nimport { ArrowDown, ArrowUp, Trash2 } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { typedNumber, useLiveDraft } from \"../../live-draft\";\nimport { radioGroupStep } from \"../../roving-radios\";\nimport {\n  fitsSideBySide,\n  type SideBySideRoom,\n} from \"../../styles/style-numeric\";\nimport { propWrites } from \"../code-hints\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport { CssHint } from \"../css-hint\";\nimport { propLabel, type EditableProp } from \"../inspector\";\n\nimport { CollectionControl, SortControl } from \"./collection-loop-controls\";\nimport {\n  CONTENT_CONTROL_TYPES,\n  hasContentControl,\n  type ContentControlType,\n} from \"./content-control-types\";\nimport type { ContentControl, ContentControlProps } from \"./content-services\";\nimport { EntryFieldControl } from \"./entry-field-control\";\nimport { loadLucideIcons } from \"./lucide-icon-source\";\nimport { MediaControl } from \"./media-controls\";\nimport { useRecentIcons } from \"./recent-icons\";\nimport { RelationControl } from \"./relation-control\";\nimport { RichTextControl } from \"./rich-text-control\";\n\n// The host's services and what every control takes, the media controls and\n// the rich text control live in modules of their own beside it; every name\n// this module exported still is.\n// Part of this module's exported names; no importer in the package reads it.\n// fallow-ignore-next-line unused-type\nexport type { LoopRelation } from \"./content-services\";\nexport {\n  type ContentControl,\n  type ContentControlProps,\n  type ContentServices,\n  ContentServicesContext,\n  type EntryQuery,\n  type FoundEntry,\n  type FoundMedia,\n  type LinkTarget,\n  type LinkTargetQuery,\n  type ListEntriesCount,\n  type LoopCollection,\n  type LoopListField,\n  type MediaPickerProps,\n  type MediaSummary,\n  type PickedMedia,\n} from \"./content-services\";\nexport {\n  ChosenMedia,\n  MediaChoice,\n  MediaField,\n  useMediaSummary,\n} from \"./media-controls\";\nexport { RichTextField } from \"./rich-text-control\";\n\nexport { CONTENT_CONTROL_TYPES };\n\n/**\n * The words a block gives a prop to explain it (`hint`), shown under its\n * control and read as its description, or `undefined` for none.\n */\nfunction propHint(prop: EditableProp): string | undefined {\n  return typeof prop.schema.hint === \"string\" && prop.schema.hint !== \"\"\n    ? prop.schema.hint\n    : undefined;\n}\n\n/** A prop's value as editable text, or empty when it is not representable. */\nfunction storedText(value: unknown): string {\n  if (value === undefined || value === null) return \"\";\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\" || typeof value === \"boolean\") {\n    return String(value);\n  }\n  return \"\";\n}\n\n/**\n * A field the author types into: text, textarea, url, number.\n *\n * Holds its own text while focused, and writes each keystroke as it goes in,\n * so the canvas follows the typing; the stretch is one undo step, ended by\n * blur or Enter. A number that is not one yet (emptied, a lone sign) writes\n * nothing, so the canvas keeps the last one, and the field shows that last\n * number again when it is left.\n */\nfunction TextishControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  label,\n}: ContentControlProps): React.JSX.Element {\n  // Only a primitive becomes text. `String({})` is \"[object Object]\", and a\n  // field showing that would WRITE it, turning a prop the panel cannot\n  // represent into a string that permanently replaces it. An unrepresentable\n  // value shows empty and, because a write compares against this, an\n  // untouched field writes nothing.\n  const stored = storedText(prop.value);\n  const live = useLiveDraft(stored);\n  const number = prop.schema.type === \"number\";\n\n  // A keystroke's write, answering whether it moved the document.\n  const write = (text: string): boolean => {\n    if (!number) {\n      return text !== stored && onCommit(prop.name, text) !== null;\n    }\n    // A number field writes only a number: NaN survives JSON as `null` and\n    // reaches the renderer as a missing prop.\n    const parsed = typedNumber(text);\n    if (parsed === undefined) return false;\n    if (stored.trim() !== \"\" && parsed === Number(stored)) return false;\n    return onCommit(prop.name, parsed) !== null;\n  };\n\n  // The edit ends: a number that is not one yet goes back to the last one\n  // written, and the next keystroke starts a new undo step.\n  const send = () => {\n    if (number && typedNumber(live.draft) === undefined) {\n      live.setDraft(stored);\n    }\n    live.end();\n  };\n\n  const hint = propHint(prop);\n  const shared = {\n    id,\n    disabled,\n    value: live.draft,\n    ...(hint === undefined ? {} : { \"aria-describedby\": `${id}-hint` }),\n    onBlur: send,\n    onChange: (\n      event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\n    ) => live.type(event.target.value, write),\n  };\n\n  return (\n    <div\n      className=\"nx-inspector__field\"\n      data-content-control={prop.schema.type}\n    >\n      <Label htmlFor={id}>{label ?? propLabel(prop.name, prop.schema)}</Label>\n      {prop.schema.type === \"textarea\" ? (\n        <Textarea {...shared} rows={3} />\n      ) : (\n        <Input\n          {...shared}\n          type={prop.schema.type === \"number\" ? \"number\" : \"text\"}\n          inputMode={prop.schema.type === \"url\" ? \"url\" : undefined}\n          // Enter ends the edit as well as blur: a single-line field is\n          // where an author expects Enter to mean \"done\", so what they type\n          // next is a new undo step.\n          onKeyDown={event => {\n            commitOnEnter(event, send);\n          }}\n        />\n      )}\n      {hint === undefined ? null : (\n        <p className=\"nx-inspector__note\" id={`${id}-hint`}>\n          {hint}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/**\n * A `text` prop: typed, unless its block asks for a control that offers the\n * values it can hold (`display: \"collection\"` or `display: \"sort\"`), which\n * fall back to typing where the host cannot list them.\n */\nfunction TextControl(props: ContentControlProps): React.JSX.Element {\n  const typed = <TextishControl {...props} />;\n  const display = props.prop.schema.display;\n  if (display === \"collection\") {\n    return <CollectionControl {...props} fallback={typed} />;\n  }\n  if (display === \"sort\") {\n    return <SortControl {...props} fallback={typed} />;\n  }\n  return typed;\n}\n\n/**\n * A yes-or-no prop, as a switch whose label says what \"on\" does (\"Open by\n * default\"), committed the moment it changes.\n */\nfunction CheckboxControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  label,\n}: ContentControlProps): React.JSX.Element {\n  return (\n    // As every other row is: the label in the label column, the switch in the\n    // control column, where a switch drawn before its label broke the column.\n    <div className=\"nx-inspector__field\" data-content-control=\"checkbox\">\n      <Label htmlFor={id}>{label ?? propLabel(prop.name, prop.schema)}</Label>\n      <Switch\n        id={id}\n        disabled={disabled}\n        checked={(prop.value ?? prop.defaultValue) === true}\n        onCheckedChange={checked => onCommit(prop.name, checked)}\n      />\n    </div>\n  );\n}\n\n/**\n * How much room the Content tab's control column has for a row of options:\n * the Level of a heading (H1 to H6) and \"This tab · A new tab\" fit; a set of\n * long names does not, and stays a menu.\n */\nconst CONTENT_ROW: SideBySideRoom = { maxCount: 6, maxEach: 9, maxTotal: 18 };\n\n/**\n * The option a switch turns on and the one it turns off, for a select whose\n * block asks for a switch (`display: \"switch\"`, `switchOn: \"<option>\"`), or\n * `undefined` where the declaration is not one a switch can draw (anything\n * but exactly two options, one of them `switchOn`) or `stored` is neither.\n */\nfunction switchPairOf(\n  prop: EditableProp,\n  stored: string | undefined\n): readonly [on: string, off: string] | undefined {\n  const on = prop.schema.switchOn;\n  if (prop.schema.display !== \"switch\" || typeof on !== \"string\") {\n    return undefined;\n  }\n  if (prop.options.length !== 2 || !prop.options.includes(on)) return undefined;\n  const off = prop.options.find(option => option !== on);\n  if (off === undefined) return undefined;\n  return stored === undefined || stored === on || stored === off\n    ? [on, off]\n    : undefined;\n}\n\n/**\n * A pair of options as one switch, named by the words of the option it turns\n * on, with the block's `hint`, when it gives one, as its description.\n */\nfunction PairSwitch({\n  id,\n  prop,\n  pair: [on, off],\n  on: checked,\n  disabled,\n  onCommit,\n}: Pick<ContentControlProps, \"id\" | \"prop\" | \"disabled\" | \"onCommit\"> & {\n  pair: readonly [on: string, off: string];\n  on: boolean;\n}): React.JSX.Element {\n  const hint = propHint(prop);\n  return (\n    <div\n      className=\"nx-inspector__field\"\n      data-content-control=\"select\"\n      data-display=\"switch\"\n    >\n      <Label htmlFor={id}>{optionLabel(prop.schema, on)}</Label>\n      <Switch\n        id={id}\n        disabled={disabled}\n        checked={checked}\n        {...(hint === undefined ? {} : { \"aria-describedby\": `${id}-hint` })}\n        onCheckedChange={next => onCommit(prop.name, next ? on : off)}\n      />\n      {hint === undefined ? null : (\n        <p className=\"nx-inspector__note\" id={`${id}-hint`}>\n          {hint}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/**\n * One of a declared set of options, committed the moment it is chosen. A set\n * whose words fit side by side is drawn as a row of buttons, so every choice\n * is on screen; a longer one is a menu, and a pair the block asks to show as\n * a switch is one.\n */\nfunction SelectControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  label,\n}: ContentControlProps): React.JSX.Element {\n  const name = label ?? propLabel(prop.name, prop.schema);\n  const labels = prop.options.map(option => optionLabel(prop.schema, option));\n  // The stored choice, or the block's default while none is stored.\n  const shown = prop.value ?? prop.defaultValue;\n  const stored = typeof shown === \"string\" ? shown : undefined;\n  // Two options and a block asking for a switch: one yes-or-no row, named by\n  // the words of the option it turns on. A stored value that is neither is\n  // left to the menu below, which can show it, rather than read as \"off\" and\n  // replaced at the first click.\n  const pair = switchPairOf(prop, stored);\n  if (pair !== undefined) {\n    return (\n      <PairSwitch\n        id={id}\n        prop={prop}\n        pair={pair}\n        on={stored === pair[0]}\n        disabled={disabled}\n        onCommit={onCommit}\n      />\n    );\n  }\n  // A stored value outside the options is shown by the menu, which can say\n  // what it is; a row of buttons would show none chosen and replace it.\n  // A block can ask for a menu with `display: \"menu\"`, so one prop reads the\n  // same on every block whatever options each offers. Read through the\n  // schema's open option keys rather than a declared field, so a block\n  // already using `display` for something of its own keeps type-checking;\n  // only the value \"menu\" means anything here.\n  // A menu, too, where the block declares what each choice writes: the menu\n  // is where that code is shown beside the words.\n  const segmented =\n    prop.schema.display !== \"menu\" &&\n    !prop.options.some(\n      option => optionCode(prop.schema, option) !== undefined\n    ) &&\n    fitsSideBySide(labels, CONTENT_ROW) &&\n    (stored === undefined || prop.options.includes(stored));\n  if (segmented) {\n    return (\n      <div className=\"nx-inspector__field\" data-content-control=\"select\">\n        <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n          {name}\n        </p>\n        <SegmentedChoice\n          id={id}\n          labelledBy={`${id}-label`}\n          options={prop.options}\n          labels={labels}\n          value={stored}\n          disabled={disabled}\n          onChoose={next => onCommit(prop.name, next)}\n        />\n      </div>\n    );\n  }\n  return (\n    <div className=\"nx-inspector__field\" data-content-control=\"select\">\n      <Label htmlFor={id}>{name}</Label>\n      <Select\n        disabled={disabled}\n        value={stored}\n        onValueChange={next => onCommit(prop.name, next)}\n      >\n        {/* What the chosen option writes, on hover or keyboard focus. */}\n        <CssHint writes={propWrites(prop.schema, stored)}>\n          <SelectTrigger id={id}>\n            <SelectValue placeholder=\"Choose\" />\n          </SelectTrigger>\n        </CssHint>\n        <SelectContent>\n          {prop.options.map((option, index) => {\n            const written = shownCode(prop.schema, option, labels[index]);\n            return (\n              <SelectItem key={option} value={option}>\n                {labels[index]}\n                {/* What the choice writes, muted, where the block says: an\n                    HTML tag reads as words, with the tag still there. The\n                    closed menu draws the chosen item's text, so it reads the\n                    same. */}\n                {written === undefined ? null : (\n                  <code className=\"nx-inspector__option-value\">{written}</code>\n                )}\n              </SelectItem>\n            );\n          })}\n        </SelectContent>\n      </Select>\n    </div>\n  );\n}\n\n/**\n * A choice of one among a few options, as a row of radio buttons: the arrow\n * keys move the choice, as in any radio group, and only the chosen one (or the\n * first, with none chosen) is in the tab order.\n */\nexport function SegmentedChoice({\n  id,\n  labelledBy,\n  options,\n  labels,\n  value,\n  disabled,\n  onChoose,\n}: {\n  id: string;\n  labelledBy: string;\n  options: readonly string[];\n  labels: readonly string[];\n  value: string | undefined;\n  disabled: boolean;\n  onChoose: (option: string) => void;\n}): React.JSX.Element {\n  const buttons = React.useRef<Array<HTMLButtonElement | null>>([]);\n  const chosen = value === undefined ? -1 : options.indexOf(value);\n  const stop = chosen === -1 ? 0 : chosen;\n  return (\n    <div\n      id={id}\n      className=\"nx-style-inspector__toggle\"\n      role=\"radiogroup\"\n      aria-labelledby={labelledBy}\n    >\n      {options.map((option, index) => (\n        <button\n          key={option}\n          ref={element => {\n            buttons.current[index] = element;\n          }}\n          type=\"button\"\n          role=\"radio\"\n          aria-checked={index === chosen}\n          tabIndex={index === stop ? 0 : -1}\n          disabled={disabled}\n          onClick={() => onChoose(option)}\n          onKeyDown={event => {\n            const step = radioGroupStep(event.key);\n            if (step === null) return;\n            event.preventDefault();\n            const next = (index + step + options.length) % options.length;\n            buttons.current[next]?.focus();\n            onChoose(options[next] ?? option);\n          }}\n        >\n          {labels[index]}\n        </button>\n      ))}\n    </div>\n  );\n}\n\n/** An item field as a control sees it: a prop of its own, read from one record. */\nfunction itemProp(\n  name: string,\n  schema: EditableProp[\"schema\"],\n  value: unknown\n): EditableProp {\n  const options = Array.isArray(schema.options)\n    ? schema.options.filter(\n        (option): option is string => typeof option === \"string\"\n      )\n    : [];\n  return {\n    name,\n    schema,\n    value,\n    supported: hasContentControl(schema.type),\n    options,\n    // An item's fields are drawn whole: the rules that leave a block's prop\n    // out read the block's other props, which an item does not have.\n    offered: true,\n    // The parent array control's `disabled` already holds the item fields.\n    readOnly: false,\n  };\n}\n\n/** A record's own fields, or none for a value that is not a plain record. */\nfunction recordOf(value: unknown): Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value)\n    ? (value as Record<string, unknown>)\n    : {};\n}\n\n/** An item schema's fields, when the prop declares one. */\nfunction itemSchemaOf(\n  schema: EditableProp[\"schema\"]\n): readonly [string, EditableProp[\"schema\"]][] | undefined {\n  const item = schema.item;\n  if (typeof item !== \"object\" || item === null || Array.isArray(item))\n    return undefined;\n  const fields = Object.entries(item).filter(\n    (entry): entry is [string, EditableProp[\"schema\"]] =>\n      typeof entry[1] === \"object\" &&\n      entry[1] !== null &&\n      typeof entry[1].type === \"string\"\n  );\n  return fields.length > 0 ? fields : undefined;\n}\n\n/**\n * A list: of plain text (`of: \"text\"`), or of records an item schema\n * describes (`of: \"object\"` with `item`). Each item is edited with the\n * registry's own controls, and every change — an edit, an add, a removal, a\n * move — writes the whole list once, so each is one entry in the history.\n */\nfunction ArrayControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  services,\n  depth = 0,\n}: ContentControlProps): React.JSX.Element {\n  // Items past the engine's bound are not drawn, so nothing is offered that\n  // the readers bounded the same way (a relation search) would refuse.\n  if (depth >= ITEM_SCHEMA_MAX_DEPTH) return <UnsupportedField prop={prop} />;\n  return (\n    <ArrayItems\n      id={id}\n      prop={prop}\n      disabled={disabled}\n      onCommit={onCommit}\n      services={services}\n      depth={depth}\n    />\n  );\n}\n\n/** A list's items and its actions, inside the bound {@link ArrayControl} keeps. */\nfunction ArrayItems({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  services,\n  depth,\n}: ContentControlProps & { depth: number }): React.JSX.Element {\n  const label = propLabel(prop.name, prop.schema);\n  const list = Array.isArray(prop.value) ? prop.value : [];\n  const records = prop.schema.of === \"object\";\n  const fields = records ? itemSchemaOf(prop.schema) : undefined;\n  // The list as last written, not as this render drew it. Clicking an\n  // action blurs the item being typed in first, and that blur commits it; an\n  // action built from the drawn list would then write over the words just\n  // committed. Every write goes through here and every action reads from it.\n  const latest = React.useRef(list);\n  latest.current = list;\n  const write = (next: unknown[]) => {\n    // Advanced only when the write lands: a refused one (a cap, a lock that\n    // arrived) changed nothing, and the next action must not start from it.\n    const outcome = onCommit(prop.name, next);\n    if (outcome !== null) latest.current = next;\n    // Answered as is, so an item's field typing live reads a refusal as one\n    // and does not take the next stored value for its own write's echo.\n    return outcome;\n  };\n  // \"Item 1\", \"Item 2\": each item sits in the group the setting's own name\n  // labels, so repeating that name (\"Items, item 1\") says it twice.\n  const position = (index: number) => `Item ${index + 1}`;\n  const move = (index: number, by: -1 | 1) => {\n    const next = [...latest.current];\n    const [taken] = next.splice(index, 1);\n    next.splice(index + by, 0, taken);\n    write(next);\n  };\n\n  return (\n    <div\n      className=\"nx-inspector__field nx-inspector__field--stacked\"\n      data-content-control=\"array\"\n    >\n      <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n        {label}\n      </p>\n      <div\n        className=\"nx-inspector__array\"\n        role=\"group\"\n        aria-labelledby={`${id}-label`}\n      >\n        {records && fields === undefined ? (\n          <p className=\"nx-inspector__note\">\n            These items can&apos;t be edited here.\n          </p>\n        ) : (\n          <>\n            {list.map((item, index) => (\n              <div\n                // Positions are what identify an item: a list holds no ids.\n                key={index}\n                className=\"nx-inspector__array-item\"\n                role=\"group\"\n                aria-label={position(index)}\n              >\n                <div className=\"nx-inspector__array-fields\">\n                  {fields === undefined ? (\n                    <TextishControl\n                      id={`${id}-${index}`}\n                      prop={itemProp(\n                        `${prop.name}.${index}`,\n                        { type: \"text\" },\n                        item\n                      )}\n                      label={position(index)}\n                      disabled={disabled}\n                      onCommit={(_, value) =>\n                        write(\n                          latest.current.map((each, at) =>\n                            at === index ? value : each\n                          )\n                        )\n                      }\n                    />\n                  ) : (\n                    fields.map(([name, schema]) => {\n                      const Control = contentControlFor(schema.type);\n                      const record = recordOf(item);\n                      return Control === undefined ? (\n                        <UnsupportedField key={name} prop={{ name, schema }} />\n                      ) : (\n                        <Control\n                          key={name}\n                          id={`${id}-${index}-${name}`}\n                          depth={depth + 1}\n                          prop={itemProp(name, schema, record[name])}\n                          disabled={disabled}\n                          services={services}\n                          onCommit={(field, value) =>\n                            write(\n                              latest.current.map((each, at) => {\n                                if (at !== index) return each;\n                                const next = { ...recordOf(each) };\n                                if (value === undefined) delete next[field];\n                                else next[field] = value;\n                                return next;\n                              })\n                            )\n                          }\n                        />\n                      );\n                    })\n                  )}\n                </div>\n                <div className=\"nx-inspector__array-actions\">\n                  <Button\n                    type=\"button\"\n                    size=\"icon-sm\"\n                    variant=\"ghost\"\n                    disabled={disabled || index === 0}\n                    aria-label={`Move ${position(index)} up`}\n                    onClick={() => move(index, -1)}\n                  >\n                    <ArrowUp aria-hidden=\"true\" />\n                  </Button>\n                  <Button\n                    type=\"button\"\n                    size=\"icon-sm\"\n                    variant=\"ghost\"\n                    disabled={disabled || index === list.length - 1}\n                    aria-label={`Move ${position(index)} down`}\n                    onClick={() => move(index, 1)}\n                  >\n                    <ArrowDown aria-hidden=\"true\" />\n                  </Button>\n                  <Button\n                    type=\"button\"\n                    size=\"icon-sm\"\n                    variant=\"ghost\"\n                    disabled={disabled}\n                    aria-label={`Remove ${position(index)}`}\n                    onClick={() =>\n                      write(latest.current.filter((_, at) => at !== index))\n                    }\n                  >\n                    <Trash2 aria-hidden=\"true\" />\n                  </Button>\n                </div>\n              </div>\n            ))}\n            <Button\n              type=\"button\"\n              size=\"sm\"\n              variant=\"outline\"\n              disabled={disabled}\n              aria-label={`Add to ${label}`}\n              onClick={() => write([...latest.current, records ? {} : \"\"])}\n            >\n              Add\n            </Button>\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/**\n * A prop this panel has no control for, listed rather than omitted, at the\n * top level and inside a list's items alike. A block declaring a prop the\n * panel cannot draw is still a block with that prop, and hiding it presents\n * an incomplete block as a complete one: an author would conclude the field\n * does not exist rather than that it is edited elsewhere.\n *\n * Named in plain text, not by a label: a label names a control, and one\n * pointing at nothing reads to a screen reader as a field nobody can reach.\n */\nexport function UnsupportedField({\n  prop,\n}: {\n  prop: Pick<EditableProp, \"name\" | \"schema\">;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-inspector__field\" data-unsupported=\"\">\n      <p className=\"nx-inspector__field-name\">\n        {propLabel(prop.name, prop.schema)}\n      </p>\n      <p className=\"nx-inspector__note\">\n        Not editable here ({prop.schema.type}).\n      </p>\n    </div>\n  );\n}\n\n/**\n * An `icon` prop: the chosen icon, drawn with its name and set, as one button\n * that opens a search-first picker, and a clear button. The picker offers the\n * author's recent icons first, from the host's store. The set loads when\n * the control first draws an icon or opens its picker. A chosen icon commits\n * at once, as one undo step; clearing removes the prop. An id the set no\n * longer draws is shown with a warning and kept until another is chosen.\n */\nfunction IconControl({\n  id,\n  prop,\n  disabled,\n  onCommit,\n  label,\n  services,\n}: ContentControlProps): React.JSX.Element {\n  const name = label ?? propLabel(prop.name, prop.schema);\n  const store = services?.recentIcons;\n  // One list per store, which every Icon control on screen draws: a choice\n  // made in another is here too, at once.\n  const [recent, remember] = useRecentIcons(store);\n  return (\n    <div className=\"nx-inspector__field\" data-content-control=\"icon\">\n      <Label htmlFor={id}>{name}</Label>\n      <IconField\n        id={id}\n        label={name}\n        value={\n          typeof prop.value === \"string\" && prop.value !== \"\"\n            ? prop.value\n            : null\n        }\n        disabled={disabled}\n        loadIcons={loadLucideIcons}\n        {...(store === undefined ? {} : { recentIcons: recent })}\n        onChange={next => {\n          if (next !== null) remember(next);\n          onCommit(prop.name, next ?? undefined);\n        }}\n      />\n    </div>\n  );\n}\n\n/**\n * A `textarea` prop: typed words, or, for a value restricted to one paragraph\n * with bold, italic and links (`oneParagraph`, a Text's), the rich-text\n * field held to that.\n */\nfunction TextareaControl(props: ContentControlProps): React.JSX.Element {\n  return isOneParagraphProp(props.prop.schema) ? (\n    <RichTextControl {...props} />\n  ) : (\n    <TextishControl {...props} />\n  );\n}\n\n/** Each type's control. Total over the list, so neither can gain a member alone. */\nconst CONTROLS: Readonly<Record<ContentControlType, ContentControl>> = {\n  text: TextControl,\n  textarea: TextareaControl,\n  url: TextishControl,\n  number: TextishControl,\n  checkbox: CheckboxControl,\n  select: SelectControl,\n  media: MediaControl,\n  icon: IconControl,\n  richText: RichTextControl,\n  array: ArrayControl,\n  relation: RelationControl,\n  entryField: EntryFieldControl,\n};\n\n/**\n * The control for a prop type, or `undefined` when there is none. Asked of the\n * listed names only, so an inherited name such as `constructor` resolves to\n * nothing rather than to something that is not a control.\n */\nexport function contentControlFor(type: string): ContentControl | undefined {\n  return hasContentControl(type) ? CONTROLS[type] : undefined;\n}\n\n/**\n * The code to show beside a choice's words, or `undefined` where there is none\n * or the words already are it. Compared without regard to case, so \"Section\"\n * and `section` show the tag once, not as \"Section section\".\n */\nfunction shownCode(\n  schema: PropSchema,\n  option: string,\n  words: string | undefined\n): string | undefined {\n  const written = optionCode(schema, option);\n  if (written === undefined) return undefined;\n  return words?.toLowerCase() === written.toLowerCase() ? undefined : written;\n}\n\n/**\n * What one of a select's choices writes to the page, as the block declares it\n * in its `code`, one string per option value. `undefined` where it declares\n * none for that choice.\n */\nfunction optionCode(schema: PropSchema, option: string): string | undefined {\n  const code = schema.code;\n  if (code === null || typeof code !== \"object\") return undefined;\n  const written = (code as Readonly<Record<string, unknown>>)[option];\n  return typeof written === \"string\" && written !== \"\" ? written : undefined;\n}\n","\"use client\";\n\n/**\n * A collection list's filter values: the control each field's kind is given\n * (typed, yes or no, choices, entries), and the titles of the entries a\n * filter names.\n *\n * @module list-query-filter-values\n */\nimport type { ListFilterOp } from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { X } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useStoredDraft } from \"../../stored-draft\";\n\nimport {\n  SegmentedChoice,\n  type ContentServices,\n  type LoopListField,\n} from \"./content-controls\";\nimport { takesList, type DraftFilter } from \"./list-query-model\";\nimport { RelationControl } from \"./relation-control\";\n\n/** The titles of entries a filter names, read once each through the host. */\nexport function useEntryTitles(\n  find: ContentServices[\"findEntries\"],\n  fields: readonly LoopListField[],\n  rows: readonly DraftFilter[]\n): (id: string) => string | undefined {\n  const [titles, setTitles] = React.useState<ReadonlyMap<string, string>>(\n    () => new Map()\n  );\n  // Each entry field's ids, by its collection, as text: what is asked, so a\n  // render asking the same ids reads nothing again.\n  const asked = JSON.stringify(\n    [...entryIdsByCollection(fields, rows)].map(([collection, ids]) => [\n      collection,\n      [...ids].sort(),\n    ])\n  );\n  React.useEffect(() => {\n    const wanted = JSON.parse(asked) as [string, string[]][];\n    if (find === undefined || wanted.length === 0) return;\n    let live = true;\n    for (const [collection, ids] of wanted) {\n      find({ collection, ids, limit: ids.length }).then(\n        found => {\n          if (!live) return;\n          setTitles(current => {\n            const next = new Map(current);\n            for (const entry of found) next.set(entry.id, entry.title);\n            return next;\n          });\n        },\n        () => undefined\n      );\n    }\n    return () => {\n      live = false;\n    };\n  }, [find, asked]);\n  return id => titles.get(id);\n}\n\n/** The entry ids the rows name, by the collection each field points at. */\nfunction entryIdsByCollection(\n  fields: readonly LoopListField[],\n  rows: readonly DraftFilter[]\n): Map<string, Set<string>> {\n  const byCollection = new Map<string, Set<string>>();\n  for (const row of rows) {\n    const named = entryIdsOf(row, fields);\n    if (named === undefined) continue;\n    const set = byCollection.get(named.collection) ?? new Set<string>();\n    for (const id of named.ids) set.add(id);\n    byCollection.set(named.collection, set);\n  }\n  return byCollection;\n}\n\n/**\n * The entry ids one row names and the collection they are entries of, when\n * the row filters an entry field; nothing for any other row.\n */\nfunction entryIdsOf(\n  row: DraftFilter,\n  fields: readonly LoopListField[]\n): { readonly collection: string; readonly ids: string[] } | undefined {\n  const field = fields.find(each => each.name === row.field);\n  if (field?.kind !== \"entry\" || field.relationTo === undefined) {\n    return undefined;\n  }\n  const values = Array.isArray(row.value) ? row.value : [row.value];\n  return {\n    collection: field.relationTo,\n    ids: values.filter(\n      (id): id is string => typeof id === \"string\" && id !== \"\"\n    ),\n  };\n}\n\n/** A value typed as text, committed when the field is left or Enter pressed. */\nfunction TypedValue({\n  id,\n  labelledBy,\n  kind,\n  value,\n  disabled,\n  describedBy,\n  onDone,\n}: {\n  id: string;\n  labelledBy: string;\n  kind: \"text\" | \"number\" | \"date\";\n  value: unknown;\n  disabled: boolean;\n  describedBy?: string | undefined;\n  onDone: (value: unknown) => void;\n}): React.JSX.Element {\n  const stored =\n    typeof value === \"string\" || typeof value === \"number\" ? String(value) : \"\";\n  // The inspector's own draft: an edit in progress from the first\n  // keystroke, which Save pressed from here writes first and Escape puts back.\n  const [draft, setDraft] = useStoredDraft(stored);\n  const send = () => {\n    if (draft === stored) return;\n    if (kind === \"number\") {\n      const parsed = Number(draft);\n      onDone(draft.trim() === \"\" || Number.isNaN(parsed) ? undefined : parsed);\n      return;\n    }\n    onDone(draft === \"\" ? undefined : draft);\n  };\n  return (\n    <Input\n      id={id}\n      aria-labelledby={labelledBy}\n      aria-describedby={describedBy}\n      type={kind}\n      inputMode={kind === \"number\" ? \"decimal\" : undefined}\n      value={draft}\n      disabled={disabled}\n      className=\"nx-list-filter__value\"\n      onChange={event => setDraft(event.target.value)}\n      onBlur={send}\n      onKeyDown={event => {\n        if (event.key === \"Enter\") {\n          event.preventDefault();\n          send();\n        }\n      }}\n    />\n  );\n}\n\n/** Text values for \"is any of\", one chip each, added with Enter. */\nfunction ChipValues({\n  id,\n  labelledBy,\n  values,\n  disabled,\n  onDone,\n}: {\n  id: string;\n  labelledBy: string;\n  values: readonly string[];\n  disabled: boolean;\n  onDone: (values: string[]) => void;\n}): React.JSX.Element {\n  // A value being typed is an edit in progress over the empty field, as any\n  // other field's draft is: Save pressed from here adds it first.\n  const [draft, setDraft] = useStoredDraft(\"\");\n  const add = () => {\n    const text = draft.trim();\n    if (text === \"\" || values.includes(text)) return;\n    setDraft(\"\");\n    onDone([...values, text]);\n  };\n  return (\n    <div className=\"nx-list-filter__chips\">\n      {values.map(value => (\n        <span key={value} className=\"nx-list-filter__chip\">\n          {value}\n          <button\n            type=\"button\"\n            aria-label={`Remove ${value}`}\n            disabled={disabled}\n            onClick={() => onDone(values.filter(each => each !== value))}\n          >\n            <X aria-hidden=\"true\" size={12} />\n          </button>\n        </span>\n      ))}\n      <Input\n        id={id}\n        aria-labelledby={labelledBy}\n        value={draft}\n        disabled={disabled}\n        placeholder=\"Type a value, then Enter\"\n        className=\"nx-list-filter__value\"\n        onChange={event => setDraft(event.target.value)}\n        onBlur={add}\n        onKeyDown={event => {\n          if (event.key === \"Enter\" || event.key === \",\") {\n            event.preventDefault();\n            add();\n          }\n        }}\n      />\n    </div>\n  );\n}\n\n/** A choice field's values for \"is any of\": a checklist of its choices. */\nfunction ChoiceChecklist({\n  labelledBy,\n  field,\n  values,\n  disabled,\n  onDone,\n}: {\n  labelledBy: string;\n  field: LoopListField;\n  values: readonly unknown[];\n  disabled: boolean;\n  onDone: (values: string[]) => void;\n}): React.JSX.Element {\n  const options = field.options ?? [];\n  return (\n    <div\n      className=\"nx-list-filter__checklist\"\n      role=\"group\"\n      aria-labelledby={labelledBy}\n    >\n      {options.map(option => {\n        const checked = values.includes(option.value);\n        return (\n          <label key={option.value} className=\"nx-list-filter__check\">\n            <input\n              type=\"checkbox\"\n              checked={checked}\n              disabled={disabled}\n              onChange={() =>\n                onDone(\n                  options\n                    .map(each => each.value)\n                    .filter(value =>\n                      value === option.value ? !checked : values.includes(value)\n                    )\n                )\n              }\n            />\n            {option.label}\n          </label>\n        );\n      })}\n    </div>\n  );\n}\n\n/** What every value control is given. */\nexport interface ValueProps {\n  readonly id: string;\n  readonly labelledBy: string;\n  readonly field: LoopListField;\n  readonly draft: DraftFilter & { op: ListFilterOp };\n  readonly disabled: boolean;\n  readonly invalid: boolean;\n  readonly describedBy: string | undefined;\n  readonly services: ContentServices | undefined;\n  readonly entryTitle: (id: string) => string | undefined;\n  readonly onValue: (value: unknown) => void;\n}\n\n/** The list values a row holds, for \"is any of\" and \"is none of\". */\nfunction listValues(draft: DraftFilter): readonly unknown[] {\n  return Array.isArray(draft.value) ? draft.value : [];\n}\n\n/** A yes-or-no value: Yes and No, side by side. */\nfunction BooleanValue({\n  id,\n  labelledBy,\n  draft,\n  disabled,\n  onValue,\n}: Pick<\n  ValueProps,\n  \"id\" | \"labelledBy\" | \"draft\" | \"disabled\" | \"onValue\"\n>): React.JSX.Element {\n  return (\n    <SegmentedChoice\n      id={id}\n      labelledBy={labelledBy}\n      options={[\"yes\", \"no\"]}\n      labels={[\"Yes\", \"No\"]}\n      value={draft.value === false ? \"no\" : \"yes\"}\n      disabled={disabled}\n      onChoose={option => onValue(option === \"yes\")}\n    />\n  );\n}\n\n/** A choice field's value: a menu of its choices, or a checklist of several. */\nfunction ChoiceValue(\n  props: Pick<\n    ValueProps,\n    | \"id\"\n    | \"labelledBy\"\n    | \"field\"\n    | \"draft\"\n    | \"disabled\"\n    | \"invalid\"\n    | \"describedBy\"\n    | \"onValue\"\n  >\n): React.JSX.Element {\n  const { id, labelledBy, field, draft, disabled, invalid, describedBy } =\n    props;\n  if (takesList(draft.op)) {\n    return (\n      <ChoiceChecklist\n        labelledBy={labelledBy}\n        field={field}\n        values={listValues(draft)}\n        disabled={disabled}\n        onDone={props.onValue}\n      />\n    );\n  }\n  return (\n    <Select\n      value={typeof draft.value === \"string\" ? draft.value : \"\"}\n      disabled={disabled}\n      onValueChange={props.onValue}\n    >\n      <SelectTrigger\n        id={id}\n        size=\"sm\"\n        aria-labelledby={labelledBy}\n        aria-invalid={invalid ? true : undefined}\n        aria-describedby={describedBy}\n        className=\"nx-list-filter__value\"\n      >\n        <SelectValue placeholder=\"Choose one\" />\n      </SelectTrigger>\n      <SelectContent>\n        {(field.options ?? []).map(option => (\n          <SelectItem key={option.value} value={option.value}>\n            {option.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\n/** The entries chosen for \"is any of\", each a chip that removes it. */\nfunction EntryChips({\n  ids,\n  disabled,\n  entryTitle,\n  onValue,\n}: {\n  ids: readonly string[];\n  disabled: boolean;\n  entryTitle: (id: string) => string | undefined;\n  onValue: (value: unknown) => void;\n}): React.JSX.Element {\n  return (\n    <>\n      {ids.map(entry => {\n        const title = entryTitle(entry);\n        return (\n          <span key={entry} className=\"nx-list-filter__chip\">\n            {title ?? \"An entry\"}\n            <button\n              type=\"button\"\n              aria-label={`Remove ${title ?? \"this entry\"}`}\n              disabled={disabled}\n              onClick={() => onValue(ids.filter(each => each !== entry))}\n            >\n              <X aria-hidden=\"true\" size={12} />\n            </button>\n          </span>\n        );\n      })}\n    </>\n  );\n}\n\n/**\n * An entry field's value: the entry picker, once or for each of several.\n * The picker names itself by the field and shows its own errors, so the\n * row's label and error are not handed to it.\n */\nfunction EntryValue(\n  props: Pick<\n    ValueProps,\n    | \"id\"\n    | \"field\"\n    | \"draft\"\n    | \"disabled\"\n    | \"services\"\n    | \"entryTitle\"\n    | \"onValue\"\n  >\n): React.JSX.Element {\n  const { id, field, draft, disabled, services, onValue } = props;\n  const many = takesList(draft.op);\n  const ids = many\n    ? listValues(draft).filter(\n        (value): value is string => typeof value === \"string\"\n      )\n    : [];\n  // In a class of its own, so the filter's styles reach the picker inside\n  // and take the row under the operator, or under the chips.\n  const pick = (\n    <div className=\"nx-list-filter__entry\">\n      <RelationControl\n        id={id}\n        label={many ? `Add to ${field.label}` : field.label}\n        prop={{\n          name: \"value\",\n          schema: { type: \"relation\", relationTo: field.relationTo },\n          value: many ? undefined : draft.value,\n          defaultValue: undefined,\n          supported: true,\n          options: [],\n          offered: true,\n          readOnly: false,\n        }}\n        disabled={disabled}\n        services={services}\n        onCommit={(_name, chosen) => {\n          if (!many) onValue(chosen);\n          else if (typeof chosen === \"string\" && !ids.includes(chosen)) {\n            onValue([...ids, chosen]);\n          }\n        }}\n      />\n    </div>\n  );\n  if (!many) return pick;\n  return (\n    <div className=\"nx-list-filter__entries\">\n      <EntryChips\n        ids={ids}\n        disabled={disabled}\n        entryTitle={props.entryTitle}\n        onValue={onValue}\n      />\n      {pick}\n    </div>\n  );\n}\n\n/** A typed value: text, a number or a day, or several texts as chips. */\nfunction TypedFilterValue(\n  props: Pick<\n    ValueProps,\n    | \"id\"\n    | \"labelledBy\"\n    | \"field\"\n    | \"draft\"\n    | \"disabled\"\n    | \"describedBy\"\n    | \"onValue\"\n  >\n): React.JSX.Element {\n  const { id, labelledBy, field, draft, disabled } = props;\n  if (takesList(draft.op)) {\n    return (\n      <ChipValues\n        id={id}\n        labelledBy={labelledBy}\n        values={listValues(draft).map(String)}\n        disabled={disabled}\n        onDone={props.onValue}\n      />\n    );\n  }\n  const kind =\n    field.kind === \"number\" || field.kind === \"date\" ? field.kind : \"text\";\n  return (\n    <TypedValue\n      id={id}\n      labelledBy={labelledBy}\n      kind={kind}\n      value={draft.value}\n      disabled={disabled}\n      describedBy={props.describedBy}\n      onDone={props.onValue}\n    />\n  );\n}\n\n/** The value control for each kind of field. */\nconst VALUE_CONTROLS: Readonly<\n  Record<LoopListField[\"kind\"], (props: ValueProps) => React.JSX.Element>\n> = {\n  boolean: BooleanValue,\n  choice: ChoiceValue,\n  entry: EntryValue,\n  text: TypedFilterValue,\n  number: TypedFilterValue,\n  date: TypedFilterValue,\n};\n\n/** The value control a row's field and operator call for; none for exists. */\nexport function FilterValue(props: ValueProps): React.JSX.Element | null {\n  if (props.draft.op === \"exists\") return null;\n  const Control = VALUE_CONTROLS[props.field.kind];\n  return <Control {...props} />;\n}\n","\"use client\";\n\n/**\n * The pieces every group of a collection list's query is drawn with: a\n * group's title, and the line under a field saying what is wrong with it.\n * Their own module, so the list's own groups and its custom source's groups\n * draw them from one place.\n *\n * @module list-query-parts\n */\nimport * as React from \"react\";\n\n/** The note under a field that says what is wrong with it. */\nexport function FieldError({\n  id,\n  children,\n}: {\n  id: string;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <p id={id} className=\"nx-inspector__error nx-list-query__error\">\n      {children}\n    </p>\n  );\n}\n\n/** A group's title, as the Advanced summary is titled. */\nexport function GroupTitle({\n  id,\n  children,\n}: {\n  id: string;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <h3 id={id} className=\"nx-list-query__title\">\n      {children}\n    </h3>\n  );\n}\n\n/**\n * A caution under a field: something a save warns about rather than\n * refuses, which the author cannot fix here, in the theme's warning tone.\n */\nexport function FieldCaution({\n  id,\n  children,\n}: {\n  id?: string;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <p id={id} className=\"nx-list-query__caution\">\n      {children}\n    </p>\n  );\n}\n","/**\n * A collection list's custom source as its inspector reads, words and\n * writes it: a named query a developer registered, and the inputs an author\n * gives it.\n *\n * What is JUDGED is the engine's: `judgeNamedParams` is the one judgement of\n * a list's inputs against its query, the one the save and the run use, and\n * every sentence is the engine's `NAMED_QUERY_TEXT`, so what the inspector\n * says and what a save refuses are one judgement in one set of words. This\n * module adds only what an editor needs on top of that:\n *\n * - which inputs need a value an author must give, as the group's note\n *   names them;\n * - what each input shows while it is empty, which is what an empty input\n *   means (\"Today\", \"Any venue\", its default);\n * - whether a draft of the inputs can be written yet, and the one write that\n *   makes a custom source a list's source, clearing every other part of it.\n *\n * Pure, so each rule is tested without a panel.\n *\n * @module named-query-model\n */\nimport {\n  judgeNamedParams,\n  NAMED_QUERY_TEXT,\n  namedQueryParamNeedsInput,\n  type NamedParamProblem,\n  type NamedQueryDeclaration,\n  type NamedQueryHiddenRead,\n  type NamedQueryNeed,\n  type NamedQueryParam,\n  type NamedQueryParamValue,\n  type NamedQuerySource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { dayWords } from \"./list-query-model\";\n\n/** One custom source the site offers: a registered query, without its run. */\nexport interface CustomSource {\n  readonly declaration: NamedQueryDeclaration;\n  /**\n   * The collections it reads that visitors can read nothing of, as the\n   * server judged them with the engine's `namedQueryHiddenReads`.\n   */\n  readonly readsHidden: readonly NamedQueryHiddenRead[];\n}\n\n/** The site's custom sources, as the engine looks a list's query up. */\nexport function customSourceLookup(\n  sources: readonly CustomSource[]\n): NamedQuerySource {\n  const byName = new Map(\n    sources.map(source => [source.declaration.name, source.declaration])\n  );\n  return { declarationOf: name => byName.get(name) };\n}\n\n/** A query's inputs, by key, in the order it declares them. */\nexport function inputsOf(\n  declaration: NamedQueryDeclaration\n): [string, NamedQueryParam][] {\n  return Object.entries(declaration.params ?? {});\n}\n\n/** Whether an input is picked from a list rather than typed. */\nfunction chosen(param: NamedQueryParam): boolean {\n  return (\n    param.type === \"choice\" || param.type === \"day\" || param.type === \"entry\"\n  );\n}\n\n/**\n * The inputs an author must give a value to before the query can run: those\n * required with no default, in the query's order. One with a default never\n * shows as empty, so it is never among them.\n */\nfunction neededInputs(\n  declaration: NamedQueryDeclaration\n): [string, NamedQueryParam][] {\n  return inputsOf(declaration).filter(([, param]) =>\n    namedQueryParamNeedsInput(param)\n  );\n}\n\n/** Whether picking the query must wait for an input before it is written. */\nexport function needsInput(declaration: NamedQueryDeclaration): boolean {\n  return neededInputs(declaration).length > 0;\n}\n\n/**\n * The Inputs group's note: the inputs the query needs, and, while one of\n * them is still empty, that nothing on the page changes until it is set.\n * Past two needed inputs, each needed label carries a dot instead\n * ({@link marksNeeded}), and the note says what the dot means.\n */\nexport function inputsNote(\n  declaration: NamedQueryDeclaration,\n  missing: readonly NamedParamProblem[]\n): string {\n  const needed = neededInputs(declaration);\n  const needs: NamedQueryNeed[] = needed.map(([, param]) => ({\n    label: param.label,\n    chosen: chosen(param),\n  }));\n  return NAMED_QUERY_TEXT.inputsNote(declaration.label, needs, {\n    others: inputsOf(declaration).length > needed.length,\n    waiting: missing.some(problem => problem.kind === \"missing\"),\n  });\n}\n\n/** Whether the needed inputs' labels carry a dot, as the note says past two. */\nexport function marksNeeded(declaration: NamedQueryDeclaration): boolean {\n  return neededInputs(declaration).length > 2;\n}\n\n/** A label as it sits mid-sentence: its first letter lowercased. */\nfunction inSentence(label: string): string {\n  return label.charAt(0).toLowerCase() + label.slice(1);\n}\n\n/** \"Choose a city\", for an input that needs one picked. */\nfunction choosePrompt(param: NamedQueryParam): string {\n  return `Choose a ${inSentence(param.label)}`;\n}\n\n/** \"Any venue\", for an optional input that narrows nothing while empty. */\nfunction anyPrompt(param: NamedQueryParam): string {\n  return `Any ${inSentence(param.label)}`;\n}\n\n/**\n * What an input shows while it is empty: what empty means for it. Its\n * default where it has one (\"Today\", \"30\", a choice's name), a prompt to\n * choose where it is needed, and otherwise that it narrows nothing (\"Any\n * venue\"), or the developer's own placeholder for text.\n */\nexport function emptyWords(param: NamedQueryParam): string | undefined {\n  const needed = namedQueryParamNeedsInput(param);\n  switch (param.type) {\n    case \"text\":\n      return param.placeholder ?? param.default;\n    case \"number\":\n      return param.default === undefined ? undefined : String(param.default);\n    case \"boolean\":\n      return undefined;\n    case \"choice\": {\n      if (needed) return choosePrompt(param);\n      const fallback = param.options.find(\n        option => option.value === param.default\n      );\n      return fallback?.label ?? anyPrompt(param);\n    }\n    case \"day\":\n      if (param.default === \"today\") return \"Today\";\n      if (param.default !== undefined) return dayWords(param.default);\n      return needed ? choosePrompt(param) : anyPrompt(param);\n    case \"entry\":\n      return needed ? choosePrompt(param) : anyPrompt(param);\n  }\n}\n\n/** A query's inputs as a list stores them: one literal per input set. */\nexport type StoredParams = Readonly<Record<string, NamedQueryParamValue>>;\n\n/**\n * The inputs with one set, or emptied: an emptied input (`undefined`) is\n * left out, never stored as `null`, so it reads its default. Each control\n * says when it is empty; an empty string is a value, as a choice may\n * declare `\"\"` among its options.\n */\nexport function withInput(\n  params: StoredParams,\n  key: string,\n  value: NamedQueryParamValue | undefined\n): StoredParams {\n  const next: Record<string, NamedQueryParamValue> = { ...params };\n  if (value === undefined) delete next[key];\n  else next[key] = value;\n  return next;\n}\n\n/**\n * A draft of a query's inputs judged as a save would: its problems, each by\n * input, and whether it can be written. Judged without a today of its own,\n * as the save is, so a day defaulting to today counts as set.\n */\nexport function judgedDraft(\n  declaration: NamedQueryDeclaration,\n  params: StoredParams\n): {\n  readonly problems: readonly NamedParamProblem[];\n  readonly writable: boolean;\n  /** Stored inputs the query no longer takes, which are left out. */\n  readonly unknown: readonly string[];\n} {\n  const judged = judgeNamedParams(declaration, params);\n  return {\n    problems: judged.problems,\n    writable: judged.problems.length === 0,\n    unknown: judged.unknown,\n  };\n}\n\n/**\n * The one write that makes a custom source the list's source: its name and\n * inputs, with the collection, the related source, the filters and the sort\n * removed in the same edit, so it is one undo step and never stored beside\n * another source. Pages go too: a custom source's list is not split into\n * pages yet, which its save refuses. No inputs set stores none.\n */\nexport function namedSourceChanges(\n  name: string,\n  params: StoredParams\n): Record<string, unknown> {\n  return {\n    namedQuery: Object.keys(params).length === 0 ? { name } : { name, params },\n    collection: undefined,\n    relation: undefined,\n    filters: undefined,\n    sort: undefined,\n    paginate: undefined,\n  };\n}\n\n/** The inputs a stored list holds, as the note under a removed query lists them. */\nexport function keptInputs(\n  params: StoredParams\n): (readonly [string, NamedQueryParamValue])[] {\n  return Object.entries(params);\n}\n\n/** What a list of custom sources is searched by: its name and its line. */\nexport function sourceSearchText(declaration: NamedQueryDeclaration): string {\n  return declaration.description === undefined\n    ? declaration.label\n    : `${declaration.label} ${declaration.description}`;\n}\n","/**\n * What a collection list's query controls read once and share: the props the\n * query is stored in, the fields a list may offer, the problems each part\n * shows, the relations a list can read, and the site's custom sources.\n *\n * @module list-query-reading\n */\nimport {\n  COLLECTION_LIST_TYPE,\n  LIST_ENTRY_SLOT,\n  listQueryIssues,\n  locateNode,\n  outerListOf,\n  readListQuery,\n  type BindingFieldShape,\n  type BlockDocument,\n  type BlockNode,\n  type ListFieldKind,\n  type ListFieldSource,\n  type ListQuery,\n  type ListRelation,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { EditableProp } from \"../inspector\";\n\nimport {\n  useLoopCollections,\n  type LoopCollections,\n} from \"./collection-loop-controls\";\nimport type {\n  ContentServices,\n  LoopCollection,\n  LoopListField,\n} from \"./content-controls\";\nimport { customSourceLookup, type CustomSource } from \"./named-query-model\";\n\n/** The props a list's query is stored in, in the order the group draws them. */\nexport const LIST_QUERY_PROPS = [\n  \"collection\",\n  \"relation\",\n  \"filters\",\n  \"sort\",\n  \"limit\",\n  \"offset\",\n  \"namedQuery\",\n  \"paginate\",\n] as const;\n\n/** What the group is drawn with: the Content tab's group context. */\nexport interface ListQueryFieldProps {\n  readonly props: readonly EditableProp[];\n  readonly writable: (name: string) => boolean;\n  readonly services: ContentServices | undefined;\n  readonly onCommitMany: (\n    changes: Readonly<Record<string, unknown>>\n  ) => BlockDocument | null | void;\n  /** The document the list is in, for the list around it and its judgement. */\n  readonly document: BlockDocument;\n  readonly nodeId: string;\n  /** Whether the canvas draws this list's empty state. */\n  readonly showsEmpty: boolean;\n  /**\n   * The count of the latest ask, from the list's canvas note, to fix its\n   * sort: each new count takes the author to its first sort row.\n   */\n  readonly sortFieldAsked?: number | undefined;\n  /** Draw its empty state, or its entries; absent where nothing can. */\n  readonly onShowEmpty?: ((empty: boolean) => void) | undefined;\n  /**\n   * Tag the list on the canvas while a new source waits for an input, with\n   * what it still shows (\"Still showing Events\"); `undefined` clears it.\n   */\n  readonly onStillShowing?: ((words: string | undefined) => void) | undefined;\n}\n\n/**\n * A collection's fields in the engine's terms, for judging a list against:\n * the public's fields as the host read them for the save's own judgement,\n * so what is said here is what a save would refuse. A host that names none\n * is judged by what it offers, which a save may judge more widely.\n */\nexport function fieldSourceOf(\n  collections: readonly LoopCollection[]\n): ListFieldSource {\n  const bySlug = new Map(collections.map(each => [each.slug, each]));\n  return {\n    fieldsOf: slug => {\n      const found = bySlug.get(slug);\n      if (found === undefined) return undefined;\n      const readable: BindingFieldShape[] = [\n        ...(found.readable ?? offeredShapes(found)),\n      ];\n      return {\n        declared: new Set([\n          ...(found.declared ?? []),\n          ...readable.map(shape => shape.name),\n        ]),\n        readable,\n        // The name the Source menu shows, for the engine's words.\n        label: found.label,\n      };\n    },\n  };\n}\n\n/**\n * A field type of each list kind, the one the engine's `listFieldKind` reads\n * back as that kind: a kind's own name is not always a field type (a choice\n * is a `select`, a yes/no a `checkbox`), and a type the engine does not know\n * has no kind, so its filters and sorts would be refused.\n */\nconst FIELD_TYPE_OF_KIND: Readonly<Record<ListFieldKind, string>> = {\n  text: \"text\",\n  number: \"number\",\n  date: \"date\",\n  boolean: \"checkbox\",\n  choice: \"select\",\n  entry: \"relationship\",\n};\n\n/** The shapes of what a collection offers, for a host naming no others. */\nfunction offeredShapes(found: LoopCollection): BindingFieldShape[] {\n  return [\n    { name: \"id\", type: \"text\" },\n    ...found.fields.map(field => ({\n      name: field.name,\n      type: FIELD_TYPE_OF_KIND[field.kind],\n      ...(field.relationTo === undefined\n        ? {}\n        : { relationTo: field.relationTo }),\n    })),\n    ...(found.relations ?? []).map(relation => ({\n      name: relation.field,\n      type: \"relationship\",\n      hasMany: true,\n      relationTo: relation.collection,\n    })),\n  ];\n}\n\n/** The problems the engine finds with one list, as a save would. */\nexport type Issues = ReturnType<typeof listQueryIssues>;\n\n/** The issues about one prop of the list, by the path's last step. */\nexport function issuesAt(issues: Issues, props: readonly string[]): string[] {\n  return issues\n    .filter(issue => props.some(prop => issue.path.endsWith(`/props/${prop}`)))\n    .map(issue => issue.message);\n}\n\n/**\n * The engine's judgement of one part of a list on its own: the list with\n * only that part, inside the same surroundings, so a row's own problem is\n * said beside that row.\n */\nexport function partIssues(\n  node: BlockNode,\n  part: Readonly<Record<string, unknown>>,\n  fields: ListFieldSource | undefined\n): Issues {\n  const props = node.props;\n  return listQueryIssues(\n    [\n      {\n        ...node,\n        props: { collection: props.collection, ...part },\n        slots: {},\n      },\n    ],\n    fields === undefined ? {} : { fields }\n  ).filter(issue => issue.severity === \"error\");\n}\n\n/** A relation as the menu offers it, of the page's entry or the outer item. */\nexport interface RelatedSource {\n  readonly of: ListRelation[\"of\"];\n  readonly field: string;\n  readonly collection: string;\n  /** \"This post's categories\", \"Each category's featured posts\". */\n  readonly words: string;\n  /** What the relation holds, in words: \"categories\". */\n  readonly what: string;\n}\n\n/** The words for a relation source, by whose relation it is. */\nfunction relatedWords(\n  of: ListRelation[\"of\"],\n  owner: LoopCollection | undefined,\n  relationLabel: string\n): string {\n  const one = (owner?.singular ?? owner?.label ?? \"entry\").toLowerCase();\n  const what = relationLabel.toLowerCase();\n  return of === \"entry\" ? `This ${one}'s ${what}` : `Each ${one}'s ${what}`;\n}\n\n/** The related sources a list may show where it sits, with their headings. */\nexport interface Related {\n  readonly entry: readonly RelatedSource[];\n  readonly item: readonly RelatedSource[];\n  /** \"Related to this post\", over the entry's relations. */\n  readonly entryHeading: string;\n  /** \"Related to each category\", over the outer item's relations. */\n  readonly itemHeading: string;\n  /**\n   * Whether the nearest list around this one holds it in its empty state,\n   * which is drawn only when that list has no entries, so with none to\n   * relate to.\n   */\n  readonly inEmptyState?: boolean;\n}\n\n/** Whether the nearest list around `id` holds it anywhere but per entry. */\nfunction inListEmptyState(nodes: BlockNode[], id: string): boolean {\n  let at = locateNode(nodes, id);\n  // Bounded by the document's depth: each step moves one parent out.\n  while (at?.parent !== undefined) {\n    const parent = at.parent;\n    if (parent.type === COLLECTION_LIST_TYPE) {\n      return at.slot !== LIST_ENTRY_SLOT;\n    }\n    at = locateNode(nodes, parent.id);\n  }\n  return false;\n}\n\n/** The related sources a list may show where it sits. */\nfunction relatedSources(\n  collections: readonly LoopCollection[],\n  entryCollection: string | null | undefined,\n  outer: ListQuery | undefined\n): Related {\n  const ownerOf = (slug: string | null | undefined) =>\n    collections.find(each => each.slug === slug);\n  const one = (owner: LoopCollection | undefined) =>\n    (owner?.singular ?? owner?.label ?? \"entry\").toLowerCase();\n  const sources = (\n    of: ListRelation[\"of\"],\n    owner: LoopCollection | undefined\n  ): RelatedSource[] =>\n    (owner?.relations ?? []).map(relation => ({\n      of,\n      field: relation.field,\n      collection: relation.collection,\n      words: relatedWords(of, owner, relation.label),\n      what: relation.label.toLowerCase(),\n    }));\n  const entryOwner = ownerOf(entryCollection);\n  // Related entries go one level deep: a list inside a list that already\n  // shows related entries is offered none of its own.\n  const itemOwner =\n    outer === undefined || outer.relation !== undefined\n      ? undefined\n      : ownerOf(outer.collection);\n  return {\n    entry: sources(\"entry\", entryOwner),\n    item: sources(\"item\", itemOwner),\n    entryHeading: `Related to this ${one(entryOwner)}`,\n    itemHeading: `Related to each ${one(itemOwner)}`,\n  };\n}\n\n/** A list's query as the group reads it: stored, offered and judged. */\nexport interface ListQueryReading {\n  readonly values: Readonly<Record<string, unknown>>;\n  readonly query: ListQuery;\n  readonly listed: LoopCollections | undefined;\n  /** The site's custom sources, none while they are read or where none can be. */\n  readonly customs: readonly CustomSource[];\n  /** The same, or `undefined` until they are read, so \"not set up\" waits. */\n  readonly customsRead: readonly CustomSource[] | undefined;\n  /**\n   * Whether the site's collections could be listed: where they could not,\n   * the Source menu offers its custom sources alone.\n   */\n  readonly collectionsOffered: boolean;\n  readonly collections: readonly LoopCollection[];\n  readonly fieldSource: ListFieldSource | undefined;\n  readonly issues: Issues;\n  readonly related: Related;\n  readonly fields: readonly LoopListField[];\n}\n\n/**\n * The list's query, read by the engine from its props; the host's\n * collections; and the engine's judgement of the list where it sits, the\n * collection its document is an entry of and the list around it included.\n */\nexport function useListQueryReading(\n  props: readonly EditableProp[],\n  services: ContentServices | undefined,\n  document: BlockDocument,\n  nodeId: string\n): ListQueryReading {\n  const values = React.useMemo(\n    () => Object.fromEntries(props.map(prop => [prop.name, prop.value])),\n    [props]\n  );\n  const { query } = readListQuery(values);\n  const listed = useLoopCollections(services?.listLoopCollections);\n  const customs = useCustomSources(services?.listCustomSources);\n  const collections = listed?.kind === \"ready\" ? listed.collections : [];\n  const fieldSource = React.useMemo(\n    () =>\n      listed?.kind === \"ready\" ? fieldSourceOf(listed.collections) : undefined,\n    [listed]\n  );\n  const entryCollection = services?.entryCollection;\n  // A custom source is judged against the site's queries once they are\n  // read: before that, by its shape alone, so a query not yet listed is\n  // never called unknown.\n  const namedQueries = React.useMemo(\n    () => (customs === undefined ? undefined : customSourceLookup(customs)),\n    [customs]\n  );\n  const issues = React.useMemo(\n    () =>\n      listQueryIssues(document.nodes, {\n        ...(fieldSource === undefined ? {} : { fields: fieldSource }),\n        ...(entryCollection === undefined ? {} : { entryCollection }),\n        ...(namedQueries === undefined ? {} : { namedQueries }),\n        // So a component's or a Layout region's list is told at once that it\n        // can't be split into pages, as its save would be.\n        documentKind: document.kind,\n      }).filter(issue => issue.nodeId === nodeId && issue.severity === \"error\"),\n    [document, nodeId, fieldSource, entryCollection, namedQueries]\n  );\n  // The list whose entry is this one's item, as the save judges it: never\n  // one whose empty state this list sits in.\n  const outerNode = outerListOf(document.nodes, nodeId);\n  const outer =\n    outerNode === undefined ? undefined : readListQuery(outerNode.props).query;\n  return {\n    values,\n    query,\n    listed,\n    customs: customs ?? [],\n    collectionsOffered: listed?.kind === \"ready\",\n    // A host lending no custom sources has none: a stored one is not set up.\n    customsRead: services?.listCustomSources === undefined ? [] : customs,\n    collections,\n    fieldSource,\n    issues,\n    related: {\n      ...relatedSources(collections, entryCollection, outer),\n      inEmptyState: inListEmptyState(document.nodes, nodeId),\n    },\n    fields:\n      collections.find(each => each.slug === query.collection)?.fields ?? [],\n  };\n}\n\n/** The words a related source is shown in, for the line under Filters. */\nexport function relatedShownOf(\n  query: ListQuery,\n  related: Related\n): string | undefined {\n  const relation = query.relation;\n  if (relation === undefined) return undefined;\n  return [...related.entry, ...related.item].find(\n    each => each.of === relation.of && each.field === relation.field\n  )?.words;\n}\n\n/** How long the inspector waits before asking again for custom sources. */\nconst SOURCES_RETRY_MS = 2000;\n/** The longest it waits between asks. */\nconst SOURCES_RETRY_MOST_MS = 60_000;\n\n/** The host's custom sources, read once for every list asking while it runs. */\ntype ListCustomSources = NonNullable<ContentServices[\"listCustomSources\"]>;\n\n/**\n * The read in flight, per host function, shared only while it runs, for the\n * reason the collections' read is (`collection-loop-controls`): an answer\n * is one signed-in author's.\n */\nconst customsInFlight = new WeakMap<\n  ListCustomSources,\n  Promise<readonly CustomSource[]>\n>();\n\n/** The host's custom sources, one read shared by every list asking at once. */\nfunction readCustomSources(\n  list: ListCustomSources\n): Promise<readonly CustomSource[]> {\n  const held = customsInFlight.get(list);\n  if (held !== undefined) return held;\n  const answer = list();\n  customsInFlight.set(list, answer);\n  const settle = () => {\n    if (customsInFlight.get(list) === answer) customsInFlight.delete(list);\n  };\n  answer.then(settle, settle);\n  return answer;\n}\n\n/**\n * The site's custom sources, or `undefined` while they are read, where the\n * host lends no way to list them, or where the read failed: the Source menu\n * then offers collections and related entries, as it did before there were\n * custom sources.\n */\nexport function useCustomSources(\n  list: ListCustomSources | undefined\n): readonly CustomSource[] | undefined {\n  const [found, setFound] = React.useState<{\n    readonly list: ListCustomSources;\n    readonly sources: readonly CustomSource[];\n  }>();\n  // Each failed read is asked again, after a wait that doubles to a cap, so\n  // one failed request never leaves the menu without its custom sources.\n  const [failures, setFailures] = React.useState(0);\n  React.useEffect(() => {\n    if (list === undefined) return;\n    let live = true;\n    let retry: ReturnType<typeof setTimeout> | undefined;\n    readCustomSources(list).then(\n      sources => {\n        if (live) setFound({ list, sources });\n      },\n      () => {\n        if (!live) return;\n        retry = setTimeout(\n          () => setFailures(count => count + 1),\n          Math.min(SOURCES_RETRY_MS * 2 ** failures, SOURCES_RETRY_MOST_MS)\n        );\n      }\n    );\n    return () => {\n      live = false;\n      if (retry !== undefined) clearTimeout(retry);\n    };\n  }, [list, failures]);\n  return list !== undefined && found?.list === list ? found.sources : undefined;\n}\n","\"use client\";\n\n/**\n * A row that reads as one sentence and opens in place into its controls, and\n * the state of a list of them: what a list's filters and a block's\n * visibility conditions are both edited with, so the two read and behave as\n * one control.\n *\n * @module sentence-row\n */\nimport { Button } from \"@nextlyhq/ui\";\nimport { ChevronDown, ChevronRight, X } from \"lucide-react\";\nimport * as React from \"react\";\n\n/** A row as one sentence, in its three parts. */\nexport interface RowSentence {\n  readonly field: string;\n  readonly operator: string;\n  readonly value: string;\n}\n\n/** What a sentence row is drawn with, closed or open. */\nexport interface SentenceRowProps {\n  readonly id: string;\n  /** What the row is called in its buttons' names: \"filter\", \"condition\". */\n  readonly noun: string;\n  readonly open: boolean;\n  readonly disabled: boolean;\n  readonly sentence: RowSentence;\n  /** The sentence as one line, for the row's title and accessible name. */\n  readonly line: string;\n  readonly problem: string | undefined;\n  /** The row's field picker, labelled by `labelId`. */\n  readonly field: (labelId: string) => React.ReactNode;\n  /** The operator and value, once a field is chosen; `null` before. */\n  readonly body: (labelId: string, errorId: string) => React.ReactNode;\n  readonly onOpen: () => void;\n  readonly onClose: () => void;\n  readonly onRemove: () => void;\n}\n\n/** The button that removes a row, named by its sentence. */\nfunction RemoveRow({\n  noun,\n  line,\n  disabled,\n  onRemove,\n}: {\n  noun: string;\n  line: string;\n  disabled: boolean;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <Button\n      type=\"button\"\n      size=\"icon-sm\"\n      variant=\"ghost\"\n      aria-label={`Remove ${noun}: ${line}`}\n      disabled={disabled}\n      onClick={onRemove}\n    >\n      <X aria-hidden=\"true\" size={14} />\n    </Button>\n  );\n}\n\n/** A refused row's message, under it. */\nfunction RowError({\n  id,\n  problem,\n}: {\n  id: string;\n  problem: string | undefined;\n}): React.JSX.Element | null {\n  return problem === undefined ? null : (\n    <p id={id} className=\"nx-inspector__error nx-list-query__error\">\n      {problem}\n    </p>\n  );\n}\n\n/** A closed row: its sentence as one button, and its remove button. */\nfunction ClosedRow({\n  props,\n  lineRef,\n}: {\n  props: SentenceRowProps;\n  lineRef: React.RefObject<HTMLButtonElement | null>;\n}): React.JSX.Element {\n  const { sentence, line, problem } = props;\n  const errorId = `${props.id}-error`;\n  return (\n    <li\n      className=\"nx-list-filter\"\n      data-invalid={problem === undefined ? undefined : \"\"}\n    >\n      <button\n        ref={lineRef}\n        type=\"button\"\n        className=\"nx-list-filter__line\"\n        aria-expanded={false}\n        aria-describedby={problem === undefined ? undefined : errorId}\n        title={line}\n        disabled={props.disabled}\n        onClick={props.onOpen}\n      >\n        <ChevronRight aria-hidden=\"true\" size={14} />\n        <span className=\"nx-list-filter__sentence\">\n          <span className=\"nx-list-filter__field\">{sentence.field}</span>{\" \"}\n          <span className=\"nx-list-filter__op\">{sentence.operator}</span>{\" \"}\n          <span\n            className=\"nx-list-filter__said\"\n            data-missing={sentence.value === \"no value\" ? \"\" : undefined}\n          >\n            {sentence.value}\n          </span>\n        </span>\n      </button>\n      <RemoveRow\n        noun={props.noun}\n        line={line}\n        disabled={props.disabled}\n        onRemove={props.onRemove}\n      />\n      <RowError id={errorId} problem={problem} />\n    </li>\n  );\n}\n\n/** An open row: its field, the operator and value, and its error. */\nfunction OpenRow({\n  props,\n  onClose,\n}: {\n  props: SentenceRowProps;\n  onClose: () => void;\n}): React.JSX.Element {\n  const { id, noun, line, problem, disabled } = props;\n  const labelId = `${id}-label`;\n  const errorId = `${id}-error`;\n  const capital = noun.charAt(0).toUpperCase() + noun.slice(1);\n  return (\n    <li\n      className=\"nx-list-filter\"\n      data-open=\"\"\n      data-invalid={problem === undefined ? undefined : \"\"}\n      onKeyDown={event => {\n        // Escape closes the row, unless a menu inside it is taking it.\n        if (event.key !== \"Escape\" || event.defaultPrevented) return;\n        event.preventDefault();\n        onClose();\n      }}\n    >\n      <span id={labelId} className=\"nx-sr-only\">\n        {`${capital} ${line}`}\n      </span>\n      <div className=\"nx-list-filter__head\">\n        <Button\n          type=\"button\"\n          size=\"icon-sm\"\n          variant=\"ghost\"\n          aria-expanded={true}\n          aria-label={`Close ${noun}: ${line}`}\n          onClick={onClose}\n        >\n          <ChevronDown aria-hidden=\"true\" size={14} />\n        </Button>\n        {props.field(labelId)}\n        <RemoveRow\n          noun={noun}\n          line={line}\n          disabled={disabled}\n          onRemove={props.onRemove}\n        />\n      </div>\n      {props.body(labelId, errorId)}\n      <RowError id={errorId} problem={problem} />\n    </li>\n  );\n}\n\n/** One row: its sentence, opening in place into its controls. */\nexport function SentenceRow(props: SentenceRowProps): React.JSX.Element {\n  const lineRef = React.useRef<HTMLButtonElement>(null);\n  if (!props.open) return <ClosedRow props={props} lineRef={lineRef} />;\n  return (\n    <OpenRow\n      props={props}\n      onClose={() => {\n        props.onClose();\n        // Back on the line it opened from, so the keyboard keeps its place.\n        requestAnimationFrame(() => lineRef.current?.focus());\n      }}\n    />\n  );\n}\n\n/** A row as it stands: what is stored, or the draft over it. */\nexport interface ShownRow<Draft> {\n  readonly key: string;\n  /** The stored row it edits, or `undefined` for a new one. */\n  readonly index: number | undefined;\n  readonly draft: Draft;\n  /** Whether this is a draft that differs from what is stored. */\n  readonly drafted: boolean;\n}\n\n/** The rows of a list being edited, and how a row changes, closes or goes. */\nexport interface SentenceRows<Draft> {\n  readonly rows: readonly ShownRow<Draft>[];\n  readonly openKey: string | null;\n  readonly setOpenKey: (key: string | null) => void;\n  /** Add an empty row, opened. */\n  readonly add: () => void;\n  /**\n   * A row's draft changed: stored at `index` when it completed, which the\n   * caller writes, else kept as the row's draft.\n   */\n  readonly change: (\n    row: ShownRow<Draft>,\n    draft: Draft,\n    completed: boolean\n  ) => number;\n  /** Remove a row: a draft goes, a stored row's index is answered to remove. */\n  readonly remove: (row: ShownRow<Draft>) => number | undefined;\n}\n\n/** What the rows last asked of the stored list: a row written or removed. */\ntype RowEdit =\n  | { readonly kind: \"write\"; readonly index: number }\n  | { readonly kind: \"remove\"; readonly index: number };\n\n/**\n * The drafts over the stored rows after the stored list changed, by what\n * changed it. A row written keeps every other draft where it is; a row removed\n * moves the drafts after it up one. A change these rows didn't make, such as\n * an undo, leaves no draft standing, since nothing says which row is which.\n */\nfunction draftsAfter<Draft>(\n  drafts: ReadonlyMap<number, Draft>,\n  edit: RowEdit | undefined\n): ReadonlyMap<number, Draft> {\n  if (edit === undefined) return new Map();\n  const next = new Map<number, Draft>();\n  for (const [index, draft] of drafts) {\n    if (index === edit.index) continue;\n    next.set(\n      edit.kind === \"remove\" && index > edit.index ? index - 1 : index,\n      draft\n    );\n  }\n  return next;\n}\n\n/**\n * The rows of a stored list being edited: each stored row, with any draft\n * over it, then the new rows not yet complete. A draft stays with its row\n * when another row is written or removed through these rows, and goes once\n * its own row is written, since the row then holds the draft; a change made\n * elsewhere, such as an undo, clears them, as nothing says which row is\n * which.\n */\nexport function useSentenceRows<Stored, Draft>(\n  stored: readonly Stored[],\n  toDraft: (stored: Stored) => Draft,\n  empty: Draft\n): SentenceRows<Draft> {\n  // Drafts over stored rows, by index, with the stored list they were made\n  // over: a list that has since changed is read through `draftsAfter`.\n  const [overStored, setOverStored] = React.useState<{\n    readonly basis: string;\n    readonly drafts: ReadonlyMap<number, Draft>;\n  }>(() => ({ basis: JSON.stringify(stored), drafts: new Map() }));\n  const [added, setAdded] = React.useState<\n    ReadonlyArray<{ key: string; draft: Draft }>\n  >([]);\n  const [openKey, setOpenKey] = React.useState<string | null>(null);\n  // The edit these rows last asked for, with the stored list it was asked\n  // over, so it is read only for the change it makes.\n  const lastEdit = React.useRef<\n    { readonly edit: RowEdit; readonly over: string } | undefined\n  >(undefined);\n  const storedText = JSON.stringify(stored);\n  const current =\n    overStored.basis === storedText\n      ? overStored.drafts\n      : draftsAfter(overStored.drafts, lastEdit.current?.edit);\n  // Settled once the change is drawn, so the edit is read for it alone.\n  React.useEffect(() => {\n    // Read here, not in the updater: React may run that on the next render,\n    // when the line below has already spent the edit.\n    const edit = lastEdit.current?.edit;\n    setOverStored(state =>\n      state.basis === storedText\n        ? state\n        : { basis: storedText, drafts: draftsAfter(state.drafts, edit) }\n    );\n    lastEdit.current = undefined;\n  }, [storedText]);\n  // An edit that changed nothing, a row written back to what it held, is\n  // spent once drawn, so a later change made elsewhere isn't read as it.\n  React.useEffect(() => {\n    if (lastEdit.current?.over === storedText) lastEdit.current = undefined;\n  });\n  const setDraft = (index: number, draft: Draft | undefined): void => {\n    setOverStored(() => {\n      const drafts = new Map(current);\n      if (draft === undefined) drafts.delete(index);\n      else drafts.set(index, draft);\n      return { basis: storedText, drafts };\n    });\n  };\n  const nextKey = React.useRef(0);\n  const rows: ShownRow<Draft>[] = [\n    ...stored.map((each, index) => {\n      const draft = current.get(index);\n      return {\n        key: `stored:${String(index)}`,\n        index,\n        draft: draft ?? toDraft(each),\n        drafted: draft !== undefined,\n      };\n    }),\n    ...added.map(each => ({\n      key: each.key,\n      index: undefined,\n      draft: each.draft,\n      drafted: true,\n    })),\n  ];\n  return {\n    rows,\n    openKey,\n    setOpenKey,\n    add: () => {\n      nextKey.current += 1;\n      const key = `new:${String(nextKey.current)}`;\n      setAdded(current => [...current, { key, draft: empty }]);\n      // A new row opens already open, its field menu with it.\n      setOpenKey(key);\n    },\n    change: (row, draft, completed) => {\n      const index = row.index ?? stored.length;\n      if (completed) {\n        // The caller writes this row next; every other draft stays put.\n        lastEdit.current = { edit: { kind: \"write\", index }, over: storedText };\n        if (row.index !== undefined) setDraft(row.index, undefined);\n        if (row.index === undefined) {\n          setAdded(current => current.filter(each => each.key !== row.key));\n          if (openKey === row.key) setOpenKey(`stored:${String(index)}`);\n        }\n        return index;\n      }\n      if (row.index === undefined) {\n        setAdded(current =>\n          current.map(each =>\n            each.key === row.key ? { ...each, draft } : each\n          )\n        );\n      } else {\n        setDraft(row.index, draft);\n      }\n      return index;\n    },\n    remove: row => {\n      if (openKey === row.key) setOpenKey(null);\n      if (row.index === undefined) {\n        setAdded(current => current.filter(each => each.key !== row.key));\n      } else {\n        // The caller removes this row next; the rows after it move up.\n        lastEdit.current = {\n          edit: { kind: \"remove\", index: row.index },\n          over: storedText,\n        };\n        setDraft(row.index, undefined);\n      }\n      return row.index;\n    },\n  };\n}\n","\"use client\";\n\n/**\n * A collection list's Filters: the menu of fields a filter or sort may name,\n * each filter row with its field, operator and value, the group that holds\n * them, and the note when a list holds as many rows as it may.\n *\n * @module list-query-filters\n */\nimport {\n  LIST_MAX_FILTERS,\n  type BlockNode,\n  type ListFieldSource,\n  type ListFilter,\n  type ListQuery,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { ListedChoice } from \"../../choice-list\";\n\nimport { LoopPicker, type PickerList } from \"./collection-loop-controls\";\nimport type { ContentServices, LoopListField } from \"./content-controls\";\nimport { FilterValue, useEntryTitles } from \"./list-query-filter-values\";\nimport {\n  completedFilter,\n  filterLine,\n  filterSentence,\n  operatorOf,\n  OPERATORS,\n  valueFor,\n  withFilter,\n  type DraftFilter,\n  type FilterSentence,\n} from \"./list-query-model\";\nimport { FieldError, GroupTitle } from \"./list-query-parts\";\nimport { partIssues } from \"./list-query-reading\";\nimport {\n  SentenceRow,\n  useSentenceRows,\n  type ShownRow as ShownSentenceRow,\n} from \"./sentence-row\";\n\n/**\n * A field a menu offers: one a list filters by, or one a condition can only\n * ask has a value, which names its own kind.\n */\nexport interface OfferedField {\n  readonly name: string;\n  readonly label: string;\n  readonly kind: LoopListField[\"kind\"] | \"other\";\n  /** What the menu calls its kind, for a field of kind `other`. */\n  readonly kindWords?: string;\n}\n\n/** One field of the field menu, with its kind on the right. */\nexport interface FieldChoice<F extends OfferedField = LoopListField>\n  extends ListedChoice {\n  readonly field: F;\n}\n\n/** What a field's kind is called on the right of the menu. */\nconst KIND_WORDS: Readonly<Record<LoopListField[\"kind\"], string>> = {\n  text: \"Text\",\n  number: \"Number\",\n  date: \"Date\",\n  choice: \"Choice\",\n  boolean: \"Yes or no\",\n  entry: \"Entry\",\n};\n\n/** The field menu's row: the field, and the kind of value it holds. */\nexport function fieldRow(choice: FieldChoice<OfferedField>): React.ReactNode {\n  const { kind, kindWords } = choice.field;\n  return (\n    <span className=\"nx-list-query__field-row\">\n      <span>{choice.label}</span>\n      <span className=\"nx-list-query__field-kind\">\n        {kindWords ?? (kind === \"other\" ? \"\" : KIND_WORDS[kind])}\n      </span>\n    </span>\n  );\n}\n\n/** A field menu's list: the fields, each with its kind on the right. */\nexport function fieldList<F extends OfferedField>(\n  fields: readonly F[],\n  currentKey: string,\n  label: string\n): PickerList<FieldChoice<F>> {\n  return {\n    choices: fields.map(each => ({\n      key: each.name,\n      label: each.label,\n      field: each,\n    })),\n    currentKey,\n    label,\n    searchLabel: \"Search fields\",\n    noMatch: \"No field matches.\",\n    searchFrom: 1,\n    renderChoice: fieldRow,\n  };\n}\n\n/** The line under every field menu: what it leaves out, said once. */\nexport const PUBLIC_ONLY: React.JSX.Element = (\n  <p className=\"nx-list-query__menu-foot\">\n    Only fields visitors can see are listed.\n  </p>\n);\n\n/** A filter row as it stands: what is stored, or the draft over it. */\ntype ShownRow = ShownSentenceRow<DraftFilter>;\n\n/** What a filter row is drawn with, closed or open. */\ninterface FilterRowProps {\n  readonly id: string;\n  readonly row: ShownRow;\n  readonly fields: readonly LoopListField[];\n  readonly open: boolean;\n  readonly disabled: boolean;\n  /** What the engine finds wrong with the stored row, if anything. */\n  readonly storedProblem: string | undefined;\n  readonly services: ContentServices | undefined;\n  readonly entryTitle: (id: string) => string | undefined;\n  readonly onOpen: () => void;\n  readonly onClose: () => void;\n  readonly onChange: (draft: DraftFilter) => void;\n  readonly onRemove: () => void;\n}\n\n/** A row as it reads: its field, its sentence, and what is wrong with it. */\ninterface RowReading {\n  readonly field: LoopListField | undefined;\n  readonly sentence: FilterSentence;\n  readonly line: string;\n  readonly problem: string | undefined;\n  readonly errorId: string;\n}\n\n/**\n * How a row reads. A row with no field yet only asks for one; a stored row\n * the engine refuses says why; a draft says what it lacks.\n */\nfunction readRow(props: FilterRowProps): RowReading {\n  const { row, fields, storedProblem, entryTitle } = props;\n  const field = fields.find(each => each.name === row.draft.field);\n  const sentence = filterSentence(row.draft, field, entryTitle);\n  const completed = completedFilter(row.draft, field);\n  const missing =\n    row.draft.field !== undefined && \"missing\" in completed\n      ? completed.missing\n      : undefined;\n  return {\n    field,\n    sentence,\n    line: filterLine(sentence),\n    problem: storedProblem ?? missing,\n    errorId: `${props.id}-error`,\n  };\n}\n\n/** What a row's field picker shows for its stored or chosen field. */\nfunction fieldShown(\n  name: string | undefined,\n  field: LoopListField | undefined\n): { words: string; state: \"value\" | \"prompt\" | \"unknown\" } {\n  if (name === undefined) return { words: \"Choose a field\", state: \"prompt\" };\n  return field === undefined\n    ? { words: `${name} (removed)`, state: \"unknown\" }\n    : { words: field.label, state: \"value\" };\n}\n\n/** A row's field: picking one starts it on that field's first operator. */\nfunction FilterFieldPicker({\n  id,\n  labelId,\n  props,\n  field,\n}: {\n  id: string;\n  labelId: string;\n  props: FilterRowProps;\n  field: LoopListField | undefined;\n}): React.JSX.Element {\n  const { row, fields, disabled, onChange } = props;\n  const shown = fieldShown(row.draft.field, field);\n  return (\n    <LoopPicker\n      id={id}\n      labelId={labelId}\n      value={shown}\n      disabled={disabled}\n      list={fieldList(fields, row.draft.field ?? \"\", \"Fields to filter by\")}\n      around={{ below: PUBLIC_ONLY }}\n      defaultOpen={row.draft.field === undefined}\n      onPick={choice => {\n        const first = OPERATORS[choice.field.kind][0];\n        if (choice.field.name === row.draft.field || first === undefined)\n          return;\n        onChange({\n          field: choice.field.name,\n          op: first.op,\n          value: valueFor(choice.field.kind, first, undefined),\n        });\n      }}\n    />\n  );\n}\n\n/** A row's operator, from those its field's kind offers. */\nfunction OperatorPicker({\n  id,\n  field,\n  draft,\n  disabled,\n  onChange,\n}: {\n  id: string;\n  field: LoopListField;\n  draft: DraftFilter;\n  disabled: boolean;\n  onChange: (draft: DraftFilter) => void;\n}): React.JSX.Element {\n  const operators = OPERATORS[field.kind];\n  const operator =\n    draft.op === undefined\n      ? undefined\n      : operatorOf(field.kind, draft.op, draft.value);\n  return (\n    <Select\n      value={operator?.key ?? \"\"}\n      disabled={disabled}\n      onValueChange={key => {\n        const choice = operators.find(each => each.key === key);\n        if (choice === undefined) return;\n        onChange({\n          field: field.name,\n          op: choice.op,\n          value: valueFor(field.kind, choice, draft.value),\n        });\n      }}\n    >\n      <SelectTrigger\n        id={id}\n        size=\"sm\"\n        aria-label={`How ${field.label} is compared`}\n        className=\"nx-list-filter__op-pick\"\n        data-wide={draft.op === \"exists\" ? \"\" : undefined}\n      >\n        <SelectValue placeholder=\"Compare\" />\n      </SelectTrigger>\n      <SelectContent>\n        {operators.map(choice => (\n          <SelectItem key={choice.key} value={choice.key}>\n            {choice.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\n/** One filter: its sentence, opening in place into its controls. */\nfunction FilterRow(props: FilterRowProps): React.JSX.Element {\n  const { id, row, disabled } = props;\n  const { field, sentence, line, problem } = readRow(props);\n  const op = row.draft.op;\n  return (\n    <SentenceRow\n      id={id}\n      noun=\"filter\"\n      open={props.open}\n      disabled={disabled}\n      sentence={sentence}\n      line={line}\n      problem={problem}\n      field={labelId => (\n        <FilterFieldPicker\n          id={`${id}-field`}\n          labelId={labelId}\n          props={props}\n          field={field}\n        />\n      )}\n      body={(labelId, errorId) =>\n        field === undefined ? null : (\n          <div className=\"nx-list-filter__body\">\n            <OperatorPicker\n              id={`${id}-op`}\n              field={field}\n              draft={row.draft}\n              disabled={disabled}\n              onChange={props.onChange}\n            />\n            {op === undefined ? null : (\n              <FilterValue\n                id={`${id}-value`}\n                labelledBy={labelId}\n                field={field}\n                draft={{ ...row.draft, op }}\n                disabled={disabled}\n                invalid={problem !== undefined}\n                describedBy={problem === undefined ? undefined : errorId}\n                services={props.services}\n                entryTitle={props.entryTitle}\n                onValue={value => props.onChange({ ...row.draft, value })}\n              />\n            )}\n          </div>\n        )\n      }\n      onOpen={props.onOpen}\n      onClose={props.onClose}\n      onRemove={props.onRemove}\n    />\n  );\n}\n\n/** The Filters group: one row per filter, and a way to add one. */\nexport function FiltersGroup({\n  id,\n  query,\n  node,\n  fields,\n  fieldSource,\n  disabled,\n  problems,\n  services,\n  relatedWordsShown,\n  onFilters,\n}: {\n  id: string;\n  query: ListQuery;\n  node: BlockNode;\n  fields: readonly LoopListField[];\n  fieldSource: ListFieldSource | undefined;\n  disabled: boolean;\n  problems: readonly string[];\n  services: ContentServices | undefined;\n  /** The related source's words, for the line saying every entry shows. */\n  relatedWordsShown: string | undefined;\n  onFilters: (filters: ListFilter[] | undefined) => void;\n}): React.JSX.Element {\n  const stored = query.filters;\n  // Drafts over stored rows by index, and new rows by their own key. Drafts\n  // over stored rows are dropped when the stored rows change underneath\n  // them, as an undo does.\n  const editing = useSentenceRows<ListFilter, DraftFilter>(\n    stored,\n    filter => filter,\n    {}\n  );\n  const { rows, openKey, setOpenKey } = editing;\n  const entryTitle = useEntryTitles(\n    services?.findEntries,\n    fields,\n    rows.map(row => row.draft)\n  );\n  const filterLimit = listLimit(rows.length, LIST_MAX_FILTERS, id);\n  const change = (row: ShownRow, draft: DraftFilter) => {\n    const field = fields.find(each => each.name === draft.field);\n    const completed = completedFilter(draft, field);\n    // Written once complete, and a stored row from there on; kept as a draft\n    // until then, while the canvas keeps the last query.\n    const index = editing.change(row, draft, \"filter\" in completed);\n    if (\"filter\" in completed) {\n      onFilters(withFilter(stored, index, completed.filter));\n    }\n  };\n  const remove = (row: ShownRow) => {\n    const index = editing.remove(row);\n    if (index !== undefined) onFilters(withFilter(stored, index, undefined));\n  };\n  const storedProblems = (row: ShownRow): string | undefined => {\n    if (row.index === undefined || row.drafted) return undefined;\n    const issues = partIssues(\n      node,\n      { filters: [stored[row.index]] },\n      fieldSource\n    );\n    return issues.length === 0\n      ? undefined\n      : issues.map(issue => issue.message).join(\" \");\n  };\n  const titleId = `${id}-title`;\n  return (\n    <section className=\"nx-list-query__group\" aria-labelledby={titleId}>\n      <GroupTitle id={titleId}>Filters</GroupTitle>\n      <p className=\"nx-inspector__note nx-list-query__hint\">\n        {rows.length === 0\n          ? relatedWordsShown === undefined\n            ? \"Every entry is shown.\"\n            : `Every one of ${relatedWordsShown.replace(/^This /, \"this \").replace(/^Each /, \"each \")} is shown.`\n          : \"Show entries where all of these match.\"}\n      </p>\n      {rows.length === 0 ? null : (\n        <ul className=\"nx-list-query__filters\" aria-label=\"Filters\">\n          {rows.map(row => (\n            <FilterRow\n              key={row.key}\n              id={`${id}-${row.key.replace(\":\", \"-\")}`}\n              row={row}\n              fields={fields}\n              open={openKey === row.key}\n              disabled={disabled}\n              storedProblem={storedProblems(row)}\n              services={services}\n              entryTitle={entryTitle}\n              onOpen={() => setOpenKey(row.key)}\n              onClose={() => setOpenKey(null)}\n              onChange={draft => change(row, draft)}\n              onRemove={() => remove(row)}\n            />\n          ))}\n        </ul>\n      )}\n      {problems.length === 0 ? null : (\n        <FieldError id={`${id}-error`}>{problems.join(\" \")}</FieldError>\n      )}\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"nx-list-query__add\"\n        disabled={disabled || fields.length === 0 || filterLimit.full}\n        aria-describedby={filterLimit.describedBy}\n        onClick={editing.add}\n      >\n        <Plus aria-hidden=\"true\" size={14} />\n        Add filter\n      </Button>\n      <LimitNote limit={filterLimit}>\n        Up to {LIST_MAX_FILTERS} filters.\n      </LimitNote>\n    </section>\n  );\n}\n\n/** Whether a list holds the most of something it takes, and the note saying so. */\nexport interface ListLimit {\n  full: boolean;\n  /** The note's id while the limit is reached, for the Add button to name. */\n  describedBy: string | undefined;\n  id: string;\n}\n\n/** The limit of `count` against `most`, its note under `${id}-limit`. */\nexport function listLimit(count: number, most: number, id: string): ListLimit {\n  const full = count >= most;\n  const noteId = `${id}-limit`;\n  return { full, describedBy: full ? noteId : undefined, id: noteId };\n}\n\n/** Why an Add button is off: shown only once the list holds the most it takes. */\nexport function LimitNote({\n  limit,\n  children,\n}: {\n  limit: ListLimit;\n  children: React.ReactNode;\n}): React.JSX.Element | null {\n  if (!limit.full) return null;\n  return (\n    <p id={limit.id} className=\"nx-inspector__note nx-list-query__hint\">\n      {children}\n    </p>\n  );\n}\n","\"use client\";\n\n/**\n * How many of a collection list's entries show: the number of items and the\n * entries to skip, each a field that may be bound, the pages, the count of\n * matching entries, and what the canvas shows when none match.\n *\n * @module list-query-how-many\n */\nimport { listPageCount, NAMED_QUERY_TEXT } from \"@nextlyhq/blocks-engine\";\nimport { Input, Label, Switch } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useStoredDraft } from \"../../stored-draft\";\n\nimport type { ContentServices, ListEntriesCount } from \"./content-controls\";\nimport { readBound } from \"./list-query-model\";\nimport { FieldError, GroupTitle } from \"./list-query-parts\";\nimport { issuesAt, LIST_QUERY_PROPS, type Issues } from \"./list-query-reading\";\n\n/** The text a bound field opens with: the stored number, or the unset one. */\nfunction boundText(stored: unknown, unsetValue: number | undefined): string {\n  if (typeof stored === \"number\" || typeof stored === \"string\") {\n    return String(stored);\n  }\n  return unsetValue === undefined ? \"\" : String(unsetValue);\n}\n\n/**\n * A bound field's draft: the text typed, the problem with it, and the send\n * that writes it once a save would take it. The shown unset value, sent back\n * unchanged, is what the list already reads, so it is no edit.\n */\nfunction useBoundDraft(\n  prop: \"limit\" | \"offset\",\n  stored: unknown,\n  unsetValue: number | undefined,\n  onBound: (value: number | undefined) => void\n): {\n  draft: string;\n  setDraft: (text: string) => void;\n  problem: string | undefined;\n  send: () => void;\n} {\n  const text = boundText(stored, unsetValue);\n  // The inspector's own draft: an edit in progress from the first\n  // keystroke, which Save pressed from here writes first and Escape puts back.\n  const [draft, setDraft] = useStoredDraft(text);\n  const [problem, setProblem] = React.useState<string | undefined>();\n  React.useEffect(() => {\n    setProblem(undefined);\n  }, [text]);\n  const send = () => {\n    const read = readBound(prop, draft);\n    if (\"problem\" in read) {\n      // Refused here rather than written: the canvas keeps the last list.\n      setProblem(read.problem);\n      return;\n    }\n    setProblem(undefined);\n    const unchanged =\n      read.value === stored ||\n      (stored === undefined && read.value === unsetValue);\n    if (!unchanged) onBound(read.value);\n  };\n  return { draft, setDraft, problem, send };\n}\n\n/** Under a bound field: its problem, or, with none, its hint. */\nfunction BoundFoot({\n  errorId,\n  problem,\n  hint,\n}: {\n  errorId: string;\n  problem: string | undefined;\n  hint: string | undefined;\n}): React.JSX.Element | null {\n  if (problem !== undefined) {\n    return <FieldError id={errorId}>{problem}</FieldError>;\n  }\n  if (hint === undefined) return null;\n  // In the field's control column already, under the number it is about.\n  return (\n    <p className=\"nx-inspector__note nx-list-query__hint\" role=\"status\">\n      {hint}\n    </p>\n  );\n}\n\n/** A number of entries typed, written once a save would take it. */\nfunction BoundField({\n  id,\n  prop,\n  words,\n  stored,\n  fallback,\n  unsetValue,\n  disabled,\n  problem: storedProblem,\n  hint,\n  onBound,\n}: {\n  id: string;\n  prop: \"limit\" | \"offset\";\n  /** The field's label, and what it counts, said after the number. */\n  words: { readonly label: string; readonly suffix?: string };\n  stored: unknown;\n  /** What the list reads when nothing is stored, shown as the placeholder. */\n  fallback?: unknown;\n  /**\n   * What the list reads when nothing is stored, shown as the field's value:\n   * for a number an author reads as a plain fact (skip 0) rather than a hint.\n   * Sending it unchanged writes nothing, so nothing is stored for it.\n   */\n  unsetValue?: number;\n  disabled: boolean;\n  problem: string | undefined;\n  /** A line under the field, said while it has no problem to say. */\n  hint?: string | undefined;\n  onBound: (value: number | undefined) => void;\n}): React.JSX.Element {\n  const { draft, setDraft, problem, send } = useBoundDraft(\n    prop,\n    stored,\n    unsetValue,\n    onBound\n  );\n  const shown = problem ?? storedProblem;\n  const errorId = `${id}-error`;\n  return (\n    <div className=\"nx-inspector__field\" data-content-control=\"number\">\n      <Label htmlFor={id}>{words.label}</Label>\n      <div\n        className=\"nx-list-query__bound\"\n        data-suffixed={words.suffix === undefined ? undefined : \"\"}\n      >\n        <Input\n          id={id}\n          type=\"number\"\n          inputMode=\"numeric\"\n          min={prop === \"limit\" ? 1 : 0}\n          max={prop === \"limit\" ? 100 : undefined}\n          value={draft}\n          placeholder={\n            typeof fallback === \"number\" ? String(fallback) : undefined\n          }\n          disabled={disabled}\n          aria-invalid={shown === undefined ? undefined : true}\n          aria-describedby={shown === undefined ? undefined : errorId}\n          onChange={event => setDraft(event.target.value)}\n          onBlur={send}\n          onKeyDown={event => {\n            if (event.key === \"Enter\") {\n              event.preventDefault();\n              send();\n            }\n          }}\n        />\n        {words.suffix === undefined ? null : (\n          <span className=\"nx-list-query__suffix\" aria-hidden=\"true\">\n            {words.suffix}\n          </span>\n        )}\n      </div>\n      <BoundFoot errorId={errorId} problem={shown} hint={hint} />\n    </div>\n  );\n}\n\n/** The engine's issues about one prop, of one code, in its words. */\nexport function codedIssues(\n  issues: Issues,\n  prop: string,\n  code: string\n): string[] {\n  return issues\n    .filter(\n      issue => issue.path.endsWith(`/props/${prop}`) && issue.code === code\n    )\n    .map(issue => issue.message);\n}\n\n/**\n * What splitting into pages makes of the count: \"24 entries match, so 3\n * pages of 10.\", or what a switch turned on will do when nothing is counted.\n */\nfunction pagesWords(\n  counted: ListEntriesCount | undefined,\n  values: Readonly<Record<string, unknown>>,\n  limitFallback: unknown\n): string {\n  const stored = values.limit ?? limitFallback;\n  const limit = typeof stored === \"number\" && stored >= 1 ? stored : 10;\n  const each = `${String(limit)} ${limit === 1 ? \"entry\" : \"entries\"}`;\n  if (counted === undefined) {\n    return `Shows ${each} on each page, at /page/2, /page/3 and on.`;\n  }\n  const offset = typeof values.offset === \"number\" ? values.offset : 0;\n  const pages = listPageCount(counted.matching, offset, limit);\n  const match =\n    counted.matching === 1\n      ? \"1 entry matches\"\n      : `${String(counted.matching)} entries match`;\n  return `${match}, so ${pages === 1 ? \"1 page\" : `${String(pages)} pages`} of ${each}.`;\n}\n\n/** The How many group: the number of items, the entries to skip, and pages. */\n/**\n * How many entries the list's query matches and how many it shows, counted\n * once per query: drawn again with the same query, nothing is read again,\n * and an answer for a query since changed is dropped.\n */\nfunction useListCount(\n  count: ContentServices[\"countListEntries\"],\n  values: Readonly<Record<string, unknown>>\n): ListEntriesCount | undefined {\n  const asked = JSON.stringify(\n    LIST_QUERY_PROPS.map(name => values[name] ?? null)\n  );\n  const [answer, setAnswer] = React.useState<\n    { readonly asked: string; readonly count: ListEntriesCount } | undefined\n  >(undefined);\n  React.useEffect(() => {\n    if (count === undefined) return;\n    let current = true;\n    // The props the count is of, read back from the key, so the read and\n    // the key it is kept under are one value.\n    const read = JSON.parse(asked) as unknown[];\n    const props = Object.fromEntries(\n      LIST_QUERY_PROPS.flatMap((name, at) =>\n        read[at] === null ? [] : [[name, read[at]]]\n      )\n    );\n    count(props).then(\n      found => {\n        if (current && found !== undefined) setAnswer({ asked, count: found });\n      },\n      // A count that fails says nothing: the canvas's note says why the\n      // list's read failed.\n      () => undefined\n    );\n    return () => {\n      current = false;\n    };\n  }, [count, asked]);\n  return answer?.asked === asked ? answer.count : undefined;\n}\n\n/** \"4 entries match, so 3 show.\", with one entry spoken of as one. */\nfunction countWords(\n  { matching, shown }: ListEntriesCount,\n  named: boolean\n): string {\n  // A custom source's rows are not always entries: counted in its own words.\n  if (named) return NAMED_QUERY_TEXT.counted(matching, shown);\n  const match =\n    matching === 1 ? \"1 entry matches\" : `${String(matching)} entries match`;\n  const show = shown === 1 ? \"1 shows\" : `${String(shown)} show`;\n  return `${match}, so ${show}.`;\n}\n\nexport function HowManyGroup({\n  id,\n  values,\n  limitFallback,\n  issues,\n  disabled,\n  count,\n  commit,\n}: {\n  id: string;\n  values: Readonly<Record<string, unknown>>;\n  /** The number of items the block reads when none is stored. */\n  limitFallback: unknown;\n  issues: Issues;\n  disabled: boolean;\n  /** The host's count of the list's matching entries, where it has one. */\n  count: ContentServices[\"countListEntries\"];\n  commit: (changes: Readonly<Record<string, unknown>>) => void;\n}): React.JSX.Element {\n  const counted = useListCount(count, values);\n  return (\n    <section className=\"nx-list-query__group\" aria-labelledby={`${id}-title`}>\n      <GroupTitle id={`${id}-title`}>Entries shown</GroupTitle>\n      <BoundField\n        id={`${id}-limit`}\n        prop=\"limit\"\n        words={{ label: \"How many\" }}\n        stored={values.limit}\n        fallback={limitFallback}\n        disabled={disabled}\n        problem={issuesAt(issues, [\"limit\"])[0]}\n        hint={\n          counted === undefined\n            ? undefined\n            : countWords(counted, values.namedQuery !== undefined)\n        }\n        onBound={limit => commit({ limit })}\n      />\n      <BoundField\n        id={`${id}-offset`}\n        prop=\"offset\"\n        words={{ label: \"Skip\", suffix: \"entries\" }}\n        stored={values.offset}\n        unsetValue={0}\n        disabled={disabled}\n        problem={issuesAt(issues, [\"offset\"])[0]}\n        // Skipping none stores nothing, as a list that skips none always did.\n        onBound={offset =>\n          commit({ offset: offset === 0 ? undefined : offset })\n        }\n      />\n      <PagesField\n        id={`${id}-pages`}\n        on={values.paginate === true}\n        disabled={disabled}\n        problem={issuesAt(issues, [\"paginate\"])[0]}\n        hint={\n          values.paginate === true\n            ? pagesWords(counted, values, limitFallback)\n            : undefined\n        }\n        // Off stores nothing, as a list that never paginated holds nothing.\n        onChange={on => commit({ paginate: on ? true : undefined })}\n      />\n    </section>\n  );\n}\n\n/**\n * Whether the list is split into pages, each at its own address: a switch,\n * with what it makes of the count under it while on, or why the page cannot\n * serve it.\n */\nfunction PagesField({\n  id,\n  on,\n  disabled,\n  problem,\n  hint,\n  onChange,\n}: {\n  id: string;\n  on: boolean;\n  disabled: boolean;\n  problem: string | undefined;\n  hint: string | undefined;\n  onChange: (on: boolean) => void;\n}): React.JSX.Element {\n  const errorId = `${id}-error`;\n  return (\n    <div className=\"nx-inspector__field\" data-content-control=\"paginate\">\n      <Label htmlFor={id}>Split into pages</Label>\n      <Switch\n        id={id}\n        checked={on}\n        disabled={disabled}\n        aria-invalid={problem === undefined ? undefined : true}\n        aria-describedby={problem === undefined ? undefined : errorId}\n        onCheckedChange={onChange}\n      />\n      <BoundFoot errorId={errorId} problem={problem} hint={hint} />\n    </div>\n  );\n}\n\n/**\n * When nothing matches: whether the canvas previews the list's empty message\n * in place of its entries. Editor state, never stored.\n */\nexport function CanvasShowsGroup({\n  id,\n  showsEmpty,\n  onShowEmpty,\n}: {\n  id: string;\n  showsEmpty: boolean;\n  onShowEmpty: (empty: boolean) => void;\n}): React.JSX.Element {\n  const previewId = `${id}-canvas`;\n  return (\n    <section className=\"nx-list-query__group\" aria-labelledby={`${id}-title`}>\n      <GroupTitle id={`${id}-title`}>When nothing matches</GroupTitle>\n      <div className=\"nx-inspector__field\" data-content-control=\"canvasShows\">\n        <Label htmlFor={previewId}>Preview the empty message</Label>\n        <Switch\n          id={previewId}\n          checked={showsEmpty}\n          onCheckedChange={onShowEmpty}\n        />\n      </div>\n      <p className=\"nx-inspector__note nx-list-query__hint nx-list-query__indented\">\n        {showsEmpty\n          ? \"Visitors see these blocks when no entry matches. Left empty, the list shows nothing.\"\n          : \"Turn on to design what visitors see when no entry matches.\"}\n      </p>\n    </section>\n  );\n}\n","\"use client\";\n\n/**\n * A collection list's custom source in the Content tab: its row in the\n * Source menu, the Inputs group with one control per input, the line saying\n * the query sets its own filters and order, and what is said about a stored\n * query this site no longer registers.\n *\n * Every sentence is the engine's `NAMED_QUERY_TEXT`, and every problem is\n * the engine's judgement of the inputs (`judgeNamedParams`, through\n * `named-query-model`), so the inspector and a save refuse alike, in one set\n * of words. An input is written as it is set, except where the whole set\n * cannot run yet: then the list keeps what it stores (see\n * `list-query-controls`).\n *\n * @module named-query-controls\n */\nimport {\n  NAMED_QUERY_TEXT,\n  namedQueryParamNeedsInput,\n  type NamedParamProblem,\n  type NamedQueryDeclaration,\n  type NamedQueryParam,\n  type NamedQueryParamValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Label,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { CalendarDays, ListFilter, TriangleAlert } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useStoredDraft } from \"../../stored-draft\";\n\nimport { SegmentedChoice, type ContentServices } from \"./content-controls\";\nimport { FieldCaution, FieldError, GroupTitle } from \"./list-query-parts\";\nimport {\n  emptyWords,\n  inputsNote,\n  inputsOf,\n  keptInputs,\n  marksNeeded,\n  needsInput,\n  type StoredParams,\n} from \"./named-query-model\";\nimport { RelationControl } from \"./relation-control\";\n\n/** The mark a custom source wears in the Source control, beside a related one's. */\nexport const CUSTOM_SOURCE_MARK: React.JSX.Element = (\n  <ListFilter aria-hidden=\"true\" size={14} className=\"nx-list-query__icon\" />\n);\n\n/**\n * A custom source's row in the Source menu: its label, which wraps rather\n * than being cut, and under it the developer's line, with the \"Needs input\"\n * tag at that line's end, so an author sees what each does while choosing.\n */\nexport function CustomSourceRow({\n  declaration,\n}: {\n  declaration: NamedQueryDeclaration;\n}): React.JSX.Element {\n  const tagged = needsInput(declaration);\n  return (\n    <span className=\"nx-list-source\">\n      <span className=\"nx-list-source__label\">{declaration.label}</span>\n      {declaration.description === undefined && !tagged ? null : (\n        <span className=\"nx-list-source__line\">\n          <span className=\"nx-list-source__description\">\n            {declaration.description}\n          </span>\n          {tagged ? (\n            <span className=\"nx-list-source__tag\">\n              {NAMED_QUERY_TEXT.needsInput}\n            </span>\n          ) : null}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/** What every input control is given. */\ninterface InputControlProps {\n  readonly id: string;\n  readonly param: NamedQueryParam;\n  readonly value: NamedQueryParamValue | undefined;\n  readonly disabled: boolean;\n  readonly invalid: boolean;\n  readonly describedBy: string | undefined;\n  readonly services: ContentServices | undefined;\n  readonly onInput: (value: NamedQueryParamValue | undefined) => void;\n}\n\n/** Text typed, set when the field is left or Enter pressed. */\nfunction useTypedDraft(\n  stored: string,\n  onDone: (text: string) => void\n): {\n  draft: string;\n  setDraft: (text: string) => void;\n  send: () => void;\n  keys: (event: React.KeyboardEvent) => void;\n} {\n  // The inspector's own draft: an edit in progress from the first\n  // keystroke, which Save pressed from here writes first and Escape puts back.\n  const [draft, setDraft] = useStoredDraft(stored);\n  const send = () => {\n    if (draft !== stored) onDone(draft);\n  };\n  return {\n    draft,\n    setDraft,\n    send,\n    keys: event => {\n      if (event.key === \"Enter\") {\n        event.preventDefault();\n        send();\n      }\n    },\n  };\n}\n\n/** What a typed input reads of its props. */\ntype TypedProps = Pick<\n  InputControlProps,\n  \"id\" | \"param\" | \"value\" | \"disabled\" | \"invalid\" | \"describedBy\" | \"onInput\"\n>;\n\n/** A text input: the developer's placeholder, or its default, while empty. */\nfunction TextInput(props: TypedProps): React.JSX.Element {\n  const { id, param, value, disabled, invalid, describedBy, onInput } = props;\n  const typed = useTypedDraft(typeof value === \"string\" ? value : \"\", text =>\n    onInput(text.trim() === \"\" ? undefined : text)\n  );\n  return (\n    <Input\n      id={id}\n      value={typed.draft}\n      placeholder={emptyWords(param)}\n      maxLength={param.type === \"text\" ? param.maxLength : undefined}\n      disabled={disabled}\n      aria-invalid={invalid ? true : undefined}\n      aria-describedby={describedBy}\n      onChange={event => typed.setDraft(event.target.value)}\n      onBlur={typed.send}\n      onKeyDown={typed.keys}\n    />\n  );\n}\n\n/** A number input, with what it counts after it (\"days\"). */\nfunction NumberInput(props: TypedProps): React.JSX.Element {\n  const { id, param, value, disabled, invalid, describedBy, onInput } = props;\n  const unit = param.type === \"number\" ? param.unit : undefined;\n  const typed = useTypedDraft(\n    typeof value === \"number\" ? String(value) : \"\",\n    text => {\n      const parsed = Number(text);\n      // What is not a number is sent as typed, so the judgement names it.\n      onInput(\n        text.trim() === \"\" ? undefined : Number.isNaN(parsed) ? text : parsed\n      );\n    }\n  );\n  return (\n    <div\n      className=\"nx-list-query__bound\"\n      data-suffixed={unit === undefined ? undefined : \"\"}\n    >\n      <Input\n        id={id}\n        type=\"number\"\n        inputMode=\"decimal\"\n        value={typed.draft}\n        placeholder={emptyWords(param)}\n        min={param.type === \"number\" ? param.min : undefined}\n        max={param.type === \"number\" ? param.max : undefined}\n        disabled={disabled}\n        aria-invalid={invalid ? true : undefined}\n        aria-describedby={describedBy}\n        onChange={event => typed.setDraft(event.target.value)}\n        onBlur={typed.send}\n        onKeyDown={typed.keys}\n      />\n      {unit === undefined ? null : (\n        <span className=\"nx-list-query__suffix\" aria-hidden=\"true\">\n          {unit}\n        </span>\n      )}\n    </div>\n  );\n}\n\n/** A yes-or-no input: Yes and No, side by side, its default chosen. */\nfunction BooleanInput(\n  props: Pick<\n    InputControlProps,\n    \"id\" | \"param\" | \"value\" | \"disabled\" | \"onInput\"\n  >\n): React.JSX.Element {\n  const { id, param, value, disabled, onInput } = props;\n  const fallback = param.type === \"boolean\" ? param.default === true : false;\n  const on = typeof value === \"boolean\" ? value : fallback;\n  return (\n    <SegmentedChoice\n      id={id}\n      labelledBy={`${id}-label`}\n      options={[\"yes\", \"no\"]}\n      labels={[\"Yes\", \"No\"]}\n      value={on ? \"yes\" : \"no\"}\n      disabled={disabled}\n      // Its default is no edit: choosing it again stores nothing.\n      onChoose={option => {\n        const next = option === \"yes\";\n        onInput(next === fallback ? undefined : next);\n      }}\n    />\n  );\n}\n\n/** The menu value that empties an optional choice. */\nconst ANY_CHOICE = \"any\";\n\n/**\n * The menu's own value for an option, by its place: an option's value may\n * be any text, the empty one included, which the menu cannot carry as is.\n */\nfunction optionKey(index: number): string {\n  return `option:${String(index)}`;\n}\n\n/** A choice input: its options, and \"Any city\" first where it is optional. */\nfunction ChoiceInput(props: TypedProps): React.JSX.Element {\n  const { id, param, value, disabled, invalid, describedBy, onInput } = props;\n  const options = param.type === \"choice\" ? param.options : [];\n  const optional =\n    param.type === \"choice\" &&\n    param.required !== true &&\n    param.default === undefined;\n  const chosen = options.findIndex(option => option.value === value);\n  return (\n    <Select\n      value={chosen < 0 ? \"\" : optionKey(chosen)}\n      disabled={disabled}\n      onValueChange={key =>\n        onInput(\n          key === ANY_CHOICE\n            ? undefined\n            : options.find((_, index) => optionKey(index) === key)?.value\n        )\n      }\n    >\n      <SelectTrigger\n        id={id}\n        size=\"sm\"\n        aria-labelledby={`${id}-label`}\n        aria-invalid={invalid ? true : undefined}\n        aria-describedby={describedBy}\n        className=\"nx-list-input__choice\"\n      >\n        <SelectValue placeholder={emptyWords(param)} />\n      </SelectTrigger>\n      <SelectContent>\n        {optional ? (\n          <SelectItem value={ANY_CHOICE}>{emptyWords(param)}</SelectItem>\n        ) : null}\n        {options.map((option, index) => (\n          <SelectItem key={optionKey(index)} value={optionKey(index)}>\n            {option.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\n/**\n * A day input: what empty means (\"Today\") until it is focused, then the\n * platform's own date field, as a date filter's is.\n */\nfunction DayInput(props: TypedProps): React.JSX.Element {\n  const { id, param, value, disabled, invalid, describedBy, onInput } = props;\n  const stored = typeof value === \"string\" ? value : \"\";\n  const [focused, setFocused] = React.useState(false);\n  const typed = useTypedDraft(stored, text =>\n    onInput(text === \"\" ? undefined : text)\n  );\n  const dated = focused || typed.draft !== \"\";\n  return (\n    <div className=\"nx-list-input__day\" data-dated={dated ? \"\" : undefined}>\n      <Input\n        id={id}\n        type={dated ? \"date\" : \"text\"}\n        value={typed.draft}\n        placeholder={emptyWords(param)}\n        disabled={disabled}\n        aria-invalid={invalid ? true : undefined}\n        aria-describedby={describedBy}\n        onFocus={() => setFocused(true)}\n        onChange={event => typed.setDraft(event.target.value)}\n        onBlur={() => {\n          setFocused(false);\n          typed.send();\n        }}\n        onKeyDown={typed.keys}\n      />\n      {dated ? null : (\n        <CalendarDays\n          aria-hidden=\"true\"\n          size={14}\n          className=\"nx-list-input__day-icon\"\n        />\n      )}\n    </div>\n  );\n}\n\n/** An entry input: the entry picker, saying what empty means (\"Any venue\"). */\nfunction EntryInput(\n  props: Pick<\n    InputControlProps,\n    \"id\" | \"param\" | \"value\" | \"disabled\" | \"services\" | \"onInput\"\n  >\n): React.JSX.Element {\n  const { id, param, value, disabled, services, onInput } = props;\n  return (\n    <div className=\"nx-list-input__entry\">\n      <RelationControl\n        id={id}\n        label={param.label}\n        emptyWords={emptyWords(param)}\n        prop={{\n          name: \"value\",\n          schema: {\n            type: \"relation\",\n            relationTo: param.type === \"entry\" ? param.collection : undefined,\n          },\n          value: value === undefined ? undefined : String(value),\n          defaultValue: undefined,\n          supported: true,\n          options: [],\n          offered: true,\n          readOnly: false,\n        }}\n        disabled={disabled}\n        services={services}\n        onCommit={(_name, chosen) =>\n          onInput(\n            typeof chosen === \"string\" && chosen !== \"\" ? chosen : undefined\n          )\n        }\n      />\n    </div>\n  );\n}\n\n/** The control for each type of input. */\nconst INPUT_CONTROLS: Readonly<\n  Record<\n    NamedQueryParam[\"type\"],\n    (props: InputControlProps) => React.JSX.Element\n  >\n> = {\n  text: TextInput,\n  number: NumberInput,\n  boolean: BooleanInput,\n  choice: ChoiceInput,\n  day: DayInput,\n  entry: EntryInput,\n};\n\n/** One input: its label, its control, and what is wrong with its value. */\nfunction InputField({\n  marked,\n  problem,\n  ...props\n}: InputControlProps & {\n  readonly marked: boolean;\n  readonly problem: string | undefined;\n}): React.JSX.Element {\n  const Control = INPUT_CONTROLS[props.param.type];\n  // The entry picker labels itself, stacked, as it does in a filter.\n  if (props.param.type === \"entry\") {\n    return (\n      <div className=\"nx-list-input\" data-input-type=\"entry\">\n        <Control {...props} />\n        {problem === undefined ? null : (\n          <FieldError id={`${props.id}-error`}>{problem}</FieldError>\n        )}\n      </div>\n    );\n  }\n  return (\n    <div\n      className=\"nx-inspector__field nx-list-input\"\n      data-content-control=\"namedInput\"\n      data-input-type={props.param.type}\n    >\n      <Label id={`${props.id}-label`} htmlFor={props.id}>\n        {props.param.label}\n        {marked ? (\n          <span className=\"nx-list-input__needed\" aria-label=\"needed\">\n            {\" \"}\n            •\n          </span>\n        ) : null}\n      </Label>\n      <Control {...props} />\n      {problem === undefined ? null : (\n        <FieldError id={`${props.id}-error`}>{problem}</FieldError>\n      )}\n    </div>\n  );\n}\n\n/**\n * The Inputs group: one note naming what the query needs, then one control\n * per input, each refused inline as a save would refuse it, and a caution\n * for a stored input the query no longer takes.\n */\nexport function InputsGroup({\n  id,\n  declaration,\n  params,\n  problems,\n  unknown,\n  disabled,\n  services,\n  onInput,\n}: {\n  id: string;\n  declaration: NamedQueryDeclaration;\n  /** The inputs shown: what is stored, or the draft over it. */\n  params: StoredParams;\n  problems: readonly NamedParamProblem[];\n  unknown: readonly string[];\n  disabled: boolean;\n  services: ContentServices | undefined;\n  onInput: (key: string, value: NamedQueryParamValue | undefined) => void;\n}): React.JSX.Element | null {\n  const inputs = inputsOf(declaration);\n  if (inputs.length === 0 && unknown.length === 0) return null;\n  const titleId = `${id}-title`;\n  const marked = marksNeeded(declaration);\n  return (\n    <section className=\"nx-list-query__group\" aria-labelledby={titleId}>\n      <GroupTitle id={titleId}>Inputs</GroupTitle>\n      {inputs.length === 0 ? null : (\n        <p className=\"nx-inspector__note nx-list-query__hint\">\n          {inputsNote(declaration, problems)}\n        </p>\n      )}\n      {inputs.map(([key, param]) => {\n        const problem = problems.find(each => each.param === key)?.message;\n        const inputId = `${id}-${key}`;\n        return (\n          <InputField\n            key={key}\n            id={inputId}\n            param={param}\n            value={params[key]}\n            disabled={disabled}\n            invalid={problem !== undefined}\n            describedBy={problem === undefined ? undefined : `${inputId}-error`}\n            services={services}\n            marked={marked && namedQueryParamNeedsInput(param)}\n            problem={problem}\n            onInput={value => onInput(key, value)}\n          />\n        );\n      })}\n      {unknown.map(key => (\n        <FieldCaution key={key}>\n          <TriangleAlert aria-hidden=\"true\" size={12} />\n          {NAMED_QUERY_TEXT.paramUnknown(declaration.label, key)}\n        </FieldCaution>\n      ))}\n    </section>\n  );\n}\n\n/**\n * The Inputs group of a stored query this site no longer registers: what\n * the list keeps, said once, until another source is chosen.\n */\nexport function KeptInputsGroup({\n  id,\n  params,\n}: {\n  id: string;\n  params: StoredParams;\n}): React.JSX.Element {\n  const titleId = `${id}-title`;\n  return (\n    <section className=\"nx-list-query__group\" aria-labelledby={titleId}>\n      <GroupTitle id={titleId}>Inputs</GroupTitle>\n      <p className=\"nx-inspector__note nx-list-query__hint\">\n        {NAMED_QUERY_TEXT.inputsKept(keptInputs(params))}\n      </p>\n    </section>\n  );\n}\n\n/**\n * Filters and sort under a custom source: one read-only line where their\n * controls would be, since the query decides which entries show and in what\n * order, so an author looking for them finds why they are not there.\n */\nexport function FiltersSetBy({\n  id,\n  declaration,\n}: {\n  id: string;\n  declaration: NamedQueryDeclaration;\n}): React.JSX.Element {\n  const titleId = `${id}-title`;\n  return (\n    <section className=\"nx-list-query__group\" aria-labelledby={titleId}>\n      <GroupTitle id={titleId}>Filters and sort</GroupTitle>\n      <p className=\"nx-inspector__note nx-list-query__hint\">\n        {NAMED_QUERY_TEXT.filtersSetBy(declaration.label)}\n      </p>\n    </section>\n  );\n}\n","\"use client\";\n\n/**\n * A collection list's Source field: the menu of collections, relations and\n * custom sources, what each choice changes, and the hint and foot under it.\n *\n * @module list-query-source\n */\nimport { NAMED_QUERY_TEXT, type ListQuery } from \"@nextlyhq/blocks-engine\";\nimport { Label } from \"@nextlyhq/ui\";\nimport { Link2, TriangleAlert } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { ListedChoice } from \"../../choice-list\";\n\nimport {\n  alphabetical,\n  LoopPicker,\n  type LoopCollections,\n} from \"./collection-loop-controls\";\nimport type { LoopCollection } from \"./content-controls\";\nimport { FieldCaution, FieldError } from \"./list-query-parts\";\nimport type {\n  ListQueryReading,\n  Related,\n  RelatedSource,\n} from \"./list-query-reading\";\nimport { CUSTOM_SOURCE_MARK, CustomSourceRow } from \"./named-query-controls\";\nimport {\n  sourceSearchText,\n  type CustomSource,\n  type StoredParams,\n} from \"./named-query-model\";\n\n/** One row of the Source menu. */\nexport interface SourceChoice extends ListedChoice {\n  readonly pick:\n    | { readonly kind: \"collection\"; readonly slug: string | undefined }\n    | { readonly kind: \"related\"; readonly source: RelatedSource }\n    | { readonly kind: \"custom\"; readonly source: CustomSource };\n}\n\n/** A pick that names a collection or a related source, not a custom one. */\ntype CollectionPick = Exclude<SourceChoice[\"pick\"], { kind: \"custom\" }>;\n\n/** The props a new source writes: a new collection clears what named the old. */\nexport function sourceChanges(\n  query: ListQuery,\n  pick: CollectionPick\n): Record<string, unknown> {\n  const collection =\n    pick.kind === \"collection\" ? pick.slug : pick.source.collection;\n  const relation =\n    pick.kind === \"related\"\n      ? { of: pick.source.of, field: pick.source.field }\n      : undefined;\n  // Filters and sort name the old collection's fields, which the new one may\n  // not have, so a save would refuse them: they go with it, in the same edit.\n  return {\n    collection,\n    relation,\n    // A collection or a related source is the list's whole source: a custom\n    // one goes in the same edit.\n    namedQuery: undefined,\n    ...(collection === query.collection\n      ? {}\n      : { filters: undefined, sort: undefined }),\n  };\n}\n\n/** What the Source button shows, and whether it is a prompt or a lost value. */\nfunction sourceShown(\n  listed: LoopCollections,\n  query: ListQuery,\n  related: RelatedSource | undefined,\n  current: LoopCollection | undefined,\n  named: ShownNamed | undefined\n): { words: string; state: \"value\" | \"prompt\" | \"unknown\" } {\n  if (listed.kind === \"loading\") {\n    return { words: \"Loading collections…\", state: \"prompt\" };\n  }\n  if (named !== undefined) {\n    if (named.source !== undefined) {\n      return { words: named.source.declaration.label, state: \"value\" };\n    }\n    return named.loading\n      ? { words: \"Loading sources…\", state: \"prompt\" }\n      : { words: `${named.name} · not available`, state: \"unknown\" };\n  }\n  // No collection could be listed: a stored one is shown by its name, as\n  // it is not known to be gone, and an unset one asks for a custom source.\n  if (listed === NO_COLLECTIONS) {\n    const stored = query.relation?.field ?? query.collection;\n    return stored === undefined\n      ? { words: \"Choose a custom source\", state: \"prompt\" }\n      : { words: stored, state: \"value\" };\n  }\n  if (query.relation !== undefined) {\n    return related === undefined\n      ? {\n          words: `${query.relation.field} · not available here`,\n          state: \"unknown\",\n        }\n      : { words: related.words, state: \"value\" };\n  }\n  if (query.collection === undefined) {\n    return { words: \"Choose a collection\", state: \"prompt\" };\n  }\n  return current === undefined\n    ? { words: `${query.collection} · not available`, state: \"unknown\" }\n    : { words: current.label, state: \"value\" };\n}\n\n/** The Source menu's rows: related sources first, then the collections. */\nfunction sourceChoices(\n  related: Related,\n  collections: readonly LoopCollection[] | undefined,\n  customs: readonly CustomSource[]\n): SourceChoice[] {\n  const relatedRow = (source: RelatedSource): SourceChoice => ({\n    key: `${source.of}:${source.field}`,\n    label: source.words,\n    group: source.of,\n    pick: { kind: \"related\", source },\n  });\n  return [\n    ...related.entry.map(relatedRow),\n    ...related.item.map(relatedRow),\n    // A site's own queries, above its collections: few, made for this site,\n    // and kept in view above a collection list that may scroll.\n    ...customs.map(\n      (source): SourceChoice => ({\n        key: `custom:${source.declaration.name}`,\n        label: source.declaration.label,\n        group: \"custom\",\n        // Searched by its line too, which the row draws under its name.\n        search: sourceSearchText(source.declaration),\n        pick: { kind: \"custom\", source },\n      })\n    ),\n    // No collection row, nor any collection, where none could be listed.\n    ...(collections === undefined\n      ? []\n      : [\n          {\n            key: \"collection:\",\n            label: \"No collection\",\n            group: \"collections\",\n            pick: { kind: \"collection\", slug: undefined },\n          } satisfies SourceChoice,\n        ]),\n    ...alphabetical(collections ?? []).map(\n      (each): SourceChoice => ({\n        key: `collection:${each.slug}`,\n        label: each.label,\n        group: \"collections\",\n        pick: { kind: \"collection\", slug: each.slug },\n      })\n    ),\n  ];\n}\n\n/** The Source menu's headings, for the groups that hold a row. */\nfunction sourceGroups(\n  related: Related,\n  customs: readonly CustomSource[],\n  collectionsOffered: boolean\n): { group: string; heading: string }[] {\n  return [\n    ...(related.entry.length === 0\n      ? []\n      : [{ group: \"entry\", heading: related.entryHeading }]),\n    ...(related.item.length === 0\n      ? []\n      : [{ group: \"item\", heading: related.itemHeading }]),\n    ...(customs.length === 0\n      ? []\n      : [{ group: \"custom\", heading: \"Custom sources\" }]),\n    ...(collectionsOffered\n      ? [{ group: \"collections\", heading: \"Collections\" }]\n      : []),\n  ];\n}\n\n/** A Source menu row as drawn: a custom source on two lines, any other on one. */\nfunction sourceRow(choice: SourceChoice): React.ReactNode {\n  return choice.pick.kind === \"custom\" ? (\n    <CustomSourceRow declaration={choice.pick.source.declaration} />\n  ) : (\n    choice.label\n  );\n}\n\n/** The Source menu's note where no related source can be offered. */\nfunction NoRelated({\n  inEmptyState,\n}: {\n  inEmptyState: boolean;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-list-query__menu-note\">\n      <p className=\"nx-vars__group-name nx-font-pick__heading\">\n        Related entries\n      </p>\n      <p className=\"nx-list-query__menu-text\">\n        {inEmptyState ? (\n          <>\n            Not available in When empty: it only shows when the list has no\n            entries, so there&apos;s no entry to relate to.\n          </>\n        ) : (\n          <>\n            Not available here. On a collection&apos;s entry, or inside another\n            list, a list can show the entry&apos;s related entries, such as its\n            categories or tags.\n          </>\n        )}\n      </p>\n    </div>\n  );\n}\n\n/** What a related source shows, said under Source. */\nfunction SourceHint({\n  id,\n  source,\n  collections,\n}: {\n  id: string;\n  source: RelatedSource;\n  collections: readonly LoopCollection[];\n}): React.JSX.Element {\n  const whose =\n    source.of === \"entry\"\n      ? \"chosen on the entry this page shows\"\n      : \"of each entry the list around this one shows\";\n  const fields =\n    collections.find(each => each.slug === source.collection)?.label ??\n    source.collection;\n  return (\n    <p id={id} className=\"nx-inspector__note nx-list-query__hint\">\n      The {source.what} {whose}. Filters and sort use the fields of {fields}.\n    </p>\n  );\n}\n\n/** The mark a related source wears in the Source control. */\nconst RELATED_MARK = (\n  <Link2 aria-hidden=\"true\" size={14} className=\"nx-list-query__icon\" />\n);\n\n/** The related source a stored relation names, among those offered. */\nfunction relatedSourceOf(\n  offered: readonly RelatedSource[],\n  relation: ListQuery[\"relation\"]\n): RelatedSource | undefined {\n  return relation === undefined\n    ? undefined\n    : offered.find(\n        each => each.of === relation.of && each.field === relation.field\n      );\n}\n\n/** The Source menu's key for what is stored: a relation, or a collection. */\nfunction sourceKey(query: ListQuery, named: ShownNamed | undefined): string {\n  if (named !== undefined) return `custom:${named.name}`;\n  return query.relation === undefined\n    ? `collection:${query.collection ?? \"\"}`\n    : `${query.relation.of}:${query.relation.field}`;\n}\n\n/**\n * The custom source a list shows in its inspector: the one it stores, or the\n * one just picked and waiting for an input, with its inputs as shown and the\n * source the site offers under that name, if it still does.\n */\nexport interface ShownNamed {\n  readonly name: string;\n  readonly params: StoredParams;\n  readonly source: CustomSource | undefined;\n  /** Picked but not written yet: an input it needs is still empty. */\n  readonly drafted: boolean;\n  /** The site's sources are still being read, so `source` is not known yet. */\n  readonly loading: boolean;\n}\n\n/** What a custom source's Source hint says: the developer's line. */\nfunction NamedHint({\n  id,\n  named,\n}: {\n  id: string;\n  named: ShownNamed;\n}): React.JSX.Element | null {\n  const description = named.source?.declaration.description;\n  const hidden = named.source?.readsHidden ?? [];\n  if (description === undefined && hidden.length === 0) return null;\n  return (\n    <div id={id} className=\"nx-list-query__hints\">\n      {description === undefined ? null : (\n        <p className=\"nx-inspector__note nx-list-query__hint\">{description}</p>\n      )}\n      {hidden.map(read => (\n        <FieldCaution key={read.collection}>\n          <TriangleAlert aria-hidden=\"true\" size={12} />\n          {NAMED_QUERY_TEXT.readsHidden(read.label, read.fields)}\n        </FieldCaution>\n      ))}\n    </div>\n  );\n}\n\n/** What describes the Source control: its error, else its hint, else none. */\nfunction sourceDescribedBy(state: {\n  readonly refused: boolean;\n  readonly hinted: boolean;\n  readonly errorId: string;\n  readonly hintId: string;\n}): string | undefined {\n  if (state.refused) return state.errorId;\n  return state.hinted ? state.hintId : undefined;\n}\n\n/** The collections where none could be listed: the custom sources stand alone. */\nexport const NO_COLLECTIONS: LoopCollections = {\n  kind: \"ready\",\n  collections: [],\n};\n\n/** The mark the Source control's value wears: a custom or a related source's. */\nfunction sourceMark(\n  query: ListQuery,\n  named: ShownNamed | undefined\n): React.JSX.Element | undefined {\n  if (named !== undefined) return CUSTOM_SOURCE_MARK;\n  return query.relation === undefined ? undefined : RELATED_MARK;\n}\n\n/** Whether a custom source has a line to say under Source: its own, or a caution. */\nfunction namedHinted(named: ShownNamed | undefined): boolean {\n  const source = named?.source;\n  return (\n    source !== undefined &&\n    (source.declaration.description !== undefined ||\n      source.readsHidden.length > 0)\n  );\n}\n\n/** Under the Source control: its error, or the hint for what it names. */\nfunction SourceFoot({\n  ids,\n  problems,\n  related,\n  named,\n  collections,\n}: {\n  ids: { readonly error: string; readonly hint: string };\n  problems: readonly string[];\n  related: RelatedSource | undefined;\n  named: ShownNamed | undefined;\n  collections: readonly LoopCollection[];\n}): React.JSX.Element | null {\n  if (problems.length > 0) {\n    return <FieldError id={ids.error}>{problems.join(\" \")}</FieldError>;\n  }\n  if (related !== undefined) {\n    return (\n      <SourceHint id={ids.hint} source={related} collections={collections} />\n    );\n  }\n  return named === undefined ? null : <NamedHint id={ids.hint} named={named} />;\n}\n\n/** The Source control: a collection, a relation where one can be read, or a custom source. */\nexport function SourceField({\n  id,\n  reading,\n  listed,\n  named,\n  disabled,\n  problems,\n  onPick,\n}: {\n  id: string;\n  reading: ListQueryReading;\n  listed: LoopCollections;\n  named: ShownNamed | undefined;\n  disabled: boolean;\n  problems: readonly string[];\n  onPick: (pick: SourceChoice[\"pick\"]) => void;\n}): React.JSX.Element {\n  const { query, collections, customs, related, collectionsOffered } = reading;\n  const labelId = `${id}-label`;\n  const ids = { error: `${id}-error`, hint: `${id}-hint` };\n  const all = [...related.entry, ...related.item];\n  const currentRelated =\n    named === undefined ? relatedSourceOf(all, query.relation) : undefined;\n  const shown = sourceShown(\n    listed,\n    query,\n    currentRelated,\n    collections.find(each => each.slug === query.collection),\n    named\n  );\n  const refused = problems.length > 0;\n  const hinted =\n    !refused && (currentRelated !== undefined || namedHinted(named));\n  return (\n    <div className=\"nx-inspector__field\" data-content-control=\"listSource\">\n      <Label id={labelId} htmlFor={id}>\n        Show entries from\n      </Label>\n      <LoopPicker\n        id={id}\n        labelId={labelId}\n        value={{\n          ...shown,\n          icon: sourceMark(query, named),\n          invalid: refused,\n          describedBy: sourceDescribedBy({\n            refused,\n            hinted,\n            errorId: ids.error,\n            hintId: ids.hint,\n          }),\n        }}\n        disabled={disabled || listed.kind === \"loading\"}\n        list={{\n          choices: sourceChoices(\n            related,\n            collectionsOffered ? collections : undefined,\n            customs\n          ),\n          groups: sourceGroups(related, customs, collectionsOffered),\n          currentKey: sourceKey(query, named),\n          label: \"Sources\",\n          searchLabel: \"Search sources\",\n          noMatch: \"No source matches.\",\n          searchFrom: 1,\n          renderChoice: sourceRow,\n          // Two-line rows need the room; a menu of collections alone keeps\n          // its control's width.\n          wide: customs.length > 0,\n        }}\n        around={{\n          // Where no collection could be listed, no related entry could be\n          // either, and the note above says why.\n          above:\n            all.length > 0 || !collectionsOffered ? undefined : (\n              <NoRelated inEmptyState={related.inEmptyState === true} />\n            ),\n        }}\n        onPick={choice => onPick(choice.pick)}\n      />\n      <SourceFoot\n        ids={ids}\n        problems={problems}\n        related={currentRelated}\n        named={named}\n        collections={collections}\n      />\n      {/* A list with no source asks on the canvas, over the list itself,\n          where its first step picks the entries and a starting layout. */}\n      {hasNoSource(query, named) ? (\n        <p className=\"nx-inspector__note\">{CHOOSE_ON_CANVAS}</p>\n      ) : null}\n    </div>\n  );\n}\n\n/** What the panel says while a list has no source. */\nconst CHOOSE_ON_CANVAS = \"Choose on the canvas to start.\";\n\n/** Whether a list shows nothing yet: no collection, relation or custom source. */\nfunction hasNoSource(query: ListQuery, named: ShownNamed | undefined): boolean {\n  return (\n    named === undefined &&\n    query.relation === undefined &&\n    (query.collection === undefined || query.collection.trim() === \"\")\n  );\n}\n","/**\n * Editing a collection list's custom source in place: the draft of its\n * values, which parts it declares, what it still shows while it is read, and\n * the change of source a choice makes.\n *\n * @module list-query-named-source\n */\nimport {\n  NAMED_QUERY_TEXT,\n  type ListQuery,\n  type NamedQueryParamValue,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport {\n  relatedShownOf,\n  type ListQueryFieldProps,\n  type ListQueryReading,\n} from \"./list-query-reading\";\nimport {\n  sourceChanges,\n  type ShownNamed,\n  type SourceChoice,\n} from \"./list-query-source\";\nimport {\n  judgedDraft,\n  namedSourceChanges,\n  needsInput,\n  withInput,\n  type CustomSource,\n  type StoredParams,\n} from \"./named-query-model\";\n\n/** Whether a new source changes what the list stores. */\nfunction changesSource(\n  query: ListQuery,\n  changes: Readonly<Record<string, unknown>>\n): boolean {\n  return (\n    changes.collection !== query.collection ||\n    JSON.stringify(changes.relation) !== JSON.stringify(query.relation) ||\n    JSON.stringify(changes.namedQuery) !== JSON.stringify(query.namedQuery)\n  );\n}\n\n/**\n * A custom source picked, or its inputs changed, that cannot run yet: kept\n * here and never written, so the list keeps what it stores and the draft is\n * never a page that cannot be saved. For one list, by its id.\n */\ninterface NamedDraft {\n  readonly nodeId: string;\n  readonly name: string;\n  readonly params: StoredParams;\n}\n\n/**\n * The inputs a list may store for a query: only those it declares, so a\n * write leaves out an input the query no longer takes, as its run does.\n */\nfunction declaredOnly(\n  source: CustomSource,\n  params: StoredParams\n): StoredParams {\n  const declared = source.declaration.params ?? {};\n  return Object.fromEntries(\n    Object.entries(params).filter(([key]) => Object.hasOwn(declared, key))\n  );\n}\n\n/** The custom source shown: the draft over what is stored, if any. */\nfunction shownNamedOf(\n  query: ListQuery,\n  draft: NamedDraft | undefined,\n  customs: readonly CustomSource[] | undefined\n): ShownNamed | undefined {\n  const find = (name: string) =>\n    customs?.find(each => each.declaration.name === name);\n  if (draft !== undefined) {\n    return {\n      name: draft.name,\n      params: draft.params,\n      source: find(draft.name),\n      drafted: true,\n      loading: customs === undefined,\n    };\n  }\n  const stored = query.namedQuery;\n  if (stored === undefined) return undefined;\n  return {\n    name: stored.name,\n    params: stored.params,\n    source: find(stored.name),\n    drafted: false,\n    loading: customs === undefined,\n  };\n}\n\n/**\n * What the canvas still draws while a new source waits for an input: the\n * stored source in the words the Source control shows it in. Nothing for a\n * list with no source, which draws its template.\n */\nfunction storedSourceWords(reading: ListQueryReading): string | undefined {\n  const { query, related, collections, customs } = reading;\n  const stored = query.namedQuery;\n  if (stored !== undefined) {\n    return (\n      customs.find(each => each.declaration.name === stored.name)?.declaration\n        .label ?? stored.name\n    );\n  }\n  const relation = relatedShownOf(query, related);\n  if (relation !== undefined) return relation;\n  if (query.collection === undefined) return undefined;\n  return (\n    collections.find(each => each.slug === query.collection)?.label ??\n    query.collection\n  );\n}\n\n/**\n * The canvas's tag for a list whose new source waits: set while it waits,\n * and cleared once it is written or abandoned, once the inspector shows\n * another list, and once it is gone. Each tag is cleared through the\n * function that set it, which names its own list.\n */\nfunction useStillShowing(\n  nodeId: string,\n  tag: ((words: string | undefined) => void) | undefined,\n  words: string | undefined\n): void {\n  const latest = React.useRef(tag);\n  latest.current = tag;\n  const shown = React.useRef<\n    | {\n        readonly nodeId: string;\n        readonly words: string;\n        readonly clear: () => void;\n      }\n    | undefined\n  >(undefined);\n  React.useEffect(() => {\n    const held = shown.current;\n    if (held?.nodeId === nodeId && held.words === words) return;\n    held?.clear();\n    shown.current = undefined;\n    const set = latest.current;\n    if (words === undefined || set === undefined) return;\n    set(words);\n    shown.current = { nodeId, words, clear: () => set(undefined) };\n  }, [nodeId, words]);\n  React.useEffect(() => () => shown.current?.clear(), []);\n}\n\n/** The draft of a custom source, dropped when what the list stores changes. */\nfunction useNamedDraft(\n  nodeId: string,\n  query: ListQuery\n): readonly [\n  NamedDraft | undefined,\n  (draft: Omit<NamedDraft, \"nodeId\"> | undefined) => void,\n] {\n  const [draft, setDraft] = React.useState<NamedDraft | undefined>(undefined);\n  // An undo, a redo or a write elsewhere changes what is stored under a\n  // draft; the draft would then describe a list that no longer exists.\n  const storedText = JSON.stringify([\n    query.collection,\n    query.relation,\n    query.namedQuery,\n  ]);\n  React.useEffect(() => setDraft(undefined), [storedText, nodeId]);\n  const set = React.useCallback(\n    (next: Omit<NamedDraft, \"nodeId\"> | undefined) =>\n      setDraft(next === undefined ? undefined : { ...next, nodeId }),\n    [nodeId]\n  );\n  return [draft?.nodeId === nodeId ? draft : undefined, set];\n}\n\n/** The tag the canvas shows while a draft waits: what the list still draws. */\nfunction stillWords(\n  draft: NamedDraft | undefined,\n  reading: ListQueryReading\n): string | undefined {\n  if (draft === undefined) return undefined;\n  const words = storedSourceWords(reading);\n  return words === undefined ? undefined : NAMED_QUERY_TEXT.stillShowing(words);\n}\n\n/** A list's custom source as the inspector edits it: shown, picked and set. */\nexport interface NamedEditing {\n  readonly named: ShownNamed | undefined;\n  readonly pickSource: (pick: SourceChoice[\"pick\"]) => void;\n  readonly setInput: (\n    key: string,\n    value: NamedQueryParamValue | undefined\n  ) => void;\n}\n\n/**\n * The custom source a list shows and the edits that change its source: a\n * source picked or an input set is written once the query can run, as one\n * write of the props, and kept here until then, the canvas told to tag the\n * list with what it still draws.\n */\nexport function useNamedEditing(\n  nodeId: string,\n  reading: ListQueryReading,\n  commit: (changes: Readonly<Record<string, unknown>>) => void,\n  onStillShowing: ListQueryFieldProps[\"onStillShowing\"]\n): NamedEditing {\n  const { query } = reading;\n  const [draft, setDraft] = useNamedDraft(nodeId, query);\n  const named = shownNamedOf(query, draft, reading.customsRead);\n  useStillShowing(nodeId, onStillShowing, stillWords(draft, reading));\n  const pickCustom = (source: CustomSource) => {\n    const name = source.declaration.name;\n    setDraft(undefined);\n    if (query.namedQuery?.name === name) return;\n    // A query with an input that needs a value waits for it: chosen on\n    // screen, nothing written, the canvas still drawing what is stored.\n    if (needsInput(source.declaration)) setDraft({ name, params: {} });\n    else commit(namedSourceChanges(name, {}));\n  };\n  const pickSource = (pick: SourceChoice[\"pick\"]) => {\n    if (pick.kind === \"custom\") {\n      pickCustom(pick.source);\n      return;\n    }\n    setDraft(undefined);\n    const changes = sourceChanges(query, pick);\n    if (changesSource(query, changes)) commit(changes);\n  };\n  const setInput = (key: string, value: NamedQueryParamValue | undefined) => {\n    const source = named?.source;\n    if (named === undefined || source === undefined) return;\n    const params = withInput(named.params, key, value);\n    if (!judgedDraft(source.declaration, params).writable) {\n      setDraft({ name: named.name, params });\n      return;\n    }\n    setDraft(undefined);\n    const kept = declaredOnly(source, params);\n    // The source and its inputs in one write, so it is one undo step: a\n    // new source is a change even when its inputs equal the stored ones.\n    const stored = query.namedQuery;\n    if (\n      named.name !== stored?.name ||\n      JSON.stringify(kept) !== JSON.stringify(stored.params)\n    ) {\n      commit(namedSourceChanges(named.name, kept));\n    }\n  };\n  return { named, pickSource, setInput };\n}\n","\"use client\";\n\n/**\n * A collection list's Sort: a row per key with its drag handle, field,\n * direction and menu, moved by drag or Alt+arrow, and the button that adds\n * one.\n *\n * @module list-query-sort\n */\nimport {\n  LIST_MAX_SORT_KEYS,\n  listKindSortable,\n  type BlockNode,\n  type ListFieldSource,\n  type ListQuery,\n  type ListSortKey,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { GripVertical, MoreHorizontal, Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChoiceList } from \"../../choice-list\";\n\nimport { LoopPicker } from \"./collection-loop-controls\";\nimport type { LoopListField } from \"./content-controls\";\nimport {\n  fieldList,\n  fieldRow,\n  LimitNote,\n  listLimit,\n  PUBLIC_ONLY,\n  type FieldChoice,\n} from \"./list-query-filters\";\nimport {\n  directionWords,\n  firstDirection,\n  movedKey,\n  sortValue,\n} from \"./list-query-model\";\nimport { FieldError, GroupTitle } from \"./list-query-parts\";\nimport { partIssues } from \"./list-query-reading\";\n\n/** Each key's React key: its field, and how many times it came before. */\nfunction sortRowKeys(keys: readonly ListSortKey[]): string[] {\n  const seen = new Map<string, number>();\n  return keys.map(key => {\n    const count = seen.get(key.field) ?? 0;\n    seen.set(key.field, count + 1);\n    return `${key.field}:${String(count)}`;\n  });\n}\n\n/**\n * The index a dragged row lands at: the row under the pointer, asked of the\n * document rather than measured, so no rectangle is read here; `undefined`\n * where the pointer is over no row of this list.\n */\nfunction dropIndex(\n  list: HTMLElement,\n  at: { readonly clientX: number; readonly clientY: number }\n): number | undefined {\n  const under = list.ownerDocument\n    .elementFromPoint(at.clientX, at.clientY)\n    ?.closest(\".nx-list-sort\");\n  if (under === null || under === undefined || under.parentElement !== list) {\n    return undefined;\n  }\n  return Array.from(list.children).indexOf(under);\n}\n\n/**\n * The step Alt+↑ or Alt+↓ moves a row, as Layers moves a block; nothing for\n * any other key.\n */\nfunction altStep(event: React.KeyboardEvent): -1 | 1 | undefined {\n  if (!event.altKey) return undefined;\n  if (event.key === \"ArrowUp\") return -1;\n  return event.key === \"ArrowDown\" ? 1 : undefined;\n}\n\n/** A key's field, from those a list may sort by; a lost one is marked. */\nfunction SortFieldPicker({\n  id,\n  labelId,\n  sortKey,\n  field,\n  fields,\n  disabled,\n  errorId,\n  onField,\n}: {\n  id: string;\n  labelId: string;\n  sortKey: ListSortKey;\n  field: LoopListField | undefined;\n  fields: readonly LoopListField[];\n  disabled: boolean;\n  /** The id of the key's error, when it has one. */\n  errorId: string | undefined;\n  onField: (field: LoopListField) => void;\n}): React.JSX.Element {\n  return (\n    <LoopPicker\n      id={id}\n      labelId={labelId}\n      value={{\n        words: field?.label ?? `${sortKey.field} · not in this collection`,\n        state: field === undefined ? \"unknown\" : \"value\",\n        invalid: errorId !== undefined,\n        describedBy: errorId,\n      }}\n      disabled={disabled}\n      list={fieldList(fields, sortKey.field, \"Fields to sort by\")}\n      around={{ below: PUBLIC_ONLY }}\n      onPick={choice => onField(choice.field)}\n    />\n  );\n}\n\n/** A key's direction, in the words its field's kind is ordered in. */\nfunction DirectionPicker({\n  name,\n  words,\n  descending,\n  disabled,\n  onDirection,\n}: {\n  name: string;\n  words: { readonly ascending: string; readonly descending: string };\n  descending: boolean;\n  disabled: boolean;\n  onDirection: (descending: boolean) => void;\n}): React.JSX.Element {\n  return (\n    <Select\n      value={descending ? \"descending\" : \"ascending\"}\n      disabled={disabled}\n      onValueChange={value => onDirection(value === \"descending\")}\n    >\n      <SelectTrigger\n        size=\"sm\"\n        aria-label={`Order of ${name}`}\n        className=\"nx-list-sort__direction\"\n      >\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent>\n        <SelectItem value=\"descending\">{words.descending}</SelectItem>\n        <SelectItem value=\"ascending\">{words.ascending}</SelectItem>\n      </SelectContent>\n    </Select>\n  );\n}\n\n/** A key's menu: move it up or down, with the keys that do so, or remove it. */\nfunction SortRowMenu({\n  name,\n  index,\n  count,\n  disabled,\n  onMove,\n  onRemove,\n}: {\n  name: string;\n  index: number;\n  count: number;\n  disabled: boolean;\n  onMove: (to: number) => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <DropdownMenu>\n      <DropdownMenuTrigger asChild>\n        <Button\n          type=\"button\"\n          size=\"icon-sm\"\n          variant=\"ghost\"\n          aria-label={`More for sort by ${name}`}\n          disabled={disabled}\n        >\n          <MoreHorizontal aria-hidden=\"true\" size={14} />\n        </Button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align=\"end\">\n        <DropdownMenuItem\n          disabled={index === 0}\n          onSelect={() => onMove(index - 1)}\n        >\n          Move up\n          <kbd className=\"nx-list-query__kbd\">Alt+↑</kbd>\n        </DropdownMenuItem>\n        <DropdownMenuItem\n          disabled={index === count - 1}\n          onSelect={() => onMove(index + 1)}\n        >\n          Move down\n          <kbd className=\"nx-list-query__kbd\">Alt+↓</kbd>\n        </DropdownMenuItem>\n        <DropdownMenuItem onSelect={onRemove}>Remove</DropdownMenuItem>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/** What a sort row's actions do to the stored keys. */\ninterface SortRowActions {\n  readonly field: (field: LoopListField) => void;\n  readonly direction: (descending: boolean) => void;\n  readonly move: (to: number) => void;\n  readonly remove: () => void;\n  readonly dragStart: (event: React.PointerEvent<HTMLElement>) => void;\n}\n\n/** The handle a sort row is dragged by, which a pointer alone uses. */\nfunction SortHandle({\n  disabled,\n  onDragStart,\n}: {\n  disabled: boolean;\n  onDragStart: SortRowActions[\"dragStart\"];\n}): React.JSX.Element {\n  return (\n    <span\n      className=\"nx-list-sort__handle\"\n      aria-hidden=\"true\"\n      title=\"Drag to reorder\"\n      onPointerDown={disabled ? undefined : onDragStart}\n    >\n      <GripVertical size={14} />\n    </span>\n  );\n}\n\n/** Alt+↑ and Alt+↓ on a sort row move it, unless the group is disabled. */\nfunction altMover(\n  disabled: boolean,\n  index: number,\n  move: SortRowActions[\"move\"]\n): (event: React.KeyboardEvent<HTMLElement>) => void {\n  return event => {\n    const step = disabled ? undefined : altStep(event);\n    if (step === undefined) return;\n    event.preventDefault();\n    move(index + step);\n  };\n}\n\n/** One sort key: handle, field, direction in words, and its menu. */\nfunction SortRow({\n  id,\n  index,\n  count,\n  sortKey,\n  fields,\n  disabled,\n  problem,\n  dragging,\n  on,\n}: {\n  id: string;\n  index: number;\n  count: number;\n  sortKey: ListSortKey;\n  fields: readonly LoopListField[];\n  disabled: boolean;\n  problem: string | undefined;\n  dragging: boolean;\n  on: SortRowActions;\n}): React.JSX.Element {\n  const field = fields.find(each => each.name === sortKey.field);\n  const name = field?.label ?? sortKey.field;\n  const labelId = `${id}-label`;\n  // The row's error, by id, when it has one.\n  const errorId = problem === undefined ? undefined : `${id}-error`;\n  return (\n    <li\n      className=\"nx-list-sort\"\n      data-dragging={dragging ? \"\" : undefined}\n      data-invalid={errorId === undefined ? undefined : \"\"}\n      onKeyDown={altMover(disabled, index, on.move)}\n    >\n      <span id={labelId} className=\"nx-sr-only\">\n        {`Sort ${String(index + 1)} of ${String(count)}, by`}\n      </span>\n      <SortHandle disabled={disabled} onDragStart={on.dragStart} />\n      <SortFieldPicker\n        id={`${id}-field`}\n        labelId={labelId}\n        sortKey={sortKey}\n        field={field}\n        fields={fields}\n        disabled={disabled}\n        errorId={errorId}\n        onField={on.field}\n      />\n      <DirectionPicker\n        name={name}\n        words={directionWords(field?.kind)}\n        descending={sortKey.descending}\n        disabled={disabled || field === undefined}\n        onDirection={on.direction}\n      />\n      <SortRowMenu\n        name={name}\n        index={index}\n        count={count}\n        disabled={disabled}\n        onMove={on.move}\n        onRemove={on.remove}\n      />\n      {errorId === undefined ? null : (\n        <FieldError id={errorId}>{problem}</FieldError>\n      )}\n    </li>\n  );\n}\n\n/**\n * Focus the first sort row's field, or Add sort when there is no row, once\n * per new ask. After the frame the ask is drawn in, since the ask can move\n * the inspector to its Content tab in the same draw, which reveals the row.\n */\nfunction useFocusOnAsk(\n  group: React.RefObject<HTMLElement | null>,\n  asked: number | undefined,\n  firstFieldId: string\n): void {\n  const answered = React.useRef<number | undefined>(undefined);\n  React.useEffect(() => {\n    if (asked === undefined || asked === answered.current) return;\n    const timer = setTimeout(() => {\n      // Answered once it has run, not once it is scheduled: an effect run\n      // again (React's StrictMode does so at once) clears the timer first, and\n      // an ask already marked answered would then never be answered at all.\n      answered.current = asked;\n      const root = group.current;\n      if (root === null) return;\n      const target =\n        root.ownerDocument.getElementById(firstFieldId) ??\n        root.querySelector<HTMLElement>(\"[data-list-add-sort]\");\n      target?.scrollIntoView({ block: \"nearest\" });\n      target?.focus();\n    }, 0);\n    return () => clearTimeout(timer);\n  }, [group, asked, firstFieldId]);\n}\n\n/** The menu of fields a new sort key can order by. */\nfunction AddSortButton({\n  fields,\n  disabled,\n  describedBy,\n  onPick,\n}: {\n  fields: readonly LoopListField[];\n  disabled: boolean;\n  /** The note saying why the button is off, when it is. */\n  describedBy: string | undefined;\n  onPick: (field: LoopListField) => void;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const choices: FieldChoice[] = fields.map(each => ({\n    key: each.name,\n    label: each.label,\n    field: each,\n  }));\n  return (\n    <Popover open={open} onOpenChange={setOpen} modal={false}>\n      <PopoverTrigger asChild>\n        <Button\n          type=\"button\"\n          size=\"sm\"\n          variant=\"ghost\"\n          className=\"nx-list-query__add\"\n          // Where an ask to fix the sort lands when there is no row.\n          data-list-add-sort=\"\"\n          disabled={disabled || fields.length === 0}\n          aria-describedby={describedBy}\n        >\n          <Plus aria-hidden=\"true\" size={14} />\n          Add sort\n        </Button>\n      </PopoverTrigger>\n      <PopoverContent\n        align=\"start\"\n        sideOffset={4}\n        className=\"nx-font-pick__popover\"\n        onOpenAutoFocus={event => event.preventDefault()}\n      >\n        <div className=\"nx-font-pick__body\">\n          <ChoiceList\n            choices={choices}\n            currentKey={undefined}\n            label=\"Fields to sort by\"\n            searchLabel=\"Search fields\"\n            noMatch=\"No field matches.\"\n            searchFrom={1}\n            renderChoice={fieldRow}\n            onPick={choice => {\n              setOpen(false);\n              onPick(choice.field);\n            }}\n          />\n          {PUBLIC_ONLY}\n        </div>\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/** The Sort group: one row per key, in order, and a way to add one. */\nexport function SortGroup({\n  id,\n  query,\n  node,\n  fields,\n  fieldSource,\n  disabled,\n  problems,\n  fieldAsked,\n  onSort,\n}: {\n  id: string;\n  query: ListQuery;\n  node: BlockNode;\n  fields: readonly LoopListField[];\n  fieldSource: ListFieldSource | undefined;\n  disabled: boolean;\n  problems: readonly string[];\n  /** The count of the latest ask to fix this sort, from the canvas. */\n  fieldAsked: number | undefined;\n  onSort: (keys: readonly ListSortKey[]) => void;\n}): React.JSX.Element {\n  const keys = query.sort;\n  const sortLimit = listLimit(keys.length, LIST_MAX_SORT_KEYS, id);\n  const group = React.useRef<HTMLElement>(null);\n  useFocusOnAsk(group, fieldAsked, `${id}-0-field`);\n  const sortable = fields.filter(field => listKindSortable(field.kind));\n  const rowKeys = sortRowKeys(keys);\n  const list = React.useRef<HTMLOListElement>(null);\n  const [drag, setDrag] = React.useState<{ from: number; to: number } | null>(\n    null\n  );\n  const startDrag =\n    (from: number) => (event: React.PointerEvent<HTMLElement>) => {\n      const handle = event.currentTarget;\n      const rows = list.current;\n      if (rows === null) return;\n      handle.setPointerCapture(event.pointerId);\n      let to = from;\n      setDrag({ from, to });\n      const move = (moved: PointerEvent) => {\n        to = dropIndex(rows, moved) ?? to;\n        setDrag({ from, to });\n      };\n      const end = () => {\n        handle.removeEventListener(\"pointermove\", move);\n        handle.removeEventListener(\"pointerup\", end);\n        handle.removeEventListener(\"pointercancel\", end);\n        setDrag(null);\n        if (to !== from) onSort(movedKey(keys, from, to));\n      };\n      handle.addEventListener(\"pointermove\", move);\n      handle.addEventListener(\"pointerup\", end);\n      handle.addEventListener(\"pointercancel\", end);\n    };\n  const shown = drag === null ? keys : movedKey(keys, drag.from, drag.to);\n  const shownRowKeys =\n    drag === null\n      ? rowKeys\n      : movedKey(\n          rowKeys.map(each => ({ field: each, descending: false })),\n          drag.from,\n          drag.to\n        ).map(each => each.field);\n  const titleId = `${id}-title`;\n  return (\n    <section\n      ref={group}\n      className=\"nx-list-query__group\"\n      aria-labelledby={titleId}\n    >\n      <GroupTitle id={titleId}>Sort</GroupTitle>\n      {shown.length === 0 ? (\n        <p className=\"nx-inspector__note nx-list-query__hint\">\n          {query.relation === undefined\n            ? \"No sort: entries show in the order they were added.\"\n            : \"No sort: entries show in the order chosen on the entry.\"}\n        </p>\n      ) : (\n        <ol ref={list} className=\"nx-list-query__sort\" aria-label=\"Sort keys\">\n          {shown.map((key, index) => {\n            const original = drag === null ? index : keys.indexOf(key);\n            const problems = partIssues(\n              node,\n              { sort: sortValue([key]) },\n              fieldSource\n            );\n            return (\n              <SortRow\n                key={shownRowKeys[index] ?? String(index)}\n                id={`${id}-${String(index)}`}\n                index={index}\n                count={shown.length}\n                sortKey={key}\n                fields={sortable}\n                disabled={disabled}\n                problem={\n                  problems.length === 0\n                    ? undefined\n                    : problems.map(issue => issue.message).join(\" \")\n                }\n                dragging={drag !== null && drag.to === index}\n                on={{\n                  field: field =>\n                    onSort(\n                      keys.map((each, at) =>\n                        at === index\n                          ? { field: field.name, descending: each.descending }\n                          : each\n                      )\n                    ),\n                  direction: descending =>\n                    onSort(\n                      keys.map((each, at) =>\n                        at === index ? { ...each, descending } : each\n                      )\n                    ),\n                  move: to => {\n                    if (to < 0 || to >= keys.length) return;\n                    onSort(movedKey(keys, index, to));\n                  },\n                  remove: () => onSort(keys.filter((_, at) => at !== index)),\n                  dragStart: startDrag(original),\n                }}\n              />\n            );\n          })}\n        </ol>\n      )}\n      {problems.length === 0 ? null : (\n        <FieldError id={`${id}-error`}>{problems.join(\" \")}</FieldError>\n      )}\n      <AddSortButton\n        fields={sortable.filter(\n          field => !keys.some(key => key.field === field.name)\n        )}\n        // No key past the most a list sorts by, which the save refuses.\n        disabled={disabled || sortLimit.full}\n        describedBy={sortLimit.describedBy}\n        onPick={field =>\n          onSort([\n            ...keys,\n            { field: field.name, descending: firstDirection(field.kind) },\n          ])\n        }\n      />\n      <LimitNote limit={sortLimit}>Up to {LIST_MAX_SORT_KEYS} sorts.</LimitNote>\n      {shown.length === 0 ? null : (\n        <p className=\"nx-inspector__note nx-list-query__hint\">\n          Entries with the same values keep a fixed order. Entries with no value\n          come last.\n        </p>\n      )}\n    </section>\n  );\n}\n","\"use client\";\n\n/**\n * A collection list's query in the Content tab, as one group of controls:\n * where its entries come from, the filters that narrow them, the order they\n * come in, how many show, and what the canvas shows when none match.\n *\n * - **Source**: a collection, or a to-many relation of the page's entry or\n *   of each item of the list this one sits in. A relation is offered only\n *   where it can be read, and the menu says why when none is.\n * - **Filters**: one sentence per row (\"Category is any of News, Guides\")\n *   that opens in place into its field, operator and value. A new filter\n *   opens already open. A row is written once it is complete; until then it\n *   is kept here and says what it lacks, and the canvas keeps the last\n *   query that read.\n * - **Sort**: a row per key, each with a drag handle, its field, its\n *   direction in words for the field's kind, and a menu to move or remove\n *   it. Alt+↑ and Alt+↓ move the focused row, as they move a block in Layers.\n * - **How many**: the number of items and the entries to skip, each refused\n *   inline while it is not one a save takes.\n * - **When nothing matches**: whether the canvas draws the entries or the\n *   empty state, which is editor state and never stored.\n *\n * Everything stored is read by the engine's `readListQuery`, and every\n * problem shown is the engine's `listQueryIssues`, so what this says and what\n * a save refuses are one judgement. Each action is one write of the block's\n * props, so it is one undo step. Only fields visitors can see are offered,\n * and none holding several values: the host's list is the public's.\n *\n * This module draws the field and the parts of its query; each area is a\n * module of its own: what the controls read and share\n * (`list-query-reading`), the Source field (`list-query-source`), the\n * filters (`list-query-filters`, with their values in\n * `list-query-filter-values`), the sort (`list-query-sort`), how many show\n * (`list-query-how-many`) and editing a custom source\n * (`list-query-named-source`).\n *\n * @module list-query-controls\n */\nimport { findNode, type BlockNode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { ContentServices } from \"./content-controls\";\nimport { FiltersGroup } from \"./list-query-filters\";\nimport {\n  CanvasShowsGroup,\n  codedIssues,\n  HowManyGroup,\n} from \"./list-query-how-many\";\nimport { sortValue } from \"./list-query-model\";\nimport { useNamedEditing, type NamedEditing } from \"./list-query-named-source\";\nimport {\n  issuesAt,\n  LIST_QUERY_PROPS,\n  relatedShownOf,\n  useListQueryReading,\n  type ListQueryFieldProps,\n  type ListQueryReading,\n} from \"./list-query-reading\";\nimport { SortGroup } from \"./list-query-sort\";\nimport { NO_COLLECTIONS, SourceField } from \"./list-query-source\";\nimport {\n  FiltersSetBy,\n  InputsGroup,\n  KeptInputsGroup,\n} from \"./named-query-controls\";\nimport { judgedDraft } from \"./named-query-model\";\n\nexport { FilterValue, useEntryTitles } from \"./list-query-filter-values\";\nexport {\n  fieldList,\n  LimitNote,\n  listLimit,\n  PUBLIC_ONLY,\n} from \"./list-query-filters\";\nexport {\n  fieldSourceOf,\n  LIST_QUERY_PROPS,\n  useCustomSources,\n  type ListQueryFieldProps,\n} from \"./list-query-reading\";\n// Part of this module's exported names; no importer in the package reads them.\n// fallow-ignore-next-line unused-type\nexport type { ValueProps } from \"./list-query-filter-values\";\n// fallow-ignore-next-line unused-type\nexport type { FieldChoice } from \"./list-query-filters\";\n// fallow-ignore-next-line unused-type\nexport type { ListLimit } from \"./list-query-filters\";\n// fallow-ignore-next-line unused-type\nexport type { OfferedField } from \"./list-query-filters\";\n\n/** What the groups under Source are drawn with. */\ninterface QueryPartsProps {\n  readonly id: string;\n  readonly reading: ListQueryReading;\n  readonly node: BlockNode;\n  readonly editing: NamedEditing;\n  readonly held: boolean;\n  readonly services: ContentServices | undefined;\n  readonly sortFieldAsked: number | undefined;\n  readonly commit: (changes: Readonly<Record<string, unknown>>) => void;\n}\n\n/** Filters and Sort, for a collection or a related source. */\nfunction CollectionParts({\n  id,\n  reading,\n  node,\n  held,\n  services,\n  sortFieldAsked,\n  commit,\n}: QueryPartsProps): React.JSX.Element {\n  const { query, issues, fields, fieldSource } = reading;\n  const unsourced = held || query.collection === undefined;\n  return (\n    <>\n      <FiltersGroup\n        key={query.collection ?? \"\"}\n        id={`${id}-filters`}\n        query={query}\n        node={node}\n        fields={fields}\n        fieldSource={fieldSource}\n        disabled={unsourced}\n        problems={codedIssues(issues, \"filters\", \"list-filter-invalid\")}\n        services={services}\n        relatedWordsShown={relatedShownOf(query, reading.related)}\n        onFilters={filters => commit({ filters })}\n      />\n      <SortGroup\n        id={`${id}-sort`}\n        query={query}\n        node={node}\n        fields={fields}\n        fieldSource={fieldSource}\n        disabled={unsourced}\n        problems={codedIssues(issues, \"sort\", \"list-sort-invalid\")}\n        fieldAsked={sortFieldAsked}\n        onSort={keys => commit({ sort: sortValue(keys) })}\n      />\n    </>\n  );\n}\n\n/**\n * The groups under Source: Filters and Sort for a collection or a related\n * source; Inputs and the read-only Filters and sort line for a custom one;\n * and for a stored custom source the site no longer registers, what it\n * keeps, once the site's sources are known to lack it.\n */\nfunction QueryParts(props: QueryPartsProps): React.JSX.Element | null {\n  const { id, reading, editing, held, services } = props;\n  const named = editing.named;\n  if (named === undefined) return <CollectionParts {...props} />;\n  const source = named.source;\n  if (source === undefined) {\n    return reading.customsRead === undefined ? null : (\n      <KeptInputsGroup id={`${id}-inputs`} params={named.params} />\n    );\n  }\n  const judged = judgedDraft(source.declaration, named.params);\n  return (\n    <>\n      <InputsGroup\n        key={named.name}\n        id={`${id}-inputs`}\n        declaration={source.declaration}\n        params={named.params}\n        problems={judged.problems}\n        unknown={judged.unknown}\n        disabled={held}\n        services={services}\n        onInput={editing.setInput}\n      />\n      <FiltersSetBy id={`${id}-filters`} declaration={source.declaration} />\n    </>\n  );\n}\n\n/**\n * The Source control, and, where the site's collections could not be\n * listed, the note saying so: then the custom sources are offered alone, or\n * no source can be chosen where there are none.\n */\nfunction SourcePart({\n  id,\n  reading,\n  editing,\n  held,\n}: {\n  id: string;\n  reading: ListQueryReading;\n  editing: NamedEditing;\n  held: boolean;\n}): React.JSX.Element {\n  const { listed, issues } = reading;\n  const unlisted = listed === undefined || listed.kind === \"failed\";\n  const offersCustom = reading.customs.length > 0;\n  // Custom sources read before the collections are usable at once: the\n  // collections join the menu when they arrive.\n  const waiting = listed?.kind === \"loading\" && offersCustom;\n  return (\n    <>\n      {unlisted ? (\n        <p className=\"nx-inspector__note\">\n          {offersCustom ? (\n            <>\n              The site&apos;s collections could not be listed, so only its\n              custom sources are offered here.\n            </>\n          ) : (\n            <>\n              The site&apos;s collections could not be listed, so this\n              list&apos;s source, filters and sort can&apos;t be chosen here.\n            </>\n          )}\n        </p>\n      ) : null}\n      {unlisted && !offersCustom ? null : (\n        <SourceField\n          id={id}\n          reading={reading}\n          listed={unlisted || waiting ? NO_COLLECTIONS : listed}\n          named={editing.named}\n          disabled={held}\n          // A source just picked has nothing stored to refuse yet.\n          problems={\n            editing.named?.drafted === true\n              ? []\n              : issuesAt(issues, [\"collection\", \"relation\", \"namedQuery\"])\n          }\n          onPick={editing.pickSource}\n        />\n      )}\n    </>\n  );\n}\n\n/**\n * A collection list's query, drawn as one group in the Content tab where its\n * `collection` prop would sit.\n */\nexport function ListQueryField({\n  props,\n  writable,\n  services,\n  onCommitMany,\n  document,\n  nodeId,\n  showsEmpty,\n  onShowEmpty,\n  sortFieldAsked,\n  onStillShowing,\n}: ListQueryFieldProps): React.JSX.Element | null {\n  const id = React.useId();\n  const reading = useListQueryReading(props, services, document, nodeId);\n  const commit = (changes: Readonly<Record<string, unknown>>) => {\n    onCommitMany(changes);\n  };\n  const editing = useNamedEditing(nodeId, reading, commit, onStillShowing);\n  const node = findNode(document.nodes, nodeId);\n  if (node === undefined) return null;\n  const held = LIST_QUERY_PROPS.some(\n    name => props.some(prop => prop.name === name) && !writable(name)\n  );\n  const { issues } = reading;\n  return (\n    <div className=\"nx-list-query\" data-content-control=\"listQuery\">\n      <SourcePart\n        id={`${id}-source`}\n        reading={reading}\n        editing={editing}\n        held={held}\n      />\n      <QueryParts\n        id={id}\n        reading={reading}\n        node={node}\n        editing={editing}\n        held={held}\n        services={services}\n        sortFieldAsked={sortFieldAsked}\n        commit={commit}\n      />\n      <HowManyGroup\n        id={`${id}-many`}\n        values={reading.values}\n        limitFallback={props.find(prop => prop.name === \"limit\")?.defaultValue}\n        issues={issues}\n        disabled={held}\n        count={services?.countListEntries}\n        commit={commit}\n      />\n      {onShowEmpty === undefined ? null : (\n        <CanvasShowsGroup\n          id={`${id}-empty`}\n          showsEmpty={showsEmpty}\n          onShowEmpty={onShowEmpty}\n        />\n      )}\n    </div>\n  );\n}\n","/**\n * Which blocks' visibility conditions the page can't check: the ones the\n * engine finds a problem with, judged as a save judges them, and the ones\n * stored in a shape no condition row can show. Visitors never see such a\n * block, so the editor says so wherever it draws one: the inspector's notice\n * and the canvas's red badge read this one answer.\n *\n * @module condition-checks\n */\nimport {\n  conditionIssues,\n  DEFAULT_LIMITS,\n  placementGatesOf,\n  revealConditioned,\n  resolveComponentInstances,\n  isPlainRecord,\n  walkNodes,\n  type BlockDocument,\n  type BlockNode,\n  type Condition,\n  type DefinitionsById,\n  type DocumentLimits,\n  type NodeVisibility,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { useLoopCollections } from \"../inspector/content/collection-loop-controls\";\nimport type {\n  ContentServices,\n  LoopCollection,\n} from \"../inspector/content/content-controls\";\nimport { fieldSourceOf } from \"../inspector/content/list-query-controls\";\n\nimport { asStoredDefinitions, gatedAsStored } from \"./condition-gate\";\n\n/** Whether a stored value is a condition a row can show: a field and an operator. */\nfunction isConditionRecord(value: unknown): value is Condition {\n  if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n    return false;\n  }\n  const { field, op } = value as { field?: unknown; op?: unknown };\n  return typeof field === \"string\" && typeof op === \"string\";\n}\n\n/**\n * The stored groups, an OR of AND groups of conditions; none when nothing is\n * stored, and `undefined` for a shape no row can show, such as a flat list of\n * conditions or a group holding something else. The engine hides a block\n * whose conditions it can't read, and says why.\n */\nexport function storedGroups(\n  node: BlockNode\n): readonly (readonly Condition[])[] | undefined {\n  const envelope: unknown = node.visibility;\n  if (envelope === undefined || envelope === null) return [];\n  // A visibility that is not a record, a string or a list, is one the engine\n  // reads as a restriction it can't check.\n  if (!isPlainRecord(envelope)) return undefined;\n  const groups: unknown = envelope.conditions;\n  if (groups === undefined) return [];\n  // Stored as `null`, which the save refuses as malformed although the page\n  // reads it as no restriction: offered for removal, as any shape no row can\n  // show is.\n  if (groups === null) return undefined;\n  if (!Array.isArray(groups)) return undefined;\n  const read: Condition[][] = [];\n  for (const group of groups as unknown[]) {\n    // Every position read, holes included: `every` skips a hole, which would\n    // reach the rows as a condition that isn't there.\n    if (!Array.isArray(group) || !Array.from(group).every(isConditionRecord)) {\n      return undefined;\n    }\n    read.push(group);\n  }\n  return read;\n}\n\n/**\n * The blocks in a forest whose conditions the page can't check. A problem\n * that needs the collections' fields is judged once they are listed, so a\n * block isn't marked while they load. If they can't be listed, what needs no\n * fields is still judged (an operator conditions don't have, an entry a\n * Single's page doesn't have). One stored in a shape no row can show needs no\n * fields and is always marked. Read as far as `maxNodes`, the limit a save\n * surveys a document to.\n */\nexport function uncheckedConditionIds(\n  nodes: readonly BlockNode[],\n  collections: readonly LoopCollection[] | \"loading\" | \"unavailable\",\n  entryCollection: string | null | undefined,\n  maxNodes: number = DEFAULT_LIMITS.maxNodes\n): ReadonlySet<string> {\n  const found = new Set<string>();\n  // The engine's guarded walk, which tolerates a malformed entry and a tree\n  // deeper than a call stack, as a stored document may be, and stops where a\n  // save stops surveying.\n  walkNodes(\n    [...nodes],\n    node => {\n      if (gatedAsStored(node) && storedGroups(node) === undefined) {\n        found.add(node.id);\n      }\n    },\n    { maxNodes }\n  );\n  if (collections === \"loading\") return found;\n  for (const issue of conditionIssues(nodes, {\n    ...(collections === \"unavailable\"\n      ? {}\n      : { fields: fieldSourceOf(collections) }),\n    // As far as a save surveys a document, and no further.\n    maxNodes,\n    ...(entryCollection === undefined ? {} : { entryCollection }),\n  })) {\n    if (issue.severity === \"error\") found.add(issue.nodeId);\n  }\n  return found;\n}\n\n/**\n * A composed tree once for each depth of placement gates it carries. In the\n * k-th, a block carrying more than k gates holds the k-th as its own\n * visibility and every other block holds none, so each gate a placement\n * nested in a component put on a block is judged as conditions are, where\n * the block is drawn, inside the lists around it, and by the id the canvas\n * draws it with.\n */\nfunction placementGatePasses(nodes: readonly BlockNode[]): BlockNode[][] {\n  const passes: BlockNode[][] = [];\n  for (let depth = 0; ; depth += 1) {\n    const found = { any: false };\n    const pass = withGateAt(nodes, depth, found);\n    if (!found.any) return passes;\n    passes.push(pass);\n  }\n}\n\n/** A forest with each block's `depth`-th placement gate as its visibility. */\nfunction withGateAt(\n  nodes: readonly BlockNode[],\n  depth: number,\n  found: { any: boolean }\n): BlockNode[] {\n  return nodes.map(node => {\n    const gate = isPlainRecord(node.visibility)\n      ? placementGatesOf(node.visibility)[depth]\n      : undefined;\n    const next: BlockNode = { ...node };\n    if (gate === undefined) {\n      delete next.visibility;\n    } else {\n      found.any = true;\n      // As the placement stored it, an unreadable one included, which the\n      // judgement marks as it marks one stored on a block.\n      next.visibility = gate as NodeVisibility;\n    }\n    if (isPlainRecord(node.slots)) {\n      const slots: Record<string, BlockNode[]> = {};\n      for (const [name, children] of Object.entries(node.slots)) {\n        if (Array.isArray(children)) {\n          slots[name] = withGateAt(children, depth, found);\n        }\n      }\n      next.slots = slots;\n    }\n    return next;\n  });\n}\n\n/**\n * {@link uncheckedConditionIds} for a document, as an editor's services list\n * the collections: its own blocks, and with `definitions` the blocks its\n * placed components hold too, judged in the tree composed as the canvas\n * draws it, by the ids the canvas draws them with.\n */\nexport function useConditionsUnchecked(\n  document: BlockDocument,\n  services:\n    | Pick<ContentServices, \"listLoopCollections\" | \"entryCollection\">\n    | undefined,\n  /** The document limits the host renders and saves under. */\n  limits?: DocumentLimits,\n  /** The definitions of the components the document places. */\n  definitions?: DefinitionsById\n): ReadonlySet<string> {\n  const listed = useLoopCollections(services?.listLoopCollections);\n  const collections =\n    listed === undefined || listed.kind === \"failed\"\n      ? \"unavailable\"\n      : listed.kind === \"loading\"\n        ? \"loading\"\n        : listed.collections;\n  const entryCollection = services?.entryCollection;\n  const maxNodes = limits?.maxNodes;\n  return React.useMemo(() => {\n    const own = uncheckedConditionIds(\n      document.nodes,\n      collections,\n      entryCollection,\n      maxNodes\n    );\n    if (definitions === undefined || definitions.size === 0) return own;\n    // The page's own conditions lifted, as the canvas composes it, so a\n    // composed block holds only what its definition gave it.\n    const composed = resolveComponentInstances(\n      revealConditioned(document),\n      asStoredDefinitions(definitions, limits),\n      {\n        conditioned: \"carry\",\n        // Every limit the canvas composes under, so a site that raises the\n        // depth has its deeper blocks judged as they are drawn.\n        ...(limits === undefined ? {} : { limits }),\n      }\n    ).document;\n    const judged = (nodes: readonly BlockNode[]) => [\n      ...uncheckedConditionIds(nodes, collections, entryCollection, maxNodes),\n    ];\n    return new Set([\n      ...own,\n      ...judged(composed.nodes),\n      // And each gate a placement nested in a component put on its roots.\n      ...placementGatePasses(composed.nodes).flatMap(judged),\n    ]);\n  }, [document, collections, entryCollection, maxNodes, limits, definitions]);\n}\n","/**\n * A block's visibility conditions as the \"Show when\" controls read and write\n * them: the operators each kind of field offers, worded as the list filter\n * words them where the two share a meaning, a condition as one sentence, and\n * a draft row as the stored condition it would be.\n *\n * The operators are exactly the engine's `CONDITION_KIND_OPS`, which the save\n * judges a condition by, so the menu never offers one the save refuses.\n *\n * @module condition-model\n */\nimport {\n  CONDITION_KIND_OPS,\n  conditionFieldKind,\n  conditionOp,\n  type BindingFieldShape,\n  type Condition,\n  type ConditionFieldKind,\n  type ConditionOp,\n  type ListFilterOp,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type {\n  LoopCollection,\n  LoopListField,\n} from \"../inspector/content/content-controls\";\nimport {\n  filterSentence,\n  type QueryField,\n} from \"../inspector/content/list-query-model\";\n\n/**\n * A field a condition can check: one a list filters by, with its kind, or a\n * field the public may read that no list filters by (several entries, media,\n * rich text, a time of day), which a condition can only ask has a value.\n */\nexport interface ConditionField {\n  readonly name: string;\n  readonly label: string;\n  readonly kind: ConditionFieldKind;\n  readonly options?: QueryField[\"options\"];\n  readonly relationTo?: string;\n  readonly dateOnly?: boolean;\n  /** What the field menu calls a field of kind `other`: \"Several entries\". */\n  readonly kindWords?: string;\n}\n\n/** One readable field, as a collection sends it. */\ntype ReadableField = NonNullable<LoopCollection[\"readable\"]>[number];\n\n/** What the field menu calls a field no list filters by, by what it holds. */\nfunction otherKindWords(shape: ReadableField): string {\n  // Before relations: an upload names the collection its files are in too.\n  if (shape.type === \"upload\") {\n    return shape.hasMany === true ? \"Several files\" : \"Media\";\n  }\n  if (shape.relationTo !== undefined) {\n    return shape.hasMany === true ? \"Several entries\" : \"Entry\";\n  }\n  if (shape.timeOnly === true) return \"Time of day\";\n  if (shape.type === \"richText\") return \"Rich text\";\n  if (shape.hasMany === true) return \"Several values\";\n  return \"Other\";\n}\n\n/**\n * The fields a block's conditions can check in a collection: its list\n * fields, then every other field the public may read, as the engine's kind\n * for it says (`other`), in the collection's order. Derived from the readable\n * schema the save judges by, so the editor offers what the save accepts.\n */\nexport function conditionFieldsOf(\n  collection: LoopCollection\n): readonly ConditionField[] {\n  const listed = new Set(collection.fields.map(field => field.name));\n  const others = (collection.readable ?? []).flatMap(shape =>\n    listed.has(shape.name) ? [] : [conditionFieldOf(shape)]\n  );\n  return [...collection.fields, ...others];\n}\n\n/**\n * The fields a block's conditions can check in a list's items whose source\n * is a named query with rows of its own schema: the fields its rows declare,\n * each of the kind the save judges it by.\n */\nexport function conditionFieldsOfShapes(\n  shapes: readonly BindingFieldShape[]\n): readonly ConditionField[] {\n  return shapes.map(shape => {\n    const field = conditionFieldOf(shape);\n    // A row's choices are declared as their stored values, which are also\n    // what an author picks between; a day-only date is entered as a day.\n    if (field.kind === \"choice\" && shape.options !== undefined) {\n      return {\n        ...field,\n        options: shape.options.map(value => ({ value, label: value })),\n      };\n    }\n    return field.kind === \"date\" && shape.dateOnly === true\n      ? { ...field, dateOnly: true }\n      : field;\n  });\n}\n\n/**\n * One field as a condition checks it, of the kind the save judges it by: a\n * field no list offers may still be a scalar, such as an entry's id, with\n * that kind's operators.\n */\nfunction conditionFieldOf(shape: ReadableField): ConditionField {\n  const kind = conditionFieldKind(shape);\n  return {\n    name: shape.name,\n    label: shape.label ?? shape.name,\n    kind,\n    ...(kind === \"other\" ? { kindWords: otherKindWords(shape) } : {}),\n    ...(kind === \"entry\" && typeof shape.relationTo === \"string\"\n      ? { relationTo: shape.relationTo }\n      : {}),\n  };\n}\n\n/** A field as a list's filter controls take it, for one a list filters by. */\nexport function asListField(\n  field: ConditionField | undefined\n): LoopListField | undefined {\n  if (field === undefined || field.kind === \"other\") return undefined;\n  return { ...field, kind: field.kind };\n}\n\n/** One operator an author picks, keyed for a menu. */\nexport interface ConditionChoice {\n  readonly key: string;\n  readonly op: ConditionOp;\n  readonly label: string;\n}\n\n/** What each operator is called, an order worded as a number's. */\nconst LABELS: Readonly<Record<ConditionOp, string>> = {\n  equals: \"is\",\n  not_equals: \"is not\",\n  contains: \"contains\",\n  not_contains: \"doesn’t contain\",\n  greater_than: \"is more than\",\n  less_than: \"is less than\",\n  exists: \"has a value\",\n  not_exists: \"is empty\",\n  is_true: \"is\",\n  is_false: \"is\",\n};\n\n/** A date's order, worded as days, as a list's date filter is. */\nconst DATE_LABELS: Readonly<Partial<Record<ConditionOp, string>>> = {\n  greater_than: \"is after\",\n  less_than: \"is before\",\n};\n\n/**\n * A yes-or-no field's `equals` and `not_equals` against No, worded apart from\n * \"is\": unlike `is_false`, `equals` No doesn't hold for a field with no value,\n * and `not_equals` No holds for one.\n */\nconst BOOLEAN_EXACT: Readonly<Partial<Record<ConditionOp, string>>> = {\n  equals: \"is set to\",\n  not_equals: \"isn’t set to\",\n};\n\n/**\n * The operators offered for a field of each kind, in menu order. A yes-or-no\n * field offers one, \"is\", whose Yes or No is stored as `is_true` or\n * `is_false`. The engine's `equals` and `not_equals` against Yes read as\n * those (see `toDraft`); against No they differ on an empty value, so a\n * stored one is listed as it is, `current`, and is otherwise not offered.\n */\nexport function conditionChoices(\n  kind: ConditionFieldKind,\n  current?: ConditionOp\n): readonly ConditionChoice[] {\n  if (kind === \"boolean\") {\n    const exact = current === undefined ? undefined : BOOLEAN_EXACT[current];\n    return [\n      { key: \"is\", op: \"is_true\", label: \"is\" },\n      ...(exact === undefined || current === undefined\n        ? []\n        : [{ key: current, op: current, label: exact }]),\n    ];\n  }\n  return CONDITION_KIND_OPS[kind].map(op => ({\n    key: op,\n    op,\n    label: (kind === \"date\" ? DATE_LABELS[op] : undefined) ?? LABELS[op],\n  }));\n}\n\n/** The menu key a stored condition's operator is listed under. */\nexport function choiceKey(op: ConditionOp): string {\n  return op === \"is_true\" || op === \"is_false\" ? \"is\" : op;\n}\n\n/** Whether an operator compares the field with a value an author gives. */\nfunction takesValue(op: ConditionOp): boolean {\n  return (\n    op === \"equals\" ||\n    op === \"not_equals\" ||\n    op === \"contains\" ||\n    op === \"not_contains\" ||\n    op === \"greater_than\" ||\n    op === \"less_than\"\n  );\n}\n\n/**\n * The list filter operator whose value control a condition's value is chosen\n * with: the same value, compared the other way round for a negation. A\n * yes-or-no field's \"is\" is the filter's \"is\" with Yes or No.\n */\nexport function valueOpFor(op: ConditionOp): ListFilterOp | undefined {\n  switch (op) {\n    case \"not_contains\":\n      return \"contains\";\n    case \"is_true\":\n    case \"is_false\":\n      return \"equals\";\n    case \"exists\":\n    case \"not_exists\":\n      return undefined;\n    default:\n      return op;\n  }\n}\n\n/** A condition being edited: any part may be missing until it is chosen. */\nexport interface DraftCondition {\n  readonly field?: string;\n  readonly op?: ConditionOp;\n  readonly value?: unknown;\n}\n\n/**\n * A stored condition as a row reads it, its operator in its canonical\n * spelling; an operator conditions do not have reads as not chosen, and the\n * engine's finding says why.\n */\nexport function conditionDraftOf(condition: Condition): DraftCondition {\n  const op = conditionOp(condition.op);\n  // `equals` Yes and `not_equals` Yes hold exactly where \"is Yes\" and \"is No\"\n  // do, so they read and edit as those; written only once the row changes.\n  if (condition.value === true && (op === \"equals\" || op === \"not_equals\")) {\n    return {\n      field: condition.field,\n      op: op === \"equals\" ? \"is_true\" : \"is_false\",\n    };\n  }\n  return {\n    field: condition.field,\n    ...(op === undefined ? {} : { op }),\n    ...(condition.value === undefined ? {} : { value: condition.value }),\n  };\n}\n\n/** The value a yes-or-no condition's Yes or No stands for. */\nexport function booleanValueOf(\n  op: ConditionOp | undefined\n): boolean | undefined {\n  if (op === \"is_true\") return true;\n  if (op === \"is_false\") return false;\n  return undefined;\n}\n\n/** A condition as one sentence, in its three parts. */\nexport interface ConditionSentence {\n  readonly field: string;\n  readonly operator: string;\n  readonly value: string;\n}\n\n/** What an operator is called for a field of a kind. */\nfunction operatorWords(op: ConditionOp, kind: ConditionFieldKind): string {\n  const special =\n    kind === \"date\"\n      ? DATE_LABELS[op]\n      : kind === \"boolean\"\n        ? BOOLEAN_EXACT[op]\n        : undefined;\n  return special ?? LABELS[op];\n}\n\n/** A condition as the closed line reads it: \"Reading time · is more than · 5\". */\nexport function conditionSentence(\n  draft: DraftCondition,\n  field: ConditionField | undefined,\n  entryTitle: (id: string) => string | undefined = () => undefined\n): ConditionSentence {\n  const fieldWords =\n    draft.field === undefined\n      ? \"Choose a field\"\n      : (field?.label ?? `${draft.field} (not offered here)`);\n  if (draft.op === undefined) {\n    return { field: fieldWords, operator: \"\", value: \"\" };\n  }\n  // A field this collection doesn't offer still has its operator said in\n  // words, as one it does: \"has a value\", not the stored \"exists\".\n  const operator =\n    field === undefined\n      ? LABELS[draft.op]\n      : operatorWords(draft.op, field.kind);\n  const valueOp = valueOpFor(draft.op);\n  if (valueOp === undefined) return { field: fieldWords, operator, value: \"\" };\n  const value = booleanValueOf(draft.op) ?? draft.value;\n  return {\n    field: fieldWords,\n    operator,\n    // Said as a list's filter says the same value, so one value reads one way.\n    value: filterSentence(\n      { field: draft.field, op: valueOp, value },\n      asListField(field),\n      entryTitle\n    ).value,\n  };\n}\n\n/** A sentence as one line of text, for a row's title and accessible name. */\nexport function conditionLine(sentence: ConditionSentence): string {\n  return [sentence.field, sentence.operator, sentence.value]\n    .filter(part => part !== \"\")\n    .join(\" \");\n}\n\n/**\n * A draft as the stored condition it would be, or why it is not one yet, in\n * words naming what to choose. Whether the value fits its field is the\n * engine's to say, as the save does, once the condition is stored.\n */\nexport function completedCondition(\n  draft: DraftCondition,\n  field: Pick<ConditionField, \"label\" | \"kind\"> | undefined\n): { readonly condition: Condition } | { readonly missing: string } {\n  if (draft.field === undefined || field === undefined) {\n    return { missing: \"Choose a field, or remove this condition.\" };\n  }\n  if (draft.op === undefined) {\n    return { missing: \"Choose how to compare, or remove this condition.\" };\n  }\n  if (!takesValue(draft.op)) {\n    return { condition: { field: draft.field, op: draft.op } };\n  }\n  // Empty text is a value text equality compares with, as the save reads\n  // it; every other comparison needs something to compare.\n  const emptyAllowed =\n    field.kind === \"text\" &&\n    (draft.op === \"equals\" || draft.op === \"not_equals\");\n  if (draft.value === undefined || (draft.value === \"\" && !emptyAllowed)) {\n    return {\n      missing: `Choose a value for ${field.label}, or remove this condition.`,\n    };\n  }\n  // A number too large to hold, read as Infinity, is one the save refuses,\n  // so it is never written.\n  if (typeof draft.value === \"number\" && !Number.isFinite(draft.value)) {\n    return {\n      missing: `Enter a smaller number for ${field.label}, or remove this condition.`,\n    };\n  }\n  return {\n    condition: { field: draft.field, op: draft.op, value: draft.value },\n  };\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 * The marker a block hidden by its conditions is drawn as on the canvas, while\n * conditions are applied: one dashed line naming the block and why a visitor\n * doesn't see it, in the block's place.\n *\n * An editor-only block definition, known only to the canvas's renderer and\n * never stored, so the renderer draws it with the block's own id and the\n * canvas selects, hit-tests and outlines it as the block it stands for. Its\n * root is a plain element, which is what the renderer marks with that id.\n *\n * @module condition-hidden-block\n */\nimport {\n  CONDITION_HIDDEN_TYPE,\n  defineBlock,\n  type BlockDefinition,\n  type BlockRenderArgs,\n} from \"@nextlyhq/blocks-engine\";\nimport type { BlockResolver } from \"@nextlyhq/blocks-react\";\nimport { AlertCircle, EyeOff } from \"lucide-react\";\nimport type { ReactElement } from \"react\";\n\nimport type { ConditionHiddenProps } from \"./applied-conditions\";\n\n/** One hidden block's line: its name, then why it is hidden. */\nfunction renderConditionHidden({\n  props,\n  className,\n}: BlockRenderArgs<ConditionHiddenProps>): ReactElement {\n  // Read as stored data, since a marker is a node like any other on its way\n  // through the renderer.\n  const name = typeof props.name === \"string\" ? props.name : \"\";\n  const reason = typeof props.reason === \"string\" ? props.reason : \"\";\n  const unchecked = props.unchecked === true;\n  const Icon = unchecked ? AlertCircle : EyeOff;\n  // The look is the definition's base styles, in the site's colours: the\n  // canvas may draw in a frame that loads no editor stylesheet.\n  return (\n    <div\n      className={[\"nx-condition-hidden\", className].filter(Boolean).join(\" \")}\n      data-unchecked={unchecked ? \"\" : undefined}\n    >\n      <Icon aria-hidden=\"true\" size={14} />\n      <span>\n        <b>{name}</b> · {reason}\n      </span>\n    </div>\n  );\n}\n\n/**\n * How the marker looks: one dashed line in the site's own colours. Compiled\n * into the page's sheet with the page, as any block's defaults are, because\n * the canvas may draw the page in a frame of the site's own that loads the\n * site's stylesheet and none of the editor's.\n */\nconst CONDITION_HIDDEN_BASE_STYLES = {\n  base: {\n    base: {\n      display: \"flex\",\n      alignItems: \"center\",\n      gap: \"0.5rem\",\n      padding: {\n        blockStart: \"0.375rem\",\n        blockEnd: \"0.375rem\",\n        inlineStart: \"0.625rem\",\n        inlineEnd: \"0.625rem\",\n      },\n      border: {\n        width: {\n          blockStart: \"1px\",\n          blockEnd: \"1px\",\n          inlineStart: \"1px\",\n          inlineEnd: \"1px\",\n        },\n        style: \"dashed\",\n        color: { $token: \"color.border-strong\" },\n      },\n      borderRadius: \"2px\",\n      backgroundColor: { $token: \"color.surface\" },\n      color: { $token: \"color.muted\" },\n      // 13px at the page's own scale, over the 12px floor, in the muted\n      // colour, which the site's default tokens hold at 4.6:1 on the surface\n      // in light and 6.8:1 in dark.\n      fontSize: \"0.8125rem\",\n      lineHeight: \"1.35\",\n    },\n  },\n} as const;\n\n/** The marker's definition: no settings, never offered, never stored. */\nconst conditionHidden: BlockDefinition<ConditionHiddenProps> = defineBlock({\n  name: CONDITION_HIDDEN_TYPE,\n  version: 1,\n  description: \"A block hidden by its conditions, while they are applied.\",\n  props: {},\n  defaultProps: { name: \"\", reason: \"\", unchecked: false },\n  example: { props: { name: \"\", reason: \"\", unchecked: false } },\n  baseStyles: CONDITION_HIDDEN_BASE_STYLES,\n  render: renderConditionHidden,\n});\n\n/**\n * The blocks the canvas draws with, the hidden-block marker among them. Any\n * other type is answered as the resolver given answers it.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function withConditionHiddenBlock(blocks: BlockResolver): BlockResolver {\n  return {\n    get: type =>\n      type === CONDITION_HIDDEN_TYPE ? conditionHidden : blocks.get(type),\n  };\n}\n","\"use client\";\n\n/**\n * The regions of the page's Layout around the page: which parts are drawn,\n * in what order, each with how it treats the site sheet, and the header and\n * footer drawn around the page.\n *\n * @module canvas-layout-parts\n */\n\nimport type { RegionArea } from \"@nextlyhq/blocks-engine\";\nimport {\n  layoutPartSheets,\n  type PagePart,\n  type PageRendererProps,\n  type PartSheet,\n} from \"@nextlyhq/blocks-react\";\nimport {\n  BlockEnvironmentProvider,\n  type BlockEnvironment,\n} from \"@nextlyhq/blocks-react/environment\";\nimport { useEffect, useMemo, useRef, useState } from \"react\";\n\nimport type { CanvasEditingRegion } from \"./canvas-props\";\nimport {\n  CanvasRegionFrame,\n  EditedRegionFrame,\n  EmptyRegionBand,\n  REGION_ATTRIBUTE,\n  type CanvasRegion,\n  type EmptyRegionBandProps,\n} from \"./canvas-regions\";\nimport { isHTMLElement } from \"./dom-kind\";\n\n/** A region of the page's Layout, with how it treats the site sheet. */\ninterface DrawnRegion {\n  region: CanvasRegion;\n  sheet: PartSheet;\n}\n\n/** The page and the regions drawn around it, each with its sheet inputs. */\nexport interface LayoutParts {\n  page: PartSheet;\n  header: DrawnRegion | undefined;\n  footer: DrawnRegion | undefined;\n}\n\n/**\n * The page and the regions around it, each with its site-sheet inputs.\n *\n * Asked of `layoutPartSheets`, the answer the published route uses, so the\n * first part drawn emits the site sheet and each part compiles under its own\n * scope. `undefined` when there is no region to draw.\n */\nexport function useLayoutParts(\n  regions: readonly CanvasRegion[] | undefined,\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined,\n  sheet: NonNullable<PageRendererProps[\"siteStyles\"]>\n): LayoutParts | undefined {\n  return useMemo(\n    () => layoutPartsOf(regions, rendered, sheet),\n    [regions, rendered, sheet]\n  );\n}\n\n/** {@link useLayoutParts}'s answer, computed. */\nfunction layoutPartsOf(\n  regions: readonly CanvasRegion[] | undefined,\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined,\n  sheet: NonNullable<PageRendererProps[\"siteStyles\"]>\n): LayoutParts | undefined {\n  const header = regions?.find(region => region.area === \"header\");\n  const footer = regions?.find(region => region.area === \"footer\");\n  if (header === undefined && footer === undefined) return undefined;\n  const parts = drawingOrder(header !== undefined, footer !== undefined);\n  const sheets = layoutPartSheets({\n    parts,\n    styleContext: rendered?.styleContext,\n    siteStyles: sheet,\n    pageScope: pageScopeOf(rendered),\n  });\n  const sheetFor = (part: PagePart): PartSheet =>\n    sheets[parts.indexOf(part)] ?? {};\n  return {\n    page: sheetFor(\"page\"),\n    header: drawnRegion(header, sheetFor),\n    footer: drawnRegion(footer, sheetFor),\n  };\n}\n\n/** The parts in the order they are drawn: header, page, footer. */\nfunction drawingOrder(hasHeader: boolean, hasFooter: boolean): PagePart[] {\n  return [\n    ...(hasHeader ? ([\"header\"] as const) : []),\n    \"page\",\n    ...(hasFooter ? ([\"footer\"] as const) : []),\n  ];\n}\n\n/** The scope the page's own styles compile under, when it states one. */\nfunction pageScopeOf(\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined\n): string | undefined {\n  const scope = rendered?.styles?.scope;\n  return typeof scope === \"string\" ? scope : undefined;\n}\n\n/** One region with its sheet inputs, or nothing for a region not drawn. */\nfunction drawnRegion(\n  region: CanvasRegion | undefined,\n  sheetFor: (part: PagePart) => PartSheet\n): DrawnRegion | undefined {\n  return region === undefined\n    ? undefined\n    : { region, sheet: sheetFor(region.area) };\n}\n\n/**\n * The page between its Layout's header and footer, as the canvas draws them.\n *\n * Each region is drawn in the page's environment, so a header block that\n * measures itself or listens is told the frame the canvas draws in, as the\n * page is. Without regions it is the page alone, exactly as before.\n *\n * With regions, the page sits in a part of its own that lays out as if it\n * were not there (`display: contents`), always, so editing a region in place\n * and leaving it never draws the page again from scratch: the part only\n * turns `inert` and hidden from assistive technology while a region is\n * edited, with the other region likewise, and the edited one is drawn from\n * its live document. Leaving gives that region back its focus, where the\n * author went in.\n */\nexport function RegionsAround({\n  drawn,\n  rendered,\n  environment,\n  selection,\n  editing,\n  bands,\n  children,\n}: {\n  drawn: LayoutParts | undefined;\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined;\n  environment: BlockEnvironment | undefined;\n  /** The region selected, and the ways to select and edit one. */\n  selection: {\n    readonly selectedRegion?: RegionArea | null;\n    readonly onSelectRegion?: (area: RegionArea) => void;\n    readonly onEditRegion?: (area: RegionArea) => void;\n  };\n  /** The region edited in place, while one is. */\n  editing: CanvasEditingRegion | undefined;\n  /**\n   * What is drawn where an area has no region, by area: the host's band\n   * saying so, with its ways to fill it. None while a region is edited.\n   */\n  bands?: Partial<Readonly<Record<RegionArea, EmptyRegionBandProps>>>;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const pagePart = useRef<HTMLDivElement | null>(null);\n  useFocusBackOnLeaving(pagePart, editing?.area);\n  const dimmed = editing !== undefined;\n  // An area with no region, and a band for it: the band in the region's\n  // place, while nothing is edited in place.\n  const band = (area: RegionArea) => {\n    const given = bands?.[area];\n    return given === undefined || dimmed ? null : (\n      <EmptyRegionBand area={area} band={given} />\n    );\n  };\n  if (drawn === undefined) {\n    return (\n      <>\n        {band(\"header\")}\n        {children}\n        {band(\"footer\")}\n      </>\n    );\n  }\n  const frame = (part: DrawnRegion | undefined) =>\n    part === undefined ? null : (\n      <BlockEnvironmentProvider value={environment}>\n        {editing?.area === part.region.area ? (\n          <EditedRegionFrame\n            area={part.region.area}\n            document={editing.document}\n            definitions={editing.definitions}\n            rendered={rendered}\n            sheet={part.sheet}\n          />\n        ) : (\n          <CanvasRegionFrame\n            region={part.region}\n            rendered={rendered}\n            sheet={part.sheet}\n            selected={!dimmed && selection.selectedRegion === part.region.area}\n            onSelect={selection.onSelectRegion}\n            onEdit={selection.onEditRegion}\n            dimmed={dimmed}\n          />\n        )}\n      </BlockEnvironmentProvider>\n    );\n  return (\n    <>\n      {drawn.header === undefined ? band(\"header\") : frame(drawn.header)}\n      <div\n        ref={pagePart}\n        className={PAGE_PART_CLASS}\n        inert={dimmed}\n        aria-hidden={dimmed ? \"true\" : undefined}\n      >\n        {children}\n      </div>\n      {drawn.footer === undefined ? band(\"footer\") : frame(drawn.footer)}\n    </>\n  );\n}\n\n/**\n * The class on the part holding the page between its regions. Laid out as if\n * it were not there (`display: contents`): `contents` for a canvas drawn in\n * the editor's own document, whose sheet has the utility, and the frame\n * sheet's rule for one drawn in its frame.\n */\nconst PAGE_PART_CLASS = \"nx-canvas-page-part contents\";\n\n/**\n * Focus the region just left, once, as the editing of it ends: found beside\n * the page's part, in the canvas it is drawn in. A leave is its own value,\n * so leaving the same region twice focuses it twice.\n */\nfunction useFocusBackOnLeaving(\n  pagePart: React.RefObject<HTMLDivElement | null>,\n  area: RegionArea | undefined\n): void {\n  const [held, setHeld] = useState(area);\n  const [left, setLeft] = useState<{ area: RegionArea } | null>(null);\n  if (held !== area) {\n    setHeld(area);\n    setLeft(area === undefined && held !== undefined ? { area: held } : null);\n  }\n  useEffect(() => {\n    if (left === null) return;\n    const frame = pagePart.current?.parentElement?.querySelector(\n      `[${REGION_ATTRIBUTE}=\"${left.area}\"]`\n    );\n    if (isHTMLElement(frame)) frame.focus({ preventScroll: true });\n  }, [left, pagePart]);\n}\n","\"use client\";\n\n/**\n * What the canvas draws in the page's place for a document that has no page\n * of its own: a grey box with a line of words, between the header and the\n * footer drawn around it, so the author sees how they sit on a page.\n *\n * Drawn by the editor only, never stored and never published: it stands for\n * whichever page will be drawn there. It is not editor chrome either, so a\n * press on it is a press on the page's ground, which clears the selection.\n *\n * @module canvas/page-placeholder\n */\nimport type { JSX } from \"react\";\n\n/** The attribute the placeholder carries, which its rules are written on. */\nexport const PAGE_PLACEHOLDER_ATTRIBUTE = \"data-nx-page-placeholder\";\n\n/** The placeholder, saying `words`. */\nexport function PagePlaceholder({ words }: { words: string }): JSX.Element {\n  return (\n    <div {...{ [PAGE_PLACEHOLDER_ATTRIBUTE]: \"\" }}>\n      <span>{words}</span>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The page as the canvas draws it: the definitions it reaches with their\n * conditions lifted, what the renderer is given while conditions are or are\n * not applied, the document and window blocks are drawn in, and the page\n * rendered with the regions of its Layout.\n *\n * @module canvas-drawn-page\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport {\n  PageRenderer,\n  registeredBlocks,\n  type PageRendererProps,\n} from \"@nextlyhq/blocks-react\";\nimport {\n  BlockEnvironmentProvider,\n  type BlockEnvironment,\n} from \"@nextlyhq/blocks-react/environment\";\nimport { useEffect, useMemo, useState } from \"react\";\n\nimport {\n  revealedDefinitions,\n  revealedForCanvas,\n  type AppliedConditions,\n} from \"../conditions/applied-conditions\";\nimport { withConditionHiddenBlock } from \"../conditions/condition-hidden-block\";\n\nimport { useLayoutParts, type LayoutParts } from \"./canvas-layout-parts\";\nimport type { CanvasRegion } from \"./canvas-regions\";\nimport { PagePlaceholder } from \"./page-placeholder\";\n\n// Moved beside `revealedForCanvas`, so a reader with no React (the page\n// checks) composes the page from the same definitions; kept importable here.\nexport { revealedDefinitions } from \"../conditions/applied-conditions\";\n\n/**\n * The document and window the canvas draws in, held where nothing walking an\n * object's own keys can reach them.\n *\n * The value is a prop of the environment provider, and React's development\n * build describes every changed prop for its performance panel by walking the\n * object's own enumerable keys a few levels down. A plain `{ document, window }`\n * leads that walk into the window, whose own keys include each child frame —\n * and a page with an Embed block has one in an opaque origin, where reading\n * anything throws a `SecurityError`. It threw while React was running the\n * commit's effects, so the effects after it never ran: the canvas stopped\n * measuring its region, and the device and zoom controls stopped moving it.\n *\n * Private fields behind getters are not own enumerable keys, so the walk finds\n * nothing to enter, while `environment.window` reads exactly as before.\n */\nclass CanvasEnvironment implements BlockEnvironment {\n  readonly #document: Document;\n  readonly #window: Window;\n\n  constructor(document: Document, view: Window) {\n    this.#document = document;\n    this.#window = view;\n  }\n\n  get document(): Document {\n    return this.#document;\n  }\n\n  get window(): Window {\n    return this.#window;\n  }\n}\n\n/**\n * The document and window the blocks are drawn in, for block code that\n * measures itself or listens (`useBlockEnvironment`). Read from the canvas\n * root's OWN document rather than the globals, so the answer is the frame's\n * once the canvas renders inside one, with nothing here to change.\n * `undefined` until the root has mounted, which the hook passes on rather\n * than falling back to the admin page. Built as a `CanvasEnvironment` rather\n * than an object literal; see there for why.\n */\nexport function useCanvasEnvironment(\n  root: React.RefObject<HTMLDivElement | null>\n): BlockEnvironment | undefined {\n  const [environment, setEnvironment] = useState<BlockEnvironment | undefined>(\n    undefined\n  );\n  useEffect(() => {\n    const view = root.current?.ownerDocument.defaultView;\n    if (root.current === null || view == null) return;\n    setEnvironment(new CanvasEnvironment(root.current.ownerDocument, view));\n  }, [root]);\n  return environment;\n}\n\n/**\n * What the canvas renders the page with. Conditions not applied, a placed\n * component's definitions with their conditions lifted, so each conditioned\n * block is drawn. Applied, the definitions as stored, their blocks judged\n * for the previewed entry by the renderer as the page's route judges them\n * (`entryJudged`), and the blocks with the hidden-block marker among them.\n */\nfunction drawnRenderOf(\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined,\n  document: BlockDocument,\n  applied: AppliedConditions | undefined\n): Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined {\n  if (applied === undefined) {\n    return rendered?.definitions === undefined\n      ? rendered\n      : {\n          ...rendered,\n          definitions: revealedDefinitions(\n            document,\n            rendered.definitions,\n            rendered.limits\n          ),\n        };\n  }\n  return {\n    ...rendered,\n    entryJudged: applied.entryJudgement,\n    blocks: withConditionHiddenBlock(rendered?.blocks ?? registeredBlocks()),\n  };\n}\n\n/**\n * The page, drawn, and the regions of its Layout around it.\n *\n * The parts in drawing order, each with how it treats the site sheet:\n * `undefined` when there are no regions, so a canvas without a Layout renders\n * exactly as it did.\n */\nexport function useDrawnPage({\n  regions,\n  rendered,\n  sheet,\n  document,\n  environment,\n  applied,\n  addressed,\n  placeholder,\n}: {\n  regions: readonly CanvasRegion[] | undefined;\n  rendered: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined;\n  sheet: NonNullable<PageRendererProps[\"siteStyles\"]>;\n  document: BlockDocument;\n  environment: BlockEnvironment | undefined;\n  applied: AppliedConditions | undefined;\n  /**\n   * Whether the page's blocks carry their addresses: false while a region of\n   * its layout is edited in place, so no surface can find, mark or select a\n   * block of the page then, nor take one for the region's block of the same\n   * id.\n   */\n  addressed: boolean;\n  /**\n   * Words for a grey box drawn after the page, where any page goes, for a\n   * document view with no page of its own; absent, none is drawn.\n   */\n  placeholder?: string | undefined;\n}): { drawn: LayoutParts | undefined; page: React.JSX.Element } {\n  const drawn = useLayoutParts(regions, rendered, sheet);\n  // Every conditioned block drawn, whoever the page would show it to, so the\n  // author can see and select it; the marks say it isn't shown to everyone.\n  // While conditions are applied, `document` is already the page as they\n  // leave it (a hidden block as its marker), with the previewed entry's\n  // blocks composed in, which are revealed as they are without conditions.\n  // A block a list's entry decides keeps its conditions while the entries\n  // are judged, for the renderer to judge against each one drawn.\n  const limits = rendered?.limits;\n  const drawable = useMemo(\n    () => revealedForCanvas(document, applied, limits),\n    [document, applied, limits]\n  );\n  // A placed component's definition too: its conditioned blocks are drawn,\n  // as the page's are. While conditions are applied, the renderer also knows\n  // the marker a hidden block is drawn as.\n  const drawnRender = useMemo(\n    () => drawnRenderOf(rendered, document, applied),\n    [rendered, document, applied]\n  );\n  const page = useMemo(\n    () => (\n      <BlockEnvironmentProvider value={environment}>\n        <PageRenderer\n          {...drawnRender}\n          document={drawable}\n          siteStyles={sheet}\n          {...drawn?.page}\n          // What makes the hit-testing above possible at all. The renderer emits\n          // the node attribute only when asked, because a PUBLISHED page should\n          // not carry an editor's addressing — so the canvas asks and a route\n          // does not. Spread first and set here deliberately: a caller passing\n          // `nodeAttribute: false` through `render` would silently disable\n          // selection for the whole canvas. Withheld only while a region is\n          // edited in place, when the page is not the document being edited.\n          nodeAttribute={addressed}\n          // What its images and lists drew is kept as it is while it is not\n          // addressed, as it is while it is: the node attribute alone would\n          // otherwise run them again on every edit in the region.\n          {...(addressed ? {} : { keepAsyncOutputs: true })}\n        />\n        {placeholder === undefined ? null : (\n          <PagePlaceholder words={placeholder} />\n        )}\n      </BlockEnvironmentProvider>\n    ),\n    [drawnRender, drawable, sheet, environment, drawn, addressed, placeholder]\n  );\n  return { drawn, page };\n}\n","\"use client\";\n\n/**\n * The notice that says why a dragged block cannot land, and what would.\n *\n * One component for both places a drag is refused, the canvas and Layers, so\n * an author reads the refusal on the same surface in the same words wherever\n * they drag: the editor's notice surface with a red edge and a warning mark,\n * not a red fill, so the reason reads beside ordinary content at AA contrast\n * in both themes. Each place only positions it.\n *\n * @module refusal-notice\n */\nimport { CircleAlert } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\n\n/** The two lines of a refusal, and where its place puts it. */\nexport interface RefusalNoticeProps {\n  /** Why the drop will not happen. */\n  readonly headline: string;\n  /** What the spot or the block takes instead, when the rule names it. */\n  readonly remedy: string | null;\n  /** The place's own class, which positions the notice there. */\n  readonly className: string;\n  /** Where the place puts it, worked out by the place. */\n  readonly style?: React.CSSProperties;\n}\n\n/**\n * A refusal's notice.\n *\n * Hidden from assistive technology: it describes a POINTER gesture, and each\n * place announces the same sentence through its own live region to the one\n * who is dragging. Marked as chrome, so a canvas's hit-testing skips it.\n */\nexport const RefusalNotice: React.ForwardRefExoticComponent<\n  RefusalNoticeProps & React.RefAttributes<HTMLDivElement>\n> = React.forwardRef<HTMLDivElement, RefusalNoticeProps>(function RefusalNotice(\n  { headline, remedy, className, style },\n  ref\n) {\n  return (\n    <div\n      ref={ref}\n      className={`nx-refusal-notice ${className}`}\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n      style={style}\n      aria-hidden=\"true\"\n    >\n      <CircleAlert\n        className=\"nx-refusal-notice__mark\"\n        size={14}\n        aria-hidden=\"true\"\n      />\n      <span className=\"nx-refusal-notice__text\">\n        <span className=\"nx-refusal-notice__why\">{headline}</span>\n        {remedy === null ? null : (\n          <span className=\"nx-refusal-notice__takes\">{remedy}</span>\n        )}\n      </span>\n    </div>\n  );\n});\n","\"use client\";\n\n/**\n * Why a dragged block can't land where it is, drawn over the container that\n * refuses it and kept in the part of the canvas the author can see.\n *\n * @module canvas-drop-refusal\n */\n\nimport { findNode, type BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport { type JSX, useRef, useState } from \"react\";\n\nimport { lockRefusalWording } from \"../lock-refusal\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { ownedNodeElement } from \"./canvas-addressing\";\nimport type { CanvasDragState } from \"./canvas-drag\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { refusalWording } from \"./drag-refusal\";\nimport {\n  canvasContentRect,\n  canvasScroller,\n  overlaySpaceOf,\n  scrollEventTarget,\n  visibleBandOf,\n} from \"./geometry-dom\";\nimport { RefusalNotice } from \"./refusal-notice\";\n\n/**\n * The refusal a canvas should DRAW, which is not every refusal it is given.\n *\n * `useCanvasDrag` holds the committed target across a short crossing so the\n * indicator does not flicker, while setting the refusal from the region under\n * the pointer immediately — so both are non-null for the width of the switch\n * threshold. Drawing the refusal there contradicts two things at once: the\n * line still points at the held target, and releasing commits it. The chrome\n * would say the block cannot land while letting go moves it.\n *\n * So a refusal is the honest answer only once there is no target to disagree\n * with. One function rather than the same condition written at the mark and\n * again at the message, because two spellings of one rule drift and the drift\n * shows up as chrome that half-agrees with itself.\n */\nexport function drawnRefusal(\n  drag: CanvasDragState | undefined\n): CanvasDragState[\"refusal\"] {\n  if (drag === undefined || drag.target !== null) return null;\n  // A drag state built without a refusal at all reads as none.\n  return drag.refusal ?? null;\n}\n\n/**\n * The sentence a refused drop draws, over the container that refused it.\n *\n * Anchored to the CONTAINER rather than to the pointer. The drag state carries\n * no pointer coordinate — reading one back would mean a second answer to a\n * question `useCanvasDrag` already owns — and a message pinned to the region is\n * steadier to read than one that moves with the hand.\n *\n * Measured in the canvas's own CONTENT coordinates, the space the drop\n * indicator and the block toolbar are already positioned in, so the three agree\n * at any scroll offset and under zoom.\n *\n * Keyed on the region and the reason rather than on the refusal OBJECT: the\n * drag hook returns a fresh object every pointer move, and re-measuring per\n * frame would cost a layout read for an answer that changes only when the\n * pointer crosses into a different container.\n */\nfunction DropRefusalNotice({\n  refusal,\n  movingType,\n  regionType,\n}: {\n  refusal: NonNullable<CanvasDragState[\"refusal\"]>;\n  movingType: string;\n  regionType: string | undefined;\n}): React.JSX.Element {\n  const notice = useRef<HTMLDivElement | null>(null);\n  const [at, setAt] = useState<{ x: number; y: number } | null>(null);\n  // Whether the canvas is in the editor's frame, whose viewport scrolls it,\n  // and the zoom, which moves the region on screen while nothing in the frame\n  // changes.\n  const canvasFrame = useCanvasFrame();\n  const framed = canvasFrame.frame !== null;\n  const { parentId } = refusal;\n  // One wording per rule: a lock's from the function every lock refusal uses,\n  // a nesting refusal's from the drag's own.\n  const { headline, remedy } =\n    \"lock\" in refusal\n      ? lockRefusalWording(refusal.lock)\n      : refusalWording(refusal, movingType, regionType);\n\n  /*\n   * Measured BEFORE the browser paints, not after.\n   *\n   * A plain effect runs after paint, so the message draws once at the canvas's\n   * top-left — where an unpositioned absolute box lands — and jumps to the\n   * container on the next frame. During a drag that is not a single flash: a\n   * refusal is re-entered every time the pointer crosses into a region that\n   * will not take the block, so the jump repeats.\n   *\n   * The isomorphic form rather than `useLayoutEffect` directly, because a\n   * client component is still server-rendered and the plain hook warns there.\n   */\n  useIsomorphicLayoutEffect(() => {\n    const element = notice.current;\n    if (element === null) return;\n    /*\n     * The canvas the notice is drawn over and the space it is drawn in: inside\n     * the root over a canvas sharing the editor's document, or in the layer\n     * over the canvas's frame, where the root's coordinates are scaled to the\n     * zoom and the notice keeps its own size. The clamp below is worked out in\n     * the root's coordinates and only the result is placed.\n     */\n    const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) return;\n    const { root } = space;\n    const scroller = canvasScroller(root, framed);\n    const place = (point: { x: number; y: number }): void => {\n      const placed = space.place({ ...point, width: 0, height: 0 });\n      setAt({ x: placed.x, y: placed.y });\n    };\n    const measure = (): void => {\n      // The root itself when the refusal is at the page level: there is no\n      // container node to point at, which is the whole of what\n      // `restricted-at-root` means.\n      /*\n       * Resolved within THIS canvas, for the reason the marks are: a node id is\n       * unique in a document and not across documents, so a block rendering a\n       * second canvas can put a matching id earlier in the tree — and the message\n       * would then be anchored over a block belonging to another document.\n       */\n      const region =\n        parentId === undefined ? root : ownedNodeElement(root, parentId);\n      if (region === null) return;\n      const rect = canvasContentRect(region, root);\n\n      /*\n       * Clamped into the part of the canvas the author can actually see.\n       *\n       * The anchor alone is not enough. A root refusal has no container to point\n       * at, so it resolves to the canvas itself and lands at the page origin —\n       * which on a long page is several screens above someone dragging near the\n       * bottom, so the explanation for what just refused them is drawn where they\n       * are not looking. A very tall container scrolled past does the same.\n       *\n       * The scroller defines \"visible\": the shell scrolls an ancestor rather than\n       * the canvas, and in a frame of its own the frame's viewport scrolls it.\n       * The same scroller this effect listens to below, so what is measured\n       * and what is heard cannot be two different elements, and its visible\n       * part measured in this canvas's own content coordinates is exactly the\n       * band on screen.\n       */\n      if (scroller === null) {\n        place({ x: rect.x, y: rect.y });\n        return;\n      }\n      const band = visibleBandOf(scroller, root);\n      const inset = 12;\n      // The notice's height in the root's coordinates: drawn at its own size\n      // over a frame painted at another.\n      const height = space.sizeOf(element).height / space.scale;\n      const lowest = band.y + band.height - inset - height;\n      const top = band.y + inset;\n      // A band shorter than the message puts `lowest` above its own top, which\n      // makes the range inverted rather than narrow. Taking the top there keeps\n      // the message on screen instead of pinning it to a bound derived from a\n      // height that does not fit.\n      place({\n        x: rect.x,\n        y: lowest < top ? top : Math.max(top, Math.min(rect.y, lowest)),\n      });\n    };\n\n    measure();\n\n    /*\n     * Re-measured while the canvas scrolls under a stationary pointer.\n     *\n     * Autoscroll is the case that makes this necessary rather than tidy: a drag\n     * held near an edge keeps scrolling without the pointer moving, so the\n     * refusal does not change and nothing in this effect's inputs does either —\n     * while the band the message was clamped into travels away from it. The\n     * explanation would sit still and the page would leave.\n     *\n     * Passive, because this only reads geometry, and on the SCROLLER rather\n     * than the canvas: the canvas does not scroll, its ancestor does — or, in\n     * a frame of its own, the frame's viewport, whose scroll is dispatched at\n     * the frame's document rather than at any element.\n     */\n    if (scroller === null) return;\n    const source = scrollEventTarget(scroller);\n    source.addEventListener(\"scroll\", measure, { passive: true });\n    return () => {\n      source.removeEventListener(\"scroll\", measure);\n    };\n    /*\n     * Re-measured when the WORDING changes, not merely when the container does.\n     *\n     * Two slots on one container share a `parentId` and a reason while carrying\n     * different permitted lists, so the message can be replaced without any of\n     * the identity this effect anchors on moving. A longer remedy wraps onto\n     * another line, and the clamp would still be holding the height of the\n     * sentence it replaced — which is exactly the case that pushes it back out\n     * of the band near the bottom of the viewport.\n     *\n     * Keyed on the rendered strings rather than on `regionId`, because height\n     * is a property of the text: two regions producing identical sentences need\n     * no re-measure, and one region whose list changed does.\n     */\n  }, [parentId, headline, remedy, framed, canvasFrame]);\n\n  return (\n    <RefusalNotice\n      ref={notice}\n      className=\"nx-drop-refusal\"\n      style={at === null ? undefined : { left: at.x, top: at.y }}\n      /*\n       * NOT announced, matching {@link DropIndicator} rather than differing\n       * from it: this describes a POINTER gesture, and a live region here\n       * would speak to someone who is not the one dragging. The spoken\n       * counterpart is `keyboard-actions`, which refuses a move the nesting\n       * rule forbids and announces the same reason and remedy through its own\n       * live region, asked of the same wording function.\n       */\n      headline={headline}\n      remedy={remedy}\n    />\n  );\n}\n\n/**\n * Why the block being dragged cannot land where it is, drawn over the\n * container that refused it, or nothing while there is no refusal to draw.\n *\n * Chrome like the drop line, so it goes where the chrome goes: the overlay of\n * the `CanvasFrame` the canvas is drawn in, in the editor's document, or the\n * canvas's own `overlay` over a canvas sharing that document.\n *\n * @experimental\n */\nexport function DropRefusal({\n  drag,\n  document,\n}: {\n  /** What the pointer means, from `useCanvasDrag`, as the canvas is given it. */\n  drag: CanvasDragState | undefined;\n  /** The document the canvas is drawing, which names the refusing block. */\n  document: BlockDocument;\n}): JSX.Element | null {\n  const refusal = drawnRefusal(drag);\n  if (refusal === null) return null;\n  const { parentId } = refusal;\n  return (\n    <DropRefusalNotice\n      refusal={refusal}\n      movingType={drag?.draggingBlockName ?? \"\"}\n      /*\n       * The container's TYPE, resolved from the document the canvas is\n       * drawing. The refusal names the node; what an author reads is the\n       * block's name, and the document is the only place that mapping exists.\n       */\n      regionType={\n        parentId === undefined\n          ? undefined\n          : findNode(document.nodes, parentId)?.type\n      }\n    />\n  );\n}\n","\"use client\";\n\n/**\n * A region of the page's layout edited in place, drawn as the canvas draws\n * the page it edits: every conditioned block shown, whoever the visitor, a\n * block hidden on the device shown striped, and a placed component's\n * conditioned blocks shown too, so each can be seen and selected. The marks\n * blocks carry (locked, conditioned, hidden here) are the region's then, not\n * the page's: the page's blocks carry no address while the region is edited,\n * and its ids may repeat the region's.\n *\n * The stored document is never changed: only what is drawn.\n *\n * @module canvas-edited-region\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport type { PageRendererProps } from \"@nextlyhq/blocks-react\";\nimport { useMemo } from \"react\";\n\nimport { revealedForCanvas } from \"../conditions/applied-conditions\";\n\nimport {\n  conditionMarksOf,\n  lockMarksOf,\n  type ConditionMarks,\n  type LockMark,\n} from \"./canvas-block-marks\";\nimport {\n  drawnBreakpoints,\n  useDeviceHiddenDrawing,\n} from \"./canvas-device-hidden\";\nimport { revealedDefinitions } from \"./canvas-drawn-page\";\nimport type { CanvasEditingRegion } from \"./canvas-props\";\n\n/** The marks the canvas writes on the blocks of the document it edits. */\nexport interface EditedMarks {\n  readonly locks: ReadonlyMap<string, LockMark>;\n  readonly conditions: ConditionMarks;\n  readonly entryContent: ReadonlyMap<string, string>;\n  readonly deviceHidden: ReadonlyMap<string, string>;\n}\n\n/** No region edited: an empty document to draw nothing from. */\nconst NO_REGION: BlockDocument = {\n  formatVersion: 1,\n  kind: \"component\",\n  nodes: [],\n};\n\n/** A region carries no Entry content words: it draws no entry. */\nconst NO_WORDS: ReadonlyMap<string, string> = new Map();\n\n/**\n * The region as drawn while it is edited, and the marks of the document the\n * canvas edits: the region's while one is edited, else `page`'s as the\n * canvas worked them out, unchanged.\n */\nexport function useEditedRegionDrawing(\n  editing: CanvasEditingRegion | undefined,\n  render: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined,\n  siteStyles: PageRendererProps[\"siteStyles\"],\n  page: { document: BlockDocument } & Omit<EditedMarks, \"locks\">\n): { drawn: CanvasEditingRegion | undefined; marks: EditedMarks } {\n  const limits = render?.limits;\n  const stored = editing?.document ?? NO_REGION;\n  const definitions = editing?.definitions;\n  // Every conditioned block drawn, as the page's are while it is edited.\n  const revealed = useMemo(\n    () => revealedForCanvas(stored, undefined, limits),\n    [stored, limits]\n  );\n  const shownDefinitions = useMemo(\n    () =>\n      definitions === undefined\n        ? undefined\n        : revealedDefinitions(stored, definitions, limits),\n    [stored, definitions, limits]\n  );\n  // A block hidden on the device shown, drawn anyway and striped.\n  const deviceHidden = useDeviceHiddenDrawing(\n    revealed,\n    drawnBreakpoints(render, siteStyles),\n    editing !== undefined\n  );\n  const regionMarks = useMemo(\n    () => ({\n      locks: lockMarksOf(stored),\n      conditions: conditionMarksOf(stored, undefined, {\n        ...(definitions === undefined ? {} : { definitions }),\n        ...(limits === undefined ? {} : { limits }),\n      }),\n    }),\n    [stored, definitions, limits]\n  );\n  const pageLocks = useMemo(() => lockMarksOf(page.document), [page.document]);\n  return useMemo(() => {\n    if (editing === undefined) {\n      return {\n        drawn: undefined,\n        marks: {\n          locks: pageLocks,\n          conditions: page.conditions,\n          entryContent: page.entryContent,\n          deviceHidden: page.deviceHidden,\n        },\n      };\n    }\n    return {\n      drawn: {\n        area: editing.area,\n        document: deviceHidden.document,\n        ...(shownDefinitions === undefined\n          ? {}\n          : { definitions: shownDefinitions }),\n      },\n      marks: {\n        ...regionMarks,\n        entryContent: NO_WORDS,\n        deviceHidden: deviceHidden.marks,\n      },\n    };\n  }, [\n    editing,\n    deviceHidden,\n    shownDefinitions,\n    regionMarks,\n    pageLocks,\n    page.conditions,\n    page.entryContent,\n    page.deviceHidden,\n  ]);\n}\n","/**\n * The canvas never leaves the editor.\n *\n * The canvas draws the page as it will be published, so its links are real\n * anchors and its forms real forms. A click on one is how an author selects\n * that block, and the browser's own default for the same click is to follow\n * the link or submit the form: the editor navigated away mid-edit, to whatever\n * the link named, with every unsaved change at risk. Selection and the\n * browser's default are two separate consequences of one event, so the guard\n * cancels the default and leaves the event itself alone: every handler that\n * selects, drags or opens a menu still receives it.\n *\n * ## What it covers\n *\n * - `click` inside a link, which also covers Enter on a focused link (the\n *   browser activates a link from the keyboard by dispatching a click) and\n *   a modified click that would open a new tab or window;\n * - `auxclick`, the middle button, which opens a new tab without any `click`;\n * - `submit` from a form inside the canvas, however it was triggered. A\n *   submit is also stopped from propagating: a block's own script may send\n *   the real request from its submit handler, which cancelling the browser's\n *   default alone does not prevent. Nothing in the editor listens for a\n *   submit; selection comes from the click that preceded it.\n *\n * The editor's own chrome drawn inside the root (the toolbar, an overlay a\n * host adds) is not the page, so its links keep working.\n *\n * ## Listening on the canvas's own document\n *\n * The listeners go on the document that OWNS the canvas root, in the capture\n * phase, and act only on events whose target is inside the root. The owner\n * rather than the global `document`, so a canvas drawn inside a frame is\n * guarded in that frame's document too; capture, so nothing inside the canvas\n * that stops propagation can stop the guard. Nodes are recognised by\n * `nodeType` and `closest` rather than `instanceof`, because a node from a\n * frame is not an instance of this window's constructors.\n *\n * @module canvas-link-guard\n */\n\n/** The events whose default can navigate: see the module notes. */\nconst GUARDED = [\"click\", \"auxclick\", \"submit\"] as const;\n\n/** The anchors a click follows: a link or an image-map area with an address. */\nconst FOLLOWED = \"a[href], area[href]\";\n\n/** The element an event started at, or null for one that is not in a page. */\nfunction elementOf(target: EventTarget | null): Element | null {\n  if (target === null || !(\"nodeType\" in target)) return null;\n  const node = target as Node;\n  if (node.nodeType === 1) return node as Element;\n  // A click on a link's text arrives at the text node, not the anchor.\n  return node.parentElement;\n}\n\n/** Whether an event's default would take the page somewhere else. */\nfunction navigates(event: Event, root: Element, chrome: string): boolean {\n  const element = elementOf(event.target);\n  if (element === null || !root.contains(element)) return false;\n  if (element.closest(chrome) !== null) return false;\n  if (event.type === \"submit\") return true;\n  return element.closest(FOLLOWED) !== null;\n}\n\n/**\n * Stops every link and form inside `root` from navigating, and answers the\n * function that stops guarding.\n *\n * Call it once per mounted canvas root; the root is the boundary, so a link\n * in the editor's own chrome outside it still works. `chrome` is the selector\n * that marks the editor's chrome drawn INSIDE the root, which is left alone\n * too. It is passed in rather than imported, because the canvas that owns the\n * marker is the module that installs this guard.\n */\nexport function guardCanvasNavigation(\n  root: HTMLElement,\n  chrome: string\n): () => void {\n  const owner = root.ownerDocument;\n  const guard = (event: Event): void => {\n    if (!navigates(event, root, chrome)) return;\n    event.preventDefault();\n    if (event.type === \"submit\") event.stopPropagation();\n  };\n  for (const type of GUARDED) {\n    owner.addEventListener(type, guard, true);\n  }\n  return () => {\n    for (const type of GUARDED) {\n      owner.removeEventListener(type, guard, true);\n    }\n  };\n}\n","/**\n * Which entry of each list the author last clicked on the canvas, for the\n * block that click selected: the binding picker shows that entry's values\n * beside a list item's fields, else the first entry's.\n *\n * Read from the element pressed, as the canvas draws it: a list draws each\n * entry as a box of its own, without a node id, straight inside the list's\n * element. Kept only while the block the click selected stays selected, so\n * a block selected another way (from Layers, by key) samples the first\n * entry, as before.\n * Editor state only, never stored.\n *\n * @module clicked-entry\n */\nimport {\n  blockTypeClassName,\n  COLLECTION_LIST_TYPE,\n} from \"@nextlyhq/blocks-engine\";\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\nimport * as React from \"react\";\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { isElement } from \"./dom-kind\";\n\n/** The class a list's element and each of its entries carry. */\nconst LIST_CLASS = blockTypeClassName(COLLECTION_LIST_TYPE);\n\n/** The entries clicked, by list id, for the block the click selected. */\ninterface Clicked {\n  readonly nodeId: string;\n  readonly entries: ReadonlyMap<string, number>;\n}\n\nlet clicked: Clicked | undefined;\nconst listeners = new Set<() => void>();\n\n/** Whether `element` is one entry a list drew: no node of its own, in a list. */\nfunction isListEntry(element: Element): boolean {\n  const list = element.parentElement;\n  return (\n    list !== null &&\n    !element.hasAttribute(NODE_ID_ATTRIBUTE) &&\n    element.classList.contains(LIST_CLASS) &&\n    list.hasAttribute(NODE_ID_ATTRIBUTE) &&\n    list.classList.contains(LIST_CLASS)\n  );\n}\n\n/** The entry's place among its list's entries, from 0. */\nfunction placeOf(entry: Element): number {\n  let place = 0;\n  for (\n    let before = entry.previousElementSibling;\n    before !== null;\n    before = before.previousElementSibling\n  ) {\n    if (isListEntry(before)) place += 1;\n  }\n  return place;\n}\n\n/**\n * The entry of each list around `target`, by the list's id, innermost\n * first; none for an element outside the canvas.\n */\nfunction entriesAround(target: unknown): ReadonlyMap<string, number> {\n  const entries = new Map<string, number>();\n  if (!isElement(target)) return entries;\n  const canvas = target.closest(`.${CANVAS_ROOT_CLASS}`);\n  if (canvas === null) return entries;\n  // Bounded by the canvas: each step moves one element out.\n  for (\n    let at: Element | null = target;\n    at !== null && at !== canvas;\n    at = at.parentElement\n  ) {\n    if (!isListEntry(at)) continue;\n    const listId = at.parentElement?.getAttribute(NODE_ID_ATTRIBUTE);\n    if (listId != null && !entries.has(listId)) {\n      entries.set(listId, placeOf(at));\n    }\n  }\n  return entries;\n}\n\n/**\n * Keep the entries `target` sits in for `nodeId`, the block a click on it\n * selected; a click that selected nothing, or nothing in a list, forgets them.\n */\nexport function rememberClickedEntries(\n  nodeId: string | null,\n  target: unknown\n): void {\n  const entries = entriesAround(target);\n  const next =\n    nodeId === null || entries.size === 0 ? undefined : { nodeId, entries };\n  if (next === undefined && clicked === undefined) return;\n  clicked = next;\n  for (const listener of listeners) listener();\n}\n\n/**\n * Keep the clicked entries only while the block they were kept for is\n * selected: a selection made another way (Layers, the keyboard) to any\n * other block forgets them, so coming back to the block from there samples\n * the first entry.\n */\nexport function keepClickedEntriesFor(selected: readonly string[]): void {\n  if (clicked === undefined || selected.includes(clicked.nodeId)) return;\n  forgetClickedEntries();\n}\n\n/** Forget every clicked entry. */\nexport function forgetClickedEntries(): void {\n  rememberClickedEntries(null, null);\n}\n\n/**\n * The entry of list `listId` the author clicked to select `nodeId`, or\n * `undefined` where the block was selected another way.\n */\nexport function clickedEntryOf(\n  nodeId: string,\n  listId: string\n): number | undefined {\n  return clicked?.nodeId === nodeId ? clicked.entries.get(listId) : undefined;\n}\n\n/**\n * The entry of each list the author clicked to select `nodeId`, by list id,\n * or `undefined` where the block was selected another way; drawn again when\n * the author clicks elsewhere.\n */\nexport function useClickedEntries(\n  nodeId: string\n): ReadonlyMap<string, number> | undefined {\n  const subscribe = React.useCallback((listener: () => void) => {\n    listeners.add(listener);\n    return () => {\n      listeners.delete(listener);\n    };\n  }, []);\n  return React.useSyncExternalStore(subscribe, () =>\n    clicked?.nodeId === nodeId ? clicked.entries : undefined\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 * What the pointer does on the canvas: a click selects, a context gesture\n * selects and finds the block a menu acts on, a list note's buttons do their\n * own thing, a move points the hovered block, and a click on the frame around\n * the page lets go of the selection. Chrome drawn over the canvas is never\n * the page.\n *\n * @module canvas-pointer\n */\n\nimport {\n  LIST_ACTION_ATTRIBUTE,\n  LIST_REF_ATTRIBUTE,\n  NODE_ID_ATTRIBUTE,\n} from \"@nextlyhq/blocks-react\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport { useCallback, useEffect, useRef } from \"react\";\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { nodeAddressOf, nodeIdFromEvent } from \"./canvas-addressing\";\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport type { CanvasProps } from \"./canvas-props\";\nimport { keepClickedEntriesFor, rememberClickedEntries } from \"./clicked-entry\";\nimport { isElement } from \"./dom-kind\";\nimport { useHoveredBlockSetter } from \"./hovered-block\";\nimport { selectionModeFor, type SelectionMode } from \"./selection\";\n\n/**\n * The block a context gesture is aimed at, or `null` when it is aimed at\n * nothing a block menu could act on.\n *\n * Published because a context menu can be opened TWO ways and they arrive by\n * different events. A secondary click arrives as `contextmenu`, which the\n * canvas sees; a touch or pen long-press is opened by Radix from its own timer\n * on `pointerdown`, and never produces a `contextmenu` event at all. A menu\n * that filtered one path and not the other would offer a block's verbs for a\n * press aimed at chrome, or — worse — offer the PREVIOUS selection's verbs,\n * with Delete among them, for a press on a block that was never selected.\n *\n * So the decision lives here once and both callers ask it, rather than each\n * spelling out three rejections and drifting.\n */\nexport function contextMenuTargetOf(\n  target: EventTarget | null,\n  root: Element\n): string | null {\n  if (isEditableTarget(target) || isChrome(target)) return null;\n  // By node kind rather than `instanceof Element`: a press inside a canvas\n  // mounted in an iframe targets an element that window built.\n  if (!isElement(target)) return null;\n  const owner = target.closest(`[${NODE_ID_ATTRIBUTE}]`);\n  if (owner === null) return null;\n  /*\n   * Owned by THIS canvas, not merely by A canvas.\n   *\n   * `nodeIdFromEvent` asks the weaker question — its own comment claims this\n   * one, and it checks only that some canvas is an ancestor. That is enough\n   * for selection, where a foreign id is ignored and nothing happens. It is\n   * not enough here: a canvas rendered inside a block of another canvas sends\n   * its events up through the outer one, which would then let a menu open\n   * while the outer selection stayed where it was — and its verbs would act on\n   * a block nobody was pointing at.\n   */\n  if (owner.closest(`.${CANVAS_ROOT_CLASS}`) !== root) return null;\n  // The same address the click path resolves. Returning the raw attribute here\n  // hands the menu a re-minted id the stored document does not contain, so\n  // `applySelection` keeps the PREVIOUS selection — and a destructive verb then\n  // acts on a block nobody pointed at.\n  return nodeAddressOf(owner);\n}\n\n/**\n * Whether the gesture landed in text the author is editing.\n *\n * Asked apart from {@link isChrome} because the answer is the same and the\n * reason is not: chrome is not the page, while this IS the page and is being\n * typed into. The browser's own menu carries spelling, selection and clipboard\n * for a caret, and none of that has a replacement here — taking it away mid\n * sentence to offer \"Move up\" is a straight loss.\n *\n * `contenteditable=\"false\"` is excluded explicitly: it marks a region the\n * editor has deliberately made uneditable INSIDE an editable one, which is a\n * block again rather than text.\n */\nfunction isEditableTarget(target: EventTarget | null): boolean {\n  if (!isElement(target)) return false;\n  const editable = target.closest(\"[contenteditable]\");\n  return (\n    editable !== null && editable.getAttribute(\"contenteditable\") !== \"false\"\n  );\n}\n\nfunction isChrome(target: EventTarget | null): boolean {\n  return isElement(target) && target.closest(`[${CHROME_ATTRIBUTE}]`) !== null;\n}\n\n/** How long a list note's Copy ref says \"Copied\" once pressed. */\nconst COPIED_FOR_MS = 2000;\n\n/**\n * A list note's Copy ref, when a press landed on it: the log reference it\n * names goes to the clipboard, and the button says so for a moment. Answers\n * whether it was one, so the press does nothing else.\n */\nfunction copyNoteReference(target: EventTarget | null): boolean {\n  if (!isElement(target)) return false;\n  const button = target.closest(`[${LIST_ACTION_ATTRIBUTE}=\"copy-ref\"]`);\n  const ref = button?.getAttribute(LIST_REF_ATTRIBUTE);\n  if (\n    button === null ||\n    button === undefined ||\n    ref === null ||\n    ref === undefined\n  ) {\n    return false;\n  }\n  // The editor's own clipboard, not the canvas frame's: a frame may not be\n  // allowed to write to it.\n  const clipboard: Clipboard | undefined =\n    typeof navigator === \"undefined\" ? undefined : navigator.clipboard;\n  void clipboard?.writeText(ref).then(\n    () => {\n      button.setAttribute(\"data-nx-list-copied\", \"\");\n      setTimeout(\n        () => button.removeAttribute(\"data-nx-list-copied\"),\n        COPIED_FOR_MS\n      );\n    },\n    // A clipboard the page may not write to leaves the reference selectable\n    // in the note, where it is set apart to be copied by hand.\n    () => undefined\n  );\n  return true;\n}\n\n/** The action a list's note offers, when a press landed on it. */\nfunction listActionOf(target: EventTarget | null): string | null {\n  if (!isElement(target)) return null;\n  return (\n    target\n      .closest(`[${LIST_ACTION_ATTRIBUTE}]`)\n      ?.getAttribute(LIST_ACTION_ATTRIBUTE) ?? null\n  );\n}\n\n/**\n * Which ids to mark, given what the host supplied.\n *\n * The primary alone when a host has not adopted the set yet, which keeps every\n * existing caller correct without a change. `[]` rather than `[null]` for an\n * empty selection: the marker is applied by id, and a null in the set would\n * match the elements carrying no id at all.\n */\nexport function markedIds(\n  selectedIds: readonly string[] | undefined,\n  selectedId: string | null\n): readonly string[] {\n  if (selectedIds !== undefined) return selectedIds;\n  return selectedId === null ? [] : [selectedId];\n}\n\n/**\n * The canvas's pointer handlers, which share one rule: chrome is not the page.\n *\n * Together rather than separately, because that rule is the whole of what they\n * have in common and a version where each handler remembers it for itself is\n * the version where the next one does not. Pressing a control drawn over the\n * canvas would otherwise resolve to \"no node\" and deselect the very block that\n * control acts on.\n */\nexport function useCanvasPointer(\n  onSelect: ((id: string | null, mode: SelectionMode) => void) | undefined,\n  onDoubleClick:\n    | ((event: React.MouseEvent<HTMLDivElement>) => void)\n    | undefined,\n  marked: readonly string[],\n  onListSortField?: (id: string) => void\n): {\n  onClick: (event: React.MouseEvent<HTMLDivElement>) => void;\n  onDoubleClick: (event: React.MouseEvent<HTMLDivElement>) => void;\n  onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => void;\n  onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => void;\n} {\n  // A selection made any other way than a click on an entry forgets the\n  // entries clicked, which the binding picker samples.\n  useEffect(() => keepClickedEntriesFor(marked), [marked]);\n  const click = useCallback(\n    (event: React.MouseEvent<HTMLDivElement>) => {\n      if (onSelect === undefined || isChrome(event.target)) return;\n      const id = nodeIdFromEvent(event.target);\n      // A failed list's Copy ref copies the reference and stays on the\n      // list: the author is about to paste it to a developer, not edit.\n      if (copyNoteReference(event.target)) {\n        if (id !== null) onSelect(id, \"replace\");\n        return;\n      }\n      // A list note's \"Choose a field\", pressed or activated from the\n      // keyboard: the host selects the list and takes the author to its sort,\n      // in place of the plain selection a click inside the list makes.\n      if (\n        id !== null &&\n        onListSortField !== undefined &&\n        listActionOf(event.target) === \"choose-sort-field\"\n      ) {\n        onListSortField(id);\n        return;\n      }\n      // A click on the canvas background resolves to null, which CLEARS the\n      // selection rather than being ignored. Ignoring it leaves an inspector\n      // showing a node the author believes they have deselected. The list\n      // entries pressed are kept with it, for the binding picker's values.\n      rememberClickedEntries(id, event.target);\n      onSelect(id, selectionModeFor(event));\n    },\n    [onSelect, onListSortField]\n  );\n  const doubleClick = useCallback(\n    (event: React.MouseEvent<HTMLDivElement>) => {\n      if (isChrome(event.target)) return;\n      onDoubleClick?.(event);\n    },\n    [onDoubleClick]\n  );\n  /*\n   * The secondary button selects, and says whether anything above this has a\n   * block to act on.\n   *\n   * Selecting FIRST is the whole point. A menu opened over one block while the\n   * selection sits on another acts on the other one, and the author is looking\n   * at the block they aimed at — so the destructive verbs on it would be aimed\n   * somewhere they cannot see.\n   *\n   * A block already in the selection is left alone rather than replacing it.\n   * Right-clicking one of several chosen blocks to act on all of them is what\n   * every comparable editor does, and re-selecting would silently drop the rest\n   * of the author's selection at the moment they went looking for a verb.\n   *\n   * Over the canvas BACKGROUND the event is stopped instead. There is no node,\n   * so a menu of block verbs would have no subject; stopping it here rather\n   * than opening an empty one keeps that decision next to the hit test that\n   * establishes it.\n   */\n  const contextMenu = useCallback(\n    (event: React.MouseEvent<HTMLDivElement>) => {\n      /*\n       * Three ways to have no block to act on, stopped the same way and for\n       * separate reasons — see each predicate. Stopping rather than merely\n       * returning is what matters: a menu mounted ABOVE the canvas sees\n       * whatever this lets past, and the chrome and the appenders are drawn\n       * INSIDE the canvas root, so a bare return offers the selected block's\n       * verbs for a gesture aimed at a button that is not a block.\n       *\n       * `preventDefault` is deliberately not called, so the browser's own menu\n       * still appears wherever this one does not.\n       */\n      const id = contextMenuTargetOf(event.target, event.currentTarget);\n      if (id === null) {\n        event.stopPropagation();\n        return;\n      }\n      if (onSelect === undefined || marked.includes(id)) return;\n      onSelect(id, \"replace\");\n    },\n    [marked, onSelect]\n  );\n  /*\n   * The same withholding, for the gesture that carries no context event.\n   *\n   * A menu mounted above the canvas can open a touch or pen LONG PRESS from a\n   * timer of its own, started on this event — no `contextmenu` is ever\n   * dispatched, so the rule above never runs and every rejection it makes is\n   * skipped. Withholding the press from anything above keeps one decision\n   * governing both ways in.\n   *\n   * `stopPropagation` and NOT `preventDefault`, which is the whole point of\n   * doing it here. This fires at the start of every contact, long before\n   * anything knows whether it will become a long press, and cancelling the\n   * default that early takes caret placement and text selection away from an\n   * author who was only tapping into a sentence.\n   */\n  const pointerDown = useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      if (contextMenuTargetOf(event.target, event.currentTarget) === null)\n        event.stopPropagation();\n    },\n    []\n  );\n  return {\n    onClick: click,\n    onDoubleClick: doubleClick,\n    onContextMenu: contextMenu,\n    onPointerDown: pointerDown,\n  };\n}\n\n/**\n * Point the editor's hovered block at the deepest block under the pointer, so\n * the canvas outlines it as a Layers row does, and at nothing when the\n * pointer leaves the canvas or is over its background.\n *\n * Nothing while a block is dragged: the drag's own marks say where it will\n * land, and an outline under the moving pointer would compete with them. The\n * drag's own move handler runs first, so the gesture behaves exactly as it\n * did; a move over the editor's chrome points at nothing new.\n */\nexport function useCanvasHover(\n  dragMove: React.PointerEventHandler<HTMLElement> | undefined,\n  dragging: boolean\n): {\n  onPointerMove: (event: React.PointerEvent<HTMLDivElement>) => void;\n  onPointerLeave: () => void;\n} {\n  const setHovered = useHoveredBlockSetter();\n  // In the layout phase, so the frame that first draws the drag never also\n  // draws the hovered outline its marks replace: a passive effect runs after\n  // that paint.\n  useIsomorphicLayoutEffect(() => {\n    if (dragging) setHovered(null);\n  }, [dragging, setHovered]);\n  // Nothing stays pointed at once the canvas goes.\n  useEffect(() => () => setHovered(null), [setHovered]);\n  const onPointerMove = useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      dragMove?.(event);\n      if (dragging) return;\n      const { target } = event;\n      // Chrome over a block is inside the canvas, so moving onto it fires no\n      // `pointerleave`: the block is let go here instead.\n      if (isChrome(target)) {\n        setHovered(null);\n        return;\n      }\n      // A canvas a block renders is another document, with its own addresses:\n      // its moves bubble here and are left to it.\n      if (\n        !isElement(target) ||\n        target.closest(`.${CANVAS_ROOT_CLASS}`) !== event.currentTarget\n      ) {\n        return;\n      }\n      setHovered(nodeIdFromEvent(target));\n    },\n    [dragMove, dragging, setHovered]\n  );\n  const onPointerLeave = useCallback(() => setHovered(null), [setHovered]);\n  return { onPointerMove, onPointerLeave };\n}\n\n/**\n * A click on the page around the canvas, inside its frame, answered as a\n * click on the canvas's own ground: the selection is cleared.\n *\n * On a page the site serves, the site's layout decides how tall the canvas\n * is, so below a short page the frame shows the site's own page rather than\n * the canvas, and the click an author makes there to let go of a block lands\n * outside the canvas root. Only inside a frame: where the canvas shares the\n * editor's document, everything outside it is the editor's own panels.\n */\nexport function useFrameGroundClick(\n  root: React.RefObject<HTMLDivElement | null>,\n  onSelect: CanvasProps[\"onSelect\"]\n): void {\n  const framed = useCanvasFrame().frame !== null;\n  const latest = useRef(onSelect);\n  useEffect(() => {\n    latest.current = onSelect;\n  }, [onSelect]);\n  useEffect(() => {\n    const element = root.current;\n    if (!framed || element === null) return;\n    const doc = element.ownerDocument;\n    const ground = (event: MouseEvent): void => {\n      const { target } = event;\n      // The canvas answers its own clicks, and chrome is not the page.\n      if (isElement(target) && element.contains(target)) return;\n      if (isChrome(target)) return;\n      latest.current?.(null, selectionModeFor(event));\n    };\n    doc.addEventListener(\"click\", ground);\n    return () => doc.removeEventListener(\"click\", ground);\n  }, [framed, root]);\n}\n","/**\n * The nearest `data-nx-theme` marker above an element.\n *\n * The site sheet declares its token values on each marker element and custom\n * properties inherit, so what an element resolves is decided by its NEAREST\n * marker, however the markers nest. `closest()` asks exactly that question of\n * the DOM, so a surface stating this answer cannot disagree with the values it\n * draws, at any depth of alternation; a set of fixed descendant selectors can\n * only ever cover a fixed number of them.\n *\n * @module nearest-theme\n */\nimport { DARK_MODE_ATTRIBUTE, type TokenMode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\n/**\n * The mode the nearest marker names, or `null` where none does.\n *\n * Exported so the inspector reads the canvas's mode by the same rule the\n * canvas states it by, rather than by a second reading of the markers.\n */\nexport function nearestThemeMode(element: Element): TokenMode | null {\n  const mode = element\n    .closest(`[${DARK_MODE_ATTRIBUTE}]`)\n    ?.getAttribute(DARK_MODE_ATTRIBUTE);\n  return mode === \"light\" || mode === \"dark\" ? mode : null;\n}\n\n/** The attribute the canvas states the nearest marker's mode in. */\nconst NEAREST_THEME_ATTRIBUTE = \"data-nx-site-theme\";\n\n/**\n * State the mode the nearest marker above `root` names on `root` itself, as\n * `data-nx-site-theme`, and keep it current as markers are set, changed or\n * removed anywhere in its document. Absent while no marker names a mode,\n * which leaves the choice to the device.\n *\n * Written in a layout effect, so the first paint already shows the canvas in\n * its marker's scheme rather than the device's for a frame. Written to the\n * element directly rather than through state, because a state update from a\n * layout effect only lands in a second render, after the commit that mounted\n * the canvas.\n */\nexport function useNearestThemeMarker(\n  root: React.RefObject<HTMLElement | null>\n): void {\n  React.useLayoutEffect(() => {\n    const element = root.current;\n    if (element === null) return;\n    const write = (): void => {\n      const mode = nearestThemeMode(element);\n      if (mode === null) element.removeAttribute(NEAREST_THEME_ATTRIBUTE);\n      else element.setAttribute(NEAREST_THEME_ATTRIBUTE, mode);\n    };\n    write();\n    const watch = new MutationObserver(write);\n    watch.observe(element.ownerDocument.documentElement, {\n      attributes: true,\n      attributeFilter: [DARK_MODE_ATTRIBUTE],\n      subtree: true,\n    });\n    return () => watch.disconnect();\n  }, [root]);\n}\n","/**\n * The site's surface on the canvas root: the custom properties that name the\n * site's ground and ink under its token prefix, whether its dark values\n * include a dark ground, and the marks written before paint for its theme and\n * whether its ground is fully opaque.\n *\n * @module canvas-site-surface\n */\n\nimport {\n  resolveSiteTokens,\n  resolveTokenPrefix,\n  tokenCustomProperty,\n  tokenIdentity,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  sharedStyleInputs,\n  type PageRendererProps,\n} from \"@nextlyhq/blocks-react\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport { useEffect, useRef } from \"react\";\n\nimport { setFlag } from \"./canvas-block-marks\";\nimport { useNearestThemeMarker } from \"./nearest-theme\";\nimport { alphaOf, computedAlphaOf, isDarkGround } from \"./site-ground\";\n\n/**\n * The site tokens the canvas page is drawn from, by IDENTITY as the default\n * token set declares them, mapped to the custom property the stylesheet reads\n * each from, with the value it falls back to where the token is undeclared.\n *\n * Set inline on the canvas root because the property each points at depends on\n * the prefix the site's tokens are emitted under, which only the site sheet\n * knows. An identity rather than a display name, so a site that renamed a\n * token still resolves: the property is built from the identity. The\n * fallbacks are the browser's own defaults, which is what a published page\n * shows where nothing paints.\n *\n * No font: the site's Body font is written by the page's own sheet on the\n * page root (Site text's Body row), the same rule on every surface.\n */\nconst SITE_SURFACE_TOKENS = [\n  [\"--nx-canvas-site-ground\", \"color.background\", \"Canvas\"],\n  [\"--nx-canvas-site-ink\", \"color.text\", \"CanvasText\"],\n] as const;\n\n/** The token the page's ground is drawn from, by identity. */\nconst SITE_GROUND_TOKEN = \"color.background\";\n\n/** What the canvas root needs from the site sheet to draw the page as the site. */\ninterface SiteSurface {\n  /** The custom properties naming the site's tokens, under its prefix. */\n  readonly style: Record<`--${string}`, string>;\n  /** Whether the site's background token has a DARK value. */\n  readonly darkGround: boolean;\n  /** Whether every value of the site's background token is fully opaque. */\n  readonly opaqueGround: boolean;\n}\n\n/**\n * The site's own surface tokens, as the canvas root carries them, or undefined\n * when the host serves no site sheet.\n *\n * The prefix is the one the renderer compiles the sheet under:\n * `sharedStyleInputs` reconciles the site's own prefixes with the route\n * context's, exactly as `PageRenderer` does before emitting the sheet, and\n * `resolveTokenPrefix` gives what is actually written. The token set is the\n * one the sheet emits — the site's own layered over the defaults by\n * `resolveSiteTokens` — so whether the ground has a dark value is asked of the\n * same tokens the page draws with.\n *\n * The site sheet applies dark values with the device (or a dark marker), for\n * every site. The scheme goes dark only where those values include a dark\n * ground, so a site whose dark set leaves the background light keeps a light\n * page and light native controls.\n */\nexport function siteSurface(\n  render: Omit<PageRendererProps, \"document\" | \"siteStyles\"> | undefined,\n  siteStyles: NonNullable<PageRendererProps[\"siteStyles\"]>\n): SiteSurface | undefined {\n  if (typeof siteStyles !== \"object\") return undefined;\n  const stated = sharedStyleInputs(\n    render?.styleContext,\n    siteStyles\n  ).tokenPrefix;\n  const { prefix } = resolveTokenPrefix(stated ?? undefined);\n  const style: Record<`--${string}`, string> = {};\n  for (const [property, token, fallback] of SITE_SURFACE_TOKENS) {\n    style[property] = `var(${tokenCustomProperty(token, prefix)}, ${fallback})`;\n  }\n  const tokens = resolveSiteTokens(siteStyles.tokens);\n  const values = tokens.tokens.find(\n    token => tokenIdentity(token) === SITE_GROUND_TOKEN\n  )?.values;\n  const ground = values?.dark;\n  return {\n    style,\n    darkGround: ground !== undefined && isDarkGround(ground),\n    opaqueGround:\n      values !== undefined &&\n      [values.light, values.dark].every(\n        value => value === undefined || alphaOf(value.trim()) === 1\n      ),\n  };\n}\n\n/**\n * The marks the site's surface puts on the canvas root, written before paint:\n * the nearest theme marker above it (`useNearestThemeMarker`), and whether the\n * site's ground is fully opaque.\n *\n * Only an opaque ground is repeated on the rendered page as well as the\n * canvas: painted twice, an opaque ground looks exactly as it does once, while\n * a translucent one would darken where the layers overlap. Judged from the\n * colour the root's background RESOLVES to, because the host's own CSS can\n * set the token's property to something the token set does not say. The\n * token set's answer stands where the resolved colour says nothing: one that\n * cannot be read, or one fully transparent, which is what a root painting no\n * ground of its own resolves to (a page the site serves), and a transparent\n * ground repeated on the page paints nothing either way.\n */\nexport function useSiteSurfaceMarks(\n  rootRef: React.RefObject<HTMLElement | null>,\n  opaqueByTokens: boolean\n): void {\n  useNearestThemeMarker(rootRef);\n  const tokens = useRef(opaqueByTokens);\n  tokens.current = opaqueByTokens;\n  // On every render: a render is what brings new site styles.\n  useIsomorphicLayoutEffect(() => {\n    const root = rootRef.current;\n    if (root !== null) markGround(root, tokens.current);\n  });\n  /*\n   * And on what changes the ground with no render, subscribed once for the\n   * root rather than on every render:\n   *\n   * - the site's mode: the theme marker rewrites the root's\n   *   `data-nx-site-theme` from an observer of its own, and the device's\n   *   colour scheme changes on its own. A light ground and a dark one can\n   *   differ in whether they are opaque;\n   * - the canvas's window resizing, or the canvas itself: a site can override\n   *   the ground under a width or height query, which a resized frame\n   *   crosses, and under a container query, which a canvas drawn without a\n   *   frame crosses as the layout around it changes.\n   */\n  useEffect(() => {\n    const root = rootRef.current;\n    if (root === null) return;\n    const view = root.ownerDocument.defaultView;\n    const mark = (): void => markGround(root, tokens.current);\n    const Observer = view?.MutationObserver;\n    const theme =\n      typeof Observer === \"function\" ? new Observer(() => mark()) : null;\n    theme?.observe(root, {\n      attributes: true,\n      attributeFilter: [\"data-nx-site-theme\"],\n    });\n    const scheme = view?.matchMedia?.(\"(prefers-color-scheme: dark)\");\n    scheme?.addEventListener(\"change\", mark);\n    view?.addEventListener(\"resize\", mark);\n    const Sizes = view?.ResizeObserver;\n    const size = typeof Sizes === \"function\" ? new Sizes(() => mark()) : null;\n    size?.observe(root);\n    return () => {\n      theme?.disconnect();\n      scheme?.removeEventListener(\"change\", mark);\n      view?.removeEventListener(\"resize\", mark);\n      size?.disconnect();\n    };\n  }, [rootRef]);\n}\n\n/**\n * Mark whether the site's ground is fully opaque, from the colour the root's\n * background resolves to; the token set's answer where that says nothing.\n */\nfunction markGround(root: HTMLElement, opaqueByTokens: boolean): void {\n  const resolved = (\n    root.ownerDocument.defaultView?.getComputedStyle(root).backgroundColor ?? \"\"\n  ).trim();\n  const alpha = alphaOf(resolved) ?? computedAlphaOf(resolved);\n  setFlag(\n    root,\n    \"data-nx-site-ground-opaque\",\n    alpha === undefined || alpha === 0 ? opaqueByTokens : alpha === 1\n  );\n}\n","/**\n * How the canvas draws a template's Entry content block: with the previewed\n * entry's own blocks content, read-only, or the note that says why there is\n * none.\n *\n * - With an entry previewed, the block draws the entry's `editorValues` for\n *   its field, drafts included, as the person editing reads them: composed\n *   into the block by the engine's own `composeEntryContent`, the one the\n *   published page draws through, so the canvas shows what the page will.\n * - With none to draw, the block draws the canvas's note, in the words the\n *   proposal fixed: \"The post’s Body shows here.\" with no entry previewed,\n *   \"<title> has no Body content yet.\" for an empty field, and the red \"The\n *   Body field no longer exists in Posts, so this shows nothing. Choose\n *   another field.\" for a field the collection no longer has.\n *\n * Only the drawn page changes: the document the editor holds, saves and marks\n * is the template as stored, so nothing of the entry is ever written into it.\n * Outside a template nothing is previewed and the canvas draws the document\n * as it is.\n *\n * @experimental Settles when collection templates ship.\n * @module entry-content-canvas\n */\nimport {\n  composeEntryContent,\n  DOCUMENT_FORMAT_VERSION,\n  entryBlocksDocumentOf,\n  entryContentPlacements,\n  type BlockDocument,\n  type ComponentLookup,\n} from \"@nextlyhq/blocks-engine\";\nimport type {\n  EntryContentCanvas,\n  EntryContentNote,\n  PageContext,\n  PageRendererProps,\n} from \"@nextlyhq/blocks-react\";\nimport { createStandaloneContext } from \"@nextlyhq/blocks-react\";\nimport { useMemo } from \"react\";\n\nimport {\n  entryFieldRemoved,\n  fieldName,\n  usePreviewedCollection,\n  usePreviewedEntry,\n  type PreviewedCollection,\n  type PreviewedEntry,\n} from \"./previewed-entry\";\n\n/** What the canvas draws a page with, less what is the page's alone. */\ntype CanvasRender = Omit<PageRendererProps, \"document\" | \"siteStyles\">;\n\n/** The note of a block that names no field yet. */\nfunction unsetNote(\n  collection: PreviewedCollection | undefined\n): EntryContentNote {\n  return collection?.blocksFields?.length === 0\n    ? {\n        tone: \"failed\",\n        words: `${collection.plural} has no blocks field to show.`,\n      }\n    : { tone: \"muted\", words: \"Choose the field this shows.\" };\n}\n\n/**\n * The note an Entry content block draws in place of the entry's content,\n * given what is previewed and the field the block names.\n */\nfunction entryContentNote(\n  field: string | undefined,\n  previewed: PreviewedEntry,\n  collection: PreviewedCollection | undefined\n): EntryContentNote {\n  if (field === undefined) return unsetNote(collection);\n  const words = fieldName(field, collection);\n  if (entryFieldRemoved(field, collection)) {\n    return {\n      tone: \"failed\",\n      words: `The ${words} field no longer exists in ${collection?.plural ?? \"this collection\"}, so this shows nothing. Choose another field.`,\n    };\n  }\n  if (previewed.kind === \"none\") {\n    const singular = collection?.singular ?? \"entry\";\n    return { tone: \"muted\", words: `The ${singular}’s ${words} shows here.` };\n  }\n  return {\n    tone: \"muted\",\n    lead: previewed.title,\n    words: `has no ${words} content yet.`,\n  };\n}\n\n/**\n * The document and render inputs the canvas draws a template with: the\n * previewed entry's blocks composed into its Entry content block, and the\n * page context telling the block it is on the canvas. Both are the ones\n * given, by identity, outside a template or on a template holding no Entry\n * content block, so the canvas keeps everything it kept.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function useEntryContentDrawing(\n  document: BlockDocument,\n  render: CanvasRender | undefined,\n  /**\n   * `document` as drawn, where the host composed it: drawn as it is, with\n   * nothing composed here.\n   */\n  composed?: BlockDocument\n): {\n  readonly document: BlockDocument;\n  readonly render: CanvasRender | undefined;\n} {\n  const previewed = usePreviewedEntry();\n  const collection = usePreviewedCollection();\n  const maxNodes = render?.limits?.maxNodes;\n  const holds = useHoldsEntryContent(document, maxNodes);\n  // Drawn from the entry the seam names, which a host names only once the\n  // canvas's own read of it has answered, so bound values never blink in;\n  // nothing is composed where the host hands the page as drawn.\n  const own = useComposedEntryContent(\n    document,\n    composed === undefined ? previewed : undefined,\n    entryContentLimitsOf(render)\n  );\n  const drawn = composed ?? own;\n  const context = render?.context;\n  const drawnRender = useMemo((): CanvasRender | undefined => {\n    if (previewed === undefined || !holds) return render;\n    const canvas: EntryContentCanvas = {\n      noteFor: field => entryContentNote(field, previewed, collection),\n    };\n    const base: PageContext = context ?? createStandaloneContext();\n    return { ...render, context: { ...base, entryContentCanvas: canvas } };\n  }, [render, context, previewed, collection, holds]);\n  return { document: drawn, render: drawnRender };\n}\n\n/**\n * The page the canvas draws while conditions are applied (`applied`, the\n * page as they leave it): as it is where the host composed the entry into it\n * (`composed` given), else with the entry the seam names composed into it\n * here, as a host that applies conditions to the stored template expects.\n * `undefined` while no conditions are applied.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function useAppliedDrawing(\n  applied: BlockDocument | undefined,\n  composed: BlockDocument | undefined,\n  render: CanvasRender | undefined\n): BlockDocument | undefined {\n  const previewed = usePreviewedEntry();\n  const composesHere = applied !== undefined && composed === undefined;\n  const drawn = useComposedEntryContent(\n    applied ?? EMPTY_PAGE,\n    composesHere ? previewed : undefined,\n    entryContentLimitsOf(render)\n  );\n  return applied === undefined ? undefined : drawn;\n}\n\n/** No page, for the composition asked while no conditions are applied. */\nconst EMPTY_PAGE: BlockDocument = {\n  formatVersion: DOCUMENT_FORMAT_VERSION,\n  kind: \"page\",\n  nodes: [],\n};\n\n/**\n * What the canvas composes an entry's content under: its limits, and the\n * definitions of the components the page places. Held by what it reads, so\n * a render handing the same inputs composes nothing again.\n */\nfunction entryContentLimitsOf(\n  render: CanvasRender | undefined\n): EntryContentLimits {\n  const limits = render?.limits;\n  const definitions = render?.definitions;\n  return {\n    ...(limits === undefined ? {} : { maxNodes: limits.maxNodes }),\n    ...(limits === undefined ? {} : { maxDepth: limits.maxDepth }),\n    ...(definitions === undefined ? {} : { definitions }),\n  };\n}\n\n/** Whether `document` holds an Entry content block, asked once per document. */\nfunction useHoldsEntryContent(\n  document: BlockDocument,\n  maxNodes: number | undefined\n): boolean {\n  return useMemo(\n    () => entryContentPlacements(document.nodes, maxNodes).length > 0,\n    [document, maxNodes]\n  );\n}\n\n/**\n * `document` with `previewed`'s own blocks composed into its Entry content\n * block, as the canvas draws it; `document` itself, by identity, where no\n * entry is given or it holds no such block.\n *\n * The one composition everything about the canvas's template is asked of:\n * the canvas draws it, and the host asks for the sources its bindings and\n * lists read from it, so a bound block inside the entry's content reads its\n * source on the canvas as the published page, which composes first, does.\n *\n * The entry is given rather than read from the seam: a host asking for those\n * sources composes from the entry as its own read has it, since the seam\n * names the entry only once the canvas's read of it has answered, and that\n * read is asked of this composition. Composed from the seam, the read would\n * change its own ask each time it answered, and never settle.\n *\n * @experimental Settles when collection templates ship.\n */\nexport function useComposedEntryContent(\n  document: BlockDocument,\n  previewed: PreviewedEntry | undefined,\n  /**\n   * The limits the canvas draws under: the entry's blocks past its node cap\n   * or below its depth are never read, and, given the definitions of the\n   * components the page places, the template is charged what it draws once\n   * they are expanded. A number is the node cap alone, as this took before.\n   * The format's own limits where absent.\n   */\n  limits?: number | EntryContentLimits\n): BlockDocument {\n  const { maxNodes, maxDepth, definitions } =\n    typeof limits === \"number\" ? { maxNodes: limits } : (limits ?? {});\n  const holds = useHoldsEntryContent(document, maxNodes);\n  return useMemo(\n    () =>\n      previewed?.kind !== \"entry\" || !holds\n        ? document\n        : composeEntryContent(document, {\n            // The entry as the person editing reads it, drafts included;\n            // read through the engine's own reading of a stored value, so\n            // a field holding no document draws the empty note.\n            valueOf: name =>\n              entryBlocksDocumentOf(previewed.editorValues[name]) ?? undefined,\n            ...(maxNodes === undefined ? {} : { maxNodes }),\n            ...(maxDepth === undefined ? {} : { maxDepth }),\n            ...(definitions === undefined ? {} : { definitions }),\n          }),\n    [document, previewed, holds, maxNodes, maxDepth, definitions]\n  );\n}\n\n/**\n * What a composition of an entry's content is held to: the page's node cap\n * and depth, and the definitions of the components it places.\n *\n * @experimental Settles when collection templates ship.\n */\nexport interface EntryContentLimits {\n  readonly maxNodes?: number;\n  readonly maxDepth?: number;\n  readonly definitions?: ComponentLookup;\n}\n","/**\n * The entry's own blocks an Entry content block draws on the canvas, made\n * inert so nothing inside them takes focus or a press, and given back only\n * the inert the canvas added, never one a block set itself.\n *\n * @module canvas-entry-content-inert\n */\n\nimport { ENTRY_CONTENT_DRAWN_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport { ownedByCanvas } from \"./canvas-addressing\";\nimport { setMark } from \"./canvas-block-marks\";\n\n/**\n * Marks the drawn element of each of the entry's own blocks this canvas draws\n * in Entry content as ours to make `inert`. Its value says whether the `inert`\n * is ours to give back ({@link INERT_ADDED}) or was the block's own before the\n * canvas marked it ({@link INERT_KEPT}).\n */\nexport const ENTRY_CONTENT_INERT_ATTRIBUTE = \"data-nx-entry-content-inert\";\n\n/** The canvas made the element inert, and takes that back when it leaves. */\nconst INERT_ADDED = \"added\";\n\n/** The element was inert already, by its own block, and stays so. */\nconst INERT_KEPT = \"kept\";\n\n/**\n * Each canvas's observer of who owns its marked elements' `inert`, by\n * container, so a marking pass reads what it has not delivered yet first.\n */\nconst inertOwnership = new WeakMap<HTMLElement, MutationObserver>();\n\n/**\n * Watch whose `inert` each element marked in Entry content holds, as its block\n * changes its own after the canvas marked it. Returns the unsubscribe.\n *\n * A block that starts rendering inert on an element the canvas already made\n * inert changes nothing the tree shows, so only the mutation tells: React's\n * `setAttribute` on a present attribute still queues a record, with the old\n * value. The canvas writes `inert` only where it is absent, so a record with an\n * old value that leaves the attribute present is the block's write, and the\n * element's inert is now its own. One that leaves it absent is the block\n * dropping its inert, and the canvas holds the element inert in its place.\n */\nexport function observeEntryContentInertOwnership(\n  container: HTMLElement\n): () => void {\n  // From the container's own window, as the rendered tree's observer is.\n  const Mutations = container.ownerDocument.defaultView?.MutationObserver;\n  if (typeof Mutations !== \"function\") return () => undefined;\n  const observer = new Mutations(records =>\n    readInertOwnership(container, records)\n  );\n  observer.observe(container, {\n    attributes: true,\n    attributeFilter: [\"inert\"],\n    attributeOldValue: true,\n    subtree: true,\n  });\n  inertOwnership.set(container, observer);\n  return () => {\n    readInertOwnership(container, observer.takeRecords());\n    observer.disconnect();\n    if (inertOwnership.get(container) === observer) {\n      inertOwnership.delete(container);\n    }\n  };\n}\n\nfunction readInertOwnership(\n  container: HTMLElement,\n  records: readonly MutationRecord[]\n): void {\n  const marked = new Set<Element>();\n  records.forEach((record, index) => {\n    // An attribute record's target is always an element.\n    const element = record.target as Element;\n    if (\n      !element.hasAttribute(ENTRY_CONTENT_INERT_ATTRIBUTE) ||\n      !ownedByCanvas(element, container)\n    ) {\n      return;\n    }\n    marked.add(element);\n    // Absent before: an add, which is how the canvas writes it.\n    if (record.oldValue === null) return;\n    // What this write left: the next record's old value, or the tree now.\n    const next = records\n      .slice(index + 1)\n      .find(later => later.target === element);\n    const present =\n      next === undefined\n        ? element.hasAttribute(\"inert\")\n        : next.oldValue !== null;\n    if (present) setMark(element, ENTRY_CONTENT_INERT_ATTRIBUTE, INERT_KEPT);\n  });\n  marked.forEach(holdEntryContentInert);\n}\n\n/**\n * Make a marked element inert where it is not. Not inert now, the inert it\n * gets is the canvas's to give back, also where its block had one and dropped\n * it: left `kept`, it would stay inert once no longer drawn in Entry content.\n */\nfunction holdEntryContentInert(element: Element): void {\n  if (element.hasAttribute(\"inert\")) return;\n  setMark(element, ENTRY_CONTENT_INERT_ATTRIBUTE, INERT_ADDED);\n  element.setAttribute(\"inert\", \"\");\n}\n\n/**\n * Make the entry's blocks an Entry content block draws on this canvas inert,\n * and nothing else: each child of a drawn wrapper, so no link, field or button\n * inside takes focus, a caret or a press, while the wrapper, the block's own\n * element, stays the one a click lands on and selects. The page's markup is\n * not changed, so the canvas lays the blocks out as the published page does.\n * An element no longer drawn there gives back the inert this set, and only\n * that: one a block rendered inert itself (a custom block whose root is inert)\n * keeps its `inert` when it leaves, as the canvas frame keeps a site's own.\n * Written only where it changes, as every mark here is.\n */\nexport function markEntryContentInert(container: HTMLElement): void {\n  // A block's write to its inert this commit, before this pass gives any back.\n  const pending = inertOwnership.get(container);\n  if (pending !== undefined) {\n    readInertOwnership(container, pending.takeRecords());\n  }\n  const wanted = new Set<Element>();\n  container\n    .querySelectorAll(`[${ENTRY_CONTENT_DRAWN_ATTRIBUTE}]`)\n    .forEach(wrapper => {\n      if (!ownedByCanvas(wrapper, container)) return;\n      for (const child of Array.from(wrapper.children)) wanted.add(child);\n    });\n  container\n    .querySelectorAll(`[${ENTRY_CONTENT_INERT_ATTRIBUTE}]`)\n    .forEach(element => {\n      // Another canvas's marks are that canvas's to clear, as they were its\n      // to set: a canvas drawn inside this one (a component's own view) keeps\n      // its entry's blocks inert whatever this one re-marks.\n      if (wanted.has(element) || !ownedByCanvas(element, container)) return;\n      const ours =\n        element.getAttribute(ENTRY_CONTENT_INERT_ATTRIBUTE) !== INERT_KEPT;\n      element.removeAttribute(ENTRY_CONTENT_INERT_ATTRIBUTE);\n      if (ours) element.removeAttribute(\"inert\");\n    });\n  wanted.forEach(element => {\n    // Whether the inert was the block's own is read when the canvas first\n    // marks the element, before it adds any; after that, its block changing\n    // it is read by `observeEntryContentInertOwnership` and the hold below.\n    if (!element.hasAttribute(ENTRY_CONTENT_INERT_ATTRIBUTE)) {\n      element.setAttribute(\n        ENTRY_CONTENT_INERT_ATTRIBUTE,\n        element.hasAttribute(\"inert\") ? INERT_KEPT : INERT_ADDED\n      );\n    }\n    holdEntryContentInert(element);\n  });\n}\n","/**\n * When the rendered tree has changed, in one definition.\n *\n * The canvas draws a document React commits over time rather than all at once,\n * and two separate readers need to know when that drawing moved: the inspector,\n * which reads the element a node was drawn as, and the canvas itself, which\n * marks the selection and the interaction state onto those elements. Both ask\n * the same question, so both subscribe through here.\n *\n * A dependency list cannot answer it. A block whose `render` returns a promise\n * commits its Suspense fallback first and its resolved root later, and that\n * second commit changes no prop, no state and no id — `core/collection-loop`\n * awaits `data.find`, so this is an ordinary shipping block rather than an edge\n * case. A reader keyed on props alone sees the fallback, finds none of the\n * elements it was looking for, and never looks again.\n *\n * A plain function rather than a hook, because the two callers schedule\n * differently — one owns React state, the other writes to the DOM — and only\n * the subscription is common. Making it a hook would force one scheduling shape\n * onto both and put a spread dependency list in each.\n *\n * @module rendered-tree\n */\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\n/**\n * What counts as the rendered tree changing.\n *\n * Structure, because that is how a resolved block arrives. The node id\n * ATTRIBUTE as well, because a node's id moving between elements changes which\n * element every reader here is talking about while adding and removing none.\n *\n * No other attribute, and that is load-bearing rather than economical. Both\n * callers WRITE to elements inside the tree they observe — the marker walk sets\n * the selection attribute and the state class — so an observer that watched\n * attributes broadly would be triggered by its own output and re-enter for as\n * long as the canvas is mounted. The node id is written by the renderer and by\n * nothing that reads it here, which is what makes it safe to watch.\n */\nconst RENDERED_TREE_MUTATIONS: MutationObserverInit = {\n  childList: true,\n  subtree: true,\n  attributeFilter: [NODE_ID_ATTRIBUTE],\n};\n\n/**\n * Call `read` whenever the rendered tree under `root` changes.\n *\n * Returns the unsubscribe. Callers are expected to `read()` once themselves\n * first: an observer reports changes from the moment it is attached and says\n * nothing about the tree that is already there.\n *\n * `MutationObserver` is absent in some non-browser DOMs, and both callers are\n * useful without it — each still reads on the changes that ARE dependencies.\n * Guarded rather than assumed, because throwing here would take the editor down\n * on a surface that otherwise renders perfectly well.\n */\nexport function observeRenderedTree(\n  root: Element,\n  read: () => void\n): () => void {\n  // From the root's own window, so a tree rendered in a frame is watched by\n  // that frame's observer: the realm of the nodes it reports on.\n  const Mutations = root.ownerDocument.defaultView?.MutationObserver;\n  if (typeof Mutations !== \"function\") return () => undefined;\n  const observer = new Mutations(read);\n  observer.observe(root, RENDERED_TREE_MUTATIONS);\n  return () => {\n    observer.disconnect();\n  };\n}\n","/**\n * The walk that writes the marks on the rendered page: the selection, the\n * drag's marks, the locked, conditioned and Entry content blocks, the blocks\n * hidden on the device shown, and the forced interaction state, kept right as the rendered tree changes.\n *\n * @module use-canvas-markers\n */\n\nimport {\n  PAGE_ROOT_CLASS,\n  previewStateClass,\n  statePropagatesToAncestors,\n  STYLE_STATES,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\nimport { useEffect } from \"react\";\n\nimport {\n  isOutermostForAddress,\n  nodeAddressOf,\n  ownedByCanvas,\n} from \"./canvas-addressing\";\nimport {\n  CONDITIONED_ATTRIBUTE,\n  CONDITIONED_OWN_ATTRIBUTE,\n  conditionMarkFor,\n  DRAG_SOURCE_ATTRIBUTE,\n  DROP_PARENT_ATTRIBUTE,\n  DROP_REFUSED_ATTRIBUTE,\n  ENTRY_CONTENT_ATTRIBUTE,\n  outermostMarkFor,\n  LOCKED_ATTRIBUTE,\n  SELECTED_ATTRIBUTE,\n  setFlag,\n  setMark,\n  type ConditionMarks,\n  type LockMark,\n} from \"./canvas-block-marks\";\nimport { DEVICE_HIDDEN_ATTRIBUTE } from \"./canvas-device-hidden\";\nimport type { CanvasDragState } from \"./canvas-drag\";\nimport { drawnRefusal } from \"./canvas-drop-refusal\";\nimport {\n  markEntryContentInert,\n  observeEntryContentInertOwnership,\n} from \"./canvas-entry-content-inert\";\nimport { observeRenderedTree } from \"./rendered-tree\";\n\n/**\n * Mark the selected elements on the rendered tree.\n *\n * Applied AFTER the renderer has produced them, rather than asked of\n * `PageRenderer`. Which node an editor considers current is an editor's\n * concern, and a published route renders the same document without one —\n * pushing it into the renderer's contract would put editor state in the\n * component that serves live pages.\n *\n * Ids are COMPARED in JavaScript rather than matched with a selector built from\n * one. A node id reaches this from stored data, and interpolating it into\n * `querySelector` makes any character CSS treats specially either throw or,\n * worse, match something else.\n *\n * `page` is a dependency because the rendered tree is what carries the markers:\n * a re-render replaces the elements, and an effect keyed on the selection alone\n * would leave the new tree carrying none at all.\n */\nexport function useCanvasMarkers(\n  box: React.RefObject<HTMLElement | null>,\n  marked: readonly string[],\n  selectedId: string | null,\n  page: React.ReactNode,\n  forcedState: StyleState | undefined,\n  drag: CanvasDragState | undefined,\n  lockedIds: ReadonlyMap<string, LockMark>,\n  conditionMarks: ConditionMarks,\n  entryContentMarks: ReadonlyMap<string, string>,\n  deviceHiddenMarks: ReadonlyMap<string, string>\n): void {\n  /*\n   * The drag's three marks are read into plain ids here rather than inside the\n   * walk, so the effect depends on the VALUES that change the answer instead of\n   * on the drag object's identity. `useCanvasDrag` returns a fresh object on\n   * every pointer move, and an effect keyed on it would re-walk the whole tree\n   * per frame while writing nothing new.\n   */\n  const sourceId = drag?.draggingId ?? null;\n  const parentId = drag?.target?.at.parentId ?? null;\n  const refusedId = drawnRefusal(drag)?.parentId ?? null;\n  useEffect(() => {\n    const container = box.current;\n    if (container === null) return;\n    /*\n     * NAMED and re-run rather than written straight into the effect, because\n     * the dependency list is not the only thing that changes the answer.\n     *\n     * A block whose `render` returns a promise commits its Suspense fallback\n     * first and its resolved root later. That second commit inserts the element\n     * carrying the node id while changing no prop, no state and no id in this\n     * list — so an effect that ran once would have marked a tree the resolved\n     * block was not in yet, and would leave it unmarked until an unrelated\n     * selection or document change happened to run this again. Selecting a\n     * `core/collection-loop` showed exactly that: no outline and no forced\n     * state, on an ordinary shipping block.\n     */\n    const mark = (): void => {\n      /*\n       * Every element a marker can land on OR currently carries one, which are\n       * not the same set. A render can move a node id from one existing element\n       * to another without touching the child list — the attribute case this\n       * effect subscribes to — and the element that LOST the id then matches\n       * nothing selected by node id. Left out, it keeps the selection attribute\n       * and the state class it was last given: a second outline around a block\n       * nothing is editing, and a hover appearance forced on it.\n       *\n       * The rendered PAGE ROOT is named explicitly rather than reached by one\n       * of the marker selectors: `PageRenderer` draws `.nx-pb-page` as a child\n       * of this container and the page tier compiles onto that element rather\n       * than onto the canvas wrapper, so it must be markable before it has ever\n       * been marked.\n       */\n      const touched = new Set<Element>([container]);\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 — so the\n      // loop that reads more naturally does not type-check here.\n      container\n        .querySelectorAll(\n          [\n            `.${PAGE_ROOT_CLASS}`,\n            `[${NODE_ID_ATTRIBUTE}]`,\n            `[${SELECTED_ATTRIBUTE}]`,\n            // The drag marks belong here for the reason the selection attribute\n            // does, and the case is the same one: an element that LOSES its node\n            // id matches nothing selected by node id, so leaving these out\n            // strands whatever they were last given. A block that stopped being\n            // the drag source would stay dimmed with nothing left to clear it.\n            `[${DRAG_SOURCE_ATTRIBUTE}]`,\n            `[${DROP_PARENT_ATTRIBUTE}]`,\n            `[${DROP_REFUSED_ATTRIBUTE}]`,\n            `[${LOCKED_ATTRIBUTE}]`,\n            `[${CONDITIONED_ATTRIBUTE}]`,\n            `[${CONDITIONED_OWN_ATTRIBUTE}]`,\n            `[${ENTRY_CONTENT_ATTRIBUTE}]`,\n            `[${DEVICE_HIDDEN_ATTRIBUTE}]`,\n            ...STYLE_STATES.map(state => `.${previewStateClass(state)}`),\n          ].join(\", \")\n        )\n        .forEach(element => touched.add(element));\n\n      touched.forEach(element => {\n        // Another canvas's elements are that canvas's to mark, exactly as the\n        // drag pass below leaves them. Ids are scoped per document, so a nested\n        // canvas can hold an instance with the SAME address as the one selected\n        // out here — and marking it would outline a block belonging to a\n        // document this selection is not in.\n        if (!ownedByCanvas(element, container)) return;\n        // The ADDRESS, not the raw attribute. A definition-owned element\n        // carries a re-minted id the selection never holds, so comparing the\n        // attribute leaves a selected component with no outline at all.\n        const id = nodeAddressOf(element);\n        // OUTERMOST only, which draws one outline per instance while still\n        // marking every copy of a node a block rendered more than once — see\n        // `isOutermostForAddress` for why those two cases need opposite\n        // answers.\n        if (\n          id === null ||\n          !marked.includes(id) ||\n          !isOutermostForAddress(element, id, container)\n        ) {\n          // Guarded like the writes below: this walk now visits the page root\n          // and the container, which never carry the attribute, and removing an\n          // absent one still touches the element.\n          if (element.hasAttribute(SELECTED_ATTRIBUTE)) {\n            element.removeAttribute(SELECTED_ATTRIBUTE);\n          }\n          return;\n        }\n        // The VALUE carries which member the panels answer for. A boolean\n        // attribute could not, and a second attribute for the primary would be a\n        // state where a block is primary without being selected.\n        //\n        // Compared before writing, for the reason the class below is: this walk\n        // re-runs on every change to the rendered tree, and `setAttribute`\n        // queues a mutation record even when the value it writes is the value\n        // already there. Unguarded, marking a tree that did not change is\n        // itself a change — the spacing overlay observes this subtree and\n        // re-measures on one, so its own output would arrive back here as a\n        // reason to write again.\n        const value = id === selectedId ? \"primary\" : \"\";\n        if (element.getAttribute(SELECTED_ATTRIBUTE) !== value) {\n          element.setAttribute(SELECTED_ATTRIBUTE, value);\n        }\n      });\n\n      /*\n       * The drag's marks, in the SAME walk and over the SAME set, for the\n       * reason the forced state below is: all of them answer \"what is marked on\n       * this element right now\", and two walks over one question drift — one\n       * runs on a change the other does not.\n       *\n       * Over `touched` rather than a fresh query, so an element that has just\n       * LOST the node id is visited and cleared. Left out, a block that stopped\n       * being the drag source keeps the mark and stays dimmed after the drop.\n       */\n      const dragMarks: ReadonlyArray<readonly [string, string | null]> = [\n        [DRAG_SOURCE_ATTRIBUTE, sourceId],\n        [DROP_PARENT_ATTRIBUTE, parentId],\n        [DROP_REFUSED_ATTRIBUTE, refusedId],\n      ];\n      touched.forEach(element => {\n        if (!ownedByCanvas(element, container)) return;\n        const id = element.getAttribute(NODE_ID_ATTRIBUTE);\n        // Whether the engine would refuse to move this node, asked from the set\n        // rather than from the document per element: this walk re-runs on every\n        // change to the rendered tree, and a tree search per element would make\n        // that quadratic on a large page. Asked by the ADDRESS, as the selection\n        // pass above is: a placement's parts carry a re-minted id the document\n        // does not hold, and the lock that holds them is the placement's.\n        const address = nodeAddressOf(element);\n        setMark(\n          element,\n          LOCKED_ATTRIBUTE,\n          address === null ? undefined : lockedIds.get(address)\n        );\n        // On the block's own outermost element, so a block a list draws once\n        // per entry is marked once per copy and its parts are not marked again.\n        const condition = conditionMarkFor(element, container, conditionMarks);\n        setMark(element, CONDITIONED_ATTRIBUTE, condition?.mark);\n        setMark(\n          element,\n          CONDITIONED_OWN_ATTRIBUTE,\n          condition?.own === true ? (condition.nested ?? \"\") : undefined\n        );\n        // An Entry content block's words, on its outermost element alike.\n        setMark(\n          element,\n          ENTRY_CONTENT_ATTRIBUTE,\n          outermostMarkFor(element, container, entryContentMarks)\n        );\n        // A block hidden on the device shown, striped with its tag, alike.\n        setMark(\n          element,\n          DEVICE_HIDDEN_ATTRIBUTE,\n          outermostMarkFor(element, container, deviceHiddenMarks)\n        );\n        for (const [attribute, wanted] of dragMarks) {\n          setFlag(element, attribute, id !== null && id === wanted);\n        }\n      });\n\n      /*\n       * The forced interaction state, in the SAME walk rather than a second one.\n       * Both answer \"what is marked on this element right now\", and two walks\n       * over one question drift — one runs on a change the other does not.\n       *\n       * On the PRIMARY alone. A page cannot force a pseudo-class on itself, so\n       * the compiler emits a class alternative beside each one and this puts it\n       * on the element the panel is editing. Forcing it page-wide would show\n       * every other block in a state nobody asked about.\n       *\n       * Cleared from everything first, including the primary: a state that\n       * changes from hover to focus, or a selection that moves, must not leave\n       * the previous class behind on an element nothing is editing.\n       */\n      /*\n       * WHICH ELEMENTS a forced state belongs on, ASKED of the engine rather\n       * than decided here.\n       *\n       * Whether a state propagates follows from the pseudo-class the compiler\n       * emits for it — an ancestor matches `:hover` and `:active` and does not\n       * match `:focus-visible` — so the two facts live together beside that\n       * definition. Encoding the rule here as well would be a second opinion\n       * about the CSS: changing `focus` to `:focus-within` would move the\n       * published rules and leave this canvas marking the wrong chain, with both\n       * sides type-correct.\n       *\n       * Where a state does propagate the chain is required rather than tidy: the\n       * page tier compiles onto the RENDERED page root, and a marker on a\n       * descendant cannot make its ancestor match.\n       */\n      const chain = new Set<Element>();\n      if (forcedState !== undefined && forcedState !== \"base\") {\n        /*\n         * EVERY rendering of the primary node, not the first one found.\n         *\n         * A node id is unique in a DOCUMENT and not in the tree drawn from it:\n         * `core/collection-loop` draws its children once per entry, so one\n         * selected node is many elements, and the walk above has already marked\n         * all of them primary. Taking `querySelector` here would preview the\n         * state on whichever copy came first in DOM order — the outline on ten\n         * rows and the hover appearance on one, which reads as the state being\n         * broken rather than as the preview being partial.\n         */\n        container\n          .querySelectorAll(`[${SELECTED_ATTRIBUTE}=\"primary\"]`)\n          .forEach(primary => {\n            chain.add(primary);\n            if (!statePropagatesToAncestors(forcedState)) return;\n            for (\n              let node: Element | null = primary.parentElement;\n              node !== null && container.contains(node);\n              node = node.parentElement\n            ) {\n              chain.add(node);\n            }\n          });\n      }\n\n      // The SAME set the selection was written from, so the two markers cannot\n      // disagree about which elements exist.\n      const marks: Element[] = Array.from(touched);\n\n      marks.forEach(element => {\n        // `base` is not a state anything forces: it is what applies when nothing\n        // else does, and the compiler emits no marker for it.\n        const wanted =\n          chain.has(element) && forcedState !== undefined\n            ? previewStateClass(forcedState)\n            : undefined;\n\n        /*\n         * WRITTEN ONLY WHEN IT CHANGES, which is not a micro-optimisation.\n         *\n         * `classList.remove` of a token that is not present still touches the\n         * attribute, and this canvas is observed: the empty-container appender\n         * watches its subtree for layout-relevant mutations and re-measures on\n         * one. An unconditional clear across every marked element therefore made\n         * every selection change schedule a re-measure of the whole overlay,\n         * which its own test caught — it asserts the control does NOT move for a\n         * mutation of its own output, and it moved.\n         */\n        for (const state of STYLE_STATES) {\n          const marker = previewStateClass(state);\n          if (marker !== wanted && element.classList.contains(marker)) {\n            element.classList.remove(marker);\n          }\n        }\n        if (wanted !== undefined && !element.classList.contains(wanted)) {\n          element.classList.add(wanted);\n        }\n      });\n      // The entry's blocks drawn in Entry content: looked at, never used.\n      markEntryContentInert(container);\n    };\n\n    // Before the first pass, so a block's change to an element's inert after\n    // the pass marks it is seen; it writes only `inert` and the inert mark,\n    // neither of which counts as the tree changing.\n    const stopOwnership = observeEntryContentInertOwnership(container);\n    mark();\n    // Subscribed AFTER the first pass, because an observer reports what changes\n    // from the moment it attaches and says nothing about the tree already\n    // there. Writing the markers cannot re-enter this: what counts as the tree\n    // changing excludes every attribute `mark` writes.\n    const stopTree = observeRenderedTree(container, mark);\n    return () => {\n      stopTree();\n      stopOwnership();\n    };\n  }, [\n    box,\n    selectedId,\n    marked,\n    page,\n    forcedState,\n    sourceId,\n    parentId,\n    refusedId,\n    lockedIds,\n    conditionMarks,\n    entryContentMarks,\n    deviceHiddenMarks,\n  ]);\n}\n","\"use client\";\n\n/**\n * The editing canvas — the authored page, drawn by the same renderer that draws\n * the published one.\n *\n * It delegates every pixel to `PageRenderer` and adds only the things editing\n * needs on top: which node is selected, which is under the pointer, and the\n * outlines that say so. Nothing here knows how a heading or a gallery draws\n * itself, and that is the property worth protecting — a canvas with its own\n * rendering path is a second implementation of \"what does this page look like\",\n * and the two drift in the direction nobody tests, so the preview stops matching\n * the page while both look correct in isolation.\n *\n * That mattered concretely: the editor this replaces DID have its own compiler\n * and its own block set, and the two disagreed about the token namespace, about\n * where a page's nodes live, and about what a binding is. A faithful preview was\n * unreachable from there by construction, not by neglect.\n *\n * **`siteStyles` is a required prop, deliberately.** `PageRenderer` takes it as\n * optional because a standalone consumer may legitimately emit no site sheet,\n * but for the canvas an omitted sheet is never correct: the design tokens, the\n * block-type defaults and the named classes all live in it, so a canvas without\n * it shows a page whose grid, clipping and colours are missing exactly where the\n * published page has them. Making it optional here would let a faithful-looking\n * preview be wrong in a way no assertion catches, so the type demands it and the\n * host has to supply what the route supplies.\n *\n * ## Where the parts live\n *\n * This module is the canvas itself, and it re-exports every name it\n * exported before its areas moved beside it:\n *\n * - `canvas-props.ts`: {@link CanvasProps}.\n * - `canvas-addressing.ts`: which block an element stands for, and back.\n * - `canvas-block-marks.ts`: the marks blocks carry, and each block's mark.\n * - `canvas-entry-content-inert.ts`: the entry's blocks made inert.\n * - `use-canvas-markers.ts`: the walk that writes the marks.\n * - `canvas-site-surface.ts`: the site's surface on the canvas root.\n * - `canvas-pointer.ts`: clicks, context gestures, hover and the frame's\n *   ground.\n * - `canvas-drop-refusal.tsx`: why a dragged block can't land.\n * - `canvas-layout-parts.tsx`: the Layout's regions around the page.\n * - `canvas-drawn-page.tsx`: the page as the canvas draws it.\n * - `canvas-device-hidden.ts`: the blocks hidden on the device shown, drawn\n *   striped.\n *\n * @module canvas\n */\n\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport {\n  type DragEvent,\n  type JSX,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n} from \"react\";\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { conditionMarksOf, entryContentMarksOf } from \"./canvas-block-marks\";\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport {\n  drawnBreakpoints,\n  useDeviceHiddenDrawing,\n} from \"./canvas-device-hidden\";\nimport { useCanvasEnvironment, useDrawnPage } from \"./canvas-drawn-page\";\nimport { drawnRefusal } from \"./canvas-drop-refusal\";\nimport { useEditedRegionDrawing } from \"./canvas-edited-region\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { RegionsAround } from \"./canvas-layout-parts\";\nimport { guardCanvasNavigation } from \"./canvas-link-guard\";\nimport {\n  markedIds,\n  useCanvasHover,\n  useCanvasPointer,\n  useFrameGroundClick,\n} from \"./canvas-pointer\";\nimport type { CanvasProps } from \"./canvas-props\";\nimport { siteSurface, useSiteSurfaceMarks } from \"./canvas-site-surface\";\nimport { isElement } from \"./dom-kind\";\nimport {\n  useAppliedDrawing,\n  useEntryContentDrawing,\n} from \"./entry-content-canvas\";\nimport { usePreviewedCollection } from \"./previewed-entry\";\nimport { useCanvasMarkers } from \"./use-canvas-markers\";\n\n/**\n * The class marking the canvas root, and the boundary the hit-test stops at.\n *\n * Declared in `shell-state.ts` beside the other markers `builder-chrome.css`\n * spells out literally, and re-exported here because this is where a reader\n * looks for the canvas's own marker. See {@link nodeIdFromEvent} for the walk\n * that needs it as an upper bound.\n */\nexport { CANVAS_ROOT_CLASS };\n\n// Defined in its own module so the region frames drawn inside the canvas can\n// mark themselves as chrome without importing the canvas back.\nexport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\n\nexport {\n  isOutermostForAddress,\n  nodeAddressOf,\n  nodeElement,\n  nodeIdFromEvent,\n  outermostElementsOf,\n} from \"./canvas-addressing\";\nexport {\n  CONDITIONED_ATTRIBUTE,\n  CONDITIONED_OWN_ATTRIBUTE,\n  DRAG_SOURCE_ATTRIBUTE,\n  DROP_PARENT_ATTRIBUTE,\n  DROP_REFUSED_ATTRIBUTE,\n  ENTRY_CONTENT_ATTRIBUTE,\n  LOCKED_ATTRIBUTE,\n  lockMarksOf,\n  SELECTED_ATTRIBUTE,\n} from \"./canvas-block-marks\";\n// Kept so the module's exported names stay the same, though nothing imports it.\n// fallow-ignore-next-line unused-type\nexport type { LockMark } from \"./canvas-block-marks\";\nexport { revealedDefinitions } from \"./canvas-drawn-page\";\nexport { DropRefusal } from \"./canvas-drop-refusal\";\nexport {\n  ENTRY_CONTENT_INERT_ATTRIBUTE,\n  markEntryContentInert,\n  observeEntryContentInertOwnership,\n} from \"./canvas-entry-content-inert\";\nexport { contextMenuTargetOf } from \"./canvas-pointer\";\nexport type { CanvasProps } from \"./canvas-props\";\n\n/**\n * Refuse the browser's own drag of a picture or a link on the page, which\n * would take the pointer from the canvas's block drag; text being edited\n * keeps it, where dragging selected words moves them.\n */\nfunction refuseNativeDrag(event: DragEvent<HTMLElement>): void {\n  const target = event.target;\n  if (!isElement(target)) return;\n  const editing = '[contenteditable=\"true\"], [contenteditable=\"\"]';\n  if (target.closest(editing) !== null) return;\n  if (target.closest(\"img, a, picture, svg\") !== null) event.preventDefault();\n}\n\n/**\n * The canvas root's style, with the scale the page is painted at published as\n * `--nx-canvas-zoom`.\n *\n * Chrome drawn inside the page (a Layout region's badge and tag) is scaled\n * with everything else when the frame is painted smaller or larger, which\n * makes its words unreadable on a zoomed-out canvas. Reading the factor back\n * lets that chrome undo it and stay at the admin's own size, without each\n * piece measuring the canvas.\n */\nfunction withCanvasScale(\n  style: React.CSSProperties | undefined,\n  scale: number\n): React.CSSProperties {\n  return { ...style, \"--nx-canvas-zoom\": scale } as React.CSSProperties;\n}\n\n/**\n * The canvas root, published to both of its readers, and guarded.\n *\n * ONE assignment site for both publications.\n *\n * They are two APIs because they answer two questions — `rootRef` is read in\n * a pointer handler and asks \"where is the canvas now\"; `onRoot` is a value\n * so a reader can REACT to the canvas arriving, which a ref cannot express\n * because assigning `.current` changes no dependency. Neither can serve the\n * other's caller.\n *\n * But two effects deciding what the element is could drift: an edit to one is\n * invisible to the other, and the two would then hand out different answers\n * with nothing to report it. One effect, one element, published twice.\n *\n * After paint rather than through a merged ref callback: the element is the\n * same for the life of the mount, and one assignment here is easier to follow\n * than a callback keeping two refs agreeing.\n */\nfunction usePublishedRoot(\n  root: React.RefObject<HTMLDivElement | null>,\n  rootRef: CanvasProps[\"rootRef\"],\n  onRoot: CanvasProps[\"onRoot\"]\n): void {\n  useEffect(() => {\n    const element = root.current;\n    if (rootRef !== undefined) rootRef.current = element;\n    onRoot?.(element);\n    return () => {\n      if (rootRef !== undefined) rootRef.current = null;\n      onRoot?.(null);\n    };\n  }, [root, rootRef, onRoot]);\n\n  // A link or form the page draws selects its block here and never takes the\n  // editor anywhere: see `canvas-link-guard`. Same element, same lifetime as\n  // the effect above, so it is installed once per mount.\n  useEffect(() => {\n    const element = root.current;\n    return element === null\n      ? undefined\n      : guardCanvasNavigation(element, `[${CHROME_ATTRIBUTE}]`);\n  }, [root]);\n}\n\n/**\n * What is marked as selected, and the pointer handlers that select.\n *\n * The primary alone is marked when a host has not adopted the set yet, which\n * keeps every existing caller correct without a change. A drag's own pointer\n * down runs first, so its behaviour is exactly what it was.\n */\nfunction useSelectionPointer({\n  selectedIds,\n  selectedId,\n  onSelect,\n  onDoubleClick,\n  onListSortField,\n  dragPointerDown,\n}: {\n  selectedIds: CanvasProps[\"selectedIds\"];\n  selectedId: string | null;\n  onSelect: CanvasProps[\"onSelect\"];\n  onDoubleClick: CanvasProps[\"onDoubleClick\"];\n  onListSortField: CanvasProps[\"onListSortField\"];\n  dragPointerDown:\n    | ((event: React.PointerEvent<HTMLDivElement>) => void)\n    | undefined;\n}) {\n  const marked = useMemo(\n    () => markedIds(selectedIds, selectedId),\n    [selectedIds, selectedId]\n  );\n  const pointer = useCanvasPointer(\n    onSelect,\n    onDoubleClick,\n    marked,\n    onListSortField\n  );\n  const canvasPointerDown = pointer.onPointerDown;\n  const pointerDown = useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      dragPointerDown?.(event);\n      canvasPointerDown(event);\n    },\n    [canvasPointerDown, dragPointerDown]\n  );\n  return { marked, pointer, pointerDown };\n}\n\n/**\n * The canvas.\n *\n * Selection is addressed by node ID and never by position. The engine's document\n * makes ids the only addressing anything stores, and a positional selection\n * breaks the moment a sibling is inserted above it — silently, by pointing at a\n * different block rather than at nothing.\n */\nexport function Canvas({\n  document,\n  rootRef,\n  onRoot,\n  forcedState,\n  siteStyles,\n  selectedId = null,\n  selectedIds,\n  onSelect,\n  render,\n  className,\n  dragHandlers,\n  drag,\n  onDoubleClick,\n  onListSortField,\n  overlay,\n  regions,\n  conditionsUnchecked,\n  conditionsApplied,\n  composed,\n  // The selected region, the ways to select and edit one, and the one edited\n  // in place, for the regions alone; and the placeholder for the page.\n  ...regionUse\n}: CanvasProps): JSX.Element {\n  const root = useRef<HTMLDivElement | null>(null);\n  usePublishedRoot(root, rootRef, onRoot);\n  useFrameGroundClick(root, onSelect);\n  const hover = useCanvasHover(\n    dragHandlers?.onPointerMove,\n    drag?.draggingBlockName != null\n  );\n\n  const { marked, pointer, pointerDown } = useSelectionPointer({\n    selectedIds,\n    selectedId,\n    onSelect,\n    onDoubleClick,\n    onListSortField,\n    dragPointerDown: dragHandlers?.onPointerDown,\n  });\n\n  const surface = siteSurface(render, siteStyles);\n  useSiteSurfaceMarks(root, surface?.opaqueGround === true);\n  // The scale the page is painted at, for chrome drawn inside it to undo.\n  const canvasScale = useCanvasFrame().scale;\n\n  const environment = useCanvasEnvironment(root);\n  // The page as the conditions leave it while they are applied for the\n  // previewed entry (a hidden block as its marker), else the page itself.\n  const shownDocument = conditionsApplied?.document ?? document;\n  // A template draws its previewed entry's own blocks in its Entry content\n  // block; only the drawn page carries them, never the document edited.\n  // Composed once: by the host where it hands the page as drawn\n  // (`composed`), else here.\n  const entryDrawing = useEntryContentDrawing(document, render, composed);\n  // The page as composed, before any conditions are applied: what its\n  // conditioned blocks, the entry's among them, are badged on.\n  const composedPage = entryDrawing.document;\n  // Conditions applied, the page as they leave it, the entry composed into\n  // it here unless the host handed the page as composed.\n  const appliedDrawing = useAppliedDrawing(\n    conditionsApplied?.document,\n    composed,\n    render\n  );\n  // The blocks the page hides on the device shown, drawn anyway and striped;\n  // none while the page is shown as a visitor gets it.\n  const deviceHidden = useDeviceHiddenDrawing(\n    appliedDrawing ?? composedPage,\n    drawnBreakpoints(render, siteStyles),\n    conditionsApplied === undefined\n  );\n  const { drawn, page } = useDrawnPage({\n    regions,\n    rendered: entryDrawing.render,\n    sheet: siteStyles,\n    document: deviceHidden.document,\n    environment,\n    applied: conditionsApplied,\n    addressed: regionUse.editingRegion === undefined,\n    placeholder: regionUse.placeholder,\n  });\n\n  /*\n   * The locked nodes, collected in ONE traversal per document rather than asked\n   * per element inside the marker walk, which re-runs on every change to the\n   * rendered tree: `own` for a block locked itself, `inherited` for one inside\n   * a locked block, which the lock covers too.\n   */\n  const conditionMarks = useMemo(\n    () =>\n      conditionMarksOf(\n        composedPage,\n        conditionsUnchecked,\n        {\n          ...(render?.definitions === undefined\n            ? {}\n            : { definitions: render.definitions }),\n          ...(render?.limits === undefined ? {} : { limits: render.limits }),\n        },\n        conditionsApplied\n      ),\n    [\n      composedPage,\n      conditionsUnchecked,\n      render?.definitions,\n      render?.limits,\n      conditionsApplied,\n    ]\n  );\n\n  // Each Entry content block's words, named by the template's collection:\n  // of the blocks drawn, so one the conditions hide, drawn as its marker,\n  // says only that it is hidden, as a hidden block's badge does.\n  const previewedCollection = usePreviewedCollection();\n  const entryContentMarks = useMemo(\n    () =>\n      entryContentMarksOf(\n        shownDocument,\n        previewedCollection,\n        render?.limits?.maxNodes\n      ),\n    [shownDocument, previewedCollection, render?.limits]\n  );\n\n  // The region edited in place, drawn as the page is, and the marks of the\n  // document the canvas edits: the region's then, else the page's.\n  const edited = useEditedRegionDrawing(\n    regionUse.editingRegion,\n    render,\n    siteStyles,\n    {\n      document,\n      conditions: conditionMarks,\n      entryContent: entryContentMarks,\n      deviceHidden: deviceHidden.marks,\n    }\n  );\n\n  useCanvasMarkers(\n    root,\n    marked,\n    selectedId,\n    page,\n    forcedState,\n    drag,\n    edited.marks.locks,\n    edited.marks.conditions,\n    edited.marks.entryContent,\n    edited.marks.deviceHidden\n  );\n\n  // The refusal the cursor shows, asked of the same rule the notice draws by.\n  const refusalDrawn = drawnRefusal(drag);\n\n  return (\n    <div\n      ref={root}\n      className={cn(CANVAS_ROOT_CLASS, className)}\n      // On the canvas ROOT rather than an inner wrapper, because the overlays\n      // are positioned in this element's own content coordinates: a box inside\n      // it would size the page while leaving the drop indicator and the\n      // selection chrome measuring the region instead.\n      style={withCanvasScale(surface?.style, canvasScale)}\n      // The id the canvas believes is current, for a caller that wants the\n      // answer without walking the tree. Named apart from the per-element\n      // marker deliberately: one carries an id and the other is a boolean, and\n      // a single name meaning both is the kind of thing that reads correctly\n      // right up until someone writes a selector against the wrong one.\n      data-nx-selected-id={selectedId ?? undefined}\n      /*\n       * Whether the site's dark values include a dark ground. They apply with\n       * the device, or under a dark marker, exactly as the site sheet applies\n       * them, and the stylesheet pairs this with both to switch the SCHEME:\n       * Canvas, CanvasText and native controls. Absent when the dark values\n       * keep a light ground, or the host serves no site sheet.\n       */\n      data-nx-site-dark-ground={surface?.darkGround === true ? \"\" : undefined}\n      /*\n       * `data-nx-site-theme`, the mode the nearest theme marker above names,\n       * is written onto this element by `useNearestThemeMarker` before paint,\n       * not rendered here: see that hook.\n       */\n      /*\n       * `data-nx-site-ground-opaque`, whether the site's ground is fully\n       * opaque, is written onto this element by `useSiteSurfaceMarks` from the\n       * colour it resolves to, not rendered here: see that hook.\n       */\n      /*\n       * What the pointer means, for the cursor.\n       *\n       * On the ROOT rather than per block, because a cursor during a drag is a\n       * property of the gesture and not of whatever happens to be under the\n       * pointer — and pointer capture means the events keep arriving here\n       * however far the hand travels.\n       *\n       * Absent when nothing is dragging, so the hover cursor on a block is not\n       * competing with a state that does not exist.\n       */\n      data-nx-dragging={\n        drag?.draggingBlockName == null\n          ? undefined\n          : refusalDrawn === null\n            ? \"\"\n            : \"refused\"\n      }\n      onClick={pointer.onClick}\n      onDoubleClick={pointer.onDoubleClick}\n      onContextMenu={pointer.onContextMenu}\n      // Spread whole, because the set cannot be partially applied — then the\n      // one member this component also has something to say about is composed\n      // over the top, drag first so its behaviour is exactly what it was.\n      {...dragHandlers}\n      onPointerDown={pointerDown}\n      // A picture or a link pressed and moved would start the browser's own\n      // drag of it, which cancels the pointer the canvas's block drag follows,\n      // so a picture in a gallery could not be dragged to a new place.\n      onDragStart={refuseNativeDrag}\n      onPointerMove={hover.onPointerMove}\n      onPointerLeave={hover.onPointerLeave}\n    >\n      <RegionsAround\n        drawn={drawn}\n        rendered={render}\n        environment={environment}\n        selection={regionUse}\n        editing={edited.drawn}\n        bands={regionUse.emptyRegions}\n      >\n        {page}\n      </RegionsAround>\n      {overlay}\n    </div>\n  );\n}\n","/**\n * A question added to an Accordion takes the next number: \"Question 4\" after\n * three. One rule, asked by every way the editor adds a block (the Add panel's\n * click and drag, and the canvas's \"+ Add a question\"), so a question never\n * arrives titled with another's number or with the block's bare default.\n *\n * The next number is one past the highest of the accordion's question count\n * and any number its titles already carry, so a question deleted from the\n * middle, or one an author numbered by hand, is never repeated.\n *\n * @module accordion-questions\n */\nimport {\n  findNode,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { OpPosition } from \"../op-vocabulary\";\n\n/** A Question's registered name. */\nexport const QUESTION_BLOCK = \"core/accordion-item\";\n\n/**\n * The attribute the canvas marks the accordion \"+ Add a question\" is drawn\n * for with, on the canvas's element only: the frame's sheet gives it a row\n * of room after its last question, where the button sits.\n */\nexport const QUESTION_ROOM_ATTRIBUTE = \"data-nx-question-room\";\n\n/**\n * The room's height on that accordion, in the page's pixels: the button's\n * height at the canvas's zoom, written by the canvas beside the attribute.\n */\nexport const QUESTION_ROOM_PROPERTY = \"--nx-canvas-question-room\";\n\n/** The Accordion's registered name. */\nconst ACCORDION_BLOCK = \"core/accordion\";\n\n/** The slot an Accordion holds its questions in. */\nconst QUESTIONS_SLOT = \"children\";\n\n/** A title the editor numbered: \"Question\" and a whole number. */\nconst NUMBERED = /^\\s*Question\\s+(\\d{1,9})\\s*$/;\n\n/** The title the next question added to this accordion takes. */\nexport function nextQuestionTitle(accordion: BlockNode): string {\n  const questions = accordion.slots?.[QUESTIONS_SLOT] ?? [];\n  let highest = questions.length;\n  for (const question of questions) {\n    const title = question?.props?.title;\n    const match = typeof title === \"string\" ? NUMBERED.exec(title) : null;\n    if (match?.[1] !== undefined) highest = Math.max(highest, Number(match[1]));\n  }\n  return `Question ${String(highest + 1)}`;\n}\n\n/**\n * A newly made block, numbered for where it lands: a Question going into an\n * Accordion's questions takes the next number there. Any other block, or a\n * Question landing anywhere else, is returned as it was.\n */\nexport function numberedForPlace(\n  node: BlockNode,\n  at: OpPosition,\n  document: BlockDocument\n): BlockNode {\n  if (node.type !== QUESTION_BLOCK || at.parentId === undefined) return node;\n  if (at.slot !== QUESTIONS_SLOT) return node;\n  const accordion = findNode(document.nodes, at.parentId);\n  if (accordion?.type !== ACCORDION_BLOCK) return node;\n  return {\n    ...node,\n    props: { ...node.props, title: nextQuestionTitle(accordion) },\n  };\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 * Playing one block's \"Animation when it appears\" once on the canvas.\n *\n * The canvas shows every block in its final state: the frame's sheet closes\n * both of the page's gates on every page root, so no block waits hidden for a\n * scroll or a load while it is being edited. Playing one block opens the gates\n * on that block alone, for as long as one run of its animation lasts, and\n * closes them again once it ends.\n *\n * ## Nothing here knows what the animation is\n *\n * The block plays the keyframes the page's own sheet compiled for it, with its\n * own duration, delay and effect, so the canvas shows exactly what the\n * published page plays. Reduced motion wins here as it does there: the\n * keyframes exist only where the window asks for motion, so a block played\n * there finds no animation to run. The play is not even started then, as\n * `reveal-node` jumps rather than scrolls.\n *\n * ## By time, whatever its start\n *\n * \"When scrolled into view\" follows the block's view timeline on the page,\n * which on the canvas would leave a block already in view at its end, never\n * moving. Played here, the block runs on the document's timeline instead, as\n * \"When the page loads\" does, so a press shows the motion whichever start is\n * chosen.\n *\n * ## Only that block\n *\n * A gate is inherited, so opening it on a block would open it for every block\n * inside, and a section played would play all of its children too. The\n * block's descendants keep the gates closed.\n *\n * @module appear-replay\n */\nimport { APPEAR_LOAD_GATE, APPEAR_SCROLL_GATE } from \"@nextlyhq/blocks-engine\";\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { nodeElement } from \"./canvas-addressing\";\nimport { prefersReducedMotion } from \"./reduced-motion\";\n\n/**\n * The attribute on a block whose animation is playing, for as long as it\n * plays.\n *\n * @internal\n */\nexport const APPEAR_PLAYING_ATTRIBUTE = \"data-nx-appear-playing\";\n\nconst PLAYING = `.${CANVAS_ROOT_CLASS} .nx-pb-page [${APPEAR_PLAYING_ATTRIBUTE}]`;\n\n/**\n * The frame sheet's rules for a block playing: its gates open, its timeline\n * the document's, and every block inside it still. `initial` leaves a gate\n * unset, which is what lets the animation run, as on the published page.\n *\n * The timeline is set over the block's own, which its compiled rule sets at\n * whatever weight its selector has, hence the important flag; it holds only\n * while the block plays.\n *\n * @internal\n */\nexport const APPEAR_REPLAY_RULES: string = `${PLAYING} {\n  ${APPEAR_SCROLL_GATE}: initial;\n  ${APPEAR_LOAD_GATE}: initial;\n  animation-timeline: auto !important;\n}\n${PLAYING} :not([${APPEAR_PLAYING_ATTRIBUTE}]) {\n  ${APPEAR_SCROLL_GATE}: none;\n  ${APPEAR_LOAD_GATE}: none;\n}`;\n\n/** Each playing block's current play, so an earlier one ending leaves a later one be. */\nconst plays = new WeakMap<Element, object>();\n\n/** The canvas's root inside `root`, which holds every block it draws. */\nfunction canvasScope(root: Document | HTMLElement): HTMLElement {\n  if (!(\"documentElement\" in root)) return root;\n  return (\n    root.querySelector<HTMLElement>(`.${CANVAS_ROOT_CLASS}`) ??\n    root.documentElement\n  );\n}\n\n/** The block's gates closed again, and its play forgotten. */\nfunction stop(element: Element): void {\n  plays.delete(element);\n  element.removeAttribute(APPEAR_PLAYING_ATTRIBUTE);\n}\n\n/**\n * Play the block `id`'s animation once, from its start, on the canvas inside\n * `root`. A play already running on it starts again.\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 * @returns whether an animation started; `false` for a block not drawn, one\n *   with no animation, and wherever the window asks for reduced motion\n */\nexport function playAppear(root: Document | HTMLElement, id: string): boolean {\n  const element = nodeElement(canvasScope(root), id);\n  if (element === null) return false;\n  stop(element);\n  if (\n    prefersReducedMotion(element) ||\n    typeof element.getAnimations !== \"function\"\n  ) {\n    return false;\n  }\n  // Asking for the animations brings the block's style up to date first, so\n  // a run an earlier play left going ends here and the next one starts over.\n  const before = new Set(element.getAnimations());\n  element.setAttribute(APPEAR_PLAYING_ATTRIBUTE, \"\");\n  const started = element\n    .getAnimations()\n    .filter(animation => !before.has(animation));\n  if (started.length === 0) {\n    stop(element);\n    return false;\n  }\n  const play = {};\n  plays.set(element, play);\n  // Settled, not only finished: a run cut short (the block redrawn, its\n  // effect changed) closes the gates too.\n  void Promise.allSettled(started.map(animation => animation.finished)).then(\n    () => {\n      if (plays.get(element) === play) stop(element);\n    }\n  );\n  return true;\n}\n","/**\n * The stylesheet the canvas frame carries inside it.\n *\n * The editor's own sheet, `builder-chrome.css`, is imported by the host app\n * and applies to the editor's document only: nothing in it reaches a page\n * rendered inside the frame. So the few rules the page needs from the editor\n * travel with the frame instead, as a string `CanvasFrame` renders into the\n * frame's document beside the page.\n *\n * Deliberately few. Everything the editor DRAWS over the page — outlines, the\n * toolbar, the drop line, the spacing bands, notices — is drawn in the editor's\n * document over the frame, where the site's CSS cannot reach it. What is left\n * here is what has to be IN the page because it changes layout or input: the\n * base reset, the canvas surface, a placeholder giving an empty container an\n * area, text selection and the caret while editing, the cursor, and the dimmed\n * block in a drag.\n *\n * No admin tokens: they are custom properties of the editor's document and\n * resolve to nothing in here. Colours come from the site's own tokens where\n * the canvas names them, the browser's system colours where it does not, and\n * the page's own text colour for the placeholder, so it reads on any section.\n *\n * @module canvas-frame-sheet\n */\n\nimport {\n  APPEAR_LOAD_GATE,\n  APPEAR_SCROLL_GATE,\n  DEFAULT_TOKEN_PREFIX,\n  blockTypeClassName,\n  tokenCustomProperty,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  ENTRY_CONTENT_DRAWN_ATTRIBUTE,\n  ENTRY_CONTENT_NOTE_ATTRIBUTE,\n} from \"@nextlyhq/blocks-react\";\n\nimport { GALLERY_BLOCK } from \"../inspector/content/gallery-pictures\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport {\n  QUESTION_ROOM_ATTRIBUTE,\n  QUESTION_ROOM_PROPERTY,\n} from \"./accordion-questions\";\nimport { APPEAR_REPLAY_RULES } from \"./appear-replay\";\nimport { DEVICE_HIDDEN_ATTRIBUTE } from \"./canvas-device-hidden\";\nimport {\n  EMPTY_CONTAINER_SELECTOR,\n  EMPTY_DISCLOSURE_SELECTOR,\n  EMPTY_TEXT_SELECTOR,\n} from \"./empty-slot\";\nimport { PAGE_PLACEHOLDER_ATTRIBUTE } from \"./page-placeholder\";\n\nconst ROOT = `.${CANVAS_ROOT_CLASS}`;\n\n/** A site token as the page's sheet names it, with what stands in without it. */\nfunction siteToken(name: string, fallback: string): string {\n  return `var(${tokenCustomProperty(name, DEFAULT_TOKEN_PREFIX)}, ${fallback})`;\n}\n\n/** The class every Gallery's root wears, its block type's. */\nconst EMPTY_GALLERY_CLASS = blockTypeClassName(GALLERY_BLOCK);\n\n/**\n * The attribute a Collection list puts on each sample item it draws for an\n * author, spelled as the block spells it; the sheet's test draws the block\n * to find it, so the two cannot drift apart unseen.\n */\nconst LIST_SAMPLE_ATTRIBUTE = \"data-nx-list-sample\";\n\n/** A collection list drawing its empty state while that state holds nothing. */\nconst EMPTY_LIST = `${EMPTY_CONTAINER_SELECTOR}[data-nx-list-shows]`;\n\n/**\n * The attribute on the root element of the editor's blank page, which a page\n * the site serves never carries.\n *\n * @internal\n */\nexport const BLANK_PAGE_ATTRIBUTE = \"data-nx-canvas-frame\";\n\n/**\n * Scopes a rule to the editor's blank page.\n *\n * The blank page has no site around the canvas, so some rules here stand in\n * for one: a base reset, a light ground, the site's ink and body font drawn on\n * the canvas root. On a page the site serves, its own layout and stylesheets\n * already decide each of those, exactly as they do for the published page, and\n * a stand-in would override them.\n */\n// In \\`:where()\\`, so scoping a rule adds nothing to its specificity: on the\n// blank page each wins or loses exactly as it did before it was scoped.\nconst BLANK = `:where(:root[${BLANK_PAGE_ATTRIBUTE}])`;\n\n/**\n * Marks the site's own elements around the point the canvas is mounted at,\n * on a page the site serves: its header, footer and whatever else its layout\n * draws, inert and quietened.\n *\n * @internal\n */\nexport const SITE_CHROME_ATTRIBUTE = \"data-nx-site-chrome\";\n\n/**\n * Boxes size as border-box: the default most site resets set (Tailwind's\n * preflight, modern-normalize), so a padded block at full width is as wide\n * on the canvas as on most published pages.\n *\n * It stands in, on the blank page only, for the site's own stylesheets, which\n * decide on a page the site serves. So it sits in a cascade layer of its own, declared before\n * anything else in the frame: the lowest layer, which any site rule loaded\n * later wins over, whether that rule is in a layer of the site's or in none.\n * The rest of this sheet is not layered, and states what the editor needs\n * whatever the site does.\n *\n * @internal\n */\nexport const CANVAS_FRAME_DEFAULTS =\n  \"@layer nx-canvas-defaults { *, ::before, ::after { box-sizing: border-box; } }\";\n\n/**\n * The rules, in the order they cascade.\n *\n * @internal\n */\nexport const CANVAS_FRAME_SHEET: string = `\n/* A plain base, on the blank page: the user agent's body margin never shows,\n   so a bare page in the frame lines up with the same page published. A page\n   the site serves keeps the site's own base. */\n${BLANK}, ${BLANK} body { margin: 0; padding: 0; }\n\n/* The blank page is light unless the site says otherwise: the frame's document\n   is its own, so the admin's dark scheme is never inherited, and the ground\n   under the page is the browser's default canvas. */\n${BLANK} { color-scheme: light; background-color: Canvas; }\n\n/* The blank page fills the frame's viewport, so the end of a short page still\n   has pixels to drop a block on. Grown as a flex item of the body rather than\n   given a minimum height of its own: with a minimum height on the canvas root,\n   Chromium's End and Home keys stop moving the caret in text being edited\n   below the first block. On a page the site serves, the site's layout decides\n   how tall the canvas is, as it does for the published page. */\n${BLANK} body { min-height: 100vh; display: flex; flex-direction: column; }\n\n${ROOT} {\n  position: relative;\n  box-sizing: border-box;\n  /* A press on a block is a grab, not a text selection: the browser would\n     otherwise start selecting words before the drag reaches its activation\n     distance. */\n  user-select: none;\n  -webkit-user-select: none;\n}\n\n/* The page's own surface on the blank page, in the SITE's colours and type.\n   Nothing of the admin's theme is inherited in the frame; what the canvas does\n   not name falls back to the browser's defaults, which is what a published\n   page shows where nothing paints. On a page the site serves, the canvas\n   paints none of these and inherits the site's, as the published page does. */\n${BLANK} ${ROOT} {\n  /* Fills the viewport: see the body above. */\n  flex: 1 0 auto;\n  /* The site's background and text, which the canvas root names under the\n     site's token prefix (see \\`canvas.tsx\\`); they follow the site's dark\n     values by themselves. The face is a plain base, not a site variable: the\n     site's Body font is the page sheet's rule on the page root, the same rule\n     a published page and a page the site serves carry. */\n  color-scheme: light;\n  background-color: var(--nx-canvas-site-ground, Canvas);\n  color: var(--nx-canvas-site-ink, CanvasText);\n  font-family: system-ui, sans-serif;\n}\n\n/* The site's own dark mode, the one thing that darkens the blank page. The\n   canvas root carries the dark-ground marker only when the site's dark values\n   include a dark ground, and states the nearest theme marker above it as\n   data-nx-site-theme; with none stated, the device decides, as it does for\n   the token values. The admin's theme reaches nothing in this document. */\n${BLANK} ${ROOT}[data-nx-site-dark-ground][data-nx-site-theme=\"dark\"] {\n  color-scheme: dark;\n}\n@media (prefers-color-scheme: dark) {\n  ${BLANK} ${ROOT}[data-nx-site-dark-ground]:not([data-nx-site-theme]) {\n    color-scheme: dark;\n  }\n}\n\n/* On the blank page, the page is one stacking context, so a blend mode inside\n   it starts from the page's own background, and it repeats the site's ground\n   where that ground is opaque, so a blended block mixes with it as on the\n   published page. The ground at no weight, so a background the page gives its\n   own root wins. On a page the site serves, a blend mixes with the site's own\n   ground, as it does published. The page is the root's child, or its page\n   part's where the canvas draws regions around it. */\n${BLANK} ${ROOT} > .nx-pb-page {\n  isolation: isolate;\n}\n:where(${BLANK} ${ROOT}[data-nx-site-ground-opaque] > .nx-pb-page) {\n  background-color: var(--nx-canvas-site-ground, Canvas);\n}\n${BLANK} ${ROOT} > .nx-canvas-page-part > .nx-pb-page {\n  isolation: isolate;\n}\n:where(${BLANK} ${ROOT}[data-nx-site-ground-opaque] > .nx-canvas-page-part > .nx-pb-page) {\n  background-color: var(--nx-canvas-site-ground, Canvas);\n}\n\n/* Every block in its final state: an animation set to play when it appears\n   never plays here by itself, whichever start it has, so nothing on the\n   canvas waits hidden for a scroll or a load while it is being edited. Both\n   of the page's gates closed, on every page root in the frame. */\n${ROOT} .nx-pb-page {\n  ${APPEAR_SCROLL_GATE}: none;\n  ${APPEAR_LOAD_GATE}: none;\n}\n\n/* Except the one block played, once, when its animation changes or Play is\n   pressed: see \\`appear-replay.ts\\`. */\n${APPEAR_REPLAY_RULES}\n\n/* The site's own layout around the canvas, on a page the site serves: there\n   to show where the page sits, quietened as a Layout region's content is, and\n   inert, so its links and forms neither work nor navigate the frame. */\n[${SITE_CHROME_ATTRIBUTE}] {\n  opacity: var(--nx-builder-region-opacity, 0.6);\n}\n\n/* Text being edited is text again. */\n${ROOT} [contenteditable=\"true\"],\n${ROOT} [contenteditable=\"true\"] * {\n  user-select: text;\n  -webkit-user-select: text;\n}\n\n/* A block that draws nothing still has height enough to be selected: at no\n   specificity, so a min height the block sets (a Section at Full screen)\n   wins over it while it is selected, as it does on the page. */\n:where(${ROOT} [data-nx-selected]:empty) { min-height: 2px; }\n\n/* A text block emptied of its words keeps a line, so it can still be clicked:\n   see EMPTY_TEXT_SELECTOR. */\n${EMPTY_TEXT_SELECTOR} { min-height: 1lh; }\n\n/* An empty container always has an area to aim at, since without one it has\n   no height and cannot be clicked. Its height is held apart, at no\n   specificity, so a min height the block sets (a Section at Full screen) wins\n   over it, as it does on the page.\n   It is marked by a dashed OUTLINE drawn just inside its edges, square and\n   unfilled: an outline takes no room and paints over no property the author\n   styles, so the block's own background, border and corners show exactly as\n   they are set, edge to edge. In the page's own text colour, so it reads on\n   a light page and a dark section alike. */\n:where(${EMPTY_CONTAINER_SELECTOR}) { min-height: 2.75rem; }\n/* An empty Gallery is the room its \"Add images\" plate is drawn in, its two\n   buttons and its drop hint with it (\\`image-states.tsx\\`): a third of its\n   width tall, as a row of pictures would be, so the plate keeps its words\n   on a zoomed-out canvas, and never less than a small picture. At no\n   specificity, as the height above. */\n:where(${EMPTY_CONTAINER_SELECTOR}.${EMPTY_GALLERY_CLASS}) {\n  min-height: 12rem;\n  aspect-ratio: 3 / 1;\n}\n${EMPTY_CONTAINER_SELECTOR} {\n  display: block;\n  outline: 1px dashed color-mix(in srgb, currentColor 45%, transparent);\n  outline-offset: -1px;\n}\n/* An open Question emptied of its answer has the same start under its\n   title: the box an empty container draws, after the summary, where the\n   answer's blocks go. Drawn by the editor only (see\n   EMPTY_DISCLOSURE_SELECTOR); the published page draws nothing there. */\n/* The selected Accordion's row of room after its last question, where\n   \"+ Add a question\" sits (accordion-add-question.tsx): inside its own box,\n   so its margins and the blocks around it stay as set. The button's height\n   at the canvas's zoom. Marked by the canvas only; a published page never has it. */\n${ROOT} [${QUESTION_ROOM_ATTRIBUTE}]::after {\n  content: \"\";\n  display: block;\n  min-height: var(${QUESTION_ROOM_PROPERTY}, 2.75rem);\n}\n${EMPTY_DISCLOSURE_SELECTOR}::after {\n  content: \"\";\n  display: block;\n  min-height: 2.75rem;\n  margin-block-start: 0.5rem;\n  outline: 1px dashed color-mix(in srgb, currentColor 45%, transparent);\n  outline-offset: -1px;\n}\n\n/* An empty page's body, held open in the editor for its start area: the\n   overlay sets the area's height on the root while the page holds no blocks,\n   in the page's own pixels, and it is added above the Layout's footer, or\n   below the header where there is no footer. Unset, it adds nothing, and a\n   published page never has it. */\n${ROOT} > [data-nx-region=\"footer\"] { margin-block-start: var(--nx-canvas-start-room, 0px); }\n${ROOT}:not(:has(> [data-nx-region=\"footer\"])) { padding-block-end: var(--nx-canvas-start-room, 0px); }\n\n/* Where a page goes, for a document with no page of its own: a grey box\n   between the header and the footer, roomy enough to read as a page's body,\n   in the page's own ink so it reads on a light site and a dark one alike.\n   At the admin's size whatever the zoom. A visitor's page never has it. */\n${ROOT} [${PAGE_PLACEHOLDER_ATTRIBUTE}] {\n  display: grid;\n  place-items: center;\n  min-block-size: 18rem;\n  margin: 1.5rem;\n  border: 1.5px dashed color-mix(in srgb, currentColor 30%, transparent);\n  border-radius: var(--radius-md, 0.5rem);\n  background: color-mix(in srgb, currentColor 6%, transparent);\n  font-family: var(--font-sans, system-ui), sans-serif;\n  font-size: calc(0.875rem / var(--nx-canvas-zoom, 1));\n  line-height: 1.4;\n  cursor: default;\n}\n\n${ROOT} [${PAGE_PLACEHOLDER_ATTRIBUTE}] > span {\n  color: color-mix(in srgb, currentColor 70%, transparent);\n}\n\n/* The cursor says what a press does: grab a block, place a caret in text being\n   edited, and while dragging, whether the block can land. */\n${ROOT} [data-nx-node] { cursor: grab; }\n${ROOT} [data-nx-node][data-nx-locked] { cursor: default; }\n${ROOT} [data-nx-node][data-nx-editing],\n${ROOT} [data-nx-node][contenteditable=\"true\"],\n${ROOT} [data-nx-node][contenteditable=\"plaintext-only\"] { cursor: text; }\n${ROOT}[data-nx-dragging],\n${ROOT}[data-nx-dragging] [data-nx-node] { cursor: grabbing; }\n${ROOT}[data-nx-dragging=\"refused\"],\n${ROOT}[data-nx-dragging=\"refused\"] [data-nx-node] { cursor: no-drop; }\n\n/* What is being held, dimmed where it sits. */\n${ROOT} [data-nx-drag-source] { opacity: 0.4; }\n\n/* Text being edited keeps the platform's long-press callout. */\n${ROOT} [contenteditable] { -webkit-touch-callout: default; }\n${ROOT} [contenteditable=\"false\"] { -webkit-touch-callout: none; }\n\n/* A collection list's note to its author: why its sort fell back (amber) or\n   its read failed (red). Drawn in the page, where the list draws it, in the\n   admin's scheme and face, which the frame hands these notes as values. A\n   visitor's page never carries one. */\n[data-nx-list-diagnostic] {\n  /* The whole row of a list laid out as a grid or a wrapping row, so it\n     reads as a note about the list rather than one of its entries. */\n  grid-column: 1 / -1;\n  flex-basis: 100%;\n  /* Its words, and the one action a fallen-back sort offers, on one row. */\n  display: flex;\n  align-items: flex-start;\n  color-scheme: var(--nx-builder-scheme, light);\n  border: 1px solid;\n  border-radius: var(--radius-sm, 0.25rem);\n  color: var(--nx-builder-text, CanvasText);\n  font-family: var(--font-sans, system-ui), sans-serif;\n  /* The admin's size whatever the zoom, so the author can read it on a\n     page drawn small; its spacing is in its own text's units, so it keeps\n     its shape at every zoom. */\n  font-size: calc(0.8125rem / var(--nx-canvas-zoom, 1));\n  line-height: 1.5;\n  gap: 0.9em;\n  margin-block-end: 0.6em;\n  padding: 0.6em 0.9em;\n}\n\n/* A block its conditions hide while they are applied, drawn as one line in\n   its place: its words kept readable however small the canvas paints the\n   page, never under 11px on screen, and at its own 13px from full size up.\n   In pixels, not rems, so a site whose root font size is not 16px moves\n   neither. Its spacing is in its own text's units, so it keeps its shape at\n   every zoom. Written under the root, so it outweighs the marker's own\n   defaults in the page's sheet. One row, its icon centred before its words,\n   here too: a marker a list's entry draws is made as the page is drawn, so\n   the page's sheet holds no defaults for it, and a site's own sheet may set\n   an icon on a line of its own. */\n${ROOT} .nx-condition-hidden {\n  display: flex;\n  align-items: center;\n  font-size: max(13px, calc(11px / var(--nx-canvas-zoom, 1)));\n  gap: 0.6em;\n  padding: 0.45em 0.75em;\n}\n\n${ROOT} .nx-condition-hidden > svg {\n  display: inline-block;\n  flex: none;\n}\n\n/* The marker's look, in the site's own tokens, for a marker the page's sheet\n   holds no defaults for: one a list's entry draws, made as the page is\n   drawn. At no specificity, so a page marker's compiled defaults, the same\n   tokens, still win; each token stands in for itself in the page's own ink\n   where the site names its tokens otherwise. */\n:where(${ROOT} .nx-condition-hidden) {\n  border: 1px dashed ${siteToken(\"color.border-strong\", \"color-mix(in srgb, currentColor 35%, transparent)\")};\n  border-radius: 2px;\n  background-color: ${siteToken(\"color.surface\", \"color-mix(in srgb, currentColor 6%, transparent)\")};\n  color: ${siteToken(\"color.muted\", \"color-mix(in srgb, currentColor 70%, transparent)\")};\n  line-height: 1.35;\n}\n\n/* A block the page hides on the device shown, drawn anyway so it can be found\n   and edited: edged here, in the page's own Canvas and CanvasText so the edge\n   holds 3:1 against the page's ground in the light or the dark scheme it is\n   drawn in. Its stripes and its tag (\"Hidden on Mobile · still here in the\n   builder\") are the editor's marks over the canvas (canvas-marks.tsx), never\n   a box of the page's own: an overlay inside the block would need the block\n   to hold it, which moves what its fixed or absolutely placed blocks are laid\n   out against. An outline moves nothing. Only the editor's canvas carries the\n   mark; the site sheet never does. */\n${ROOT} [${DEVICE_HIDDEN_ATTRIBUTE}] {\n  --nx-canvas-hidden-edge: color-mix(in srgb, CanvasText 55%, Canvas);\n  outline: 1px dashed var(--nx-canvas-hidden-edge);\n  outline-offset: -1px;\n}\n\n[data-nx-list-diagnostic=\"sort-fallback\"] {\n  border-color: color-mix(in srgb, var(--nx-builder-warning, Mark) 55%, transparent);\n  background: color-mix(\n    in srgb,\n    var(--nx-builder-warning, Mark) 12%,\n    var(--nx-builder-surface-raised, Canvas)\n  );\n}\n\n/* The note's one action: an outlined button in the note's own ink, at the\n   row's end. Pressing it is the editor's (see the canvas's click). */\n[data-nx-list-diagnostic] > [data-nx-list-action] {\n  flex: none;\n  margin-inline-start: auto;\n  padding: 0.15em 0.6em;\n  border: 1px solid currentColor;\n  border-radius: var(--radius-sm, 0.25rem);\n  background: transparent;\n  color: inherit;\n  font: inherit;\n  font-size: 0.92em;\n  font-weight: 500;\n  cursor: pointer;\n}\n\n[data-nx-list-diagnostic] > [data-nx-list-action]:focus-visible {\n  outline: 2px solid var(--nx-builder-select, Highlight);\n  outline-offset: 2px;\n}\n\n/* A named query that ran, but reads what visitors can't: amber, as a sort\n   that fell back is, since the page still draws. */\n[data-nx-list-diagnostic=\"query-caution\"] {\n  border-color: color-mix(in srgb, var(--nx-builder-warning, Mark) 55%, transparent);\n  background: color-mix(\n    in srgb,\n    var(--nx-builder-warning, Mark) 12%,\n    var(--nx-builder-surface-raised, Canvas)\n  );\n}\n\n/* The log reference a failed run names: the exact text to quote, set as\n   code and selectable whole, though the canvas selects blocks on a press. */\n[data-nx-list-diagnostic] [data-nx-list-ref] {\n  font-family: var(--font-mono, ui-monospace), monospace;\n  font-size: 0.95em;\n  user-select: all;\n  -webkit-user-select: all;\n}\n\n/* Copy ref: its one word, and \"Copied\" for a moment once pressed. */\n[data-nx-list-diagnostic] [data-nx-list-copy=\"done\"],\n[data-nx-list-diagnostic] [data-nx-list-copied] > [data-nx-list-copy=\"ready\"] {\n  display: none;\n}\n\n[data-nx-list-diagnostic] [data-nx-list-copied] > [data-nx-list-copy=\"done\"] {\n  display: inline;\n}\n\n[data-nx-list-diagnostic=\"query-failed\"] {\n  border-color: color-mix(in srgb, var(--nx-builder-danger, CanvasText) 55%, transparent);\n  background: color-mix(\n    in srgb,\n    var(--nx-builder-danger, CanvasText) 8%,\n    var(--nx-builder-surface-raised, Canvas)\n  );\n}\n\n/* A list drawing its empty state is tagged, in the editing colour, with why:\n   the author chose to see it, nothing matched, or its read failed. The tag\n   is the first thing in the list's own flow, so it covers nothing: lifted\n   above the list's top edge it lay over whatever the page draws there, and\n   a page with no gap above the list lost that line. It spans a grid's row\n   from its start, sits first in a flex row, and is as wide as its words.\n   On the canvas only. */\n${ROOT} [data-nx-list-shows]::before {\n  display: block;\n  grid-column: 1 / -1;\n  justify-self: start;\n  align-self: start;\n  flex: none;\n  inline-size: max-content;\n  max-inline-size: 100%;\n  margin-block-end: 0.375rem;\n  padding: 0.0625rem 0.375rem;\n  border-radius: 0.1875rem;\n  background: var(--nx-builder-select, Highlight);\n  color: var(--nx-builder-select-text, HighlightText);\n  font-family: system-ui, sans-serif;\n  font-size: 0.6875rem;\n  font-weight: 500;\n  line-height: 1.4;\n  white-space: nowrap;\n  pointer-events: none;\n  zoom: calc(1 / var(--nx-canvas-zoom, 1));\n}\n\n/* A list whose empty state holds nothing yet: a roomy area, at the admin's\n   size whatever the zoom, so the \"+\" drawn over its centre, the line below\n   it and the spacing badges on its edges never meet. The tag sits at the\n   inside of its top edge, clear of the centred words. Written on the empty\n   container's own selector, so it outweighs that rule's smaller box. */\n${EMPTY_LIST} {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  min-height: calc(7.5rem / var(--nx-canvas-zoom, 1));\n}\n\n${EMPTY_LIST}::before {\n  position: absolute;\n  inset-block-start: 0;\n  inset-inline-start: 0;\n  margin: 0;\n  border-radius: 0 0 0.1875rem 0;\n}\n\n/* What the area is for, under the \"+\" and its words, faint in the page's\n   own ink so it reads on any section. */\n${EMPTY_LIST}::after {\n  content: \"Visitors see this when no entry matches. Left empty, the list shows nothing.\";\n  max-inline-size: 100%;\n  margin-block-start: 2.5rem;\n  padding-inline: 0.75rem;\n  color: color-mix(in srgb, currentColor 65%, transparent);\n  font-family: system-ui, sans-serif;\n  font-size: 0.75rem;\n  line-height: 1.4;\n  text-align: center;\n  pointer-events: none;\n  zoom: calc(1 / var(--nx-canvas-zoom, 1));\n}\n\n${ROOT} [data-nx-list-empty-because=\"chosen\"]::before {\n  content: \"When empty\";\n}\n\n/* A sample item a list draws while its collection shows nothing: greyed, so\n   it reads as a stand-in, and tagged \"Sample\" at its corner in the list's\n   own tag colours. Never on a page a visitor is served, which draws none. */\n${ROOT} [${LIST_SAMPLE_ATTRIBUTE}] {\n  position: relative;\n}\n\n${ROOT} [${LIST_SAMPLE_ATTRIBUTE}] > * {\n  opacity: 0.55;\n}\n\n${ROOT} [${LIST_SAMPLE_ATTRIBUTE}]::before {\n  content: \"Sample\";\n  position: absolute;\n  inset-block-start: 0;\n  inset-inline-end: 0;\n  z-index: 1;\n  padding: 0.0625rem 0.375rem;\n  border-radius: 0 0 0 0.1875rem;\n  background: var(--nx-builder-select, Highlight);\n  color: var(--nx-builder-select-text, HighlightText);\n  font-family: system-ui, sans-serif;\n  font-size: 0.6875rem;\n  font-weight: 500;\n  line-height: 1.4;\n  pointer-events: none;\n  zoom: calc(1 / var(--nx-canvas-zoom, 1));\n}\n\n${ROOT} [data-nx-list-empty-because=\"none\"]::before {\n  content: \"No entries match · showing When empty\";\n}\n\n${ROOT} [data-nx-list-empty-because=\"failed\"]::before {\n  content: \"Showing When empty\";\n}\n\n/* An Entry content block drawing the entry's own blocks: they are the\n   entry's, edited on the entry, so the pointer passes through them to the\n   block, which a click selects. Nothing inside is pressed, hovered or\n   followed, and no caret lands in it. */\n${ROOT} [${ENTRY_CONTENT_DRAWN_ATTRIBUTE}] * {\n  pointer-events: none;\n  cursor: inherit;\n}\n\n/* An Entry content block's note to its author, where it has none of the\n   entry's content to draw: the canvas's muted note, drawn as an empty\n   container is, in the page's own ink so it reads on any section, its words\n   faint and the entry's title in full ink; red for a field the collection\n   no longer has. At the admin's size whatever the zoom. A visitor's page\n   never carries one. */\n[${ENTRY_CONTENT_NOTE_ATTRIBUTE}] {\n  display: flex;\n  align-items: center;\n  gap: 0.6em;\n  margin: 0;\n  padding: 0.6em 0.9em;\n  border: 1px dashed color-mix(in srgb, currentColor 35%, transparent);\n  border-radius: var(--radius-sm, 0.25rem);\n  background: color-mix(in srgb, currentColor 6%, transparent);\n  font-family: var(--font-sans, system-ui), sans-serif;\n  font-size: calc(0.75rem / var(--nx-canvas-zoom, 1));\n  font-weight: 400;\n  line-height: 1.4;\n  text-align: start;\n}\n\n[${ENTRY_CONTENT_NOTE_ATTRIBUTE}] span > span {\n  color: color-mix(in srgb, currentColor 65%, transparent);\n}\n\n[${ENTRY_CONTENT_NOTE_ATTRIBUTE}] b {\n  font-weight: 500;\n}\n\n/* The red note, drawn on the page as the muted one is: its tint over the\n   page itself and its words mixed with the page's own ink, so it reads on a\n   light page and a dark section alike, whatever the admin's theme. The red\n   is the admin's danger hue, the one value taken from the editor. */\n[${ENTRY_CONTENT_NOTE_ATTRIBUTE}=\"failed\"] {\n  border-style: solid;\n  border-color: color-mix(in srgb, var(--nx-builder-danger, currentColor) 55%, transparent);\n  background: color-mix(in srgb, var(--nx-builder-danger, currentColor) 8%, transparent);\n  color: color-mix(in oklab, var(--nx-builder-danger, currentColor) 70%, currentColor);\n}\n\n[${ENTRY_CONTENT_NOTE_ATTRIBUTE}=\"failed\"] span > span {\n  color: inherit;\n}\n\n[${ENTRY_CONTENT_NOTE_ATTRIBUTE}] > svg {\n  flex: none;\n  inline-size: 1.15em;\n  block-size: 1.15em;\n}\n\n/* A list whose new source waits for an input wears what it still draws\n   (\"Still showing Events\"), in the same tag, first in its flow. Written\n   after the empty state's, so the wait is what it says while both hold. */\n${ROOT} [data-nx-list-still]::before {\n  content: attr(data-nx-list-still);\n  display: block;\n  grid-column: 1 / -1;\n  justify-self: start;\n  align-self: start;\n  flex: none;\n  inline-size: max-content;\n  max-inline-size: 100%;\n  margin-block-end: 0.375rem;\n  padding: 0.0625rem 0.375rem;\n  border-radius: 0.1875rem;\n  background: var(--nx-builder-select, Highlight);\n  color: var(--nx-builder-select-text, HighlightText);\n  font-family: system-ui, sans-serif;\n  font-size: 0.6875rem;\n  font-weight: 500;\n  line-height: 1.4;\n  white-space: nowrap;\n  pointer-events: none;\n  zoom: calc(1 / var(--nx-canvas-zoom, 1));\n}\n\n/* A list drawn as a visitor reads it, while conditions are applied, wears\n   how many of the editor's entries a visitor sees (\"Showing what visitors\n   see: 4 of 6 entries\"): the same place as the wait's tag, quieter, since\n   it reports rather than asks. A list waiting for an input says that\n   instead, as the one thing it asks. */\n${ROOT} [data-nx-list-visitors]:not([data-nx-list-still])::before {\n  content: attr(data-nx-list-visitors);\n  display: block;\n  grid-column: 1 / -1;\n  justify-self: start;\n  align-self: start;\n  flex: none;\n  inline-size: max-content;\n  max-inline-size: 100%;\n  margin-block-end: 0.375rem;\n  padding: 0.0625rem 0.375rem;\n  border: 1px solid var(--nx-builder-border, GrayText);\n  border-radius: 0.1875rem;\n  background: var(--nx-builder-surface-raised, Canvas);\n  color: var(--nx-builder-text-muted, GrayText);\n  font-family: system-ui, sans-serif;\n  font-size: 0.6875rem;\n  font-weight: 500;\n  line-height: 1.4;\n  white-space: nowrap;\n  pointer-events: none;\n  zoom: calc(1 / var(--nx-canvas-zoom, 1));\n}\n\n/* Over a list's empty area, the same tag sits inside the area's dashed edge,\n   clear of it, rather than on the corner the empty state's own tag fills. */\n${EMPTY_LIST}[data-nx-list-visitors]:not([data-nx-list-still])::before {\n  inset-block-start: 0.25rem;\n  inset-inline-start: 0.25rem;\n  border-radius: 0.1875rem;\n}\n\n/* A region of the page's layout, its header or footer, drawn around the page.\n   Its content keeps the site's own colours, quietened, so it reads as what\n   surrounds the page; its links and forms are inert. It is selected as a\n   whole, and every mark of it is drawn inside its own box, never over the\n   page: the outline as its own pseudo-element on its edge, and its tag at its\n   top left (bottom left where the top is scrolled away, by data-placement).\n   Neither takes the pointer, so leaving the region is leaving its marks.\n   The marks take the select hue for the page's ground, as the block marks\n   over the page do, from the tokens the frame hands the region alone. */\n.nx-canvas-region {\n  position: relative;\n  cursor: default;\n  --nx-region-mark: var(--nx-builder-select-on-light);\n  --nx-region-mark-text: var(--nx-builder-select-text-on-light);\n}\n\n.nx-canvas-region[data-nx-page-scheme=\"dark\"] {\n  --nx-region-mark: var(--nx-builder-select-on-dark);\n  --nx-region-mark-text: var(--nx-builder-select-text-on-dark);\n}\n\n.nx-canvas-region__content {\n  opacity: var(--nx-builder-region-opacity, 0.6);\n}\n\n/* The region's name, heard and not drawn: the editor's own hidden-text rule\n   does not reach the canvas, so the frame says it here. */\n.nx-canvas-region__name {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  padding: 0;\n  margin: -1px;\n  overflow: hidden;\n  clip-path: inset(50%);\n  white-space: nowrap;\n  border-width: 0;\n}\n\n/* Where the region meets the page: a quiet line. */\n.nx-canvas-region[data-nx-region=\"header\"] {\n  border-bottom: 1px dashed var(--nx-builder-border);\n}\n\n.nx-canvas-region[data-nx-region=\"footer\"] {\n  border-top: 1px dashed var(--nx-builder-border);\n}\n\n.nx-canvas-region:focus {\n  outline: none;\n}\n\n/* The outline: a ring on the region's own edge, over its content, haloed so\n   it reads on whatever the region paints. Thin while the pointer or focus is\n   on it, full while it is selected. */\n.nx-canvas-region::after {\n  content: \"\";\n  position: absolute;\n  inset: 0;\n  z-index: 2;\n  pointer-events: none;\n  border-radius: inherit;\n}\n\n.nx-canvas-region:hover::after,\n.nx-canvas-region:focus-visible::after {\n  box-shadow:\n    inset 0 0 0 1px var(--nx-region-mark),\n    inset 0 0 0 2px var(--nx-builder-halo, #fff);\n}\n\n.nx-canvas-region[data-selected]::after {\n  box-shadow:\n    inset 0 0 0 2px var(--nx-region-mark),\n    inset 0 0 0 4px var(--nx-builder-halo, #fff);\n}\n\n/* Where the page's header & footer set has no header (or footer): a dashed\n   band in the region's place saying so, with the ways to fill it. In the\n   admin's scheme and face, which the frame hands it as values, so it reads\n   the same over any site; its size is the admin's whatever the zoom, and\n   its spacing in its own text's units. A visitor's page never draws one. */\n.nx-canvas-region-empty {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: center;\n  justify-content: space-between;\n  gap: 0.75em 1.25em;\n  margin: 0.75em;\n  padding: 1em 1.25em;\n  color-scheme: var(--nx-builder-scheme, light);\n  border: 1.5px dashed var(--nx-builder-text-muted, GrayText);\n  border-radius: var(--radius-sm, 0.25rem);\n  background: var(--nx-builder-surface-raised, Canvas);\n  color: var(--nx-builder-text, CanvasText);\n  font-family: var(--font-sans, system-ui), sans-serif;\n  font-size: calc(0.875rem / var(--nx-canvas-zoom, 1));\n  line-height: 1.5;\n}\n\n.nx-canvas-region-empty__sentence,\n.nx-canvas-region-empty__ask {\n  margin: 0;\n  max-width: 60ch;\n}\n\n.nx-canvas-region-empty__ask {\n  color: var(--nx-builder-text-muted, GrayText);\n}\n\n.nx-canvas-region-empty__actions {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5em;\n}\n\n/* Its two buttons: the first fills the area at once, on the select hue; the\n   second opens the choice, edged in the text's own colour. */\n.nx-canvas-region-empty__actions > button {\n  padding: 0.35em 0.85em;\n  border: 1px solid currentColor;\n  border-radius: var(--radius-sm, 0.25rem);\n  background: transparent;\n  color: inherit;\n  font: inherit;\n  font-weight: 500;\n  cursor: pointer;\n}\n\n.nx-canvas-region-empty__actions > button[data-nx-region-empty-action=\"create\"] {\n  border-color: var(--nx-builder-select, Highlight);\n  background: var(--nx-builder-select, Highlight);\n  color: var(--nx-builder-select-text, HighlightText);\n}\n\n.nx-canvas-region-empty__actions > button:focus-visible {\n  outline: 2px solid var(--nx-builder-select, Highlight);\n  outline-offset: -2px;\n}\n\n.nx-canvas-region-empty__actions > button:disabled {\n  opacity: 0.6;\n  cursor: default;\n}\n\n/* The part holding the page between its regions lays out as if it were not\n   there, so the page's own layout is the same with regions as without. */\n.nx-canvas-page-part {\n  display: contents;\n}\n\n/* A region edited in place is no longer one thing to select: its blocks take\n   the canvas's own marks, so its ring and its pointer go. */\n.nx-canvas-region[data-nx-region-edited] {\n  cursor: auto;\n}\n\n.nx-canvas-region[data-nx-region-edited]::after {\n  display: none;\n}\n\n/* The tag: the region's badge while the pointer or focus is on it, its name\n   while it is selected, hidden otherwise, on the select hue as a hovered\n   block's name is. In the admin's\n   face and size however far the frame is painted down: the scale the canvas\n   publishes is undone here. Placed in the page's own pixels, so its left\n   offset is measured to keep it on screen. */\n.nx-canvas-region__tag {\n  position: absolute;\n  z-index: 3;\n  left: 0.5rem;\n  top: 0.25rem;\n  display: none;\n  max-width: calc(100% - 1rem);\n  overflow: hidden;\n  padding: 1px 6px;\n  border-radius: 4px;\n  background: var(--nx-region-mark);\n  color: var(--nx-region-mark-text);\n  font:\n    500 11px/16px var(--font-sans, system-ui),\n    sans-serif;\n  white-space: nowrap;\n  text-overflow: ellipsis;\n  pointer-events: none;\n  zoom: calc(1 / var(--nx-canvas-zoom, 1));\n}\n\n.nx-canvas-region__tag[data-placement=\"bottom\"] {\n  top: auto;\n  bottom: 0.25rem;\n}\n\n/* A region shorter than its tag shows none, rather than one over the page:\n   kept in the layout, so the next measure still reads its size. */\n.nx-canvas-region__tag[data-placement=\"none\"] {\n  visibility: hidden;\n}\n\n.nx-canvas-region:is(:hover, :focus-visible) > .nx-canvas-region__tag,\n.nx-canvas-region[data-selected] > .nx-canvas-region__tag {\n  display: block;\n}\n`;\n","/**\n * Previewing the page at a width other than the device's own: the ruler's\n * marks and how a dragged handle snaps to them, what each key does to the\n * width, and the words the canvas says about it.\n *\n * The preview width is the canvas's session state, held by the host beside\n * the device being edited and never stored. While there is one, the frame\n * lays the page out at it in place of the device's own width, and that is\n * all it changes: nothing about where an edit goes: the device the author chose keeps receiving every edit,\n * which is why every sentence here names that device rather than one read off\n * the width.\n *\n * @module canvas-preview-width\n */\n\nimport {\n  BASE_BREAKPOINT,\n  type BreakpointId,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { deviceLabel } from \"../shell/breakpoint-switcher\";\n\nimport {\n  baseWidth,\n  clampPreviewWidth,\n  editedBreakpointAtWidth,\n  NARROWEST_PREVIEW_WIDTH,\n  offeredTiers,\n  type PreviewWidthRange,\n} from \"./canvas-width\";\n\n/** A mark on the ruler: where a breakpoint starts, and its name. */\nexport interface RulerMark {\n  readonly width: number;\n  readonly label: string;\n}\n\n/**\n * How near, in screen pixels, a dragged handle comes to a mark before the\n * width becomes the mark's.\n */\nconst SNAP_DISTANCE = 6;\n\n/** What an arrow key moves the width by, and with Shift held. */\nconst ARROW_STEP = 10;\nconst FINE_STEP = 1;\n\n/**\n * The name the device switcher gives a breakpoint, read from the switcher's\n * own answer so every surface names a device as its button does; the id\n * itself for one the switcher does not offer.\n *\n * @experimental\n */\nexport function deviceLabelOf(\n  set: BreakpointSet | undefined,\n  id: BreakpointId\n): string {\n  return deviceLabel(set, id) ?? id;\n}\n\n/**\n * Where each breakpoint starts, narrowest first: one pixel past the bound of\n * the next narrower one, and Desktop one pixel past the widest bound. The\n * narrowest breakpoint starts at no width at all, and a start below the\n * narrowest preview width is not on the ruler.\n *\n * Read from the tiers the compiler emits, as the device buttons are, so the\n * ruler marks the same breakpoints the buttons offer.\n *\n * @experimental\n */\nexport function rulerMarks(set: BreakpointSet | undefined): RulerMark[] {\n  // Widest first, so each tier's next narrower one is the one after it.\n  const tiers = offeredTiers(set);\n  const marks: RulerMark[] = [];\n  const desktop = baseWidth(set);\n  if (desktop !== undefined) {\n    marks.push({ width: desktop, label: deviceLabelOf(set, BASE_BREAKPOINT) });\n  }\n  tiers.forEach((tier, index) => {\n    const narrower = tiers[index + 1];\n    if (narrower === undefined) return;\n    marks.push({\n      width: narrower.maxWidth + 1,\n      label: deviceLabelOf(set, tier.id),\n    });\n  });\n  return marks\n    .filter(mark => mark.width >= NARROWEST_PREVIEW_WIDTH)\n    .sort((a, b) => a.width - b.width);\n}\n\n/**\n * The width a dragged handle settles on: a mark's, when the handle is within\n * {@link SNAP_DISTANCE} screen pixels of it, else the width as dragged.\n *\n * Both edges move together, so a handle travels half the width's change, at\n * the frame's scale: the screen distance to a mark is half the difference in\n * width, scaled.\n *\n * @experimental\n */\nexport function snappedPreviewWidth(\n  width: number,\n  marks: readonly RulerMark[],\n  scale: number\n): number {\n  let nearest: { width: number; distance: number } | undefined;\n  for (const mark of marks) {\n    const distance = (Math.abs(width - mark.width) * scale) / 2;\n    if (distance > SNAP_DISTANCE) continue;\n    if (nearest === undefined || distance < nearest.distance) {\n      nearest = { width: mark.width, distance };\n    }\n  }\n  return nearest?.width ?? width;\n}\n\n/**\n * The painted width that puts the dragged edge where the pointer has moved\n * it, in screen pixels, from the painted width the drag `start`ed at, the\n * `region`'s width and the pointer's `travel` since.\n *\n * The frame is centred in its stage, so both edges move together and the\n * width changes by twice the travel. The stage is the region, or the width\n * the frame started at where that is wider: an overflowing frame's stage is\n * held at that width for the drag (`canvas-preview-width-edges.tsx`), so the\n * region's scroll is never clamped under the pointer. Past that width the\n * stage grows with the frame from its left edge, and the right edge moves by\n * the travel alone. A region not measured is taken as roomy enough.\n *\n * @experimental\n */\nexport function draggedPaintedWidth({\n  side,\n  start,\n  region,\n  travel,\n}: {\n  /** +1 for the right edge, -1 for the left. */\n  readonly side: 1 | -1;\n  readonly start: number;\n  readonly region: number;\n  readonly travel: number;\n}): number {\n  if (!(region > 0)) return start + side * 2 * travel;\n  const stage = Math.max(region, start);\n  if (side === 1) {\n    const edge = (stage + start) / 2 + travel;\n    return edge >= stage ? edge : 2 * edge - stage;\n  }\n  const edge = (stage - start) / 2 + travel;\n  return stage - 2 * edge;\n}\n\n/**\n * The width a key on a handle moves to: the arrows by 10px (1px with Shift),\n * Page Up and Page Down to the next and previous mark (the range's ends past\n * the last), Home and End to the narrowest and widest. `undefined` for a key\n * that is not the slider's.\n *\n * @experimental\n */\nexport function keyedPreviewWidth(\n  event: { readonly key: string; readonly shiftKey: boolean },\n  width: number,\n  marks: readonly RulerMark[],\n  range: PreviewWidthRange\n): number | undefined {\n  const step = event.shiftKey ? FINE_STEP : ARROW_STEP;\n  switch (event.key) {\n    case \"ArrowRight\":\n    case \"ArrowUp\":\n      return clampPreviewWidth(width + step, range);\n    case \"ArrowLeft\":\n    case \"ArrowDown\":\n      return clampPreviewWidth(width - step, range);\n    case \"PageUp\":\n      return (\n        marks.find(mark => mark.width > width && mark.width <= range.max)\n          ?.width ?? range.max\n      );\n    case \"PageDown\":\n      return (\n        marks.findLast(mark => mark.width < width && mark.width >= range.min)\n          ?.width ?? range.min\n      );\n    case \"Home\":\n      return range.min;\n    case \"End\":\n      return range.max;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * The slider's value in words: the width and the breakpoint whose range it is\n * in, \"900 pixels, Tablet range\".\n *\n * @experimental\n */\nexport function previewValueText(\n  set: BreakpointSet | undefined,\n  width: number\n): string {\n  const range = deviceLabelOf(set, editedBreakpointAtWidth(set, width));\n  return `${width} pixels, ${range} range`;\n}\n\n/**\n * The line under the frame while the page is previewed at a width of its own,\n * naming the device every edit still goes to.\n *\n * @experimental\n */\nexport function previewNotice(width: number, device: string): string {\n  return `Previewing at ${width}px · still editing ${device} styles`;\n}\n\n/** What a screen reader hears once the width settles. @experimental */\nexport function previewAnnouncement(width: number, device: string): string {\n  return `Previewing at ${width} pixels, still editing ${device} styles`;\n}\n","\"use client\";\n\n/**\n * The handles at the canvas frame's two edges that preview the page at any\n * width, the ruler of breakpoint starts above it, the line saying which\n * device is still being edited, and the announcement once a width settles.\n *\n * Drawn inside the frame's box (`canvas-frame.tsx`), so the handles sit at\n * its edges as it grows and shrinks, and in the well beside a frame narrower\n * than the region.\n *\n * **No render of the page per pixel.** A drag writes the width straight to\n * the frame's box and its page, once per animation frame, at the scale the\n * drag started at; the page re-lays itself out in its frame while nothing in\n * React runs. The host hears the width once, on release, and only then lays\n * the frame out at it and fits it to the region again.\n *\n * **Never a device.** The width is the host's session state and goes back to\n * the device's own on Reset, a device press or a page switch. Every edit\n * still goes to the device being edited, which the line under the frame and\n * the announcement name.\n *\n * @module canvas-preview-width-edges\n */\n\nimport type { BreakpointId, BreakpointSet } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport {\n  deviceLabelOf,\n  draggedPaintedWidth,\n  keyedPreviewWidth,\n  previewAnnouncement,\n  previewNotice,\n  previewValueText,\n  rulerMarks,\n  snappedPreviewWidth,\n} from \"./canvas-preview-width\";\nimport { clampPreviewWidth, previewWidthRange } from \"./canvas-width\";\nimport { CANVAS_FRAME_BOX_ATTRIBUTE } from \"./geometry-dom\";\n\n/**\n * What the host gives the frame to preview widths with: the site's\n * breakpoints, the device being edited and its own width, the width the\n * author previews at (`null` for the device's own), and where a new one goes.\n *\n * @experimental\n */\nexport interface PreviewWidthControl {\n  readonly breakpoints: BreakpointSet | undefined;\n  /** The breakpoint every edit goes to, whatever the width shown. */\n  readonly edited: BreakpointId;\n  /** The width the device being edited is laid out at. */\n  readonly deviceWidth: number;\n  /** The width previewed instead, or `null` for the device's own. */\n  readonly override: number | null;\n  /** Told a settled width, `null` once it is the device's own again. */\n  readonly onChange: (width: number | null) => void;\n}\n\n/** How long after the last key the settled width is announced. */\nexport const ANNOUNCE_AFTER_KEYS_MS = 500;\n\n/**\n * The room beside the frame the handles need to sit in the well, clear of the\n * panels' dividers at the region's edges; with less, as on a Desktop frame\n * that fills the region, they sit just inside its edges and show on hover or\n * focus.\n */\nconst HANDLE_ROOM = 24;\n\n/** The page's element in the frame's box, which a drag lays out directly. */\nconst FRAME_PAGE_SELECTOR = \".nx-canvas-frame__page\";\n\n/** A drag in progress, held outside React so moving it renders nothing. */\ninterface Drag {\n  readonly pointerId: number;\n  /** +1 for the right handle, -1 for the left, which widens moving left. */\n  readonly side: 1 | -1;\n  readonly startX: number;\n  readonly startWidth: number;\n  /** The scale the frame is painted at, held for the whole drag. */\n  readonly scale: number;\n  /** The region's width the frame is centred in, or 0 unmeasured. */\n  readonly region: number;\n  readonly box: HTMLElement | null;\n  readonly page: HTMLElement | null;\n  /**\n   * The widths the host last drew the box and its page at, put back as the\n   * drag ends: the host draws the settled width over them where it differs,\n   * and a fitted box the same width before and after is not drawn again.\n   */\n  readonly drawn: {\n    readonly box: string;\n    readonly page: string;\n    readonly stage: string;\n  };\n  /** The stage around the box, held at the box's width while it overflows. */\n  readonly stage: HTMLElement | null;\n  width: number;\n  frameRequest: number | null;\n}\n\n/** The box and its page as the host drew them, before a drag wrote over them. */\nfunction giveBack(held: Drag): void {\n  if (held.box !== null) held.box.style.width = held.drawn.box;\n  if (held.stage !== null) held.stage.style.minWidth = held.drawn.stage;\n  if (held.page !== null) {\n    held.page.style.width = held.drawn.page;\n    held.page.style.pointerEvents = \"\";\n  }\n}\n\n/**\n * Whether the well beside the frame has room for the handles, written to the\n * edges' root as an attribute the stylesheet places them by.\n */\nfunction placeHandles(root: HTMLElement | null): void {\n  const box = root?.closest<HTMLElement>(`[${CANVAS_FRAME_BOX_ATTRIBUTE}]`);\n  const stage = box?.parentElement;\n  if (root == null || box == null || stage == null) return;\n  // The frame is centred in the stage by its auto margins, so the room on\n  // each side is half of what it leaves. Layout sizes, not rectangles: this\n  // is a question about the editor's own document, never across the frame.\n  const beside = (stage.clientWidth - box.offsetWidth) / 2;\n  root.setAttribute(\n    \"data-handles\",\n    beside >= HANDLE_ROOM ? \"beside\" : \"inside\"\n  );\n}\n\n/**\n * The handles, the ruler, the line under the frame and the live region, for\n * a frame laid out at `width` and painted at `scale`; nothing where the host\n * previews no other width.\n *\n * @experimental\n */\nexport function PreviewWidthEdges({\n  control,\n  width,\n  scale,\n  onDragging,\n}: {\n  control: PreviewWidthControl | undefined;\n  width: number;\n  scale: number;\n  /**\n   * Told when a drag starts and ends, so the frame holds back what it reads\n   * off the page's resizing until the width settles.\n   */\n  onDragging?: (active: boolean) => void;\n}): React.JSX.Element | null {\n  if (control === undefined) return null;\n  return (\n    <Edges\n      control={control}\n      width={width}\n      scale={scale}\n      onDragging={onDragging}\n    />\n  );\n}\n\n/** {@link PreviewWidthEdges}, for a host that previews other widths. */\nfunction Edges({\n  control,\n  width,\n  scale,\n  onDragging,\n}: {\n  control: PreviewWidthControl;\n  width: number;\n  scale: number;\n  onDragging: ((active: boolean) => void) | undefined;\n}): React.JSX.Element {\n  const { breakpoints, edited, deviceWidth, override, onChange } = control;\n  const marks = React.useMemo(() => rulerMarks(breakpoints), [breakpoints]);\n  const range = React.useMemo(\n    () => previewWidthRange(breakpoints),\n    [breakpoints]\n  );\n  const device = deviceLabelOf(breakpoints, edited);\n  const root = React.useRef<HTMLDivElement | null>(null);\n  const readout = React.useRef<HTMLSpanElement | null>(null);\n  const drag = React.useRef<Drag | null>(null);\n  const keyTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n  const [dragging, setDragging] = React.useState(false);\n  const [announced, setAnnounced] = React.useState(\"\");\n\n  // Where the handles sit, again whenever the frame or the region resizes.\n  React.useLayoutEffect(() => {\n    const element = root.current;\n    placeHandles(element);\n    const box = element?.closest(`[${CANVAS_FRAME_BOX_ATTRIBUTE}]`);\n    const view = element?.ownerDocument.defaultView;\n    if (\n      box == null ||\n      view == null ||\n      typeof view.ResizeObserver !== \"function\"\n    ) {\n      return;\n    }\n    // Not mid-drag: a handle that moved between beside and inside the frame\n    // would leave the pointer that holds it.\n    const sizes = new view.ResizeObserver(() => {\n      if (drag.current === null) placeHandles(element);\n    });\n    sizes.observe(box);\n    if (box.parentElement !== null) sizes.observe(box.parentElement);\n    return () => sizes.disconnect();\n  }, []);\n\n  // A width keyed in for one device is not announced once another is edited.\n  React.useEffect(\n    () => () => {\n      if (keyTimer.current !== null) clearTimeout(keyTimer.current);\n      keyTimer.current = null;\n    },\n    [edited]\n  );\n\n  // The frame's latest listener, for a drag the handles' going cuts short.\n  const draggingSeen = React.useRef(onDragging);\n  draggingSeen.current = onDragging;\n  // Nothing left waiting once the handles go, and a drag cut short gives\n  // the page its pointer back and the frame its reads.\n  React.useEffect(\n    () => () => {\n      if (keyTimer.current !== null) clearTimeout(keyTimer.current);\n      const held = drag.current;\n      drag.current = null;\n      if (held === null) return;\n      if (held.frameRequest !== null) {\n        held.box?.ownerDocument.defaultView?.cancelAnimationFrame(\n          held.frameRequest\n        );\n      }\n      giveBack(held);\n      draggingSeen.current?.(false);\n    },\n    []\n  );\n\n  /** Tells the host a width, as `null` where it is the device's own. */\n  const settle = (next: number): number => {\n    const settled = clampPreviewWidth(next, range);\n    onChange(settled === deviceWidth ? null : settled);\n    return settled;\n  };\n\n  /** Lays the frame out at a dragged width, straight to its elements. */\n  const show = (held: Drag): void => {\n    const shown = held.width;\n    if (held.box !== null) {\n      held.box.style.width = `${String(shown * held.scale)}px`;\n    }\n    if (held.page !== null) held.page.style.width = `${String(shown)}px`;\n    root.current\n      ?.querySelectorAll<HTMLElement>('[role=\"slider\"]')\n      .forEach(slider => {\n        slider.setAttribute(\"aria-valuenow\", String(shown));\n        slider.setAttribute(\n          \"aria-valuetext\",\n          previewValueText(breakpoints, shown)\n        );\n      });\n    if (readout.current !== null) {\n      readout.current.textContent = `${String(shown)}px`;\n      readout.current.style.left = `calc(50% + ${String((shown * held.scale) / 2)}px)`;\n    }\n  };\n\n  const onPointerDown = (\n    side: 1 | -1,\n    event: React.PointerEvent<HTMLElement>\n  ): void => {\n    if (event.button !== 0) return;\n    event.preventDefault();\n    // A drag overtakes a keyed width still waiting to be announced.\n    if (keyTimer.current !== null) clearTimeout(keyTimer.current);\n    keyTimer.current = null;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const box =\n      root.current?.closest<HTMLElement>(`[${CANVAS_FRAME_BOX_ATTRIBUTE}]`) ??\n      null;\n    const page = box?.querySelector<HTMLElement>(FRAME_PAGE_SELECTOR) ?? null;\n    // The page takes no pointer while the handle is dragged across it.\n    if (page !== null) page.style.pointerEvents = \"none\";\n    const stage = box?.parentElement ?? null;\n    // The well's own width: the stage grows past it with a frame wider than\n    // it, so the canvas region around it is what the frame centres in. The\n    // stage's where the frame is drawn outside the shell.\n    const region =\n      (box?.closest(\".nx-canvas-scroller\") ?? stage)?.clientWidth ?? 0;\n    const painted = width * scale;\n    drag.current = {\n      pointerId: event.pointerId,\n      side,\n      startX: event.clientX,\n      startWidth: width,\n      scale,\n      region,\n      box,\n      page,\n      stage,\n      drawn: {\n        box: box?.style.width ?? \"\",\n        page: page?.style.width ?? \"\",\n        stage: stage?.style.minWidth ?? \"\",\n      },\n      width,\n      frameRequest: null,\n    };\n    // A frame wider than the region keeps its stage at its width for the\n    // drag, so it narrows centred in it and the region's scroll stays put\n    // under the pointer rather than being clamped as the frame narrows.\n    if (stage !== null && region > 0 && painted > region) {\n      stage.style.minWidth = `${String(painted)}px`;\n    }\n    setDragging(true);\n    onDragging?.(true);\n  };\n\n  const onPointerMove = (event: React.PointerEvent<HTMLElement>): void => {\n    const held = drag.current;\n    if (held === null || held.pointerId !== event.pointerId) return;\n    // The edge dragged follows the pointer, both edges moving together while\n    // the frame is centred, in the page's own pixels.\n    const dragged =\n      draggedPaintedWidth({\n        side: held.side,\n        start: held.startWidth * held.scale,\n        region: held.region,\n        travel: event.clientX - held.startX,\n      }) / held.scale;\n    held.width = snappedPreviewWidth(\n      clampPreviewWidth(dragged, range),\n      marks,\n      held.scale\n    );\n    const view = root.current?.ownerDocument.defaultView;\n    if (held.frameRequest !== null || view == null) return;\n    held.frameRequest = view.requestAnimationFrame(() => {\n      held.frameRequest = null;\n      show(held);\n    });\n  };\n\n  // Released, cancelled, or the capture lost without either: the drag\n  // settles where it is.\n  const onPointerEnd = (event: React.PointerEvent<HTMLElement>): void => {\n    const held = drag.current;\n    if (held === null || held.pointerId !== event.pointerId) return;\n    drag.current = null;\n    if (held.frameRequest !== null) {\n      root.current?.ownerDocument.defaultView?.cancelAnimationFrame(\n        held.frameRequest\n      );\n    }\n    // The handles' values at the settled width, then the box and page back\n    // to the host, which draws the settled width where it differs.\n    show(held);\n    giveBack(held);\n    setDragging(false);\n    // Before the width settles, so the frame reads the settled one.\n    onDragging?.(false);\n    if (keyTimer.current !== null) clearTimeout(keyTimer.current);\n    setAnnounced(previewAnnouncement(settle(held.width), device));\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLElement>): void => {\n    const next = keyedPreviewWidth(event, width, marks, range);\n    if (next === undefined) return;\n    event.preventDefault();\n    const settled = settle(next);\n    // Said once the keys stop, not on every press.\n    if (keyTimer.current !== null) clearTimeout(keyTimer.current);\n    keyTimer.current = setTimeout(() => {\n      keyTimer.current = null;\n      setAnnounced(previewAnnouncement(settled, device));\n    }, ANNOUNCE_AFTER_KEYS_MS);\n  };\n\n  const handle = (side: 1 | -1): React.JSX.Element => (\n    <div\n      role=\"slider\"\n      aria-label=\"Preview width\"\n      aria-orientation=\"horizontal\"\n      aria-valuemin={range.min}\n      aria-valuemax={range.max}\n      aria-valuenow={width}\n      aria-valuetext={previewValueText(breakpoints, width)}\n      tabIndex={0}\n      data-side={side === 1 ? \"right\" : \"left\"}\n      className=\"nx-preview-width__handle\"\n      onPointerDown={event => onPointerDown(side, event)}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerEnd}\n      onPointerCancel={onPointerEnd}\n      onLostPointerCapture={onPointerEnd}\n      onKeyDown={onKeyDown}\n    >\n      <span className=\"nx-preview-width__grip\" aria-hidden=\"true\" />\n    </div>\n  );\n\n  return (\n    <div\n      ref={root}\n      className=\"nx-preview-width\"\n      data-handles=\"inside\"\n      {...(dragging ? { \"data-dragging\": \"\" } : {})}\n    >\n      {dragging || override !== null ? (\n        <PreviewRuler\n          marks={marks}\n          scale={scale}\n          readout={readout}\n          dragging={dragging}\n        />\n      ) : null}\n      {handle(-1)}\n      {handle(1)}\n      {override === null ? null : (\n        <p className=\"nx-preview-width__notice\">\n          {previewNotice(override, device)}\n        </p>\n      )}\n      <span\n        className=\"nx-sr-only\"\n        aria-live=\"polite\"\n        data-nx-preview-width-announcer=\"\"\n      >\n        {announced}\n      </span>\n    </div>\n  );\n}\n\n/**\n * The ruler over the top of the well: a tick at each breakpoint's start on\n * both sides of the frame's centre, where an edge at that width would be,\n * labelled on the right (\"768 Tablet\"). While dragging, the width dragged to\n * follows the right edge, written by the drag rather than rendered.\n */\nfunction PreviewRuler({\n  marks,\n  scale,\n  readout,\n  dragging,\n}: {\n  marks: readonly { width: number; label: string }[];\n  scale: number;\n  readout: React.RefObject<HTMLSpanElement | null>;\n  dragging: boolean;\n}): React.JSX.Element {\n  return (\n    <div\n      className=\"nx-preview-width__ruler\"\n      data-nx-preview-ruler=\"\"\n      aria-hidden=\"true\"\n    >\n      {marks.map(mark => {\n        const offset = (mark.width * scale) / 2;\n        return (\n          <React.Fragment key={mark.width}>\n            <span\n              className=\"nx-preview-width__tick\"\n              style={{ left: `calc(50% - ${String(offset)}px)` }}\n            />\n            <span\n              className=\"nx-preview-width__tick\"\n              data-labelled=\"\"\n              style={{ left: `calc(50% + ${String(offset)}px)` }}\n            >\n              {`${String(mark.width)} ${mark.label}`}\n            </span>\n          </React.Fragment>\n        );\n      })}\n      {dragging ? (\n        <span ref={readout} className=\"nx-preview-width__readout\" />\n      ) : null}\n    </div>\n  );\n}\n","/**\n * The site's own layout around the canvas, on a page the site serves: marked\n * as its chrome and made inert, so a click on a site header never edits it,\n * and reported to the host as drawing before or after the page, so the editor\n * can say a site draws its own header or footer.\n *\n * Its own module so the canvas frame stays the entry that draws the frame and\n * wires these parts together.\n *\n * @module canvas/site-chrome\n */\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { SITE_CHROME_ATTRIBUTE } from \"./canvas-frame-sheet\";\nimport { boxInFrameViewport } from \"./geometry-dom\";\n\n/**\n * Where the site's own layout draws around the page on a page the site\n * serves: something with a box before the page, as a header is, and after it,\n * as a footer is. Read from where each part sits in the site's page against\n * the canvas's mount point, so it holds whatever the site's markup calls it.\n *\n * @experimental Settles with the editor's notices about the site's layout.\n */\nexport interface SiteChromeDrawn {\n  /** The layout draws something before the page. */\n  readonly before: boolean;\n  /** The layout draws something after the page. */\n  readonly after: boolean;\n}\n\n/** Elements of a site's layout that draw nothing, and so are left alone. */\nconst UNDRAWN_ELEMENTS: ReadonlySet<string> = new Set([\n  \"script\",\n  \"style\",\n  \"link\",\n  \"meta\",\n  \"template\",\n  \"noscript\",\n]);\n\n/**\n * Mark one element of the site's layout as its chrome, inert unless the site\n * made it so itself, remembering which it marked so they can be given back.\n * Answers whether the element is chrome at all: one that draws nothing is not.\n */\nfunction markBeside(\n  element: Element,\n  seen: Set<Element>,\n  marked: Set<Element>\n): boolean {\n  seen.add(element);\n  if (UNDRAWN_ELEMENTS.has(element.localName)) return false;\n  element.setAttribute(SITE_CHROME_ATTRIBUTE, \"\");\n  if (element.hasAttribute(\"inert\")) return true;\n  element.setAttribute(\"inert\", \"\");\n  marked.add(element);\n  return true;\n}\n\n/**\n * Forget the chrome the site's layout took away: no longer chrome, its cue\n * goes with it rather than staying over the canvas it uncovered, and it gets\n * back the state it had, since the site may put the same node to use again.\n * An element the site made inert itself stays so. Answers whether anything\n * went.\n */\nfunction dropDetached(\n  drawn: Element[],\n  ancestors: readonly Element[],\n  seen: Set<Element>,\n  marked: Set<Element>\n): boolean {\n  const kept = drawn.filter(\n    element =>\n      element.parentElement !== null &&\n      ancestors.includes(element.parentElement)\n  );\n  if (kept.length === drawn.length) return false;\n  for (const element of drawn) {\n    if (kept.includes(element)) continue;\n    seen.delete(element);\n    element.removeAttribute(SITE_CHROME_ATTRIBUTE);\n    if (marked.delete(element)) element.removeAttribute(\"inert\");\n  }\n  drawn.splice(0, drawn.length, ...kept);\n  return true;\n}\n\n/**\n * Mark what is new beside the mount point and its ancestors, adding what\n * draws to `drawn`. Answers whether anything was added.\n */\nfunction markArrivals(\n  mountPoint: HTMLElement,\n  ancestors: readonly Element[],\n  drawn: Element[],\n  seen: Set<Element>,\n  marked: Set<Element>\n): boolean {\n  let added = false;\n  for (const parent of ancestors) {\n    for (const beside of Array.from(parent.children)) {\n      const onThePath = beside === mountPoint || ancestors.includes(beside);\n      if (onThePath || seen.has(beside)) continue;\n      if (markBeside(beside, seen, marked)) {\n        drawn.push(beside);\n        added = true;\n      }\n    }\n  }\n  return added;\n}\n\n/** The mount point's ancestors below the body, and the body itself. */\nfunction ancestorsUpToBody(\n  mountPoint: HTMLElement,\n  body: HTMLElement\n): Element[] {\n  const ancestors: Element[] = [];\n  for (\n    let node = mountPoint.parentElement;\n    node !== null;\n    node = node === body ? null : node.parentElement\n  ) {\n    ancestors.push(node);\n  }\n  return ancestors;\n}\n\n/** No site chrome: the blank page, or a site page not yet ready. */\nconst NO_CHROME: readonly Element[] = [];\n\n/**\n * Make the site's own layout around the mount point inert and quiet, on a\n * page the site serves: every element beside the mount point and beside each\n * of its ancestors up to the body. The ancestors themselves cannot be inert,\n * since the canvas is inside them.\n *\n * Marked again when an ancestor gains a child, for a site whose layout draws\n * part of itself once its own scripts have run. Answers with the elements it\n * marked, for the cues drawn over them, and tells `onSiteChrome` where they\n * draw around the page.\n */\nexport function useSiteChrome(\n  page: Document | null,\n  mountPoint: HTMLElement | null,\n  /** Told where the marked parts draw around the page; see the prop. */\n  onSiteChrome: ((drawn: SiteChromeDrawn) => void) | undefined\n): readonly Element[] {\n  const [chrome, setChrome] = React.useState<readonly Element[]>(NO_CHROME);\n  useIsomorphicLayoutEffect(() => {\n    if (page === null || mountPoint === null || mountPoint === page.body)\n      return;\n    const ancestors = ancestorsUpToBody(mountPoint, page.body);\n    // Every element looked at, and the ones this marked: an element the site\n    // made inert itself stays so when the canvas leaves.\n    const seen = new Set<Element>();\n    const marked = new Set<Element>();\n    const drawn: Element[] = [];\n    const mark = (): void => {\n      const dropped = dropDetached(drawn, ancestors, seen, marked);\n      const added = markArrivals(mountPoint, ancestors, drawn, seen, marked);\n      if (dropped || added) setChrome([...drawn]);\n    };\n    mark();\n    const Mutations = page.defaultView?.MutationObserver;\n    const arrivals = Mutations === undefined ? null : new Mutations(mark);\n    for (const parent of ancestors) {\n      arrivals?.observe(parent, { childList: true });\n    }\n    return () => {\n      arrivals?.disconnect();\n      for (const element of seen)\n        element.removeAttribute(SITE_CHROME_ATTRIBUTE);\n      for (const element of marked) element.removeAttribute(\"inert\");\n      setChrome(NO_CHROME);\n    };\n  }, [page, mountPoint]);\n  useReportedSiteChrome(chrome, mountPoint, onSiteChrome);\n  return chrome;\n}\n\n/** Nothing drawn around the page: the state before any site page arrives. */\nconst NOTHING_DRAWN: SiteChromeDrawn = { before: false, after: false };\n\n/**\n * Where `elements`, the site's layout around `mountPoint`, draw: only a part\n * with a box counts, so a script or an empty announcer is no header, and a\n * part before the mount point in the page is before the page.\n */\nfunction siteChromeDrawn(\n  elements: readonly Element[],\n  mountPoint: HTMLElement\n): SiteChromeDrawn {\n  let before = false;\n  let after = false;\n  for (const element of elements) {\n    const box = boxInFrameViewport(element);\n    if (box.width === 0 || box.height === 0) continue;\n    // The constant from the node itself, which belongs to the frame's realm.\n    const precedes =\n      (mountPoint.compareDocumentPosition(element) &\n        mountPoint.DOCUMENT_POSITION_PRECEDING) !==\n      0;\n    if (precedes) before = true;\n    else after = true;\n  }\n  return { before, after };\n}\n\n/**\n * Tell the host where the site's layout draws around the page, each time\n * that changes: as its parts arrive or leave, and as one gains or loses its\n * box (a part the site's stylesheet hides until its script runs), and that\n * nothing is drawn once the frame is gone.\n */\nfunction useReportedSiteChrome(\n  elements: readonly Element[],\n  mountPoint: HTMLElement | null,\n  onSiteChrome: ((drawn: SiteChromeDrawn) => void) | undefined\n): void {\n  const latest = React.useRef(onSiteChrome);\n  React.useEffect(() => {\n    latest.current = onSiteChrome;\n  }, [onSiteChrome]);\n  const told = React.useRef<SiteChromeDrawn>(NOTHING_DRAWN);\n  const tell = React.useCallback((drawn: SiteChromeDrawn) => {\n    if (\n      drawn.before === told.current.before &&\n      drawn.after === told.current.after\n    ) {\n      return;\n    }\n    told.current = drawn;\n    latest.current?.(drawn);\n  }, []);\n  React.useEffect(() => {\n    if (mountPoint === null) return undefined;\n    const read = (): void => tell(siteChromeDrawn(elements, mountPoint));\n    read();\n    // From the frame's window, the realm of the elements it observes.\n    const Resizes = mountPoint.ownerDocument.defaultView?.ResizeObserver;\n    const sizes = Resizes === undefined ? null : new Resizes(read);\n    for (const element of elements) sizes?.observe(element);\n    return () => sizes?.disconnect();\n  }, [elements, mountPoint, tell]);\n  // Nothing is drawn once the frame is gone, so a host is never left holding\n  // a layout no frame shows.\n  React.useEffect(() => () => tell(NOTHING_DRAWN), [tell]);\n}\n","\"use client\";\n\n/**\n * The cue over the site's own layout around the canvas: on a page the site\n * serves, its header, footer and the rest are faded and inert, and an author\n * pointing at them is told why they cannot be clicked.\n *\n * Drawn in the editor's document, over the frame, rather than in the page:\n * inert content takes no hover or focus, so nothing inside the page could\n * answer the pointer, and the editor's own words and tokens never reach the\n * site's page this way. Each cue covers one element of the site's layout,\n * placed from where that element is in the frame's viewport, at the scale the\n * frame is painted at, and placed again as the page scrolls or resizes.\n *\n * @module site-chrome-cues\n */\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  boxInFrameViewport,\n  CHROME_BLEED,\n  framePaintedScale,\n} from \"./geometry-dom\";\n\n/** The words on the cue's tag. */\nconst SITE_CHROME_CUE_TAG = \"Part of your site’s layout\";\n\n/** The cue's tooltip: what the region is, and where it is changed. */\nconst SITE_CHROME_CUE_TITLE =\n  \"Part of your site’s layout. It comes from your site’s code and can’t be edited here.\";\n\n/** Place each cue over the element it covers, in the layer's space. */\nfunction placeCues(\n  frame: HTMLIFrameElement,\n  elements: readonly Element[],\n  cues: readonly (HTMLDivElement | null)[]\n): void {\n  const scale = framePaintedScale(frame);\n  elements.forEach((element, at) => {\n    const cue = cues[at];\n    if (cue == null) return;\n    const box = boxInFrameViewport(element);\n    // An element that draws nothing, such as an empty announcer, gets no cue.\n    cue.hidden = box.width === 0 || box.height === 0;\n    // The layer starts CHROME_BLEED up and left of the frame's viewport, so\n    // a cue is placed past it by as much to lie over its part.\n    cue.style.left = `${String(box.x * scale + CHROME_BLEED)}px`;\n    cue.style.top = `${String(box.y * scale + CHROME_BLEED)}px`;\n    cue.style.width = `${String(box.width * scale)}px`;\n    cue.style.height = `${String(box.height * scale)}px`;\n  });\n}\n\n/**\n * One cue per element of the site's layout around the canvas, inside the\n * chrome layer over the frame.\n *\n * @internal\n */\nexport function SiteChromeCues({\n  frame,\n  page,\n  elements,\n  scale,\n}: {\n  frame: HTMLIFrameElement | null;\n  page: Document | null;\n  elements: readonly Element[];\n  /** The scale asked for, so a zoom places the cues again. */\n  scale: number;\n}): React.JSX.Element | null {\n  const cues = React.useRef<(HTMLDivElement | null)[]>([]);\n  useIsomorphicLayoutEffect(() => {\n    const view = page?.defaultView;\n    if (frame === null || page === null || view == null) return;\n    if (elements.length === 0) return;\n    const place = (): void => placeCues(frame, elements, cues.current);\n    place();\n    // From the frame's window, the realm of the elements it observes.\n    const Sizes = view.ResizeObserver;\n    const sizes = typeof Sizes === \"function\" ? new Sizes(place) : null;\n    for (const element of elements) sizes?.observe(element);\n    // A part can MOVE without changing size — a footer pushed down as the\n    // page above it grows — and only the page's own size says so.\n    sizes?.observe(page.documentElement);\n    if (page.body !== null) sizes?.observe(page.body);\n    // A viewport's scroll is dispatched at its document.\n    page.addEventListener(\"scroll\", place, { passive: true });\n    view.addEventListener(\"resize\", place);\n    return () => {\n      sizes?.disconnect();\n      page.removeEventListener(\"scroll\", place);\n      view.removeEventListener(\"resize\", place);\n    };\n  }, [frame, page, elements, scale]);\n  if (elements.length === 0) return null;\n  return (\n    <>\n      {elements.map((_, at) => (\n        <div\n          // The elements are the page's, held in the order they were found;\n          // a new set re-renders the cues whole.\n          key={at}\n          ref={cue => {\n            cues.current[at] = cue;\n          }}\n          className=\"nx-site-chrome-cue\"\n          title={SITE_CHROME_CUE_TITLE}\n          // A pointer cue: the region is inert in the page, so a keyboard or\n          // screen reader never reaches it, and the cue has nothing to add.\n          aria-hidden=\"true\"\n        >\n          <span className=\"nx-site-chrome-cue__tag\">{SITE_CHROME_CUE_TAG}</span>\n        </div>\n      ))}\n    </>\n  );\n}\n","\"use client\";\n\n/**\n * The frame the canvas is drawn in: an iframe the editor owns, at the width of\n * the device being previewed, fitted to the room the panels leave, and as tall\n * as that room at the scale it is painted at. A page taller than the room\n * scrolls inside it, as in a visitor's browser window. A host that states a\n * height gets a frame of that height, fitted both ways.\n *\n * A frame of its own is what makes the canvas a real viewport. Inside it `vw`,\n * a hand-written `@media` rule and the site's container queries answer for the\n * device being previewed rather than for the admin window, and `vh` for the\n * canvas window the author looks through; the site's\n * sheet goes in exactly as it is published, and nothing of the admin's theme or\n * stylesheet reaches the page — nor anything of the page's the admin.\n *\n * **One React tree.** The page is PORTALLED into the frame's body: the editor's\n * state, its store and every hook stay where they are, and only the elements\n * are created in the frame's document. React delivers events from the portal\n * along the component tree, so the canvas's handlers run as they always did.\n *\n * **One iframe element for the life of the editor.** It is never re-keyed: a\n * new iframe starts from a blank page before its content loads — visibly in\n * Firefox — and everything portalled into the old one is lost with it.\n * Changing device changes its width, nothing else.\n *\n * **`srcdoc`, never a blob URL.** The admin's content security policy allows\n * frames from its own origin only, which a blob is not; a `srcdoc` document is\n * same-origin with the admin and is not subject to it.\n *\n * **Zoom is a transform.** The frame is laid out at the device's width and\n * painted at the zoom by `transform: scale()`, inside a box sized to the painted\n * result, so the zoom never changes the page's widths, its media queries or its\n * container queries. Only the window's height follows the room, as a browser\n * window's does.\n *\n * **Chrome is drawn over it, in the editor's document.** The layer above the\n * frame is clipped to the frame's viewport, its content box is laid over the\n * canvas root and moved with the frame's scroll, and the chrome in it is\n * placed by `overlaySpaceOf` (`geometry-dom.ts`) at its own size rather than\n * scaled with the page.\n *\n * @module canvas-frame\n */\n\nimport { DARK_MODE_ATTRIBUTE } from \"@nextlyhq/blocks-engine\";\nimport { ENTRY_CONTENT_NOTE_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\n\nimport { frameContentOrigin, pointToHost } from \"../geometry\";\nimport { BUILDER_CHROME_CLASS, CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport {\n  CanvasFrameProvider,\n  useFrameRegistration,\n  type CanvasFrame as CanvasFrameReading,\n} from \"./canvas-frame-context\";\nimport {\n  BLANK_PAGE_ATTRIBUTE,\n  CANVAS_FRAME_DEFAULTS,\n  CANVAS_FRAME_SHEET,\n  SITE_CHROME_ATTRIBUTE,\n} from \"./canvas-frame-sheet\";\nimport {\n  PreviewWidthEdges,\n  type PreviewWidthControl,\n} from \"./canvas-preview-width-edges\";\nimport { EMPTY_REGION_ATTRIBUTE } from \"./canvas-regions\";\nimport {\n  frameFillingRegion,\n  frameFitScale,\n  type FrameSize,\n} from \"./canvas-width\";\nimport { FIT_ZOOM, usableScale, type CanvasZoom } from \"./canvas-zoom\";\nimport { isHTMLElement } from \"./dom-kind\";\nimport {\n  CANVAS_FRAME_BOX_ATTRIBUTE,\n  CANVAS_LAYER_ATTRIBUTE,\n  CHROME_BLEED,\n  frameInsetOf,\n  framePaintedScale,\n  frameViewportOf,\n  rootInFrameViewport,\n} from \"./geometry-dom\";\nimport { useSiteChrome, type SiteChromeDrawn } from \"./site-chrome\";\nimport { SiteChromeCues } from \"./site-chrome-cues\";\nimport { pageSchemeOf } from \"./site-ground\";\n\n// Where the site's layout draws is part of what the frame reports, so its\n// shape is named here too, beside the frame's other readings.\nexport type { SiteChromeDrawn } from \"./site-chrome\";\n\n/**\n * Where the frame's page comes from, and where in it the canvas is mounted.\n *\n * Either the editor's own blank document, or a page the SITE serves: a route\n * rendering an empty mount point inside the site's own layouts, so the site's\n * global stylesheets, fonts, header and footer are around the canvas exactly\n * as they are around the published page.\n *\n * @experimental\n */\nexport type CanvasFrameSource = BlankFrameSource | SiteFrameSource;\n\n/** @experimental */\ninterface FrameSourceReading {\n  /**\n   * Whether a document the frame holds is this source's page, ready for the\n   * canvas, rather than the blank page a frame shows before its content loads\n   * or a site page still starting up.\n   */\n  readonly ready: (doc: Document) => boolean;\n  /** Where in that page the canvas is mounted. */\n  readonly mountPoint: (doc: Document) => HTMLElement | null;\n}\n\n/**\n * The editor's own document, as `srcdoc`.\n *\n * @experimental\n */\nexport interface BlankFrameSource extends FrameSourceReading {\n  readonly srcDoc: string;\n}\n\n/**\n * A page the site serves for the canvas, loaded by URL.\n *\n * The site's own React root runs in that page, so the canvas is portalled in\n * only once the page says it is ready: before the site's root has hydrated, an\n * element the editor added inside it would not match what the server sent.\n *\n * @experimental\n */\nexport interface SiteFrameSource extends FrameSourceReading {\n  /** The page's URL. Only one on the editor's own origin is loaded. */\n  readonly src: string;\n  /**\n   * Whether a loaded document is this route's page at all, ready or not. A\n   * page that is not — a \"not found\" page, a redirect elsewhere — is never\n   * going to be, and the frame falls back to the blank page.\n   */\n  readonly served: (doc: Document) => boolean;\n  /**\n   * Call `changed` whenever the page's readiness may have changed, until the\n   * returned function is called.\n   */\n  readonly watch: (doc: Document, changed: () => void) => () => void;\n}\n\n/**\n * Why the frame shows the blank page rather than the site's:\n * - `other-origin`: the page is on another origin, whose document the editor\n *   can neither reach nor draw into;\n * - `not-served`: the page loaded but is not the canvas route, so the site\n *   has not mounted it;\n * - `not-ready`: the page is the route, but never said it was ready.\n *\n * @experimental\n */\nexport type CanvasFrameFallback = \"other-origin\" | \"not-served\" | \"not-ready\";\n\n/**\n * How long a page the site serves has to say it is ready, once loaded.\n *\n * Generous, because a site's first page in development compiles on request;\n * a page that has not hydrated by then has failed in its own scripts.\n */\nconst SITE_PAGE_READY_WITHIN_MS = 20_000;\n\n/** The page's colour scheme, stated on the chrome layer for its marks. */\nconst PAGE_SCHEME_ATTRIBUTE = \"data-nx-page-scheme\";\n\n/**\n * A blank, standards-mode page of the editor's own.\n *\n * The doctype is what keeps the page out of quirks mode, where several layout\n * rules differ from the published page's. The page inherits the admin's base\n * URL, as every `srcdoc` document does, so a relative URL in the site's sheet\n * or a block resolves as it does on the admin's origin. Its head opens with\n * the frame's defaults, so their layer is the first the page declares and the\n * lowest, beneath anything loaded into the frame after it.\n *\n * @experimental\n */\nexport const SRCDOC_FRAME_SOURCE: BlankFrameSource = {\n  srcDoc:\n    \"<!doctype html>\" +\n    `<html ${BLANK_PAGE_ATTRIBUTE}=\"\">` +\n    `<head><meta charset=\"utf-8\"><style>${CANVAS_FRAME_DEFAULTS}</style></head>` +\n    \"<body></body></html>\",\n  ready: doc => doc.documentElement.hasAttribute(BLANK_PAGE_ATTRIBUTE),\n  mountPoint: doc => doc.body,\n};\n\n/** What the frame's accessible name begins with. */\nexport const CANVAS_FRAME_TITLE_PREFIX = \"Page canvas\";\n\n/**\n * The frame's accessible name, for the page it shows.\n *\n * A screen reader moving into the frame announces this, so it names the page\n * being edited rather than the editor.\n */\nexport function canvasFrameTitle(pageTitle: string | undefined): string {\n  const title = pageTitle?.trim() ?? \"\";\n  return `${CANVAS_FRAME_TITLE_PREFIX}: ${title === \"\" ? \"Untitled\" : title}`;\n}\n\n/** @experimental */\nexport interface CanvasFrameProps {\n  /** The width the page is laid out at: the device being previewed. */\n  width: number;\n  /**\n   * The height the page is laid out at, fitted into the region with the width.\n   * Left out, the frame fills the region's height at any zoom and a taller\n   * page scrolls inside it, as in a visitor's browser window; `vh` then\n   * answers for that window. See {@link frameFillingRegion}.\n   */\n  height?: number;\n  /**\n   * The zoom: fitting the device's width into the region (both dimensions,\n   * where the host states a height), or a chosen scale.\n   */\n  zoom?: CanvasZoom;\n  /** The scale the frame is painted at, reported as it changes. */\n  onScale?: (scale: number) => void;\n  /** The page's title, for the frame's accessible name. */\n  title: string | undefined;\n  /**\n   * The site's theme the page is shown in, stated as `data-nx-theme` on the\n   * frame's root element where a site's dark tokens are switched by it, and\n   * again on the element the canvas is mounted into, so a marker the site's\n   * own layout puts on `<body>` or a wrapper, nearer the canvas than the root,\n   * cannot keep the canvas in its own mode: the nearest marker is the one a\n   * site's tokens follow. When it is `light` or `dark`, it is also the iframe\n   * element's `color-scheme`, which the frame's `prefers-color-scheme`\n   * follows. Left out, the page shows whatever the site applies by default,\n   * and both markers are given back as the page stated them.\n   */\n  theme?: string;\n  /**\n   * The language the page's content is written in, as `lang` on the frame's\n   * root element: a frame's document does not inherit the language of the\n   * document embedding it, so a screen reader would otherwise have none.\n   * Left out, the editor document's own language is the nearest statement\n   * there is, and the frame takes that.\n   */\n  lang?: string | undefined;\n  /**\n   * The direction the page's content is written in, as `dir` on the frame's\n   * root element, for the same reason as `lang`. Left out, the editor\n   * document's own direction, where it states one.\n   */\n  dir?: \"ltr\" | \"rtl\" | undefined;\n  /** The editor's chrome, drawn over the frame in the editor's document. */\n  overlay?: React.ReactNode;\n  /**\n   * Chrome held at the frame's viewport rather than on the page: drawn in\n   * the same layer as `overlay` but outside the box the page's scroll moves,\n   * so it stays at the viewport's edges while a long page scrolls under it.\n   * For what says how the whole canvas is drawn, such as its preview tags.\n   *\n   * @experimental Settles with the canvas's preview tags.\n   */\n  pinned?: React.ReactNode;\n  /**\n   * Previewing the page at a width other than the device's own: the frame\n   * draws a handle at each edge, the ruler and the line saying which device\n   * is still edited, and tells the host the width settled on. The host lays\n   * the frame out at that width through `width`. Left out, no handles.\n   *\n   * @experimental Settles with the canvas's preview width.\n   */\n  previewWidth?: PreviewWidthControl;\n  /** The canvas, rendered inside the frame. */\n  children?: React.ReactNode;\n  /** Where the frame's page comes from. The editor's blank page by default. */\n  source?: CanvasFrameSource;\n  /**\n   * Told why the frame shows the blank page in place of the site's page it\n   * was given, and `null` again when it shows that page, so the host can say\n   * which the author is looking at.\n   */\n  onSourceFallback?: (reason: CanvasFrameFallback | null) => void;\n  /**\n   * Told where the site's own layout draws around the page whenever that\n   * changes: as the site's page arrives, as its layout draws a part later or\n   * takes one away, and with nothing drawn once the frame is gone. Never told\n   * on the editor's blank page, which has no layout of its own.\n   *\n   * @experimental Settles with the editor's notices about the site's layout.\n   */\n  onSiteChrome?: (drawn: SiteChromeDrawn) => void;\n  className?: string;\n}\n\n/**\n * What `useCanvasFrame` answers with, under the component's name, so a host\n * importing one `CanvasFrame` has both the component and what it provides.\n *\n * @experimental\n */\nexport type CanvasFrame = CanvasFrameReading;\n\n/**\n * The canvas's frame.\n *\n * Registers its iframe with the `CanvasFrameProvider` above it, so the panels,\n * the toolbar and the keys outside the canvas see the frame too. With no\n * provider above that waits for one, it provides for itself, which is enough\n * for the canvas and the chrome drawn over it.\n *\n * @experimental\n */\nexport function CanvasFrame(props: CanvasFrameProps): React.JSX.Element {\n  const registration = useFrameRegistration();\n  if (registration !== null) return <FramedCanvas {...props} />;\n  return (\n    <CanvasFrameProvider>\n      <FramedCanvas {...props} />\n    </CanvasFrameProvider>\n  );\n}\n\nfunction FramedCanvas({\n  width,\n  height: statedHeight,\n  zoom = FIT_ZOOM,\n  onScale,\n  title,\n  children,\n  source = SRCDOC_FRAME_SOURCE,\n  onSourceFallback,\n  onSiteChrome,\n  className,\n  ...rest\n}: CanvasFrameProps): React.JSX.Element {\n  // The chrome drawn over the frame, apart from the markers the page's own\n  // document is given.\n  // The preview width control is the frame's own, never a page marker.\n  const { overlay, pinned, previewWidth, ...markers } = rest;\n  const stage = React.useRef<HTMLDivElement | null>(null);\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const layerContent = React.useRef<HTMLDivElement | null>(null);\n  /*\n   * The iframe as STATE, through a callback ref, so everything keyed on it\n   * runs once it exists. It is created once and kept: see the module docblock.\n   */\n  const [frame, setFrame] = React.useState<HTMLIFrameElement | null>(null);\n  const { shown, pending, refuse } = useShownSource(source, onSourceFallback);\n  const { page, mountPoint } = useFramePage(frame, shown, refuse);\n  const siteChrome = useSiteChrome(page, mountPoint, onSiteChrome);\n\n  const region = useRegionSize(stage);\n  const { height, scale } = frameLayout(width, statedHeight, region, zoom);\n  useReportedScale(scale, onScale);\n\n  /*\n   * Set while the preview width's handles are dragged: the drag resizes the\n   * page's frame each animation frame, and its viewport is read again once\n   * the width settles rather than at every step, so nothing that reads the\n   * frame renders per pixel.\n   */\n  const resizing = React.useRef(false);\n  // Counted at each drag's end, so the viewport is read again then, even\n  // where the drag settles on the width it started at.\n  const [settled, setSettled] = React.useState(0);\n  const viewport = useFrameViewport(frame, page, width, height, {\n    held: resizing,\n    settled,\n  });\n  useRegistered(frame, scale, viewport);\n\n  usePageMarkers(frame, page, mountPoint, markers);\n  useLayerPlacement(frame, page, mountPoint, layer, layerContent, scale);\n\n  return (\n    <div ref={stage} className={cn(\"nx-canvas-stage\", className)}>\n      <div\n        className=\"nx-canvas-frame\"\n        {...{ [CANVAS_FRAME_BOX_ATTRIBUTE]: \"\" }}\n        // The PAINTED size, so the region around it scrolls exactly as far as\n        // the frame reaches and centres it when it is smaller.\n        style={{ width: width * scale, height: height * scale }}\n      >\n        <iframe\n          ref={setFrame}\n          className=\"nx-canvas-frame__page\"\n          title={canvasFrameTitle(title)}\n          {...frameDocumentProps(shown, pending)}\n          // Laid out at the device's size and painted at the zoom, in the\n          // colour scheme of the theme the page is shown in, where one is.\n          style={{\n            width,\n            height,\n            transform: `scale(${String(scale)})`,\n            ...frameColorScheme(markers.theme),\n          }}\n        />\n        <ChromeLayer\n          layer={layer}\n          content={layerContent}\n          cues={\n            <SiteChromeCues\n              frame={frame}\n              page={page}\n              elements={siteChrome}\n              scale={scale}\n            />\n          }\n          overlay={overlay}\n          pinned={pinned}\n        />\n        {/* At the box's edges, over the layer, so the handles sit at the\n            page's edges and beside it in the well. */}\n        <PreviewWidthEdges\n          control={previewWidth}\n          width={width}\n          scale={scale}\n          onDragging={active => {\n            resizing.current = active;\n            if (!active) setSettled(count => count + 1);\n          }}\n        />\n      </div>\n      <FramePage mountPoint={mountPoint}>{children}</FramePage>\n    </div>\n  );\n}\n\n/**\n * The layer the editor's chrome is drawn in over the frame: the site's chrome\n * cues, the content box the page's scroll moves (`overlay`), and the chrome\n * held at the viewport (`pinned`). Placed by `useLayerPlacement`.\n */\nfunction ChromeLayer({\n  layer,\n  content,\n  cues,\n  overlay,\n  pinned,\n}: {\n  layer: React.RefObject<HTMLDivElement | null>;\n  content: React.RefObject<HTMLDivElement | null>;\n  cues: React.ReactNode;\n  overlay: React.ReactNode;\n  pinned: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <div\n      ref={layer}\n      className=\"nx-canvas-layer\"\n      {...{ [CANVAS_LAYER_ATTRIBUTE]: \"\" }}\n    >\n      {cues}\n      <div ref={content} className=\"nx-canvas-layer__content\">\n        {overlay}\n      </div>\n      {/* Over the viewport itself: the layer runs CHROME_BLEED past it on\n          every side, so this is inset by as much. Never moved with the page's\n          scroll, unlike the content box above. Empty, and taking no presses,\n          while nothing is pinned. */}\n      <div className=\"nx-canvas-layer__pinned\" style={{ inset: CHROME_BLEED }}>\n        {pinned}\n      </div>\n    </div>\n  );\n}\n\n/**\n * The iframe ELEMENT's own `color-scheme`, for the theme the page is shown in.\n *\n * A frame's `prefers-color-scheme` follows the used `color-scheme` of the\n * element that embeds it, as the CSS Working Group resolved, so stating the\n * theme here is what can turn a page the site serves, whose own CSS asks\n * `@media (prefers-color-scheme)`, to that theme too; the `data-nx-theme`\n * marker reaches only the site's variables. Driven by the same `theme` the\n * marker is, so the two cannot disagree. Only `light` and `dark` are schemes:\n * any other theme, or none, states nothing, and the frame's sheet leaves the\n * scheme to the device, as a visitor's browser does.\n */\nfunction frameColorScheme(\n  theme: string | undefined\n): { colorScheme: \"light\" | \"dark\" } | Record<string, never> {\n  return theme === \"light\" || theme === \"dark\" ? { colorScheme: theme } : {};\n}\n\n/**\n * What the iframe is given to load its page: the site's page by URL, the\n * editor's blank page as `srcdoc`, or nothing while the choice is pending.\n */\nfunction frameDocumentProps(\n  source: CanvasFrameSource,\n  pending: boolean\n): { src: string } | { srcDoc: string } | Record<string, never> {\n  if (pending) return {};\n  return \"src\" in source ? { src: source.src } : { srcDoc: source.srcDoc };\n}\n\n/**\n * The page, with the frame's own sheet, portalled into the frame once its\n * page has loaded, and nothing before.\n */\nfunction FramePage({\n  mountPoint,\n  children,\n}: {\n  mountPoint: HTMLElement | null;\n  children?: React.ReactNode;\n}): React.JSX.Element | null {\n  if (mountPoint === null) return null;\n  return createPortal(\n    <>\n      <style>{CANVAS_FRAME_SHEET}</style>\n      {children}\n    </>,\n    mountPoint\n  );\n}\n\n/**\n * Hand the frame, and how it is drawn, up to the provider above, for\n * everything outside the canvas.\n */\nfunction useRegistered(\n  frame: HTMLIFrameElement | null,\n  scale: number,\n  viewport: FrameSize | null\n): void {\n  const registration = useFrameRegistration();\n  useIsomorphicLayoutEffect(() => {\n    if (registration === null || frame === null) return;\n    registration.register(frame);\n    return () => registration.register(null);\n  }, [registration, frame]);\n  useIsomorphicLayoutEffect(() => {\n    registration?.report({ scale, viewport });\n  }, [registration, scale, viewport]);\n}\n\n/**\n * The scale the frame is painted at: the chosen one, or the one fitting both\n * of its dimensions into the region.\n *\n * A chosen scale this canvas cannot paint at falls back to fitting, for the\n * reason `usableScale` gives.\n */\nfunction frameScale(\n  size: FrameSize,\n  region: Partial<FrameSize> | undefined,\n  zoom: CanvasZoom\n): number {\n  if (zoom.kind === \"fixed\") {\n    const chosen = usableScale(zoom.scale);\n    if (chosen !== null) return chosen;\n  }\n  return frameFitScale(size, region ?? {});\n}\n\n/**\n * The height the page is laid out at and the scale it is painted at.\n *\n * A height the host states is laid out as given and fitted both ways; without\n * one, the frame fills the region's height at any zoom and the page scrolls\n * inside it (see `frameFillingRegion`).\n */\nfunction frameLayout(\n  width: number,\n  statedHeight: number | undefined,\n  region: Partial<FrameSize> | undefined,\n  zoom: CanvasZoom\n): { readonly height: number; readonly scale: number } {\n  if (statedHeight === undefined) {\n    return frameFillingRegion(width, region, zoom);\n  }\n  return {\n    height: statedHeight,\n    scale: frameScale({ width, height: statedHeight }, region, zoom),\n  };\n}\n\n/**\n * The source the frame shows: the one it was given, or the blank page in its\n * place when a site's page cannot be shown, with the way to say it cannot.\n *\n * A refusal is held against the source it was made for, so a new source is\n * tried afresh. A page on another origin is refused before it is ever loaded:\n * its document could be neither reached nor drawn into, and loading it would\n * still run its scripts.\n *\n * Which origin the editor is on is known only in the browser. Until then —\n * on the server, and in the render that hydrates what the server sent — a\n * site's page is `pending`: neither it nor the blank page is asked for, so\n * the server's markup and the browser's first render agree, and the frame\n * loads once the origin is known.\n */\nfunction useShownSource(\n  source: CanvasFrameSource,\n  onSourceFallback: CanvasFrameProps[\"onSourceFallback\"]\n): {\n  shown: CanvasFrameSource;\n  pending: boolean;\n  refuse: (reason: CanvasFrameFallback) => void;\n} {\n  const editorOrigin = React.useSyncExternalStore(\n    staysTheSame,\n    readEditorOrigin,\n    noOriginYet\n  );\n  const pending = \"src\" in source && editorOrigin === null;\n  const [refusal, setRefusal] = React.useState<{\n    readonly source: CanvasFrameSource;\n    readonly reason: CanvasFrameFallback;\n  } | null>(null);\n  const reason: CanvasFrameFallback | null =\n    \"src\" in source && !pending && !onOrigin(source.src, editorOrigin)\n      ? \"other-origin\"\n      : refusal !== null && refusal.source === source\n        ? refusal.reason\n        : null;\n  const refuse = React.useCallback(\n    (refused: CanvasFrameFallback) => setRefusal({ source, reason: refused }),\n    [source]\n  );\n  const latest = React.useRef(onSourceFallback);\n  React.useEffect(() => {\n    latest.current = onSourceFallback;\n  }, [onSourceFallback]);\n  const asked = \"src\" in source;\n  React.useEffect(() => {\n    // Only a site's page can be fallen back from; the blank page is the\n    // fallback, so a host given that has nothing to be told.\n    if (asked) latest.current?.(reason);\n  }, [asked, reason]);\n  return {\n    shown: reason === null ? source : SRCDOC_FRAME_SOURCE,\n    pending,\n    refuse,\n  };\n}\n\n/** The editor's origin never changes while it runs, so nothing to hear. */\nfunction staysTheSame(): () => void {\n  return () => undefined;\n}\n\n/** The editor window's own origin, read in the browser. */\nfunction readEditorOrigin(): string | null {\n  return typeof location === \"undefined\" ? null : location.origin;\n}\n\n/** On the server, and while hydrating, the origin is not known yet. */\nfunction noOriginYet(): null {\n  return null;\n}\n\n/**\n * Whether a URL is on the editor's own origin, so the frame's document will be\n * one the editor can reach.\n */\nfunction onOrigin(src: string, origin: string | null): boolean {\n  if (origin === null) return false;\n  try {\n    return new URL(src, origin).origin === origin;\n  } catch {\n    return false;\n  }\n}\n\n/** The frame's page, and where in it the canvas mounts, once both exist. */\ninterface FramePageReading {\n  readonly page: Document | null;\n  readonly mountPoint: HTMLElement | null;\n}\n\nconst NO_PAGE: FramePageReading = { page: null, mountPoint: null };\n\n/** The document a frame holds, or `null` where it cannot be reached. */\nfunction documentOf(frame: HTMLIFrameElement): Document | null {\n  try {\n    return frame.contentDocument;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * The frame's page once it is the source's and ready, with its mount point,\n * or neither before.\n *\n * Held as state and re-read on every `load`, because a frame replaces its\n * document as it loads — the blank page it starts with gives way to the\n * source's, and a reload builds another — and nothing about that renders.\n * Read once on mount as well, for a frame that finished loading before the\n * listener was there to hear it.\n *\n * A site's page is read again whenever it says its readiness changed, since\n * the site's own React root decides when the mount point is there to portal\n * into, and can replace it. One that is not the canvas route, or that never\n * says it is ready, is refused, which shows the blank page in its place.\n */\nfunction useFramePage(\n  frame: HTMLIFrameElement | null,\n  source: CanvasFrameSource,\n  refuse: (reason: CanvasFrameFallback) => void\n): FramePageReading {\n  const [reading, setReading] = React.useState<FramePageReading>(NO_PAGE);\n  useIsomorphicLayoutEffect(() => {\n    if (frame === null) return;\n    let unwatch: (() => void) | null = null;\n    const wait = readinessDeadline(\n      frame.ownerDocument.defaultView,\n      () => {\n        const now = documentOf(frame);\n        return !(\"src\" in source && now !== null && source.ready(now));\n      },\n      () => refuse(\"not-ready\")\n    );\n    const show = (doc: Document | null): void => {\n      const mountPoint =\n        doc !== null && source.ready(doc) ? source.mountPoint(doc) : null;\n      const next = mountPoint === null ? NO_PAGE : { page: doc, mountPoint };\n      setReading(current =>\n        current.page === next.page && current.mountPoint === next.mountPoint\n          ? current\n          : next\n      );\n    };\n    // `loaded` is whether a `load` just reported this document: see\n    // `readSitePage`.\n    const read = (loaded: boolean): void => {\n      unwatch?.();\n      unwatch = null;\n      if (loaded) wait.disarm();\n      const doc = documentOf(frame);\n      if (\"src\" in source) {\n        unwatch = readSitePage(doc, loaded, source, { show, wait, refuse });\n      } else {\n        show(doc);\n      }\n    };\n    const onLoad = (): void => read(true);\n    read(false);\n    frame.addEventListener(\"load\", onLoad);\n    return () => {\n      unwatch?.();\n      wait.disarm();\n      frame.removeEventListener(\"load\", onLoad);\n    };\n  }, [frame, source, refuse]);\n  return reading;\n}\n\n/** What reading a site's page in the frame acts through. */\ninterface SitePageReader {\n  readonly show: (doc: Document | null) => void;\n  readonly wait: { arm: () => void; disarm: () => void };\n  readonly refuse: (reason: CanvasFrameFallback) => void;\n}\n\n/**\n * Read the frame's document as a site's page: show it once it is the source's\n * and ready, wait for it within the deadline, or refuse it. Answers the way to\n * stop watching its readiness, when it is the route's page.\n *\n * `loaded` is whether a `load` just reported this document. Read on mount\n * instead, a page at another address is the one an earlier source left behind\n * while this one's request is on its way — never this source's, however ready\n * it looks — and a page that is not the route's may be the empty one every\n * frame starts with, so both are waited for rather than refused.\n */\nfunction readSitePage(\n  doc: Document | null,\n  loaded: boolean,\n  source: SiteFrameSource,\n  { show, wait, refuse }: SitePageReader\n): (() => void) | null {\n  if (!loaded && leftBehind(doc, source.src)) {\n    show(null);\n    wait.arm();\n    return null;\n  }\n  if (doc === null || !source.served(doc)) {\n    show(null);\n    if (!loaded) wait.arm();\n    else refuse(doc === null ? \"other-origin\" : \"not-served\");\n    return null;\n  }\n  // Ready, or waiting for readiness again: the site's root can take the\n  // mount point away without the frame loading anything.\n  const settle = (): void => {\n    show(doc);\n    if (source.ready(doc)) wait.disarm();\n    else wait.arm();\n  };\n  const unwatch = source.watch(doc, settle);\n  settle();\n  return unwatch;\n}\n\n/** Whether a document is a page other than the one `src` names. */\nfunction leftBehind(doc: Document | null, src: string): boolean {\n  return doc !== null && !isPageAt(doc.URL, doc.baseURI, src);\n}\n\n/**\n * Whether a frame's document, at `address`, is the page `src` names: the same\n * address, whatever its fragment, `src` read against the document's `base`\n * when it is relative. The frame's starting page is at no address, so it never\n * is.\n *\n * @internal\n */\nexport function isPageAt(address: string, base: string, src: string): boolean {\n  try {\n    const want = new URL(src, base);\n    const have = new URL(address);\n    return (\n      have.origin === want.origin &&\n      have.pathname === want.pathname &&\n      have.search === want.search\n    );\n  } catch {\n    return false;\n  }\n}\n\n/**\n * The time a site's page has to be ready for the canvas, running while it is\n * not: armed once and left running when armed again, so waiting that keeps\n * being reported never pushes the deadline back.\n */\nfunction readinessDeadline(\n  view: Window | null,\n  stillWaiting: () => boolean,\n  giveUp: () => void\n): { arm: () => void; disarm: () => void } {\n  let timer: number | undefined;\n  const disarm = (): void => {\n    if (timer !== undefined) view?.clearTimeout(timer);\n    timer = undefined;\n  };\n  const arm = (): void => {\n    if (timer !== undefined || view === null) return;\n    timer = view.setTimeout(() => {\n      timer = undefined;\n      if (stillWaiting()) giveUp();\n    }, SITE_PAGE_READY_WITHIN_MS);\n  };\n  return { arm, disarm };\n}\n\n/**\n * The nearest ancestor that lays the stage out, skipping boxless wrappers.\n *\n * A `display: contents` element — the block menu's trigger wraps the canvas in\n * one — generates no box, and an observer on it reports a size of zero.\n */\nfunction layoutRegionOf(element: HTMLElement | null): HTMLElement | null {\n  const view = element?.ownerDocument.defaultView ?? null;\n  if (view === null) return null;\n  for (\n    let node = element?.parentElement ?? null;\n    node !== null;\n    node = node.parentElement\n  ) {\n    if (view.getComputedStyle(node).display !== \"contents\") return node;\n  }\n  return null;\n}\n\n/**\n * The room the region gives the frame: its CONTENT box, padding excluded, or\n * `undefined` until it has been measured.\n *\n * The region rather than the stage, because the stage grows with a frame\n * zoomed past the region and the fit would then be measured against a box the\n * frame itself made larger.\n */\nfunction useRegionSize(\n  stage: React.RefObject<HTMLElement | null>\n): FrameSize | undefined {\n  const [size, setSize] = React.useState<FrameSize | undefined>(undefined);\n  React.useEffect(() => {\n    const region = layoutRegionOf(stage.current);\n    // From the region's own window, the realm of what it observes.\n    const Sizes = region?.ownerDocument.defaultView?.ResizeObserver;\n    if (region === null || typeof Sizes !== \"function\") return;\n    const observer = new Sizes(entries => {\n      const box = entries[0]?.contentRect;\n      if (box === undefined) return;\n      setSize(current =>\n        current?.width === box.width && current.height === box.height\n          ? current\n          : { width: box.width, height: box.height }\n      );\n    });\n    observer.observe(region);\n    return () => observer.disconnect();\n  }, [stage]);\n  return size;\n}\n\n/**\n * Report the scale to the host, keyed on the value and on whether anyone is\n * listening, never on the reporter's identity: a host passing an inline\n * setter would otherwise re-report on every render.\n */\nfunction useReportedScale(\n  scale: number,\n  onScale: ((scale: number) => void) | undefined\n): void {\n  const latest = React.useRef(onScale);\n  React.useEffect(() => {\n    latest.current = onScale;\n  }, [onScale]);\n  const listening = onScale !== undefined;\n  React.useEffect(() => {\n    latest.current?.(scale);\n  }, [listening, scale]);\n}\n\n/**\n * The frame's viewport in its own pixels, read again when the page, the\n * frame's size or the window's resize changes it; not while `held`, as while\n * the preview width is dragged, and again each time `settled` counts a drag's\n * end.\n */\nfunction useFrameViewport(\n  frame: HTMLIFrameElement | null,\n  page: Document | null,\n  width: number,\n  height: number,\n  { held, settled }: { held: React.RefObject<boolean>; settled: number }\n): FrameSize | null {\n  const [viewport, setViewport] = React.useState<FrameSize | null>(null);\n  useIsomorphicLayoutEffect(() => {\n    if (frame === null || page === null) {\n      setViewport(null);\n      return;\n    }\n    const read = (): void => {\n      if (held.current) return;\n      const next = frameViewportOf(frame);\n      setViewport(current =>\n        current !== null &&\n        next !== null &&\n        current.width === next.width &&\n        current.height === next.height\n          ? current\n          : next\n      );\n    };\n    read();\n    const view = page.defaultView;\n    view?.addEventListener(\"resize\", read);\n    return () => view?.removeEventListener(\"resize\", read);\n  }, [frame, page, width, height, held, settled]);\n  return viewport;\n}\n\n/**\n * The markers on the frame's root element that rules inside the frame key on.\n *\n * - The site's theme, where a site's dark tokens are switched by it, stated\n *   on the canvas's mount point too (see `useMountThemeMarker`).\n * - The editor chrome class, so the one selector that gives an empty\n *   container its placeholder answers the same in the frame as in the\n *   editor's document. Empty containers always show, so nothing else about\n *   them is stated.\n * - The admin's tokens the page's own chrome reads (see `usePageTokens`).\n * - The page's language and direction: those named, else the page's own, else\n *   the editor document's, so a site page keeps the language it states.\n */\nfunction usePageMarkers(\n  frame: HTMLIFrameElement | null,\n  page: Document | null,\n  mountPoint: HTMLElement | null,\n  { theme, lang, dir }: Pick<CanvasFrameProps, \"theme\" | \"lang\" | \"dir\">\n): void {\n  usePageTokens(frame, page);\n  useMountThemeMarker(mountPoint, theme);\n  useIsomorphicLayoutEffect(() => {\n    const root = page?.documentElement;\n    if (root === undefined) return;\n    const editorRoot = frame?.ownerDocument.documentElement;\n    root.classList.add(BUILDER_CHROME_CLASS);\n    // Named, the editor's theme; otherwise whatever the page itself states,\n    // which on a page the site serves is the site's own, live mode.\n    stateMarker(root, DARK_MODE_ATTRIBUTE, theme);\n    stateMarker(root, \"lang\", lang, editorRoot?.lang);\n    stateMarker(root, \"dir\", dir, editorRoot?.dir);\n  }, [frame, page, theme, lang, dir]);\n}\n\n/**\n * The theme named for the page, stated on the element the canvas is mounted\n * into as well as on the page's root.\n *\n * A site's tokens follow the NEAREST `data-nx-theme` marker, so on a page the\n * site serves, a marker its layout puts on `<body>` or a wrapper around the\n * mount point would otherwise outrank the root's and keep the canvas in the\n * site's mode. The mount point is below every marker of the site's layout and\n * above the canvas, and lives in the frame's document, so the editor's own\n * chrome never sees it. A marker a block states inside the canvas is nearer\n * still and keeps its say.\n *\n * Written only while a theme is named. Each run is undone when the theme or\n * the mount point changes, or the frame goes, so the element gets back what it\n * stated before (often nothing) and a mount point the site replaced keeps no\n * editor marker.\n */\nfunction useMountThemeMarker(\n  mountPoint: HTMLElement | null,\n  theme: string | undefined\n): void {\n  useIsomorphicLayoutEffect(() => {\n    if (mountPoint === null) return;\n    stateMarker(mountPoint, DARK_MODE_ATTRIBUTE, theme);\n    return () => stateMarker(mountPoint, DARK_MODE_ATTRIBUTE, undefined);\n  }, [mountPoint, theme]);\n}\n\n/**\n * What a page's root stated for each marker when the editor began writing\n * one, held only while the editor writes it, so writing none again gives the\n * page's own back.\n */\nconst PAGE_MARKERS = new WeakMap<Element, Map<string, string | undefined>>();\n\n/**\n * State a marker on a page's root, or on the canvas's mount point for the\n * theme: the one named, else the page's own, else the fallback where the page\n * states none.\n *\n * Only what the editor supplies is written. With nothing to write, the\n * attribute is left alone, so a site that switches its own mode after\n * hydrating keeps it, unless the editor had been writing one: then the page's\n * value from before that comes back, once.\n */\nfunction stateMarker(\n  root: Element,\n  name: string,\n  named: string | undefined,\n  fallback?: string\n): void {\n  let held = PAGE_MARKERS.get(root);\n  const own = held?.has(name)\n    ? held.get(name)\n    : (root.getAttribute(name) ?? undefined);\n  const value =\n    named ?? (own === undefined || own === \"\" ? fallback : undefined);\n  if (value === undefined || value === \"\") {\n    if (held?.has(name) !== true) return;\n    stateAttribute(root, name, own);\n    held.delete(name);\n    return;\n  }\n  if (held === undefined) {\n    held = new Map();\n    PAGE_MARKERS.set(root, held);\n  }\n  if (!held.has(name)) held.set(name, own);\n  root.setAttribute(name, value);\n}\n\n/** Set an attribute to a value, or remove it where there is none to state. */\nfunction stateAttribute(\n  element: Element,\n  name: string,\n  value: string | undefined\n): void {\n  if (value === undefined || value === \"\") element.removeAttribute(name);\n  else element.setAttribute(name, value);\n}\n\n/**\n * The admin's tokens the chrome drawn INSIDE the page reads: a header or\n * footer's tag, which holds the admin's words on the site's page, its outline, and the\n * region's own edge and faded content.\n *\n * The frame's document loads none of the admin's stylesheets, so these are\n * handed in as values, read where the frame sits in the editor. Each set is\n * written onto the region chrome that reads it and nowhere above, because a\n * custom property inherits: on the page's root, the admin's `--font-sans` or\n * `--radius-sm` would replace a site's own value of the same name across the\n * whole page. The region box takes only the editor's own names, since what it\n * holds is the site's content.\n */\nconst PAGE_CHROME_TOKENS: readonly {\n  readonly selector: string;\n  readonly tokens: readonly string[];\n}[] = [\n  {\n    // A header or footer's edge, and its outline and tag, which take the\n    // select hue for the page's ground as the block marks do.\n    selector: \".nx-canvas-region\",\n    tokens: [\n      \"--nx-builder-border\",\n      \"--nx-builder-select-on-light\",\n      \"--nx-builder-select-on-dark\",\n      \"--nx-builder-select-text-on-light\",\n      \"--nx-builder-select-text-on-dark\",\n      \"--nx-builder-halo\",\n    ],\n  },\n  {\n    selector: `.nx-canvas-region__content, [${SITE_CHROME_ATTRIBUTE}]`,\n    tokens: [\"--nx-builder-region-opacity\"],\n  },\n  {\n    // A collection list's note to its author holds the admin's words alone,\n    // so it may take the admin's face as well as its colours.\n    selector: \"[data-nx-list-diagnostic]\",\n    tokens: [\n      // The focus ring of the note's one action.\n      \"--nx-builder-select\",\n      \"--nx-builder-warning\",\n      \"--nx-builder-danger\",\n      \"--nx-builder-surface-raised\",\n      \"--nx-builder-text\",\n      \"--nx-builder-scheme\",\n      \"--font-sans\",\n      \"--radius-sm\",\n    ],\n  },\n  {\n    // An Entry content block's note to its author holds the admin's words\n    // alone, so it takes the admin's face.\n    selector: `[${ENTRY_CONTENT_NOTE_ATTRIBUTE}]`,\n    // Its face, and the red hue alone: every other colour of it is the\n    // page's own, so it reads on the page in either admin theme.\n    tokens: [\"--nx-builder-danger\", \"--font-sans\", \"--radius-sm\"],\n  },\n  {\n    // A list drawing its empty state holds the site's content, so its tag\n    // reads only the editor's own names.\n    selector: \"[data-nx-list-shows]\",\n    tokens: [\"--nx-builder-select\", \"--nx-builder-select-text\"],\n  },\n  {\n    // The band where an area has no region holds the admin's words and\n    // buttons alone, so it takes the admin's scheme, colours and face.\n    selector: `[${EMPTY_REGION_ATTRIBUTE}]`,\n    tokens: [\n      \"--nx-builder-scheme\",\n      \"--nx-builder-text\",\n      \"--nx-builder-text-muted\",\n      \"--nx-builder-surface-raised\",\n      \"--nx-builder-select\",\n      \"--nx-builder-select-text\",\n      \"--font-sans\",\n      \"--radius-sm\",\n    ],\n  },\n  {\n    // Its tag holds the admin's words alone, so it takes the admin's face.\n    selector: \".nx-canvas-region__tag\",\n    tokens: [\"--font-sans\"],\n  },\n];\n\n/** Marks the frame's sheet that carries the handed tokens. */\nconst PAGE_TOKENS_ATTRIBUTE = \"data-nx-page-chrome-tokens\";\n\n/** The page's sheet for the handed tokens, made the first time it is asked. */\nfunction tokenSheet(page: Document): CSSStyleSheet | null {\n  const found = page.head.querySelector<HTMLStyleElement>(\n    `style[${PAGE_TOKENS_ATTRIBUTE}]`\n  );\n  if (found !== null) return found.sheet;\n  const holder = page.createElement(\"style\");\n  holder.setAttribute(PAGE_TOKENS_ATTRIBUTE, \"\");\n  page.head.append(holder);\n  return holder.sheet;\n}\n\n/**\n * One rule of the token sheet: `selector`, declaring each of `tokens` that\n * has a value where the frame sits.\n */\nfunction writeTokenRule(\n  sheet: CSSStyleSheet,\n  from: CSSStyleDeclaration,\n  { selector, tokens }: (typeof PAGE_CHROME_TOKENS)[number]\n): void {\n  const rule = sheet.cssRules[\n    sheet.insertRule(`${selector} {}`, sheet.cssRules.length)\n  ] as CSSStyleRule | undefined;\n  if (rule?.style === undefined) return;\n  for (const token of tokens) {\n    const value = from.getPropertyValue(token).trim();\n    if (value !== \"\") rule.style.setProperty(token, value);\n  }\n}\n\n/**\n * Write each token's value where the frame sits onto the region chrome that\n * reads it, through the style rules of one sheet of the editor's own. Set\n * through the rules' declarations rather than as text, so a value is taken\n * as a value and can never close the rule it sits in.\n */\nfunction handTokens(frame: HTMLIFrameElement, page: Document): void {\n  const view = frame.ownerDocument.defaultView;\n  const sheet = tokenSheet(page);\n  if (view === null || sheet === null) return;\n  const from = view.getComputedStyle(frame);\n  while (sheet.cssRules.length > 0) sheet.deleteRule(0);\n  for (const scope of PAGE_CHROME_TOKENS) writeTokenRule(sheet, from, scope);\n}\n\n/**\n * Hand the page's region chrome the admin's tokens it reads, and again\n * whenever the admin's theme changes: the admin switches it by a class or an\n * attribute on an element around the editor (its root, its body or its own\n * wrapper), or the system's contrast preference\n * moves the border and muted text.\n */\nfunction usePageTokens(\n  frame: HTMLIFrameElement | null,\n  page: Document | null\n): void {\n  useIsomorphicLayoutEffect(() => {\n    const host = frame?.ownerDocument;\n    const view = host?.defaultView;\n    if (frame == null || page == null || host == null || view == null) return;\n    const hand = () => handTokens(frame, page);\n    hand();\n    const watch = new view.MutationObserver(hand);\n    /*\n     * Every ancestor of the frame, because only an ancestor's class or style\n     * can change what the frame inherits, and the admin's theme provider\n     * switches it on its own wrapper rather than on the root or the body.\n     * Each is watched alone rather than the whole document's subtree, which\n     * would re-read the tokens for every class change anywhere in the admin.\n     */\n    for (\n      let target: Element | null = frame.parentElement;\n      target !== null;\n      target = target.parentElement\n    ) {\n      watch.observe(target, {\n        attributes: true,\n        attributeFilter: [\"class\", \"style\", \"data-theme\"],\n      });\n    }\n    // Absent where there is no media to query, as in a test document.\n    const contrast = view.matchMedia?.(\"(prefers-contrast: more)\");\n    contrast?.addEventListener(\"change\", hand);\n    return () => {\n      watch.disconnect();\n      contrast?.removeEventListener(\"change\", hand);\n      page.head.querySelector(`style[${PAGE_TOKENS_ATTRIBUTE}]`)?.remove();\n    };\n  }, [frame, page]);\n}\n\n/** What the layer placement needs, once every part of it exists. */\ninterface LayerParts {\n  readonly frame: HTMLIFrameElement;\n  readonly box: HTMLDivElement;\n  readonly content: HTMLDivElement;\n  readonly mountPoint: HTMLElement;\n  readonly view: Window & typeof globalThis;\n}\n\n/** The layer placement's parts, or `null` while any is still missing. */\nfunction layerParts(\n  frame: HTMLIFrameElement | null,\n  page: Document | null,\n  mountPoint: HTMLElement | null,\n  box: HTMLDivElement | null,\n  content: HTMLDivElement | null\n): LayerParts | null {\n  const view = page?.defaultView ?? null;\n  if (frame === null || mountPoint === null || view === null) return null;\n  if (box === null || content === null) return null;\n  return { frame, box, content, mountPoint, view };\n}\n\n/**\n * Keep the chrome layer over the frame's viewport, and its content box over\n * the canvas root.\n *\n * Written to the elements' styles directly rather than through state: the\n * frame's scroll moves the root on every frame of a scroll, and a render per\n * scroll event would lag the chrome behind the page it marks.\n */\nfunction useLayerPlacement(\n  frame: HTMLIFrameElement | null,\n  page: Document | null,\n  mountPoint: HTMLElement | null,\n  layer: React.RefObject<HTMLDivElement | null>,\n  layerContent: React.RefObject<HTMLDivElement | null>,\n  scale: number\n): void {\n  useIsomorphicLayoutEffect(() => {\n    const parts = layerParts(\n      frame,\n      page,\n      mountPoint,\n      layer.current,\n      layerContent.current\n    );\n    if (parts === null) return;\n    const { box, content, view } = parts;\n    let root: HTMLElement | null = null;\n    let sizes: ResizeObserver | null = null;\n    let restyled: MutationObserver | null = null;\n\n    const place = (): void => {\n      /*\n       * The painted scale, measured, rather than the one asked for: the two\n       * are the same number by construction, and the mapping every piece of\n       * chrome uses reads the measured one.\n       */\n      const painted = framePaintedScale(parts.frame);\n      const origin = frameContentOrigin(\n        { x: 0, y: 0 },\n        frameInsetOf(parts.frame),\n        painted\n      );\n      const viewport = frameViewportOf(parts.frame);\n      // The viewport, and CHROME_BLEED past it on every side, where a ring\n      // outside a block flush with the page's edge is drawn; the content is\n      // moved back by as much, so nothing drawn in it moves.\n      box.style.left = `${String(origin.x - CHROME_BLEED)}px`;\n      box.style.top = `${String(origin.y - CHROME_BLEED)}px`;\n      box.style.width = `${String((viewport?.width ?? 0) * painted + 2 * CHROME_BLEED)}px`;\n      box.style.height = `${String((viewport?.height ?? 0) * painted + 2 * CHROME_BLEED)}px`;\n      if (root === null) {\n        content.hidden = true;\n        return;\n      }\n      content.hidden = false;\n      // The scheme the page is drawn in, so the marks over it take the hue for\n      // its ground rather than for the admin's theme.\n      // Judged from the ground the page paints, not from its `color-scheme`:\n      // a site offering a dark set declares `light dark` while showing a\n      // light page, and the dark hues are faint there.\n      box.setAttribute(PAGE_SCHEME_ATTRIBUTE, pageSchemeOf(root));\n      const at = pointToHost(rootInFrameViewport(root), {\n        origin: { x: 0, y: 0 },\n        scale: painted,\n      });\n      content.style.transform = `translate(${String(at.x + CHROME_BLEED)}px, ${String(at.y + CHROME_BLEED)}px)`;\n      content.style.width = `${String(root.offsetWidth * painted)}px`;\n      content.style.height = `${String(root.offsetHeight * painted)}px`;\n    };\n\n    const find = (): void => {\n      const found = parts.mountPoint.querySelector(`.${CANVAS_ROOT_CLASS}`);\n      const next = isHTMLElement(found) ? found : null;\n      if (next !== root) {\n        sizes?.disconnect();\n        restyled?.disconnect();\n        sizes = null;\n        restyled = null;\n        root = next;\n        // From the frame's window, the realm of the root it observes.\n        const Sizes = view.ResizeObserver;\n        if (root !== null && typeof Sizes === \"function\") {\n          sizes = new Sizes(place);\n          sizes.observe(root);\n          // The root can MOVE without changing size, when what is above it\n          // in a site's own layout grows — a banner, a header image loading —\n          // and only the page's own size says so.\n          sizes.observe(view.document.documentElement);\n          if (view.document.body !== null) sizes.observe(view.document.body);\n        }\n        // The root's own attributes say how the site's dark mode applies.\n        if (root !== null && Mutations !== undefined) {\n          restyled = new Mutations(place);\n          restyled.observe(root, { attributes: true });\n        }\n      }\n      place();\n    };\n\n    const Mutations =\n      typeof view.MutationObserver === \"function\"\n        ? view.MutationObserver\n        : undefined;\n    find();\n    const arrivals = Mutations === undefined ? null : new Mutations(find);\n    arrivals?.observe(parts.mountPoint, { childList: true });\n    // A site darkening with the system changes the page's scheme with nothing\n    // else changing.\n    const systemScheme = view.matchMedia?.(\"(prefers-color-scheme: dark)\");\n    systemScheme?.addEventListener(\"change\", place);\n    // A viewport's scroll is dispatched at its document.\n    page?.addEventListener(\"scroll\", place, { passive: true });\n    view.addEventListener(\"resize\", place);\n    return () => {\n      arrivals?.disconnect();\n      sizes?.disconnect();\n      restyled?.disconnect();\n      systemScheme?.removeEventListener(\"change\", place);\n      page?.removeEventListener(\"scroll\", place);\n      view.removeEventListener(\"resize\", place);\n    };\n  }, [frame, page, mountPoint, layer, layerContent, scale]);\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 px a length comes to at a given page width, for a plain length or a\n * fluid `clamp(min, preferred, max)`, and a fluid length's range. Used to\n * draw a spacing's preview at the desktop width, and to say a fluid one as\n * \"Fluid · 16–20px\". No React.\n *\n * Plain lengths are read by {@link lengthInPx}, the inspector's own reading,\n * so a value is measured the same way in both places. The preferred term of\n * a clamp may also hold `vw` and a sum or difference of terms\n * (`0.875rem + 0.5vw`), as the built-in spacing writes it.\n *\n * @module fluid-size\n */\nimport type { FluidRangeWidths, FluidSizes } from \"@nextlyhq/blocks-engine\";\n\n/**\n * The CSS pixels a root-relative length is at the browser's default size.\n *\n * `em` is read as `rem` is: what it resolves to depends on the element it is\n * used on, and a sample has no element, so the default size is the honest\n * single answer.\n */\nconst ROOT_PX = 16;\n\n/**\n * How many CSS pixels a length is, or `undefined` for one this cannot measure\n * without a page: a percentage, a viewport unit, `clamp()`, a keyword.\n *\n * One reading of a length for every sample that sizes itself by one, the\n * Design panel's type specimen and the inspector's bars, so the two draw the\n * same variable at the same scale.\n */\nexport function lengthInPx(value: string): number | undefined {\n  const match = /^(-?\\d*\\.?\\d+)(px|rem|em)?$/.exec(value.trim());\n  if (match === null) return undefined;\n  const amount = Number(match[1]);\n  const unit = match[2];\n  // Only zero may go without a unit; any other bare number is not a length.\n  if (unit === undefined) return amount === 0 ? 0 : undefined;\n  return unit === \"px\" ? amount : amount * ROOT_PX;\n}\n\n/** The smallest and largest a fluid length comes to, in px. */\nexport interface FluidRange {\n  readonly minPx: number;\n  readonly maxPx: number;\n}\n\nconst CLAMP = /^clamp\\(\\s*([^,]+),\\s*([^,]+),\\s*([^,]+)\\)$/i;\n\n/** One term at a page width: a length, or so many `vw`. */\nfunction termPx(term: string, width: number): number | undefined {\n  const vw = /^(-?\\d*\\.?\\d+)vw$/i.exec(term.trim());\n  if (vw !== null) return (Number(vw[1]) * width) / 100;\n  return lengthInPx(term);\n}\n\n/** A sum or difference of terms, as `0.875rem + 0.5vw` writes one. */\nfunction sumPx(expression: string, width: number): number | undefined {\n  const parts = expression.trim().split(/\\s+([+-])\\s+/);\n  let total = termPx(parts[0] ?? \"\", width);\n  for (let at = 1; at < parts.length && total !== undefined; at += 2) {\n    const term = termPx(parts[at + 1] ?? \"\", width);\n    if (term === undefined) return undefined;\n    total = parts[at] === \"-\" ? total - term : total + term;\n  }\n  return total;\n}\n\n/**\n * What a length comes to at a page `width`, in px: a plain length as it\n * is, a clamp held between its bounds; `undefined` for what cannot be read.\n */\nexport function pxAtWidth(value: string, width: number): number | undefined {\n  const clamp = CLAMP.exec(value.trim());\n  if (clamp === null) return sumPx(value, width);\n  const [min, preferred, max] = [clamp[1], clamp[2], clamp[3]].map(part =>\n    sumPx(part ?? \"\", width)\n  );\n  if (min === undefined || preferred === undefined || max === undefined) {\n    return undefined;\n  }\n  // As CSS works it out: the minimum wins where it is larger than the\n  // maximum, so `clamp(32px, 2vw, 16px)` is 32px.\n  return Math.max(min, Math.min(preferred, max));\n}\n\n/** A fluid length's range, from its clamp's bounds; `undefined` otherwise. */\nexport function fluidRange(value: string): FluidRange | undefined {\n  const clamp = CLAMP.exec(value.trim());\n  if (clamp === null) return undefined;\n  const minPx = lengthInPx(clamp[1] ?? \"\");\n  const maxPx = lengthInPx(clamp[3] ?? \"\");\n  return minPx === undefined || maxPx === undefined\n    ? undefined\n    : { minPx, maxPx };\n}\n\n// The value a size made with Fluid… takes is a rule of the stored data, so\n// it is the engine's; the editor reads it from there.\nexport {\n  DEFAULT_FLUID_RANGE,\n  fluidValue,\n  type FluidRangeWidths,\n  type FluidSizes,\n} from \"@nextlyhq/blocks-engine\";\n/**\n * The two sizes a written value comes to at the range's ends, rounded to\n * the px, to start \"Fluid…\" from on a value written by hand; `undefined`\n * for one that can't be read.\n */\nexport function nearestFluidSizes(\n  value: string,\n  range: FluidRangeWidths\n): FluidSizes | undefined {\n  const small = pxAtWidth(value, range.min);\n  const large = pxAtWidth(value, range.max);\n  return small === undefined || large === undefined\n    ? undefined\n    : { small: Math.round(small), large: Math.round(large) };\n}\n","/**\n * Style properties whose two stored forms an author picks between without\n * being asked which form they mean.\n *\n * `fontWeight` stores a keyword (`bold`) or a number (`700`), and\n * `lineHeight` a number (`1.5`) or a length (`24px`). The catalogue declares each as a union, and the panel used to draw a\n * \"form\" selector above the value: \"Font weight form: Keyword\" asked a\n * question the value itself answers. Folded, each takes one control, and the\n * form follows from what the author chose or typed.\n *\n * Only these. Where the form IS the choice, as one border radius against four\n * corners, the form selector stays; and `fontStyle` keeps its own controls,\n * buttons for its keywords and a field for a free value such as an oblique\n * angle, which a single list could not hold.\n *\n * @module style-folded\n */\n\nimport {\n  STYLE_CATALOG,\n  trimCssWhitespace,\n  type StyleLeaf,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { CSS_NUMBER, steppedValue } from \"./style-numeric\";\n\n/** How a folded property is edited. */\nexport type FoldedControl = \"font-weight\" | \"number-or-length\";\n\nconst FOLDED: Readonly<Record<string, FoldedControl>> = {\n  fontWeight: \"font-weight\",\n  lineHeight: \"number-or-length\",\n};\n\n/** The folded control for a catalogue property, or `undefined` for any other. */\nexport function foldedControlFor(property: string): FoldedControl | undefined {\n  return Object.hasOwn(FOLDED, property) ? FOLDED[property] : undefined;\n}\n\n/** One choice in a folded list: what is stored, and what it is called. */\nexport interface FoldedOption {\n  /** The select's own value, a string; {@link optionValue} gives the stored one. */\n  readonly key: string;\n  readonly label: string;\n  readonly value: StyleValue;\n}\n\n/**\n * The named weights, the numbers fonts are drawn at, then the two relative\n * keywords. `normal` and `bold` are the same weights as Regular 400 and Bold\n * 700, so they are offered as the numbers; a stored keyword still shows.\n */\nconst WEIGHTS: readonly FoldedOption[] = [\n  [\"Thin\", 100],\n  [\"Extra light\", 200],\n  [\"Light\", 300],\n  [\"Regular\", 400],\n  [\"Medium\", 500],\n  [\"Semibold\", 600],\n  [\"Bold\", 700],\n  [\"Extra bold\", 800],\n  [\"Black\", 900],\n].map(([name, weight]) => ({\n  key: `n:${weight}`,\n  label: `${name} ${weight}`,\n  value: weight as number,\n}));\n\nconst RELATIVE_WEIGHTS: readonly FoldedOption[] = [\n  { key: \"s:lighter\", label: \"Lighter\", value: \"lighter\" },\n  { key: \"s:bolder\", label: \"Bolder\", value: \"bolder\" },\n];\n\n/** What a stored keyword weight is called when it is shown. */\nconst KEYWORD_WEIGHT_NAMES: Readonly<Record<string, string>> = {\n  normal: \"Normal\",\n  bold: \"Bold\",\n};\n\n/**\n * The font weight list, with what is stored first when the list does not\n * already carry it: a keyword such as `bold`, or a weight such as `450`.\n */\nexport function fontWeightOptions(\n  stored: StyleValue | undefined\n): readonly FoldedOption[] {\n  const offered = [...WEIGHTS, ...RELATIVE_WEIGHTS];\n  const key = storedKey(stored);\n  if (key === undefined || offered.some(option => option.key === key)) {\n    return offered;\n  }\n  // The stored scalar as written; a keyword gets its word.\n  const written = key.slice(2);\n  const label = KEYWORD_WEIGHT_NAMES[written] ?? written;\n  return [{ key, label, value: stored as StyleValue }, ...offered];\n}\n\n/**\n * The select key a stored scalar is listed under, or `undefined` for none.\n *\n * Typed: `n:700` for the number and `s:700` for the text \"700\", which is not\n * the same value. Sharing one key, a weight stored as text would show as the\n * number it spells, and choosing that number could not repair it, since the\n * list would think it already chosen.\n */\nexport function storedKey(stored: StyleValue | undefined): string | undefined {\n  if (typeof stored === \"string\" && stored !== \"\") return `s:${stored}`;\n  if (typeof stored === \"number\") return `n:${stored}`;\n  return undefined;\n}\n\n/**\n * A line height as typed: a plain number is stored as a number (`1.5`, a\n * multiple of the font size), anything else as written (`24px`, `150%`,\n * `normal`), for the catalogue to accept or refuse. `null` for nothing typed.\n */\nexport function lineHeightFromText(text: string): StyleValue | null {\n  // CSS whitespace only: `String.prototype.trim` also strips a non-breaking\n  // space, which CSS reads as part of the value, and would clear on one alone.\n  const trimmed = trimCssWhitespace(text);\n  if (trimmed === \"\") return null;\n  // CSS's own number grammar, the one every numeric field reads: \"1e2\" is a\n  // number, and \"1.\" goes on as typed for the catalogue to refuse.\n  if (!CSS_NUMBER.test(trimmed)) return trimmed;\n  const number = Number(trimmed);\n  return Number.isFinite(number) ? number : trimmed;\n}\n\n/**\n * Where a drag on the line height's label starts: the text in the field, or,\n * while it is empty, the value it shows from another tier — as every number\n * field starts — so dragging an inherited `1.5` writes an override from 1.5.\n * `undefined` where that is not one number or one length.\n */\nexport function lineHeightScrubOrigin(\n  draft: string,\n  inherited: string | undefined\n): string | number | undefined {\n  const text = trimCssWhitespace(draft) === \"\" ? (inherited ?? \"\") : draft;\n  const value = lineHeightFromText(text);\n  const leaf = lineHeightLeafFor(text);\n  if (value === null || leaf === undefined) return undefined;\n  if (typeof value !== \"string\" && typeof value !== \"number\") return undefined;\n  return steppedValue(leaf, value, 0) === undefined ? undefined : value;\n}\n\n/**\n * The catalogue's leaf a typed line height belongs to, its number form or its\n * length form, so an arrow key steps it as that kind of value steps.\n */\nexport function lineHeightLeafFor(text: string): StyleLeaf | undefined {\n  const entry = STYLE_CATALOG.find(\n    candidate => candidate.property === \"lineHeight\"\n  );\n  if (entry === undefined || entry.shape.kind !== \"union\") return undefined;\n  const wanted =\n    typeof lineHeightFromText(text) === \"number\" ? \"number\" : \"dimension\";\n  return entry.shape.of.find((arm): arm is StyleLeaf => arm.kind === wanted);\n}\n","/**\n * The tokens studio's view of a site's token table, and the edits it makes.\n *\n * A token is a NAME the styling layer resolves — `color.primary` becomes\n * `--site-color-primary`, and every block referencing it follows when the value\n * changes. This module is the pure half of the panel that manages them: what to\n * show for each kind, what an edit produces, and what the engine will say about\n * the result. No DOM, so the rules below are testable without rendering, and\n * the panel above stays about layout.\n *\n * ## Identity is frozen; only the label moves\n *\n * The one rule this file exists to protect. A stored reference holds a token's\n * IDENTITY, and {@link renameSiteToken} pins that identity the first time a\n * token is renamed so it never tracks the label afterwards. Rename is therefore\n * safe here by construction — every existing reference goes on resolving and no\n * document is rewritten — which is not true of the tools this pattern comes\n * from: Figma variables and Tokens Studio key on the name, so both have to STAGE\n * alias rewiring for review before a rename can be applied.\n *\n * Getting it wrong is silent in the direction that loses work. Writing the NEW\n * name as the identity moves the custom property, every stored `$token` stops\n * resolving, and the page still renders — just without the style. Nothing\n * reports it, because an unresolved custom property invalidates its declaration\n * rather than raising. So every mutation here goes through the engine's own\n * helpers rather than composing a token literal.\n *\n * ## The engine judges values; this only asks\n *\n * Whether a value is usable, whether it contradicts its kind, whether two\n * tokens collide on one custom property — all of that is `emitTokenBlocks`'s\n * verdict, asked by emitting and reading what comes back. A second copy of\n * those rules here would agree on the cases someone thought of and diverge on\n * the rest, and the divergence is invisible: the studio would accept a token\n * the canvas silently drops.\n *\n * @module tokens-studio\n */\nimport {\n  checkTokenKind,\n  emitTokenBlocks,\n  tokenDisplayLabel,\n  tokenKindExample,\n  tokenLabelIssue,\n  MAX_TOKEN_LABEL_LENGTH,\n  MAX_TOKEN_NAME_LENGTH,\n  MAX_TOKEN_NAME_SEGMENTS,\n  tokenNamingProblem,\n  renameSiteToken,\n  tokenCustomProperty,\n  tokenIdentity,\n  type SiteToken,\n  type SiteTextMap,\n  type SiteTokenSet,\n  type TokenKind,\n  type TokenMode,\n  validateStyleValues,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  DEFAULT_FLUID_RANGE,\n  fluidValue,\n  type FluidRangeWidths,\n  type FluidSizes,\n} from \"../../styles/fluid-size\";\nimport { lineHeightFromText } from \"../../styles/style-folded\";\n\nimport {\n  colourOrder,\n  orderWithCopy,\n  renamedInOrder,\n  withoutIdentity,\n} from \"./colour-groups\";\n\n/**\n * What each kind is called in the interface.\n *\n * Written out rather than derived from the union, because a label is a piece of\n * copy and `fontFamily` is not one. Keyed by the kind so adding a kind to the\n * engine surfaces here as a type error rather than as a tab labelled with its\n * own identifier.\n */\nexport const TOKEN_KIND_LABELS: Readonly<Record<TokenKind, string>> = {\n  color: \"Colour\",\n  dimension: \"Size\",\n  fontFamily: \"Font\",\n  fontWeight: \"Weight\",\n  number: \"Number\",\n  shadow: \"Shadow\",\n  duration: \"Duration\",\n  custom: \"Custom\",\n};\n\n/**\n * An example value for a new token of each kind.\n *\n * A new row has to hold SOMETHING, and an empty value is refused by the emitter\n * — so a token created empty would arrive already broken, with an error the\n * author did not cause. These are the smallest valid value of each kind, chosen\n * to be obviously placeholder rather than plausibly deliberate.\n */\n/**\n * A new shadow: one soft layer under the box, so it shows from the start.\n * It is also the layer the shadow control's \"+ Add layer\" adds.\n */\nexport const NEW_SHADOW_VALUE = \"0 4px 12px rgba(0, 0, 0, 0.12)\";\n\nconst TOKEN_KIND_SEEDS: Readonly<Record<TokenKind, string>> = {\n  color: \"#000000\",\n  dimension: \"0px\",\n  fontFamily: \"sans-serif\",\n  fontWeight: \"400\",\n  number: \"0\",\n  // A shadow that draws nothing read as a mistake; one that shows is what an\n  // author starts building from.\n  shadow: NEW_SHADOW_VALUE,\n  duration: \"0ms\",\n  // NOT a CSS-wide keyword. `initial` passes the emitter and is written without\n  // complaint, and then behaves as the guaranteed-invalid value at SUBSTITUTION\n  // — so `var(--site-custom)` invalidates the declaration reading it instead of\n  // resolving to the word. A seed has to survive the whole road to the page,\n  // not only the write.\n  custom: \"0\",\n};\n\n/** One token as the studio draws it. */\nexport interface TokenRow {\n  /**\n   * WHERE this token sits in the stored list, and the handle every edit uses.\n   *\n   * Not the identity, which is the obvious choice and is wrong: a legacy or\n   * imported set can hold two entries with the SAME identity, and the read path\n   * keeps both deliberately so the engine's complaint about the collision is\n   * visible on the row that has it. Addressed by identity, every edit to the\n   * second row would resolve to the first — so the one state the studio exists\n   * to help an author repair would be the one state it cannot address.\n   */\n  /**\n   * Whether the ENGINE emitted this token, as `emitTokenBlocks` reports it.\n   *\n   * Carried rather than re-derived because the engine refuses on five separate\n   * conditions — a name that is not a token name, no light value, a value the\n   * guard rejects, a value that would fetch, and a collision on one custom\n   * property — and a surface restating any of them agrees today and describes\n   * a different stylesheet afterwards. A preview drawn for a token the page\n   * does not carry is exactly that disagreement made visible.\n   */\n  readonly written: boolean;\n  readonly at: number;\n  /**\n   * A React key that survives a removal elsewhere in the list.\n   *\n   * The position cannot be one: deleting any non-tail token shifts every\n   * following `at`, so React reuses the deleted row's component for its\n   * successor and the uncontrolled fields and the confirm state come with it —\n   * a successor showing the deleted token's values, still in removal\n   * confirmation, one click from removing the wrong token.\n   *\n   * The identity cannot be one either, for the reason `at` exists: two entries\n   * can share one. So the key is the identity plus which occurrence of it this\n   * is, which is unique always and stable under any removal that is not of the\n   * same identity — and when it IS, remounting is the correct answer, because\n   * the row's meaning has changed.\n   */\n  readonly key: string;\n  /** What references STORE. Never changes once a token has been renamed. */\n  readonly identity: string;\n  /** What the author reads and edits. */\n  readonly name: string;\n  readonly kind: TokenKind;\n  /** The value for the mode being shown, falling back to light. */\n  readonly value: string;\n  /**\n   * What this MODE itself holds, or `undefined` when it holds nothing.\n   *\n   * Distinct from {@link value}, which is what to display and therefore falls\n   * back. An editor comparing a typed value against the display cannot tell\n   * \"unchanged\" from \"pinned to the same value the fallback was giving\" — and\n   * the second is a real edit, the one that fixes a dark value in place before\n   * the light one is changed later.\n   */\n  readonly stored: string | undefined;\n  /** Whether the shown value belongs to this mode or is inherited from light. */\n  readonly inherited: boolean;\n  /**\n   * What the engine says about this token, empty when it is happy.\n   *\n   * Shown to the author rather than counted, because the messages name the\n   * repair — \"is a measurement, not a colour\" tells them what to type next, and\n   * a bare invalid flag does not.\n   */\n  readonly issues: readonly string[];\n}\n\n/** The tokens of one kind, in stored order, as rows. */\nfunction tokenRows(\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode = \"light\"\n): readonly TokenRow[] {\n  const set: SiteTokenSet = tokens ?? { tokens: [] };\n  const all = set.tokens ?? [];\n  /*\n   * Built ONCE for the whole set rather than rediscovered per row: asking \"who\n   * else compiles to my custom property\" with a linear scan inside a per-row\n   * call makes the projection quadratic, and a DTCG import is not bounded to a\n   * size where that stays invisible.\n   *\n   * And built from what the emitter actually WROTE, not from document order.\n   * A token refused for its name, a missing light value, an unusable value or\n   * a value that fetches never reaches `seen`, so it claims no property and a\n   * later token with the same one is emitted normally. Ranking by position\n   * handed the property to the refused token and told the written one that\n   * only the refused one survives — the opposite of the compiled page.\n   *\n   * `emitTokenBlocks` reports `emitted` precisely so this question has one\n   * answer; its own docblock says a caller re-deriving it \"would have to\n   * restate all five\" refusals and would drift the first time one changed.\n   */\n  const made = emitTokenBlocks(set, \":root\");\n  const claimed = firstByProperty(made.emitted);\n  /*\n   * Which tokens the engine actually WROTE, for anything downstream that must\n   * not describe a token the page does not carry. Same list, same call: asking\n   * \"is this written\" a second way is how the panel and the stylesheet come to\n   * disagree.\n   */\n  const written = new Set(made.emitted);\n  // Indexed against the WHOLE list, so `at` addresses the stored position\n  // rather than a position within any later grouping or filter.\n  const seen = new Map<string, number>();\n  return all.map((token, at) => {\n    const identity = tokenIdentity(token);\n    const nth = seen.get(identity) ?? 0;\n    seen.set(identity, nth + 1);\n    return rowOf(\n      token,\n      at,\n      nth === 0 ? identity : `${identity}#${nth}`,\n      claimed,\n      written,\n      mode\n    );\n  });\n}\n\n/**\n * The rows of ONE kind.\n *\n * Derived from {@link tokenRows} rather than projecting again, so a caller\n * asking for every kind pays for one pass over the set instead of one per\n * kind, and the two can never disagree about a row's key or its issues.\n */\nexport function tokenRowsFor(\n  tokens: SiteTokenSet | undefined,\n  kind: TokenKind,\n  mode: TokenMode = \"light\"\n): readonly TokenRow[] {\n  return tokenRows(tokens, mode).filter(row => row.kind === kind);\n}\n\nfunction rowOf(\n  token: SiteToken,\n  at: number,\n  key: string,\n  claimed: ReadonlyMap<string, SiteToken>,\n  written: ReadonlySet<SiteToken>,\n  mode: TokenMode\n): TokenRow {\n  const own = token.values[mode];\n  const collision = collisionFor(token, claimed);\n  return {\n    at,\n    key,\n    written: written.has(token),\n    stored: own,\n    identity: tokenIdentity(token),\n    name: token.name,\n    kind: token.kind,\n    value: own ?? token.values.light,\n    inherited: own === undefined,\n    issues:\n      collision === undefined\n        ? issuesOf(token)\n        : [collision, ...issuesOf(token)],\n  };\n}\n\n/**\n * What the engine reports about ONE token, emitted on its own.\n *\n * Alone rather than within the set, so the messages that come back are about\n * this token and no other — and so the answer does not have to be found by\n * matching message text against a name, which would be a copy of wording\n * nobody promised to keep. The one verdict this cannot reach that way is the\n * collision, which is a property of the SET; {@link collisionFor} asks it.\n */\nfunction issuesOf(token: SiteToken): readonly string[] {\n  return emitTokenBlocks({ tokens: [token] }, \":root\").issues.map(\n    issue => issue.message\n  );\n}\n\n/**\n * The other token this one would collide with, or `undefined`.\n *\n * Two identities can compose one custom property — `color.primary-dark` and\n * `color-primary.dark` both give `--site-color-primary-dark` — and the emitter\n * writes the first and REFUSES the second. An author who cannot see that is\n * editing a token whose value never reaches the page, so it is reported here\n * rather than left to be discovered on the canvas.\n *\n * `tokenCustomProperty` composes the key, so the normalisation stays the\n * engine's; only the pairwise comparison is done here.\n */\n/**\n * Which token each custom property belongs to.\n *\n * Takes the tokens the emitter WROTE, so a property is owned by whatever the\n * page actually resolves rather than by whatever came first in the stored\n * order. A refused token owns nothing, which is the whole point: it is not in\n * the emitted list to be found.\n */\nfunction firstByProperty(\n  emitted: readonly SiteToken[]\n): ReadonlyMap<string, SiteToken> {\n  const claimed = new Map<string, SiteToken>();\n  for (const token of emitted) {\n    const property = tokenCustomProperty(tokenIdentity(token), \"\");\n    if (!claimed.has(property)) claimed.set(property, token);\n  }\n  return claimed;\n}\n\nfunction collisionFor(\n  token: SiteToken,\n  claimed: ReadonlyMap<string, SiteToken>\n): string | undefined {\n  const property = tokenCustomProperty(tokenIdentity(token), \"\");\n  const first = claimed.get(property);\n  if (first === undefined || first === token) return undefined;\n  return `\"${token.name}\" and \"${first.name}\" both become \"${property}\", so only \"${first.name}\" is written.`;\n}\n\n/**\n * Why this name cannot be used, or `undefined`.\n *\n * The GRAMMAR is the engine's own rule, which is the same one a stored\n * `$token` reference is held to — so a table cannot hold a name that no\n * reference could spell. Checked before the edit rather than after, because the\n * emitter's answer to a bad name is to drop the token silently.\n */\nexport function tokenNameIssue(\n  tokens: SiteTokenSet | undefined,\n  at: number,\n  name: string\n): string | undefined {\n  const trimmed = name.trim();\n  if (trimmed === \"\") return \"A token needs a name.\";\n  // Asked of the token the rename would PRODUCE, not of the label alone. A\n  // rename keeps a working identity pinned, so a long label is fine — but where\n  // the current identity is one the engine cannot write, the rename re-pins to\n  // this label and it becomes the identity, which the emission cap does reach.\n  // Validating the label alone accepts an edit that still leaves the token\n  // dropped from CSS, which is the repair appearing to succeed and not.\n  const existing = tokens?.tokens?.[at];\n  const proposed =\n    existing === undefined\n      ? { name: trimmed }\n      : renameSiteToken(existing, trimmed);\n  const problem = tokenNamingProblem(proposed);\n  if (problem?.reason === \"grammar\") {\n    return 'A name is dot-separated words of letters, digits and dashes, like \"color.primary\".';\n  }\n  if (problem?.reason === \"depth\") {\n    return `A name holds at most ${MAX_TOKEN_NAME_SEGMENTS} dot-separated parts.`;\n  }\n  if (problem?.reason === \"length\") {\n    return `A name is at most ${MAX_TOKEN_NAME_LENGTH} characters when it is what the token is written under.`;\n  }\n  // Compared by the custom property each token is WRITTEN under, not by the\n  // name an author reads. The mapping is deliberately not injective — a dot and\n  // a dash both become a dash — so `color.primary-dark` and `color-primary.dark`\n  // are two legal names that land on one property, and the engine drops\n  // whichever it reaches second. A check on raw names accepts that edit and\n  // leaves a token silently unwritten.\n  const others = (tokens?.tokens ?? []).filter((_, index) => index !== at);\n\n  // Two questions, and neither answers the other. This one is what an author\n  // reads: two tokens answering to one name is a table nobody can use, whatever\n  // each is written under.\n  if (others.some(token => token.name === trimmed)) {\n    return `Another token is already called \"${trimmed}\".`;\n  }\n\n  // And this one is what the engine writes. The name-to-property mapping is\n  // deliberately not injective — a dot and a dash both become a dash — so\n  // `color.primary-dark` and `color-primary.dark` are two legal, visibly\n  // different names landing on one custom property, and the compiler drops\n  // whichever it reaches second. The name check above cannot see that.\n  const identityOf = (token: { name: string; id?: string }) =>\n    token.id ?? token.name;\n  const claimedIdentity = identityOf(proposed);\n  const claimed = tokenCustomProperty(claimedIdentity, \"\");\n  // Whether this row ALREADY shared its identity with another before the edit.\n  // That is a repair in progress — reporting it leaves the row unfixable\n  // whatever the author types — and it is a property of the row, not of the\n  // name being proposed. Deciding it from the PROPOSED identity instead\n  // suppresses the error whenever an edit newly claims another row's identity,\n  // which is the collision this check exists for.\n  const wasAlreadyTwinned =\n    existing !== undefined &&\n    others.some(token => identityOf(token) === identityOf(existing));\n\n  const clash = others.find(token => {\n    if (wasAlreadyTwinned && identityOf(token) === claimedIdentity)\n      return false;\n    return tokenCustomProperty(identityOf(token), \"\") === claimed;\n  });\n  return clash === undefined\n    ? undefined\n    : `\"${trimmed}\" is written under the same custom property as \"${clash.name}\".`;\n}\n\n/** Replace one token in the set, leaving every other entry untouched. */\nfunction withToken(\n  tokens: SiteTokenSet,\n  index: number,\n  token: SiteToken\n): SiteTokenSet {\n  const next = [...tokens.tokens];\n  next[index] = token;\n  return { ...tokens, tokens: next };\n}\n\n/**\n * The set with one token renamed, its identity pinned where it already was.\n *\n * Delegates to {@link renameSiteToken} rather than spreading a new name over\n * the token, which is the whole point: that helper is the ONE place the freeze\n * rule lives, and a second expression of it here would be one edit away from\n * writing the new name as the identity and silently breaking every reference.\n */\nexport function renameToken(\n  tokens: SiteTokenSet,\n  at: number,\n  name: string\n): SiteTokenSet {\n  const token = tokens.tokens[at];\n  if (token === undefined) return tokens;\n  return withToken(tokens, at, renameSiteToken(token, name.trim()));\n}\n\n/**\n * The set with one token's value changed, for one mode.\n *\n * Writing `dark` never disturbs `light`, because light is what a reader with no\n * mode set resolves and a token that lost it would vanish for them.\n */\nexport function setTokenValue(\n  tokens: SiteTokenSet,\n  at: number,\n  mode: TokenMode,\n  value: string\n): SiteTokenSet {\n  const token = tokens.tokens[at];\n  if (token === undefined) return tokens;\n  return withToken(tokens, at, {\n    ...(mode === \"light\" ? withoutFluid(token) : token),\n    values: { ...token.values, [mode]: value },\n  });\n}\n\n/**\n * A token whose light value is being typed by hand: no longer the one its\n * fluid sizes made, so it keeps no sizes, and a change of the site's fluid\n * range leaves it. Every write of a light value by hand goes through here.\n */\nfunction withoutFluid(token: SiteToken): SiteToken {\n  const { fluid: _made, ...rest } = token;\n  return rest;\n}\n\n/** The site's fluid range: its own, else 360px to 1280px. */\nexport function fluidRangeOf(tokens: SiteTokenSet): FluidRangeWidths {\n  return tokens.fluidRange ?? DEFAULT_FLUID_RANGE;\n}\n\n/**\n * The set with a new fluid range, and every size made with \"Fluid…\" made\n * again across it from its own two sizes, so each still reads the same at\n * the smallest and the largest screen. A fluid value written by hand, the\n * built-in spacing among them, has no sizes and is left as it is. One set,\n * so the range and the sizes it remakes are saved and undone together.\n */\nexport function setFluidRange(\n  tokens: SiteTokenSet,\n  range: FluidRangeWidths\n): SiteTokenSet {\n  return {\n    ...tokens,\n    fluidRange: { min: range.min, max: range.max },\n    tokens: tokens.tokens.map(token =>\n      token.fluid === undefined\n        ? token\n        : {\n            ...token,\n            values: { ...token.values, light: fluidValue(token.fluid, range) },\n          }\n    ),\n    // A Site text row's own size made with Fluid… is remade across the\n    // range too, in the same edit.\n    ...(tokens.siteText === undefined\n      ? {}\n      : { siteText: siteTextAcross(tokens.siteText, range) }),\n  };\n}\n\n/** Site text with each row's own fluid size remade across a range. */\nfunction siteTextAcross(\n  siteText: SiteTextMap,\n  range: FluidRangeWidths\n): SiteTextMap {\n  return Object.fromEntries(\n    Object.entries(siteText).map(([role, row]) => [\n      role,\n      row?.fluid === undefined\n        ? row\n        : { ...row, fontSize: fluidValue(row.fluid, range) },\n    ])\n  );\n}\n\n/**\n * The set with a size made fluid from two sizes: its light value grows\n * from `small` on the range's smallest screen to `large` on its largest,\n * and the two sizes are kept beside it so it can be made again when the\n * site's fluid range changes.\n */\nexport function setFluidSize(\n  tokens: SiteTokenSet,\n  at: number,\n  sizes: FluidSizes,\n  range: FluidRangeWidths\n): SiteTokenSet {\n  const token = tokens.tokens[at];\n  if (token === undefined) return tokens;\n  return withToken(tokens, at, {\n    ...token,\n    values: { ...token.values, light: fluidValue(sizes, range) },\n    fluid: { small: sizes.small, large: sizes.large },\n  });\n}\n\n/** What a line height that cannot be stored is told, in words. */\nconst LINE_HEIGHT_REFUSAL =\n  \"A line height is a number like 1.4, or a length like 24px.\";\n\n/**\n * What a dark line height is told when it would need a kind other than\n * light's. A token has one kind, and a number token refuses a length as surely\n * as a length token refuses a number; the light value is the one that sets it.\n */\nexport const LINE_HEIGHT_MIXED =\n  \"Light and dark line heights are both numbers, like 1.4, or both lengths, like 24px. Use the light value first to change which.\";\n\n/** Whether a variable is a line height of the type scale, by its code name. */\nfunction isLineHeightToken(token: { name: string }): boolean {\n  return token.name.startsWith(LINE_HEIGHT_PREFIX);\n}\n\n/**\n * The kind a line height is held as for a value: a plain number (`1.4`, a\n * multiple of the font size, which is what scales with it) is a `number`\n * token, and anything else (`24px`, `150%`, `calc()`) a `dimension`. Read\n * with the inspector's own rule for a typed line height, so the two agree on\n * what a plain number is.\n */\nfunction lineHeightKindOf(value: string): TokenKind {\n  return typeof lineHeightFromText(value) === \"number\" ? \"number\" : \"dimension\";\n}\n\n/**\n * Why a value cannot be a line height, or nothing. Judged by the catalogue's\n * rule for a block's line height, the value a token here is read into, rather\n * than by a second list of what a line height may be.\n */\nfunction lineHeightValueIssue(value: string): string | undefined {\n  const typed = lineHeightFromText(value);\n  if (typed === null) return LINE_HEIGHT_REFUSAL;\n  const issues = validateStyleValues({ lineHeight: typed }, \"\", \"strict\");\n  return issues.some(issue => issue.severity === \"error\")\n    ? LINE_HEIGHT_REFUSAL\n    : undefined;\n}\n\n/** A number with no unit, other than zero, which a length needs a unit for. */\nconst BARE_NUMBER = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)$/;\n\n/** A zero, which is a length without a unit. */\nconst ZERO = /^[+-]?(?:0+(?:\\.0*)?|\\.0+)$/;\n\n/**\n * A length as typed, with `px` added to a bare number, as the block panel\n * adds it: `20` in a spacing variable means 20px to an author, and to CSS it\n * is no length at all. A zero needs no unit and is left as typed.\n */\nfunction withPixels(value: string): string {\n  return BARE_NUMBER.test(value) && !ZERO.test(value) ? `${value}px` : value;\n}\n\n/**\n * Why a value cannot be its variable's kind, in words with what to type\n * instead, or nothing. The engine's own kind check, the one a save runs, so\n * the field refuses exactly what the server would.\n */\nfunction kindValueIssue(kind: TokenKind, value: string): string | undefined {\n  const mismatch = checkTokenKind(kind, value);\n  if (mismatch === undefined) return undefined;\n  const example = tokenKindExample(kind);\n  return `\"${value}\" ${mismatch}.${example === undefined ? \"\" : ` Type ${example}.`}`;\n}\n\n/** What writing a variable's value comes to: the new set, or why not. */\nexport type TokenValueWrite =\n  | {\n      readonly tokens: SiteTokenSet;\n      /** Something the write changed beyond the field, said in words. */\n      readonly note?: string;\n    }\n  | { readonly issue: string };\n\n/** What the author is told when a light line height's new kind drops dark. */\nexport const DARK_FOLLOWS_LIGHT = \"Dark now follows the light value.\";\n\n/**\n * The set with one variable's value changed for one mode, or why it cannot be.\n *\n * Every variable but one is {@link setTokenValue}. A line height is the one\n * value that is right as a plain number or as a length, so its KIND follows\n * what is written: held as a `dimension`, `1.4` is a number where a length\n * belongs, and the save is refused for it. A value no line height can be is\n * refused here, in words, rather than stored for the page to drop.\n *\n * The LIGHT value sets the kind. A light edit of the other kind drops a dark\n * value that no longer fits, so dark follows light, and says so; a dark edit\n * of a kind other than light's is refused. Otherwise, with both modes set as\n * lengths, neither could be the first to become a number.\n */\nexport function writeTokenValue(\n  tokens: SiteTokenSet,\n  at: number,\n  mode: TokenMode,\n  value: string\n): TokenValueWrite {\n  const token = tokens.tokens[at];\n  if (token === undefined) return { tokens };\n  if (!isLineHeightToken(token)) {\n    const written = token.kind === \"dimension\" ? withPixels(value) : value;\n    const issue = kindValueIssue(token.kind, written);\n    return issue === undefined\n      ? { tokens: setTokenValue(tokens, at, mode, written) }\n      : { issue };\n  }\n  const issue = lineHeightValueIssue(value);\n  if (issue !== undefined) return { issue };\n  const kind = lineHeightKindOf(value);\n  if (mode === \"dark\") {\n    if (lineHeightKindOf(token.values.light) !== kind) {\n      return { issue: LINE_HEIGHT_MIXED };\n    }\n    return {\n      tokens: withToken(tokens, at, {\n        ...token,\n        // The kind both values are read as, set rather than kept: a legacy\n        // unitless zero held as a length is a number to this rule, and a\n        // number dark beside it would otherwise be refused as not a length.\n        kind,\n        values: { ...token.values, dark: value },\n      }),\n    };\n  }\n  const dark = token.values.dark;\n  const darkFits = dark === undefined || lineHeightKindOf(dark) === kind;\n  return {\n    tokens: withToken(tokens, at, {\n      ...withoutFluid(token),\n      kind,\n      values: darkFits ? { ...token.values, light: value } : { light: value },\n    }),\n    ...(darkFits ? {} : { note: DARK_FOLLOWS_LIGHT }),\n  };\n}\n\n/**\n * The set with one token's dark value REMOVED, so it follows light again.\n *\n * Distinct from writing the light value into dark, which looks identical on\n * screen and is not the same document: an explicit dark value stops tracking\n * later edits to light, so the two drift apart the next time anyone changes the\n * light one.\n */\nexport function clearDarkValue(tokens: SiteTokenSet, at: number): SiteTokenSet {\n  const token = tokens.tokens[at];\n  if (token === undefined) return tokens;\n  return withToken(tokens, at, {\n    ...token,\n    values: { light: token.values.light },\n  });\n}\n\n/**\n * The set without the token at this position. Any reference stops resolving.\n *\n * By POSITION rather than by identity, so removing one of two entries that\n * share an identity removes exactly one. Filtering on the identity would take\n * both, which is the opposite of what an author repairing a collision means.\n */\nexport function removeToken(tokens: SiteTokenSet, at: number): SiteTokenSet {\n  const removed = tokens.tokens[at];\n  // Its place in the colour order goes with it, so a later variable given\n  // its free name is not listed where it was.\n  const order =\n    removed === undefined\n      ? tokens.order\n      : withoutIdentity(tokens.order, removed);\n  return {\n    ...tokens,\n    tokens: tokens.tokens.filter((_, index) => index !== at),\n    ...(order === undefined ? {} : { order }),\n  };\n}\n\n/**\n * Every custom property the set's names and identities take. A name is folded\n * in beside the identity because a name is what a later rename freezes into\n * one.\n */\nfunction usedProperties(tokens: SiteTokenSet | undefined): Set<string> {\n  const used = new Set<string>();\n  for (const token of tokens?.tokens ?? []) {\n    used.add(tokenCustomProperty(token.name, \"\"));\n    used.add(tokenCustomProperty(tokenIdentity(token), \"\"));\n  }\n  return used;\n}\n\n/**\n * A name nothing in the set is using yet, based on the kind.\n *\n * Suffixed rather than randomised so a second colour token is `color.2` and not\n * a word the author has to read. Checked against IDENTITIES as well as names,\n * because a renamed token still holds its old name as its identity and a new\n * token taking that name would collide on the custom property.\n */\nfunction freeName(tokens: SiteTokenSet | undefined, kind: TokenKind): string {\n  // Compared as composed CUSTOM PROPERTIES, which is the real uniqueness\n  // boundary — `color-2` and `color.2` are different strings and both become\n  // `--site-color-2`, so a raw-name check hands back a name the emitter will\n  // refuse the moment it is written. Names are folded in alongside identities\n  // because a name is what a later rename freezes into one.\n  const used = usedProperties(tokens);\n  const free = (candidate: string): boolean =>\n    !used.has(tokenCustomProperty(candidate, \"\"));\n  const base = kind === \"custom\" ? \"custom\" : kind.toLowerCase();\n  if (free(base)) return base;\n  for (let n = 2; ; n += 1) {\n    const candidate = `${base}.${n}`;\n    if (free(candidate)) return candidate;\n  }\n}\n\n/**\n * The set with a new token of this kind appended, and where it landed.\n *\n * The position comes back because the panel has to address the new row, and\n * finding it afterwards by name or identity would break the moment two tokens\n * share one — which is a state this table can legitimately be in.\n *\n * Created with NO `id`, so its identity is its name until the first rename\n * freezes one. That is the same shape every token stored before `id` existed\n * has, which is why nothing needs migrating.\n */\nexport function addToken(\n  tokens: SiteTokenSet | undefined,\n  kind: TokenKind\n): { tokens: SiteTokenSet; at: number } {\n  const name = freeName(tokens, kind);\n  const token: SiteToken = {\n    name,\n    kind,\n    values: { light: TOKEN_KIND_SEEDS[kind] },\n  };\n  const base = tokens ?? { tokens: [] };\n  return {\n    tokens: { ...base, tokens: [...base.tokens, token] },\n    at: base.tokens.length,\n  };\n}\n\n/* ------------------------------------------------------------------ groups */\n\n/** The groups the Design panel shows variables in, in order. */\nexport type VariableGroup =\n  | \"colours\"\n  | \"type\"\n  | \"fonts\"\n  | \"spacing\"\n  | \"radius\"\n  | \"shadows\"\n  | \"content\"\n  | \"other\";\n\nconst VARIABLE_GROUPS: readonly VariableGroup[] = [\n  \"colours\",\n  \"type\",\n  \"fonts\",\n  \"spacing\",\n  \"radius\",\n  \"shadows\",\n  \"content\",\n  \"other\",\n];\n\n/** Each group's heading, in plain words. */\nconst VARIABLE_GROUP_LABELS: Readonly<Record<VariableGroup, string>> = {\n  colours: \"Colours\",\n  type: \"Type scale\",\n  fonts: \"Fonts and weights\",\n  spacing: \"Spacing\",\n  radius: \"Radius\",\n  shadows: \"Shadows\",\n  content: \"Content width\",\n  other: \"Other values\",\n};\n\n/** The Design panel's tabs, by kind, in the order they are shown. */\nexport type DesignTab = \"colours\" | \"type\" | \"spacing\" | \"styles\";\n\n/**\n * The variable groups each Design tab lists, in order: a font and a weight\n * sit with the type sizes, and what belongs to no other group ends Spacing.\n * Styles lists none.\n */\nexport const DESIGN_TAB_GROUPS: Readonly<\n  Record<DesignTab, readonly VariableGroup[]>\n> = {\n  colours: [\"colours\"],\n  type: [\"type\", \"fonts\"],\n  spacing: [\"spacing\", \"radius\", \"shadows\", \"content\", \"other\"],\n  styles: [],\n};\n\n/**\n * The groups narrowed to a search, matched on the name shown only: the code\n * name is hidden, so a match on it would list a row with nothing in it that\n * matches what was typed. The one rule for a variable search, so a count\n * beside a tab and the rows that tab lists cannot disagree.\n */\nexport function searchVariableGroups<\n  G extends { entries: readonly { label: string }[] },\n>(groups: readonly G[], needle: string): G[] {\n  const text = needle.trim().toLowerCase();\n  if (text === \"\") return [...groups];\n  return groups\n    .map(group => ({\n      ...group,\n      entries: group.entries.filter(entry =>\n        entry.label.toLowerCase().includes(text)\n      ),\n    }))\n    .filter(group => group.entries.length > 0);\n}\n\n/**\n * Every group with its heading, in the order the Design panel lists them, for\n * a list elsewhere that groups variables the same way.\n */\nexport function variableGroupHeadings(): readonly {\n  group: VariableGroup;\n  heading: string;\n}[] {\n  return VARIABLE_GROUPS.map(group => ({\n    group,\n    heading: VARIABLE_GROUP_LABELS[group],\n  }));\n}\n\n/** The code-name prefixes of a type size and of its line height. */\nconst SIZE_PREFIX = \"font-size.\";\nconst LINE_HEIGHT_PREFIX = \"line-height.\";\n\n/** Code-name prefixes of a spacing step, and of a radius. */\nconst SPACING_PREFIXES = [\"space.\", \"spacing.\", \"gap.\"];\n\n/**\n * A button's paddings, listed with the spacing in Design though they are\n * not offered to a block's spacing fields: they are the button's own.\n */\nconst BUTTON_PADDING_PREFIX = \"button.padding\";\n\n/** The site's content width, which has a group of its own. */\nconst CONTENT_WIDTH = \"content.width\";\nconst RADIUS_PREFIX = \"radius.\";\n\n/** The families a length variable belongs to, each made for its own fields. */\nexport type LengthFamily = \"font-size\" | \"line-height\" | \"spacing\" | \"radius\";\n\n/**\n * The family a length variable belongs to, read from its code name as the\n * Design panel groups it, or `undefined` for a length that names none (a\n * content width) and for anything that is not a length.\n *\n * The inspector offers each field its own family, so a padding lists the\n * spacing steps and a radius the radii; asked here so the Design panel's\n * groups and the inspector's lists cannot disagree about what a variable is.\n */\nexport function lengthFamilyOf(token: {\n  name: string;\n  kind: TokenKind;\n}): LengthFamily | undefined {\n  const type = typeScaleProperty(token);\n  if (type !== undefined) return type;\n  if (token.kind !== \"dimension\") return undefined;\n  if (token.name.startsWith(RADIUS_PREFIX)) return \"radius\";\n  return SPACING_PREFIXES.some(prefix => token.name.startsWith(prefix))\n    ? \"spacing\"\n    : undefined;\n}\n\n/**\n * The CSS property a type-scale variable is made for: `font-size` for a type\n * size, `line-height` for its paired line height, or `undefined` for any other\n * variable.\n *\n * Read from the code name, as the Design panel groups by it, and asked here\n * once so the panel's \"Type scale\" group and the inspector's offer of a type\n * size only where text is sized cannot disagree about what a type size is.\n */\nexport function typeScaleProperty(token: {\n  name: string;\n  kind: TokenKind;\n}): \"font-size\" | \"line-height\" | undefined {\n  if (token.kind !== \"dimension\" && token.kind !== \"number\") return undefined;\n  if (token.name.startsWith(SIZE_PREFIX)) return \"font-size\";\n  if (token.name.startsWith(LINE_HEIGHT_PREFIX)) return \"line-height\";\n  return undefined;\n}\n\n/**\n * Which group a variable belongs in: by kind for colours and shadows, and by\n * its code name for the lengths, since a size, a gap and a radius are all\n * dimensions.\n *\n * Exported so the inspector's variable list groups exactly as Design does.\n */\nexport function variableGroupOf(token: {\n  name: string;\n  kind: TokenKind;\n}): VariableGroup {\n  if (token.kind === \"color\") return \"colours\";\n  if (token.kind === \"shadow\") return \"shadows\";\n  if (token.name === CONTENT_WIDTH) return \"content\";\n  if (token.kind === \"fontFamily\" || token.kind === \"fontWeight\") {\n    return \"fonts\";\n  }\n  const family = lengthFamilyOf(token);\n  if (family === \"font-size\" || family === \"line-height\") return \"type\";\n  if (family === \"spacing\" || family === \"radius\") return family;\n  if (token.name.startsWith(BUTTON_PADDING_PREFIX)) return \"spacing\";\n  return \"other\";\n}\n\n/** One row of the Design panel. */\nexport interface VariableEntry {\n  /** The variable itself; for a type size, its font size. */\n  readonly row: TokenRow;\n  /** The plain name shown: the label, or one derived from the code name. */\n  readonly label: string;\n  /** A type size's line height, paired by name, when there is one. */\n  readonly lineHeight?: TokenRow;\n  /**\n   * What kind of variable it is, in words (\"radius\"), when another row is\n   * shown under the same name: `space.card` and `radius.card` both read\n   * \"Card\", and side by side nothing else says which is which.\n   */\n  readonly kindWord?: string;\n}\n\n/** A row's kind in words, as the panel tells two rows of one name apart. */\nfunction kindWordOf(row: TokenRow): string {\n  const family = lengthFamilyOf(row);\n  if (family === \"font-size\") return \"type size\";\n  if (family === \"line-height\") return \"line height\";\n  if (family !== undefined) return family;\n  // The kind's own label, as the panel names kinds elsewhere.\n  return TOKEN_KIND_LABELS[row.kind].toLowerCase();\n}\n\n/**\n * A group's rows with their kind added where two or more share a name,\n * ignoring case, as {@link labelClashes} compares names. Where the kinds\n * clash as well (`space.card` and `spacing.card`, both spacing steps called\n * \"Card\"), the code name, which no two variables share, tells them apart.\n */\nfunction withKindWhereNamesClash(\n  entries: readonly VariableEntry[]\n): VariableEntry[] {\n  const count = (keys: readonly string[]) => {\n    const seen = new Map<string, number>();\n    for (const key of keys) seen.set(key, (seen.get(key) ?? 0) + 1);\n    return seen;\n  };\n  const names = count(entries.map(entry => entry.label.toLowerCase()));\n  const kinds = count(\n    // JSON, so no label can run into its kind.\n    entries.map(entry =>\n      JSON.stringify([entry.label.toLowerCase(), kindWordOf(entry.row)])\n    )\n  );\n  return entries.map(entry => {\n    const name = entry.label.toLowerCase();\n    if ((names.get(name) ?? 0) < 2) return entry;\n    const kind = kindWordOf(entry.row);\n    const unique = (kinds.get(JSON.stringify([name, kind])) ?? 0) < 2;\n    return { ...entry, kindWord: unique ? kind : entry.row.name };\n  });\n}\n\n/**\n * Every group with its rows, Other included even when empty: the panel\n * decides what an empty group shows.\n *\n * A font size and the line height of the same name are ONE row, so a type\n * size reads as \"16 / 26\" the way designers write it. A line height with no\n * size of its own still gets a row.\n */\nexport function variableGroups(\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode = \"light\"\n): readonly {\n  group: VariableGroup;\n  heading: string;\n  entries: readonly VariableEntry[];\n}[] {\n  const rows = tokenRows(tokens, mode);\n  const stored = tokens?.tokens ?? [];\n  const lineHeights = new Map<string, TokenRow>();\n  for (const row of rows) {\n    if (row.name.startsWith(LINE_HEIGHT_PREFIX)) {\n      lineHeights.set(row.name.slice(LINE_HEIGHT_PREFIX.length), row);\n    }\n  }\n  const paired = new Set<TokenRow>();\n  const byGroup = new Map<VariableGroup, VariableEntry[]>(\n    VARIABLE_GROUPS.map(group => [group, []])\n  );\n  for (const row of rows) {\n    const token = stored[row.at];\n    if (token === undefined) continue;\n    const group = variableGroupOf(row);\n    const lineHeight =\n      group === \"type\" && row.name.startsWith(SIZE_PREFIX)\n        ? lineHeights.get(row.name.slice(SIZE_PREFIX.length))\n        : undefined;\n    if (lineHeight !== undefined) paired.add(lineHeight);\n    byGroup.get(group)?.push({\n      row,\n      label: tokenDisplayLabel(token),\n      ...(lineHeight === undefined ? {} : { lineHeight }),\n    });\n  }\n  // Within each group: rows of one name under two headings are told apart\n  // by the headings already.\n  return variableGroupHeadings().map(({ group, heading }) => ({\n    group,\n    heading,\n    entries: withKindWhereNamesClash(\n      inListedOrder(\n        group,\n        (byGroup.get(group) ?? []).filter(entry => !paired.has(entry.row)),\n        tokens\n      )\n    ),\n  }));\n}\n\n/**\n * A group's rows in the order they are listed: colours in the site's colour\n * order, the one every picker lists them in; any other kind as stored.\n */\nfunction inListedOrder(\n  group: VariableGroup,\n  entries: VariableEntry[],\n  tokens: SiteTokenSet | undefined\n): VariableEntry[] {\n  if (group !== \"colours\") return entries;\n  const rank = new Map(\n    colourOrder(tokens).map((identity, at) => [identity, at])\n  );\n  return [...entries].sort(\n    (a, b) =>\n      (rank.get(a.row.identity) ?? rank.size) -\n      (rank.get(b.row.identity) ?? rank.size)\n  );\n}\n\n/**\n * How many variables a search matches in each Design tab that lists\n * variables: the rows each tab would list, counted, through the same groups\n * and the same search the tab draws with, so a count beside a tab and the\n * rows under it cannot disagree.\n */\nexport function variableMatchesByTab(\n  tokens: SiteTokenSet | undefined,\n  needle: string\n): Readonly<Record<Exclude<DesignTab, \"styles\">, number>> {\n  const found = searchVariableGroups(variableGroups(tokens), needle);\n  const countOf = (tab: DesignTab): number =>\n    found\n      .filter(group => DESIGN_TAB_GROUPS[tab].includes(group.group))\n      .reduce((sum, group) => sum + group.entries.length, 0);\n  return {\n    colours: countOf(\"colours\"),\n    type: countOf(\"type\"),\n    spacing: countOf(\"spacing\"),\n  };\n}\n\n/* ------------------------------------------------------------------ labels */\n\n/**\n * Why this label cannot be given to the variable at `at`, or nothing.\n *\n * The engine's rule for a label, plus one of the panel's own: two variables\n * shown under one name cannot be told apart in a list or a picker.\n */\nexport function variableLabelIssue(\n  tokens: SiteTokenSet | undefined,\n  at: number,\n  label: string\n): string | undefined {\n  const trimmed = label.trim();\n  if (trimmed === \"\") return undefined;\n  const problem = tokenLabelIssue(trimmed);\n  if (problem !== undefined) return problem;\n  const wanted = trimmed.toLowerCase();\n  const clash = visibleNames(tokens).find(\n    shown => !shown.ats.includes(at) && shown.label.toLowerCase() === wanted\n  );\n  return clash === undefined\n    ? undefined\n    : `Another variable is already called \"${clash.label}\".`;\n}\n\n/**\n * Each variable as the panel shows it: its name, and the stored positions\n * behind it, two for a type size and its paired line height. Names are\n * compared here, over the rows an author sees, so a pair is one name.\n */\nfunction visibleNames(\n  tokens: SiteTokenSet | undefined\n): { label: string; ats: number[] }[] {\n  return variableGroups(tokens).flatMap(group =>\n    group.entries.map(entry => ({\n      label: entry.label,\n      ats:\n        entry.lineHeight === undefined\n          ? [entry.row.at]\n          : [entry.row.at, entry.lineHeight.at],\n    }))\n  );\n}\n\n/**\n * The names shown for more than one variable in a set, once each, ignoring\n * case, since \"Brand\" and \"brand\" cannot be told apart in a list.\n *\n * The same rule {@link variableLabelIssue} holds one edit to, asked of a whole\n * set, as an import produces one.\n */\nexport function labelClashes(tokens: SiteTokenSet): string[] {\n  const seen = new Set<string>();\n  const clashes = new Map<string, string>();\n  for (const { label } of visibleNames(tokens)) {\n    const key = label.toLowerCase();\n    if (seen.has(key)) clashes.set(key, label);\n    seen.add(key);\n  }\n  return [...clashes.values()];\n}\n\n/**\n * The set with one variable's label changed. A blank label is removed, so the\n * derived label shows again and nothing is stored for it.\n */\nexport function relabelToken(\n  tokens: SiteTokenSet,\n  at: number,\n  label: string\n): SiteTokenSet {\n  const token = tokens.tokens[at];\n  if (token === undefined) return tokens;\n  const { label: _previous, ...rest } = token;\n  const trimmed = label.trim();\n  return withToken(\n    tokens,\n    at,\n    trimmed === \"\" ? rest : { ...rest, label: trimmed }\n  );\n}\n\n/* --------------------------------------------------------------- adding */\n\n/** What a group's \"+\" can add. */\nexport type NewVariable =\n  | \"colour\"\n  | \"type size\"\n  | \"spacing\"\n  | \"radius\"\n  | \"shadow\"\n  | Exclude<TokenKind, \"color\" | \"shadow\">;\n\n/** The code-name prefix, kind and first value of each new variable. */\nconst NEW_VARIABLES: Readonly<\n  Record<NewVariable, { prefix: string; kind: TokenKind; value: string }>\n> = {\n  colour: { prefix: \"color\", kind: \"color\", value: \"#000000\" },\n  \"type size\": { prefix: \"font-size\", kind: \"dimension\", value: \"16px\" },\n  spacing: { prefix: \"space\", kind: \"dimension\", value: \"16px\" },\n  radius: { prefix: \"radius\", kind: \"dimension\", value: \"4px\" },\n  shadow: { prefix: \"shadow\", kind: \"shadow\", value: TOKEN_KIND_SEEDS.shadow },\n  dimension: { prefix: \"size\", kind: \"dimension\", value: \"0px\" },\n  fontFamily: { prefix: \"font\", kind: \"fontFamily\", value: \"sans-serif\" },\n  fontWeight: { prefix: \"weight\", kind: \"fontWeight\", value: \"400\" },\n  number: { prefix: \"number\", kind: \"number\", value: \"0\" },\n  duration: { prefix: \"duration\", kind: \"duration\", value: \"200ms\" },\n  custom: { prefix: \"custom\", kind: \"custom\", value: \"0\" },\n};\n\n/**\n * The line height a new type size starts with: unitless, so it is a multiple\n * of the size and follows it when the size changes, where a fixed length is\n * right for one size only. 1.25 sits between the tighter leading a heading\n * wants and the looser one body text wants, since a new size starts at 16px\n * and is usually given a heading's size next.\n */\nconst NEW_LINE_HEIGHT = \"1.25\";\n\n/** The words a new variable's code name is made from, before it is named. */\nconst NEW_WORDS: Readonly<Record<NewVariable, string>> = {\n  colour: \"new-colour\",\n  \"type size\": \"new-size\",\n  spacing: \"new-spacing\",\n  radius: \"new-radius\",\n  shadow: \"new-shadow\",\n  dimension: \"new-size\",\n  fontFamily: \"new-font\",\n  fontWeight: \"new-weight\",\n  number: \"new-number\",\n  duration: \"new-duration\",\n  custom: \"new-value\",\n};\n\n/**\n * The set with a new variable for a group's \"+\", and where it landed.\n *\n * Named so its derived label reads in plain words (\"New colour\") until the\n * author names it. A type size adds its line height too, under the same\n * name, which is what pairs them.\n */\nexport function addVariable(\n  tokens: SiteTokenSet | undefined,\n  what: NewVariable\n): { tokens: SiteTokenSet; at: number } {\n  const base = tokens ?? { tokens: [] };\n  const spec = NEW_VARIABLES[what];\n  const words = freeWords(\n    base,\n    spec.prefix,\n    NEW_WORDS[what],\n    what === \"type size\"\n  );\n  const added: SiteToken[] = [\n    {\n      name: `${spec.prefix}.${words}`,\n      kind: spec.kind,\n      values: { light: spec.value },\n    },\n  ];\n  if (what === \"type size\") {\n    added.push({\n      name: `${LINE_HEIGHT_PREFIX}${words}`,\n      // A plain number, so a number token: as a `dimension` it would be a\n      // value the engine reports as not a length.\n      kind: \"number\",\n      values: { light: NEW_LINE_HEIGHT },\n    });\n  }\n  return {\n    tokens: { ...base, tokens: [...base.tokens, ...added] },\n    at: base.tokens.length,\n  };\n}\n\n/**\n * The set with a just-added variable labelled, and its code name made from\n * that label (`Heading 1` gives `font-size.heading-1`), its line height\n * following.\n *\n * Only for a variable created moments ago, which nothing can reference yet:\n * once a variable may be in use, its code name stays put and only the label\n * changes, through {@link relabelToken}.\n */\nexport function labelNewVariable(\n  tokens: SiteTokenSet,\n  at: number,\n  label: string\n): SiteTokenSet {\n  const token = tokens.tokens[at];\n  if (token === undefined || token.id !== undefined) {\n    return relabelToken(tokens, at, label);\n  }\n  const relabelled = relabelToken(tokens, at, label);\n  const slug = slugOf(label);\n  if (slug === \"\") return relabelled;\n  const dot = token.name.indexOf(\".\");\n  const prefix = dot === -1 ? token.name : token.name.slice(0, dot);\n  const partnerAt = token.name.startsWith(SIZE_PREFIX)\n    ? tokens.tokens.findIndex(\n        other =>\n          other.name ===\n          `${LINE_HEIGHT_PREFIX}${token.name.slice(SIZE_PREFIX.length)}`\n      )\n    : -1;\n  const others = {\n    ...relabelled,\n    tokens: relabelled.tokens.filter(\n      (_, index) => index !== at && index !== partnerAt\n    ),\n  };\n  const words = freeWords(others, prefix, slug, partnerAt !== -1);\n  const next = [...relabelled.tokens];\n  const named = next[at];\n  if (named !== undefined) next[at] = { ...named, name: `${prefix}.${words}` };\n  const partner = partnerAt === -1 ? undefined : next[partnerAt];\n  if (partner !== undefined) {\n    next[partnerAt] = { ...partner, name: `${LINE_HEIGHT_PREFIX}${words}` };\n  }\n  // With no id, its code name is its identity, so the colour order follows\n  // the new name: the variable keeps its place.\n  const order = renamedInOrder(\n    relabelled.order,\n    token.name,\n    `${prefix}.${words}`\n  );\n  return {\n    ...relabelled,\n    tokens: next,\n    ...(order === undefined ? {} : { order }),\n  };\n}\n\n/**\n * The set with a copy of one variable right below it, and where the copy\n * landed: the same values, labelled \"<label> copy\" (\"<label> copy 2\" when\n * that is taken), under a free code name made from that label. A type size's line height is copied beside it, under\n * the same words, which is what pairs them.\n *\n * The copy has no `id`, as a new variable has none: nothing references it\n * yet, so its code name can still follow its label until it is first saved.\n */\nexport function duplicateVariable(\n  tokens: SiteTokenSet,\n  at: number,\n  label: string\n): { tokens: SiteTokenSet; at: number } {\n  const token = tokens.tokens[at];\n  if (token === undefined) return { tokens, at };\n  const copyLabel = copyLabelFor(tokens, label);\n  const dot = token.name.indexOf(\".\");\n  const prefix = dot === -1 ? token.name : token.name.slice(0, dot);\n  const partner = token.name.startsWith(SIZE_PREFIX)\n    ? tokens.tokens.find(\n        other =>\n          other.name ===\n          `${LINE_HEIGHT_PREFIX}${token.name.slice(SIZE_PREFIX.length)}`\n      )\n    : undefined;\n  const words = freeWords(\n    tokens,\n    prefix,\n    slugOf(copyLabel) || \"copy\",\n    partner !== undefined\n  );\n  const copies: SiteToken[] = [\n    { ...withoutId(token), name: `${prefix}.${words}`, label: copyLabel },\n  ];\n  if (partner !== undefined) {\n    const { label: _label, ...line } = withoutId(partner);\n    copies.push({ ...line, name: `${LINE_HEIGHT_PREFIX}${words}` });\n  }\n  const next = [...tokens.tokens];\n  next.splice(at + 1, 0, ...copies);\n  return {\n    tokens: {\n      ...tokens,\n      tokens: next,\n      ...orderWithCopy(tokens, token, copies),\n    },\n    at: at + 1,\n  };\n}\n\n/**\n * The first free name for a copy: \"<label> copy\", then \"copy 2\", \"copy 3\"…,\n * the label shortened where the suffix would take it past the longest\n * label the engine stores, so the copy is saved as it is.\n */\nfunction copyLabelFor(tokens: SiteTokenSet, label: string): string {\n  for (let n = 1; ; n += 1) {\n    const suffix = n === 1 ? \" copy\" : ` copy ${String(n)}`;\n    const room = MAX_TOKEN_LABEL_LENGTH - suffix.length;\n    const candidate = `${label.slice(0, room).trimEnd()}${suffix}`;\n    if (variableLabelIssue(tokens, -1, candidate) === undefined) {\n      return candidate;\n    }\n  }\n}\n\n/** A token without its frozen identity, as a copy starts. */\nfunction withoutId(token: SiteToken): SiteToken {\n  const { id: _id, ...rest } = token;\n  return rest;\n}\n\n/** A label as code-name words: lowercase letters, digits and dashes. */\nfunction slugOf(label: string): string {\n  return label\n    .normalize(\"NFKD\")\n    .toLowerCase()\n    .replaceAll(/[^a-z0-9]+/g, \"-\")\n    .replaceAll(/^-+|-+$/g, \"\");\n}\n\n/**\n * Words free under `prefix` (and under the line-height prefix too, for a type\n * size), suffixed `-2`, `-3`… when taken. Compared as custom properties, which\n * is the real uniqueness boundary, against names and identities alike.\n */\nfunction freeWords(\n  tokens: SiteTokenSet,\n  prefix: string,\n  words: string,\n  withLineHeight: boolean\n): string {\n  const used = usedProperties(tokens);\n  const free = (candidate: string): boolean =>\n    !used.has(tokenCustomProperty(`${prefix}.${candidate}`, \"\")) &&\n    (!withLineHeight ||\n      !used.has(tokenCustomProperty(`${LINE_HEIGHT_PREFIX}${candidate}`, \"\")));\n  if (free(words)) return words;\n  for (let n = 2; ; n += 1) {\n    if (free(`${words}-${n}`)) return `${words}-${n}`;\n  }\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 * A block's looks, as the Style tab offers them as tiles: which looks its\n * type has, which one it wears, what wearing another means for its classes,\n * and how a tile draws each one.\n *\n * A look is a shared style bound to one block type (`NamedClass.blockType`).\n * The block's own look, its base styles, is wearing none of them. A block\n * wears at most one look, beside at most one shared style.\n *\n * @module look-tiles\n */\n\nimport {\n  MAX_CLASSES_PER_NODE,\n  isLook,\n  isPlainRecord,\n  isTokenRef,\n  resolveSiteTokens,\n  scaledTokenText,\n  starredLooksOf,\n  tokenIdentity,\n  type NamedClass,\n  type NodeStyles,\n  type SiteTokenSet,\n  type StyleValue,\n  type TokenMode,\n  type TokenRef,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  classDeclarations,\n  usableSiteClasses,\n} from \"../../styles/class-library\";\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\n\n/** One tile: a look of the block's type, or the block's own (`id: null`). */\nexport interface LookTile {\n  /** The look's class id, or `null` for the block's own look. */\n  readonly id: string | null;\n  readonly name: string;\n  /** The look's own styles, laid over the block's base for the tile. */\n  readonly styles: NodeStyles | undefined;\n  /** A hidden style, shown only to the block already wearing it. */\n  readonly hidden: boolean;\n}\n\n/**\n * The looks a block of this type may wear, in library order: those the\n * compiler renders, read from the same view the class picker reads, so a\n * look whose name a site's own style holds is not offered.\n */\nexport function looksOfType(\n  library: readonly NamedClass[],\n  blockType: string\n): NamedClass[] {\n  return usableSiteClasses(library).filter(\n    entry => isLook(entry) && entry.blockType === blockType\n  );\n}\n\n/**\n * Every look bound to this block type, offered or not: what choosing a tile\n * takes off, so a look a site's style hides now cannot return beside the\n * chosen one when that style goes.\n */\nexport function boundLooksOf(\n  library: readonly NamedClass[],\n  blockType: string\n): NamedClass[] {\n  // An id a rendering shared style holds is that style's, as the engine gives\n  // it: never taken off as though it were the look that lost it.\n  const styles = new Set(\n    usableSiteClasses(library)\n      .filter(entry => !isLook(entry))\n      .map(entry => entry.id)\n  );\n  return library.filter(\n    entry =>\n      isLook(entry) && entry.blockType === blockType && !styles.has(entry.id)\n  );\n}\n\n/**\n * The tiles for a block: its own look first, named as its definition names\n * it, then its type's looks. A hidden look is offered only to the block\n * already wearing it (`worn`), which keeps it, so a hidden style never\n * vanishes from a block that has it. No tiles when the type has no looks: a\n * row of one tile would offer a choice that isn't there.\n */\nexport function lookTiles(\n  library: readonly NamedClass[],\n  blockType: string,\n  ownName: string | undefined,\n  worn: string | null = null\n): LookTile[] {\n  const all = looksOfType(library, blockType);\n  if (all.length === 0) return [];\n  // Picking no style gives the ★ style when one carries it, so that tile is\n  // named and drawn as the ★ style, which isn't offered a second time unless\n  // the block wears it by name.\n  const starred = starredLooksOf(usableSiteClasses(library)).get(blockType);\n  const looks = all.filter(\n    look =>\n      look.id === worn || (look.hidden !== true && look.id !== starred?.id)\n  );\n  const none: LookTile =\n    starred === undefined\n      ? {\n          id: null,\n          name: ownName ?? \"Default\",\n          styles: undefined,\n          hidden: false,\n        }\n      : {\n          id: null,\n          name: sharedStyleName(starred),\n          styles: starred.styles,\n          hidden: false,\n        };\n  return [\n    none,\n    ...looks.map(look => ({\n      id: look.id,\n      name: sharedStyleName(look),\n      styles: look.styles,\n      hidden: look.hidden === true,\n    })),\n  ];\n}\n\n/**\n * The look a block wears among these, or `null` for its own look. A block\n * listing more than one (stored or imported that way) shows the one written\n * last, in library order, as the canvas does; choosing a tile leaves one.\n */\nexport function wornLook(\n  classes: readonly string[] | undefined,\n  looks: readonly NamedClass[]\n): string | null {\n  // Only the references the engine reads: past the per-node cap, a look is\n  // listed but never applied.\n  const listed = new Set((classes ?? []).slice(0, MAX_CLASSES_PER_NODE));\n  const worn = looks.filter(look => listed.has(look.id));\n  return worn.at(-1)?.id ?? null;\n}\n\n/**\n * A block's classes wearing another look: every look of its type taken off,\n * then the chosen one added (none for the block's own look). Its shared\n * style, and anything else it lists, are kept as they are.\n */\nexport function withLook(\n  classes: readonly string[] | undefined,\n  looks: readonly NamedClass[],\n  id: string | null\n): string[] {\n  const ids = new Set(looks.map(look => look.id));\n  const kept = (classes ?? []).filter(each => !ids.has(each));\n  return id === null ? kept : [id, ...kept];\n}\n\n/**\n * What choosing a tile does to a block's classes: nothing, when they would\n * stay as they are (the no-op is the stored list's, not the visible tiles',\n * so a hidden look still comes off); a refusal, when the new list would pass\n * the classes the engine reads per node; else the classes to store.\n */\nexport function lookChoice(\n  classes: readonly string[] | undefined,\n  removable: readonly NamedClass[],\n  id: string | null\n):\n  | { readonly kind: \"unchanged\" }\n  | { readonly kind: \"full\" }\n  | { readonly kind: \"apply\"; readonly classes: string[] } {\n  const current = classes ?? [];\n  const next = withLook(current, removable, id);\n  if (\n    next.length === current.length &&\n    next.every((each, index) => each === current[index])\n  ) {\n    return { kind: \"unchanged\" };\n  }\n  if (next.length > MAX_CLASSES_PER_NODE) return { kind: \"full\" };\n  return { kind: \"apply\", classes: next };\n}\n\n/**\n * A token reference's value in one mode, at the reference's factor as the\n * page compiles it, or the reference left as it is.\n */\nfunction tokenValue(\n  ref: TokenRef,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): StyleValue {\n  // By identity alone, as the canvas declares a token: a renamed token's\n  // old display name resolves nothing there, so it resolves nothing here.\n  const token = tokens?.tokens.find(each => tokenIdentity(each) === ref.$token);\n  const value = token?.values[mode] ?? token?.values.light;\n  if (value === undefined) return ref;\n  // A number at its factor is the number the page's `calc()` computes; text\n  // takes the page's own spelling of the scale.\n  if (typeof value === \"number\") {\n    return typeof ref.times === \"number\" ? value * ref.times : value;\n  }\n  return typeof value === \"string\" ? scaledTokenText(value, ref.times) : value;\n}\n\n/** A value with every token it names resolved for one mode. */\nfunction resolved(\n  value: unknown,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): unknown {\n  if (isTokenRef(value)) {\n    return tokenValue(value, tokens, mode);\n  }\n  if (!isPlainRecord(value)) return value;\n  return Object.fromEntries(\n    Object.entries(value).map(([key, inner]) => [\n      key,\n      resolved(inner, tokens, mode),\n    ])\n  );\n}\n\n/**\n * What a tile draws a look on: a `mark` standing for the block at the tile's\n * own size (a Button's label), or a `sample` of the block drawn at the page's\n * own sizes and scaled down whole (an Image's picture, a Quote's words, a\n * Section's band), so its padding, type and height read in proportion.\n */\nexport type LookDrawing = \"mark\" | \"sample\";\n\n/**\n * Whether a tile draws this CSS property: what a small specimen can show\n * (colour, border, corners, decoration, proportion). The engine writes\n * logical properties (`border-block-start-width`), so borders are matched by\n * family rather than listed; a mark's sizes stay the tile's own.\n */\nfunction drawnOnTile(property: string): boolean {\n  return (\n    property === \"color\" ||\n    property === \"background-color\" ||\n    property === \"aspect-ratio\" ||\n    property === \"object-fit\" ||\n    property === \"font-weight\" ||\n    property.startsWith(\"border\") ||\n    property.startsWith(\"text-decoration\")\n  );\n}\n\n/**\n * What a sample draws as well as a mark: the sizes and the type that make a\n * style what it is on a block drawn whole (a Hero's height and padding, a\n * Large quote's size and centring). Never its width or margins: the sample's\n * frame places it.\n */\nconst SAMPLE_PROPERTIES: ReadonlySet<string> = new Set([\n  \"min-height\",\n  \"min-block-size\",\n  \"font-size\",\n  \"font-style\",\n  \"line-height\",\n  \"letter-spacing\",\n  \"text-align\",\n  \"text-transform\",\n]);\n\n/** Whether a sample draws this CSS property: a mark's, its sizes and type. */\nfunction drawnOnSample(property: string): boolean {\n  return (\n    drawnOnTile(property) ||\n    SAMPLE_PROPERTIES.has(property) ||\n    property.startsWith(\"padding\")\n  );\n}\n\n/**\n * A page's value as a sample reads it: a length that follows the screen\n * (`60vh`, `4vw`) follows the sample's frame instead, which stands for the\n * screen and is a size container (`cqh`, `cqw`), so a Hero is as tall in its\n * tile as on the page, in proportion, however wide the editor's window is.\n */\nfunction onSampleFrame(value: string): string {\n  return value.replace(\n    /(\\d)[sdl]?v(w|h|i|b|min|max)\\b/g,\n    (_, digit: string, axis: string) => `${digit}cq${axis}`\n  );\n}\n\n/** A CSS property as React spells it: `border-block-start-width` → `borderBlockStartWidth`. */\nfunction reactProperty(property: string): string {\n  return property.replace(/-([a-z])/g, (_, letter: string) =>\n    letter.toUpperCase()\n  );\n}\n\n/**\n * One source's declarations a tile draws, as React style entries: its tokens\n * resolved for the mode, only the properties the drawing shows, and never a\n * value still naming a variable, which has nothing to resolve against here.\n */\nfunction drawnEntries(\n  source: NodeStyles,\n  set: SiteTokenSet,\n  mode: TokenMode,\n  drawing: LookDrawing\n): [string, string][] {\n  const drawn = drawing === \"sample\" ? drawnOnSample : drawnOnTile;\n  const literal = resolved(source, set, mode) as NodeStyles;\n  return classDeclarations(literal)\n    .shown.filter(\n      entry =>\n        drawn(entry.property) &&\n        entry.descendant === undefined &&\n        !/\\b(?:var|url)\\(/i.test(entry.value)\n    )\n    .map(entry => [\n      reactProperty(entry.property),\n      drawing === \"sample\" ? onSampleFrame(entry.value) : entry.value,\n    ]);\n}\n\n/**\n * How a tile draws a look: the block's base with the look laid over, its\n * tokens resolved for the mode the canvas shows, as inline styles. On a mark,\n * only the properties a small specimen can show (colour, border, corners,\n * decoration, proportion), so every mark is the same size; on a sample, its\n * sizes and type too, with the screen read as the sample's frame.\n */\nexport function lookTileStyle(\n  base: NodeStyles | undefined,\n  look: NodeStyles | undefined,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode,\n  drawing: LookDrawing = \"mark\"\n): Record<string, string> {\n  // The site's tokens over the defaults, as the canvas compiles with them.\n  const set = resolveSiteTokens(tokens);\n  // The look's entries after the base's, so a property both set is the look's.\n  return Object.fromEntries(\n    [base, look].flatMap(source =>\n      source === undefined ? [] : drawnEntries(source, set, mode, drawing)\n    )\n  );\n}\n\n/**\n * The colours a look tile's stage is drawn in: the site's page background and\n * text, for the mode the canvas shows.\n *\n * A look names colours from the site's palette, and those read only against\n * that palette. On the editor's own surface they need not: the admin's theme\n * and the canvas's mode are chosen apart, so a look's text meets the dark\n * admin's stage in its light-mode colour and cannot be read. A colour the\n * site's tokens give no text for stays the editor's.\n */\nexport function lookStageStyle(\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): Record<string, string> {\n  const named = resolved(\n    {\n      backgroundColor: { $token: \"color.background\" },\n      color: { $token: \"color.text\" },\n    },\n    resolveSiteTokens(tokens),\n    mode\n  ) as Record<string, unknown>;\n  return Object.fromEntries(\n    Object.entries(named).filter(\n      (entry): entry is [string, string] => typeof entry[1] === \"string\"\n    )\n  );\n}\n\n/**\n * What the bar says about a look the block wears while the block is the\n * target: that an edit here changes this block only, and how to change the\n * look itself for every block wearing it. No count: what the site knows is\n * which documents an index records, not how many blocks wear the look, and a\n * count of this page's blocks beside \"every\" would read as the site's.\n */\nexport function lookLineWords(\n  lookName: string,\n  blockLabel: string\n): { here: string; everywhere: string } {\n  const block = blockLabel.toLowerCase();\n  return {\n    here: `Changes this ${block} only`,\n    everywhere: `Edit ${lookName} for every ${block} that uses it`,\n  };\n}\n","/**\n * The blocks on the page an edit to a look reaches, marked dashed on the\n * canvas while the look is edited on its own: every block of its type for a\n * block's own look, which is the base every other look of the type is laid on,\n * and every block wearing it for any other look, with, for the look carrying\n * ★, every block of its type wearing none of its type's looks.\n *\n * Which look a block wears is the Style tab's own answer (`wornLook` over the\n * looks the library renders), so the marks and the tiles cannot disagree.\n *\n * @module look-reach\n * @experimental Settles with the Design panel's Block looks group.\n */\n\nimport {\n  MAX_CLASSES_PER_NODE,\n  walkNodes,\n  type BlockDocument,\n  type NamedClass,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { BlockLookRow } from \"../../panels/design/block-look-rows\";\n\nimport { looksOfType, wornLook } from \"./look-tiles\";\n\n/** Marks a block an edit to the look being edited reaches. */\nexport const LOOK_REACH_ATTRIBUTE = \"data-nx-look-reach\";\n\n/** The ids of the blocks in `document` an edit to `look` reaches. */\nexport function lookReach(\n  document: BlockDocument,\n  library: readonly NamedClass[],\n  look: Pick<BlockLookRow, \"id\" | \"blockType\" | \"own\"> & {\n    /** The look carries ★, so a block that picked none is drawn with it. */\n    readonly starred?: boolean;\n  }\n): Set<string> {\n  const looks = looksOfType(library, look.blockType);\n  const reached = new Set<string>();\n  walkNodes(document.nodes, node => {\n    if (node.type !== look.blockType) return;\n    if (\n      look.own ||\n      appliesLook(node.classes, looks, look.id) ||\n      // Picked none of its type's looks, as the Style tab reads a block.\n      (look.starred === true && wornLook(node.classes, looks) === null)\n    ) {\n      reached.add(node.id);\n    }\n  });\n  return reached;\n}\n\n/**\n * Whether a block's classes apply the look: listed among the classes the\n * engine reads for a node, and one of the type's looks it renders. A block\n * listing two looks of its type has both applied, the later over the earlier,\n * so an edit to either reaches it.\n */\nfunction appliesLook(\n  classes: readonly string[] | undefined,\n  looks: readonly NamedClass[],\n  lookId: string\n): boolean {\n  return (\n    looks.some(each => each.id === lookId) &&\n    (classes ?? []).slice(0, MAX_CLASSES_PER_NODE).includes(lookId)\n  );\n}\n\n/**\n * Mark, under `root`, the blocks whose ids are in `ids`, and clear every other\n * mark. `null` clears them all.\n */\nexport function markLookReach(\n  root: ParentNode,\n  ids: ReadonlySet<string> | null\n): void {\n  root.querySelectorAll(`[${LOOK_REACH_ATTRIBUTE}]`).forEach(element => {\n    const id = element.getAttribute(\"data-nx-node\");\n    if (ids === null || id === null || !ids.has(id)) {\n      element.removeAttribute(LOOK_REACH_ATTRIBUTE);\n    }\n  });\n  if (ids === null) return;\n  root.querySelectorAll(\"[data-nx-node]\").forEach(element => {\n    const id = element.getAttribute(\"data-nx-node\");\n    if (\n      id !== null &&\n      ids.has(id) &&\n      !element.hasAttribute(LOOK_REACH_ATTRIBUTE)\n    ) {\n      element.setAttribute(LOOK_REACH_ATTRIBUTE, \"\");\n    }\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 * The one subscription that answers \"a node's rectangle may have moved\".\n *\n * Every overlay drawn in the canvas's content coordinates — the spacing bands,\n * the empty-container appenders — measures the nodes it draws over and has to\n * re-measure whenever the layout underneath it changes. React reports the\n * changes that come from a render; nothing reports the rest, and the rest is\n * several different mechanisms that no single browser API covers:\n *\n * - a SIZE change with no render behind it: a container query resolving at a\n *   new canvas width, a rail panel opening, a webfont swapping in, an image\n *   finishing its load. `ResizeObserver` is the only thing that sees these.\n * - a MOVE with no size change at all: a scroller between a node and the root,\n *   or a transition finishing on a neighbour. No observer reports either,\n *   because nothing resized, nothing mutated and no element the overlay knows\n *   about changed at all.\n *\n * Held here rather than written out per overlay because the drift is otherwise\n * silent and has already happened: one overlay subscribed to resizes and not\n * to scrolls, and its controls stayed at the coordinates the layout had before\n * the author scrolled a container — while the file looked like a complete copy\n * of the one beside it. A caller that asks this question asks all of it.\n *\n * A `MutationObserver` answers a THIRD question — the DOM changed, which alters\n * computed style without necessarily altering any size. It needs something the\n * other two do not, because the subtree it observes CONTAINS the overlay's own\n * output: where that output is, which only the overlay knows.\n *\n * {@link watchCanvasFor} is therefore the entry point and all three are behind\n * it, taking the one thing a caller has to supply. Offering the mechanisms\n * separately would put \"did I remember to take all of them\" back on each\n * overlay, which is the failure this module was extracted to remove and which\n * happened again the moment there were two subscriptions to remember instead of\n * one — an overlay took the geometry half, left the mutation half out, and its\n * controls stayed where a recompiled site sheet had moved the blocks from.\n *\n * @module canvas-geometry-watch\n */\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { isEditableText, isTextEntry } from \"./canvas-escape\";\nimport { isElement, isFormField } from \"./dom-kind\";\nimport {\n  overlaySpaceOf,\n  screenScrollers,\n  scrollEventTarget,\n} from \"./geometry-dom\";\nimport { nodeElements, nodeElementsIn } from \"./rendered-nodes\";\n\n/**\n * Marks a layer the editor draws OVER the page — absolutely positioned and\n * taking no part in layout — whose own redrawing can move no block.\n *\n * Every overlay's watch ignores what happens inside one, not only the caller's\n * own: one overlay drawing would otherwise make every other re-measure, for a\n * change that cannot have moved anything they measure.\n */\nexport const OVERLAY_OUTPUT_ATTRIBUTE = \"data-nx-overlay-output\";\n\n/** Whether a mutated node sits inside a layer marked as overlay output. */\nfunction insideOverlayOutput(target: Node): boolean {\n  const element = isElement(target) ? target : target.parentElement;\n  return element?.closest(`[${OVERLAY_OUTPUT_ATTRIBUTE}]`) != null;\n}\n\n/**\n * Everything an overlay drawn over this canvas has to re-measure for.\n *\n * ONE call rather than a list a caller assembles: which changes can move a\n * rectangle is a single question, and an overlay that answers part of it looks\n * exactly like one that answers all of it — the file reads as complete and the\n * controls are simply stale under whichever mechanism was left out.\n *\n * The canvas root is resolved FROM the layer rather than passed in, so a caller\n * cannot subscribe against one root while drawing into another; `undefined`\n * comes back when there is none, which is an overlay mounted outside a canvas\n * and has nothing to watch.\n *\n * @param ownLayer - reads the caller's own layer element, and is read rather\n *   than passed because the layer does not exist until after the first render;\n *   it locates the canvas AND says which mutations are the caller's own\n * @param moved - re-measure; called once per change, never per frame\n * @returns unsubscribes everything this installed, or `undefined` when there\n *   was no canvas root to install anything on\n */\nexport function watchCanvasFor(\n  ownLayer: () => HTMLElement | null,\n  moved: () => void\n): (() => void) | undefined {\n  const element = ownLayer();\n  // The root the layer is drawn over: its ancestor when the canvas shares the\n  // layer's document, the root in the frame the layer is drawn over otherwise.\n  const root =\n    element === null\n      ? null\n      : (overlaySpaceOf(element, CANVAS_ROOT_CLASS)?.root ?? null);\n  if (root === null) return undefined;\n  const geometry = watchCanvasGeometry(root, moved);\n  const styles = watchCanvasStyleMutations(root, ownLayer, moved);\n  return () => {\n    geometry();\n    styles();\n  };\n}\n\n/**\n * Call `moved` whenever the canvas's laid-out geometry may have changed.\n *\n * @param root - the canvas root every node is measured against\n * @param moved - re-measure; called once per change, never per frame\n * @returns unsubscribes everything this installed\n */\nfunction watchCanvasGeometry(root: HTMLElement, moved: () => void): () => void {\n  /*\n   * EVERY rendered node is observed, not only the ones a caller draws over:\n   * what moves a node is often a SIBLING changing size rather than the node\n   * itself. An image finishing its load resizes that sibling and nothing else\n   * — not the node laid out after it, and not the root, which is\n   * `min-height: 100%` and can absorb the change while reporting nothing.\n   *\n   * The root is observed too, for the resize the nodes cannot report: the\n   * panels around the canvas moving, which changes the frame without changing\n   * any node.\n   *\n   * Absent in jsdom unless a test supplies one, and absent in older browsers.\n   * Guarded on its own rather than gating the listeners below, because the two\n   * answer different questions: a runtime missing the observer must still hear\n   * a scroll. A missing observer costs a re-measure, not correctness — every\n   * caller measures on render as well.\n   *\n   * Built from the ROOT's window, the realm of everything it observes: a\n   * canvas rendered in a frame is laid out by that frame, and an observer from\n   * another window is not guaranteed to report on its nodes.\n   */\n  const view = root.ownerDocument.defaultView;\n  const Sizes = view?.ResizeObserver;\n  const sizes = typeof Sizes === \"function\" ? new Sizes(() => moved()) : null;\n  if (sizes !== null) {\n    sizes.observe(root);\n    for (const node of nodeElements(root)) sizes.observe(node);\n  }\n  /*\n   * And every node that arrives LATER, which the snapshot above cannot see: a\n   * block that resolves after a Suspense fallback, or one an edit inserts. Its\n   * insertion is heard as a mutation and measured then, but an image loading\n   * inside it afterwards resizes only that block — no ancestor need change —\n   * so unobserved, nothing would report it. A node leaving is released, so the\n   * observer does not hold elements the page no longer has.\n   */\n  const Arrivals = view?.MutationObserver;\n  const arrivals =\n    sizes === null || typeof Arrivals !== \"function\"\n      ? null\n      : new Arrivals(records => {\n          for (const record of records) {\n            record.addedNodes.forEach(added => {\n              if (!isElement(added)) return;\n              for (const node of nodeElementsIn(added)) sizes.observe(node);\n            });\n            record.removedNodes.forEach(removed => {\n              if (!isElement(removed)) return;\n              for (const node of nodeElementsIn(removed)) sizes.unobserve(node);\n            });\n          }\n        });\n  arrivals?.observe(root, { childList: true, subtree: true });\n\n  /*\n   * `overflow: auto` and `overflow: scroll` are catalog values, so a block can\n   * sit inside a container the author scrolls. Scrolling it moves the block\n   * relative to the canvas while resizing nothing, mutating nothing and\n   * finishing no transition — none of the observers above hear it.\n   *\n   * CAPTURE, because a scroll event does not bubble: listening on the root in\n   * the capture phase is what reaches a scroller nested anywhere inside it.\n   *\n   * `transition` is a catalog property too, and a transform or margin\n   * animating past its first frame moves a block while resizing nothing. The\n   * completion events are what the browser offers, and they DO bubble, so one\n   * listener each on the root covers every block. This corrects the FINAL\n   * geometry rather than following the animation: tracking the frames between\n   * would mean measuring on every one, which costs more than an overlay being\n   * briefly behind a transition the author is watching.\n   *\n   * `animation` likewise: an entrance motion or a site's `@keyframes` moves a\n   * block by transform, and its end and cancel bubble the same way. A block\n   * animating FOREVER never ends; its marks follow the geometry of the last\n   * measurement, re-taken whenever anything else re-measures, rather than\n   * chasing every frame — `animationiteration` would re-measure at whatever\n   * point of the motion each loop boundary falls, which moves the ring without\n   * making it right.\n   */\n  const settled = (): void => moved();\n  root.addEventListener(\"transitionend\", settled);\n  root.addEventListener(\"transitioncancel\", settled);\n  root.addEventListener(\"animationend\", settled);\n  root.addEventListener(\"animationcancel\", settled);\n  /*\n   * An authored `:hover` or `:focus-visible` rule can move a block — a\n   * transform, a margin — with no transition, so the change of state is the\n   * only signal there is. Pointer and focus entering or leaving a block\n   * bubble, so the root hears every block's. Measured on the next frame,\n   * once the state's styles apply, and once per frame however many changes\n   * arrive in it: a pointer crossing the page enters and leaves many blocks.\n   */\n  let frame: number | undefined;\n  const restated = (): void => {\n    if (frame !== undefined) return;\n    if (view === null || typeof view.requestAnimationFrame !== \"function\") {\n      moved();\n      return;\n    }\n    frame = view.requestAnimationFrame(() => {\n      frame = undefined;\n      moved();\n    });\n  };\n  /*\n   * Hover and focus entering or leaving a block, and a press ending. The\n   * input modality, which `:focus-visible` can follow with no focus event at\n   * all, is heard by the key and pointer listeners below.\n   */\n  const STATE_EVENTS = [\n    \"pointerover\",\n    \"pointerout\",\n    \"focusin\",\n    \"focusout\",\n    // A press ending ends an authored `:active` state, with no pointer\n    // leaving and no focus changing.\n    \"pointerup\",\n    \"pointercancel\",\n  ];\n  for (const type of STATE_EVENTS) root.addEventListener(type, restated);\n  /*\n   * A value can change with no DOM mutation: a form field's, or a custom\n   * element's kept in script, and either can change what `:valid`,\n   * `:invalid`, `:placeholder-shown` or a custom state styles. So every\n   * `input` and `change` re-measures, with ONE exception: editable text in\n   * the canvas's own tree, whose edits mutate the DOM, which the mutation\n   * watch already measures — hearing its `input` too would measure every\n   * character twice. An edit inside a custom element's shadow root is a\n   * mutation no observer on the root sees, so it is not the exception.\n   *\n   * Read from the composed path, whose first entry is the element the edit\n   * reached: `target` is retargeted to the shadow host by the time the event\n   * reaches the root.\n   */\n  const valueChanged = (event: Event): void => {\n    const origin = event.composedPath()[0] ?? event.target;\n    // The editing host itself, the element carrying `contenteditable`, is\n    // where a browser fires an edit's `input`. A control nested in editable\n    // text that dispatches on itself inherits editability without being one,\n    // and its value can change with no mutation at all.\n    const mutatesOurTree =\n      isElement(origin) &&\n      !isFormField(origin) &&\n      origin.hasAttribute(\"contenteditable\") &&\n      origin.getRootNode() === root.getRootNode() &&\n      isEditableText(origin);\n    if (!mutatesOurTree) restated();\n  };\n  root.addEventListener(\"input\", valueChanged);\n  root.addEventListener(\"change\", valueChanged);\n  /*\n   * The keyboard is heard for what it can change, not for every key: an\n   * author typing would otherwise re-measure every overlay once a frame. A\n   * key changes what a style reads when it is the first after a pointer (the\n   * modality, which `:focus-visible` follows), or when it activates a\n   * control — Space or Enter down and up, outside editable text — which\n   * `:active` follows. A pointer press is always a change: it starts\n   * `:active`, and hands the modality back to the pointer.\n   */\n  let modality: \"keyboard\" | \"pointer\" | undefined;\n  const activates = (event: Event): boolean => {\n    // Read by shape: a canvas in a frame dispatches the frame's own\n    // KeyboardEvent, which no `instanceof` against this window matches.\n    const key = \"key\" in event ? event.key : undefined;\n    if (key !== \" \" && key !== \"Enter\") return false;\n    // Text entry is the one place these keys activate nothing; a checkbox,\n    // a radio or a button the keyboard presses is a control, as Escape's\n    // own reading of the canvas already tells them apart.\n    const target = event.target;\n    return !(isElement(target) && isTextEntry(target));\n  };\n  const keyDown = (event: Event): void => {\n    if (modality !== \"keyboard\") {\n      modality = \"keyboard\";\n      restated();\n    } else if (activates(event)) {\n      restated();\n    }\n  };\n  const keyUp = (event: Event): void => {\n    if (activates(event)) restated();\n  };\n  const pointerDown = (): void => {\n    modality = \"pointer\";\n    restated();\n  };\n  root.addEventListener(\"keydown\", keyDown);\n  root.addEventListener(\"keyup\", keyUp);\n  root.addEventListener(\"pointerdown\", pointerDown);\n  root.addEventListener(\"scroll\", settled, true);\n  /*\n   * And the root's DOCUMENT, in the bubble phase, for the viewport itself\n   * scrolling. A canvas in a frame of its own is scrolled by that frame's\n   * viewport, and a viewport's scroll is dispatched at the document, which no\n   * listener on the root can hear. Not in the capture phase: that would hear\n   * every element's scroll anywhere in the document, which the listener above\n   * already covers for the ones inside the canvas.\n   */\n  const doc = root.ownerDocument;\n  doc.addEventListener(\"scroll\", settled);\n\n  return () => {\n    sizes?.disconnect();\n    arrivals?.disconnect();\n    root.removeEventListener(\"transitionend\", settled);\n    root.removeEventListener(\"transitioncancel\", settled);\n    root.removeEventListener(\"animationend\", settled);\n    root.removeEventListener(\"animationcancel\", settled);\n    for (const type of STATE_EVENTS) root.removeEventListener(type, restated);\n    root.removeEventListener(\"input\", valueChanged);\n    root.removeEventListener(\"change\", valueChanged);\n    root.removeEventListener(\"keydown\", keyDown);\n    root.removeEventListener(\"keyup\", keyUp);\n    root.removeEventListener(\"pointerdown\", pointerDown);\n    if (frame !== undefined) view?.cancelAnimationFrame(frame);\n    root.removeEventListener(\"scroll\", settled, true);\n    doc.removeEventListener(\"scroll\", settled);\n  };\n}\n\n/**\n * What each attribute held BEFORE this batch, or `undefined` if the batch\n * carries anything that is not an attribute change.\n *\n * The FIRST record for an attribute is the one holding its pre-batch value; a\n * later record for the same attribute reports an intermediate one.\n */\ninterface AttributeBefore {\n  /**\n   * Kept because `attributeName` is the LOCAL name.\n   *\n   * A namespaced attribute — `xlink:href` on an SVG `<use>`, say — is reported\n   * as `href`, and `getAttribute(\"href\")` answers `null` for it however it was\n   * set. Reading it back by local name alone therefore asks about a DIFFERENT\n   * attribute, one that is usually absent, so `null` matches `null` and every\n   * namespaced change passes as no change at all.\n   */\n  readonly namespace: string | null;\n  readonly name: string;\n  readonly was: string | null;\n}\n\nfunction beforeBatch(\n  records: readonly MutationRecord[]\n): Map<Element, Map<string, AttributeBefore>> | undefined {\n  const before = new Map<Element, Map<string, AttributeBefore>>();\n  for (const record of records) {\n    const name = record.attributeName;\n    if (record.type !== \"attributes\" || name === null) return undefined;\n    // A node this can read an attribute off, asked without naming a realm.\n    if (!isElement(record.target)) return undefined;\n    const namespace = record.attributeNamespace;\n    const byName =\n      before.get(record.target) ?? new Map<string, AttributeBefore>();\n    const key = `${namespace ?? \"\"}\\u0000${name}`;\n    if (!byName.has(key))\n      byName.set(key, { namespace, name, was: record.oldValue });\n    before.set(record.target, byName);\n  }\n  return before;\n}\n\n/**\n * Whether this batch left the subtree exactly as it found it.\n *\n * An overlay that MEASURES by writing has to write into the subtree it is\n * watching: the spacing probe pushes a value, reads the edge and puts the\n * attribute back, all inside one task. Reacting to that would have every\n * measurement schedule the next one forever. Remembering an answer across\n * measurements avoids that and buys a staleness of its own, since the applied\n * CSS changes for reasons nothing here reports. Ignoring a batch that changed\n * nothing removes the need to choose between the two.\n *\n * Judged across the WHOLE batch rather than per record, because per record the\n * restore looks like a change: its `oldValue` is the value the probe wrote,\n * while the attribute now holds the original. Only the first `oldValue` for an\n * attribute describes what it held before any of this, and comparing THAT with\n * what it holds now is the net question.\n *\n * A batch carrying a `childList` or `characterData` record changed something by\n * construction, and is never filtered.\n */\nfunction changedNothing(records: readonly MutationRecord[]): boolean {\n  const before = beforeBatch(records);\n  if (before === undefined) return false;\n  for (const [target, byName] of before) {\n    for (const [, { namespace, name, was }] of byName) {\n      if (target.getAttributeNS(namespace, name) !== was) return false;\n    }\n  }\n  return true;\n}\n\n/**\n * Call `moved` when a mutation OUTSIDE the caller's own output lands in the\n * canvas.\n *\n * The change this reaches and {@link watchCanvasGeometry} cannot: a recompiled\n * site sheet. `PageRenderer` emits the sheet as a `<style>` inside the page\n * root, so a save mutates this subtree — and a class-driven margin, position or\n * transform then moves blocks while resizing nothing, scrolling nothing and\n * finishing no transition. Every subscription in the function above stays\n * silent, and an overlay drawn over one of those blocks keeps the coordinates\n * the old rule gave it until something else re-measures.\n *\n * SEPARATE from that function rather than folded into it, and this is the part\n * a caller has to supply. An overlay draws INTO the subtree being observed, so\n * every measurement mutates it — a control appearing or leaving is a\n * `childList` record, a new rectangle rewrites a `style` attribute — and an\n * observer that reacted to those would have each measurement schedule the next.\n * Which mutations are the caller's own is therefore not answerable here, which\n * is why it is an argument rather than a rule written into this module.\n *\n * The test applied to that answer IS shared, because both overlays give the\n * same one: a full-bleed layer of their own, so containment within it decides\n * ownership exactly. An overlay that drew into the page itself — inline\n * chrome attached to a block rather than a layer above it — could not be\n * answered by containment and should not use this.\n *\n * @param root - the canvas root whose subtree is watched\n * @param ownOutput - the caller's own layer, read at delivery time because it\n *   does not exist when the subscription is taken\n * @param moved - re-measure; called once per batch of foreign mutations\n * @returns unsubscribes\n */\nfunction watchCanvasStyleMutations(\n  root: HTMLElement,\n  ownOutput: () => HTMLElement | null,\n  moved: () => void\n): () => void {\n  // Absent in jsdom unless a test supplies one, and absent in older browsers.\n  // A missing observer costs a re-measure rather than correctness: every caller\n  // measures on render as well. From the root's window, the realm of the\n  // subtree it watches.\n  const Mutations = root.ownerDocument.defaultView?.MutationObserver;\n  if (typeof Mutations !== \"function\") return () => {};\n  const styles = new Mutations(records => {\n    const own = ownOutput();\n    /*\n     * `own === null` counts as OUTSIDE rather than as the caller's own. The\n     * layer is null only once the caller has unmounted, and an unmounted\n     * overlay owns nothing in this subtree; treating it as own-output would\n     * silently drop a real site-style change in any window where the reference\n     * were momentarily unset.\n     */\n    /*\n     * The foreign records are separated rather than counted, because the net\n     * question below has to be asked of THOSE alone. One batch can carry both:\n     * the overlay redraws its own layer in the same task as a probe writes to a\n     * block and puts it back, and judging the whole batch then finds the\n     * layer's `childList` records and reports a change the caller caused.\n     */\n    const foreign = records.filter(\n      record =>\n        (own === null || !own.contains(record.target)) &&\n        !insideOverlayOutput(record.target)\n    );\n    if (foreign.length > 0 && !changedNothing(foreign)) moved();\n  });\n  /*\n   * Every kind of record, because every kind can carry a new rule: a sheet\n   * being replaced is `childList`, a sheet's bytes changing in place is\n   * `characterData`, and a class or inline style moving on a block is\n   * `attributes`. `subtree` because the sheet sits inside the page root rather\n   * than beside it.\n   */\n  styles.observe(root, {\n    childList: true,\n    subtree: true,\n    attributes: true,\n    // What each attribute held before, which is what makes a net-zero batch\n    // recognisable. See {@link changedNothing}.\n    attributeOldValue: true,\n    characterData: true,\n  });\n  return () => styles.disconnect();\n}\n\n/**\n * Call `moved` whenever what of the canvas is on screen may have changed:\n * a scroll of the canvas's own scroller or of the host's around its frame,\n * either one resizing, or a window resizing. Chrome kept to the screen band\n * (the block toolbar, the marks' tags) re-measures for all of them.\n *\n * One subscription rather than each consumer listening for its own share, for\n * the reason this module exists: an overlay that heard the scrolls and not\n * the resizes looked complete and stayed where a resized panel had left the\n * band. A scroller's scroll is heard where it is dispatched\n * (`scrollEventTarget`): a document's scrolling element scrolls at its\n * document, never at itself.\n *\n * @param root - the canvas root the band is read for\n * @param frame - the frame the canvas is drawn in, or `null`\n * @param moved - re-measure; called once per change\n * @returns unsubscribes everything this installed\n */\nexport function watchScreenBand(\n  root: HTMLElement,\n  frame: HTMLIFrameElement | null,\n  moved: () => void\n): () => void {\n  const changed = (): void => moved();\n  const stops: (() => void)[] = [];\n  const views = new Set<Window>();\n  for (const scroller of screenScrollers(root, frame)) {\n    const source = scrollEventTarget(scroller);\n    source.addEventListener(\"scroll\", changed, { passive: true });\n    stops.push(() => source.removeEventListener(\"scroll\", changed));\n    const view = scroller.ownerDocument.defaultView;\n    if (view === null) continue;\n    views.add(view);\n    // Absent in jsdom unless a test supplies one, and in older browsers: a\n    // missing observer costs a re-measure, not correctness.\n    const Sizes = view.ResizeObserver;\n    if (typeof Sizes !== \"function\") continue;\n    const sizes = new Sizes(changed);\n    sizes.observe(scroller);\n    stops.push(() => sizes.disconnect());\n  }\n  for (const view of views) {\n    view.addEventListener(\"resize\", changed);\n    stops.push(() => view.removeEventListener(\"resize\", changed));\n  }\n  return () => {\n    for (const stop of stops) stop();\n  };\n}\n","\"use client\";\n\n/**\n * Where the tabs drawn on blocks' outlines go, so that no two cover each\n * other, whichever layer of the editor's chrome draws them.\n *\n * Three layers draw over a block's top edge: the marks' at-rest tabs\n * (\"Conditional\", an Entry content block's words) in `canvas-marks.tsx`, the\n * \"Visitors won't see this\" badge in `visitor-unreadable-badges.tsx`, and the\n * block toolbar over the selection in `block-toolbar.tsx`. Each is a layer of\n * its own (the marks are hidden from assistive technology, the badge and the\n * toolbar are controls a keyboard reaches), so none can place what another\n * draws. Placed apart, layer by layer, each would keep clear of its own and\n * sit on the others: a block both conditional and read by a field visitors\n * can't read had its two tabs on one corner, and the toolbar over a selected\n * block covered its badge.\n *\n * So the layers share one board per canvas root. Each posts what it draws\n * there, the tabs it would place (`TabDraft`) and the boxes it has already\n * placed and keeps (the toolbar's), and every layer places its tabs by ONE\n * pass over everything posted (`tabsApart`). The pass is a pure function of\n * what is posted, so every layer reading the same board gets the same\n * answer, and its own part of it; a post that changes the board tells the\n * other layers, which place their tabs again from what they last measured.\n *\n * @module canvas-tab-places\n */\n\nimport * as React from \"react\";\n\nimport type { Rect } from \"../geometry\";\n\n/** Where a tab stands on its outline: on the top edge, the bottom, or inside the top. */\nexport type TabAt = \"above\" | \"below\" | \"inside\";\n\n/**\n * One tab to place: the block it marks, the outline whose edge it stands on,\n * where it may go in order of preference, and how big it is.\n */\nexport interface TabDraft {\n  /**\n   * The block's own box, which orders the pass: an at-rest outline and a\n   * visitor badge's outline around the same block start at its box.\n   */\n  readonly block: Rect;\n  /** The outline the tab stands on, in the chrome's coordinates. */\n  readonly edge: Rect;\n  /** Where it may go, in order of preference; the first is where it goes alone. */\n  readonly places: readonly TabAt[];\n  /** How far in from the outline's right edge it is drawn alone. */\n  readonly side: number;\n  /** About how wide it is drawn, no wider than the stylesheet lets it run. */\n  readonly width: number;\n  /** How tall it is drawn. */\n  readonly height: number;\n  /**\n   * How much of its height it shares with the outline's dash, where its foot\n   * sits on it: drawn that far over the edge rather than wholly past it.\n   */\n  readonly foot: number;\n  /**\n   * The furthest left its box may start: the left edge of what of the canvas\n   * is on screen, past which a tab stepped left would be drawn out of view.\n   */\n  readonly leftmost: number;\n}\n\n/** Where a tab is placed: on which edge, and how far in from the right. */\nexport interface TabPlacement {\n  readonly at: TabAt;\n  readonly side: number;\n}\n\n/**\n * The gap between two tabs stepped apart along one edge: the gap between one\n * at-rest mark's own tabs.\n */\nconst TAB_GAP = 2;\n\n/** Whether two rectangles share any area: touching edges share none. */\nexport function overlaps(a: Rect, b: Rect): boolean {\n  return (\n    a.x < b.x + b.width &&\n    b.x < a.x + a.width &&\n    a.y < b.y + b.height &&\n    b.y < a.y + a.height\n  );\n}\n\n/**\n * About where a tab is drawn, placed `at` its outline's edge and `side` in\n * from its right: right-anchored, drawn leftwards, its foot `foot` over the\n * edge it stands on.\n */\nfunction tabBoxOf(draft: TabDraft, at: TabAt, side: number): Rect {\n  const { edge, width, height, foot } = draft;\n  const y =\n    at === \"above\"\n      ? edge.y - height + foot\n      : at === \"below\"\n        ? edge.y + edge.height - foot\n        : edge.y;\n  return { x: edge.x + edge.width - side - width, y, width, height };\n}\n\n/**\n * Where each tab goes so no two overlap, nor any overlaps a box already\n * `taken`: in the order the drafts are given.\n *\n * Each tab sits on its own outline's top edge, so on blocks drawn shorter\n * than a tab (a line of text at a zoomed-out canvas, a spacer) stacked one on\n * another, the lower block's tab lands on the upper one's: both run leftwards\n * from the same right edge, and the second covers the first. No rule one tab\n * can apply from its own block alone keeps two such tabs apart, since every\n * tab shifting alike shifts both, so the tabs are placed together, in a fixed\n * order: from the top of the page down, then from the left, the order given\n * breaking ties (an outer block before the one it holds, and one block's\n * at-rest tabs before its visitor badge, as the board lists the layers). The\n * first keeps its place alone. A later one that would overlap one already\n * placed, or a taken box, takes its next place in the order it may use\n * (above, below, inside its top), the first that is clear, so a short block\n * under another carries its tab on its bottom edge, still on its own outline.\n * Where every place it may use is taken, as in a stack of several very short\n * blocks, it keeps its first place and steps left along that edge, past what\n * it would cover. A tab that is clear is placed exactly as it is alone.\n */\nexport function tabsApart(\n  drafts: readonly TabDraft[],\n  taken: readonly Rect[] = []\n): TabPlacement[] {\n  const order = drafts\n    .map((draft, index) => ({ block: draft.block, index }))\n    .sort((a, b) => a.block.y - b.block.y || a.block.x - b.block.x)\n    .map(({ index }) => index);\n  const placed: Rect[] = [...taken];\n  const placements: TabPlacement[] = drafts.map(draft => ({\n    at: draft.places[0] ?? \"inside\",\n    side: draft.side,\n  }));\n  for (const index of order) {\n    const draft = drafts[index];\n    if (draft === undefined) continue;\n    const hit = (box: Rect): Rect | undefined =>\n      placed.find(other => overlaps(box, other));\n    const clear = draft.places.find(\n      at => hit(tabBoxOf(draft, at, draft.side)) === undefined\n    );\n    const at = clear ?? draft.places[0] ?? \"inside\";\n    let side = draft.side;\n    let box = tabBoxOf(draft, at, side);\n    // The furthest in from the outline's right edge it may step: its box then\n    // starts at the screen's left edge. A tab stopped there may still cover\n    // another, but it stays in view and reachable, where one stepped further\n    // would be drawn, and its button placed, off the canvas.\n    const furthest = Math.max(\n      draft.side,\n      draft.edge.x + draft.edge.width - draft.width - draft.leftmost\n    );\n    // Ends: each step leaves the tab wholly left of the box it hits, and it\n    // only moves left, so no placed box is hit twice; or it reaches the\n    // screen's left edge and stops.\n    for (let over = hit(box); over !== undefined; over = hit(box)) {\n      const next = draft.edge.x + draft.edge.width - (over.x - TAB_GAP);\n      side = Math.min(next, furthest);\n      box = tabBoxOf(draft, at, side);\n      if (next >= furthest) break;\n    }\n    placed.push(box);\n    placements[index] = { at, side };\n  }\n  return placements;\n}\n\n/** The layers that post to a board, in the order the pass lists them. */\nexport type TabLayer = \"toolbar\" | \"at-rest\" | \"visitor\";\n\nconst LAYERS: readonly TabLayer[] = [\"toolbar\", \"at-rest\", \"visitor\"];\n\n/** What one layer posts: the tabs it places, and the boxes it keeps. */\nexport interface TabPost {\n  readonly tabs: readonly TabDraft[];\n  readonly taken: readonly Rect[];\n}\n\nconst NOTHING_POSTED: TabPost = { tabs: [], taken: [] };\n\n/** What one layer has posted, comparable, and how to tell it of another's post. */\ninterface Posted {\n  readonly post: TabPost;\n  readonly key: string;\n  readonly heard: (() => void) | undefined;\n}\n\n/** One canvas root's board, which every layer drawn over it shares. */\ninterface TabBoard {\n  /**\n   * Replace what `layer` has posted; `heard` is called when another layer's\n   * post changes the board. Tells the other layers when this one changes it.\n   */\n  post(layer: TabLayer, post: TabPost, heard?: () => void): void;\n  /** Where `layer`'s posted tabs go, in the order it posted them. */\n  placesOf(layer: TabLayer): TabPlacement[];\n}\n\n/** Per canvas root, so a root replaced (a page reloaded into the frame) starts clean. */\nconst BOARDS = new WeakMap<HTMLElement, TabBoard>();\n\nfunction newBoard(): TabBoard {\n  const posted = new Map<TabLayer, Posted>();\n  return {\n    post(layer, post, heard) {\n      const key = JSON.stringify(post);\n      const before = posted.get(layer);\n      posted.set(layer, { post, key, heard });\n      if (before?.key === key) return;\n      // Placing only reads the board, so a layer told here posts nothing\n      // back: one post is heard once by each other layer, and ends there.\n      posted.forEach((other, name) => {\n        if (name !== layer) other.heard?.();\n      });\n    },\n    placesOf(layer) {\n      const posts = LAYERS.map(name => ({\n        name,\n        post: posted.get(name)?.post ?? NOTHING_POSTED,\n      }));\n      const tabs = posts.flatMap(({ name, post }) =>\n        post.tabs.map(draft => ({ name, draft }))\n      );\n      const placements = tabsApart(\n        tabs.map(({ draft }) => draft),\n        posts.flatMap(({ post }) => post.taken)\n      );\n      return placements.filter((_, index) => tabs[index]?.name === layer);\n    },\n  };\n}\n\n/** The board of the canvas drawn at `root`. */\nexport function tabBoardOf(root: HTMLElement): TabBoard {\n  let board = BOARDS.get(root);\n  if (board === undefined) {\n    board = newBoard();\n    BOARDS.set(root, board);\n  }\n  return board;\n}\n\n/**\n * Posts what a layer draws to the board of the canvas it is drawn over, and\n * takes it off again when the layer draws nothing there or is gone, so the\n * other layers stop keeping clear of it. `heard` places the layer's tabs again\n * from what it last measured, called when another layer's post changes the\n * board; the latest one given is called.\n *\n * Returns the post: given no root (the layer is over no canvas, or draws\n * nothing), it takes the layer's last post off its board.\n */\nexport function useTabPost(\n  layer: TabLayer,\n  heard?: () => void\n): (root: HTMLElement | null, post?: TabPost) => void {\n  const board = React.useRef<TabBoard | null>(null);\n  const latest = React.useRef(heard);\n  // Kept current after each render, so the board calls the layer's latest\n  // placing rather than the one it posted with.\n  React.useLayoutEffect(() => {\n    latest.current = heard;\n  });\n  React.useEffect(\n    () => () => {\n      board.current?.post(layer, NOTHING_POSTED);\n      board.current = null;\n    },\n    [layer]\n  );\n  return React.useCallback(\n    (root: HTMLElement | null, post: TabPost = NOTHING_POSTED) => {\n      const next = root === null ? null : tabBoardOf(root);\n      if (board.current !== null && board.current !== next) {\n        board.current.post(layer, NOTHING_POSTED);\n      }\n      board.current = next;\n      next?.post(layer, post, () => latest.current?.());\n    },\n    [layer]\n  );\n}\n","/**\n * The dashed outline on the parts of a selected placement an author can edit.\n *\n * A component's own design and the fields it exposes look alike on the page,\n * so the editor marks the second: while a placement is selected, each element\n * that draws one of its exposed values carries {@link EXPOSED_ATTRIBUTE}, and\n * the canvas marks outline it, dashed, in the accent a component\n * wears. The composed page's exposure map says which those are, so the marks\n * are exactly the values a double-click edits or the panel lists.\n *\n * @module exposed-outline\n */\nimport type {\n  BlockDocument,\n  PropExposure,\n  ResolvedBlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\n/** Marks an element drawing one of the selected placement's exposed values. */\nexport const EXPOSED_ATTRIBUTE = \"data-nx-exposed\";\n\n/**\n * Mark, under `root`, the elements drawing the exposed values of the placement\n * `placementId`, and clear every other mark. `null` clears them all.\n *\n * @param root - the canvas, or the document holding it\n * @param placementId - the selected placement, or `null`\n * @param composed - the editor's composition, with the exposure map\n */\nexport function markExposedParts(\n  root: ParentNode,\n  placementId: string | null,\n  composed: BlockDocument | undefined\n): void {\n  const fed =\n    placementId === null || composed === undefined\n      ? new Map<string, Readonly<Record<string, PropExposure>>>()\n      : exposuresOf(composed.nodes, placementId);\n  const wanted = new Set<Element>();\n  root.querySelectorAll(\"[data-nx-node]\").forEach(owner => {\n    const exposed = fed.get(owner.getAttribute(\"data-nx-node\") ?? \"\");\n    if (exposed === undefined) return;\n    const parts = [\n      owner,\n      ...Array.from(owner.querySelectorAll(\"[data-nx-prop]\")),\n    ];\n    for (const part of parts) {\n      const prop = part.getAttribute(\"data-nx-prop\");\n      // A value of this node, not of a block nested inside it.\n      if (prop === null || part.closest(\"[data-nx-node]\") !== owner) continue;\n      if (!Object.hasOwn(exposed, prop)) continue;\n      if (exposed[prop]?.type === \"visibility\") continue;\n      wanted.add(part);\n    }\n  });\n  root.querySelectorAll(`[${EXPOSED_ATTRIBUTE}]`).forEach(element => {\n    if (!wanted.has(element)) element.removeAttribute(EXPOSED_ATTRIBUTE);\n  });\n  wanted.forEach(element => {\n    if (!element.hasAttribute(EXPOSED_ATTRIBUTE)) {\n      element.setAttribute(EXPOSED_ATTRIBUTE, \"\");\n    }\n  });\n}\n\n/** Each composed node of the placement that carries an exposure map, by id. */\nfunction exposuresOf(\n  nodes: readonly ResolvedBlockNode[],\n  placementId: string\n): Map<string, Readonly<Record<string, PropExposure>>> {\n  const found = new Map<string, Readonly<Record<string, PropExposure>>>();\n  const queue = [...nodes];\n  for (let head = 0; head < queue.length; head += 1) {\n    const node = queue[head];\n    if (typeof node !== \"object\" || node === null) continue;\n    if (node.instanceOf === placementId && node.exposedProps !== undefined) {\n      found.set(node.id, node.exposedProps);\n    }\n    const slots: unknown = node.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  }\n  return found;\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","\"use client\";\n\n/**\n * The control that chooses which interaction state the Style tab edits: a\n * compact menu named \"State\" on the bar's second line, as the editor mock\n * draws it (\"State: Normal ⌄\"), its items the four states.\n *\n * **At the top of the Style tab, not in the canvas chrome.** A breakpoint is a\n * fact about the whole page and belongs beside the canvas it resizes; a state\n * is a fact about the SELECTED BLOCK, and the panel is already scoped to that\n * block. Putting the two together would promise a symmetry that does not hold\n * and would leave this control needing a dead state whenever nothing is\n * selected. Webflow, Framer and Plasmic all place it inside the style panel for\n * the same reason, so an author arriving from any of them finds it where they\n * expect.\n *\n * **It reports which states already carry values**, which is the question\n * reading the values cannot answer. Styles inherit: opening `focus` on a block\n * with no focus styles shows the base values, so an author checking each state\n * in turn sees plausible numbers everywhere and still cannot tell which ones\n * were set. Marking the states that hold declarations of their own turns four\n * clicks and a misreading into one glance.\n *\n * @module state-switcher\n */\n\nimport {\n  type BreakpointSet,\n  type NodeStyles,\n  STYLE_STATES,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { Check, ChevronDown } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { stateHasOwnValues } from \"../../styles/style-values\";\n\n/**\n * What each state is CALLED, in this product's vocabulary.\n *\n * The engine's identifiers are CSS's — `base`, `hover`, `focus`, `active` — and\n * they are the wrong words for the people using this control. `active` is the\n * most misread term in CSS: authors reliably take it to mean \"current\" or\n * \"selected\" rather than \"being pressed\". The labels describe what the visitor\n * is DOING, which is the thing an author is styling.\n *\n * Typed as a total record rather than a lookup with a fallback, so adding a\n * state to the engine fails to compile here instead of shipping a control with\n * an unnamed option.\n */\nconst STATE_LABELS: Readonly<Record<StyleState, string>> = {\n  base: \"Normal\",\n  hover: \"Hover\",\n  focus: \"Focus\",\n  active: \"Pressed\",\n};\n\n/** A state's name in this product's words: Normal, Hover, Focus, Pressed. */\nexport function stateLabel(state: StyleState): string {\n  return STATE_LABELS[state];\n}\n\n/**\n * What each state MEANS, for the accessible name and the tooltip.\n *\n * The label alone does not say what selecting it will do — \"Pressed\" names a\n * state without saying whose, and a screen reader user gets no more from it\n * than the word.\n */\nconst STATE_HINTS: Readonly<Record<StyleState, string>> = {\n  base: \"the normal appearance, before any interaction\",\n  hover: \"while the pointer is over it\",\n  focus: \"while it has keyboard focus\",\n  active: \"while it is being pressed\",\n};\n\n/**\n * Props for StateSwitcher.\n * @experimental\n */\nexport interface StateSwitcherProps {\n  /** The state currently being edited. */\n  state: StyleState;\n  /** Choose a different state to edit and preview. */\n  onSelect: (state: StyleState) => void;\n  /**\n   * The selected node's stored styles, for reporting which states carry values.\n   *\n   * Optional because the marker is an affordance rather than the control: a\n   * host that cannot supply them gets a working switcher with nothing marked,\n   * which is honest. Supplying an empty object would claim every state is\n   * unstyled.\n   */\n  styles?: NodeStyles | undefined;\n  /**\n   * The site's breakpoints, so a marker counts only tiers the sheet has.\n   *\n   * A value stored under a deleted tier reaches no visitor, and marking it\n   * sends an author looking for an appearance nobody can see.\n   */\n  breakpoints?: BreakpointSet | undefined;\n}\n\nexport function StateSwitcher({\n  state,\n  onSelect,\n  styles,\n  breakpoints,\n}: StateSwitcherProps): React.JSX.Element {\n  /*\n   * Not marked on `base`. It carries values on almost every block, so a dot\n   * there is on permanently and says nothing, and a marker that is always lit\n   * is read as decoration, which costs the other three the meaning they\n   * depend on.\n   */\n  const marked = (option: StyleState): boolean =>\n    option !== \"base\" && stateHasOwnValues(styles, option, breakpoints);\n  // The states with values that the canvas is NOT showing, which the trigger\n  // names so a hidden state stays discoverable with the menu closed.\n  const elsewhere = STYLE_STATES.filter(\n    option => option !== state && marked(option)\n  );\n  const triggerName = [\n    `State: ${STATE_LABELS[state]}`,\n    ...elsewhere.map(option => `${STATE_LABELS[option]} has values`),\n  ].join(\", \");\n  return (\n    <>\n      {/* Not modal, as the editor's other menus are not: a modal menu hides\n          the editor around it while its controls stay focusable. */}\n      <DropdownMenu modal={false}>\n        <DropdownMenuTrigger asChild>\n          <button\n            type=\"button\"\n            className=\"nx-state-menu\"\n            aria-label={triggerName}\n            title={`${STATE_LABELS[state]}: ${STATE_HINTS[state]}`}\n          >\n            <span aria-hidden=\"true\">{STATE_LABELS[state]}</span>\n            <ChevronDown aria-hidden=\"true\" size={12} />\n          </button>\n        </DropdownMenuTrigger>\n        <DropdownMenuContent align=\"start\" collisionPadding={8}>\n          {STYLE_STATES.map(option => (\n            <DropdownMenuItem\n              key={option}\n              // One choice of four: a radio item, its choice marked with a\n              // tick, which cannot be mistaken for the \"has values\" dot.\n              role=\"menuitemradio\"\n              aria-checked={option === state}\n              /*\n               * The marker is in the ACCESSIBLE NAME, not only in the dot: it\n               * is the one piece of information this control adds beyond its\n               * labels.\n               */\n              aria-label={\n                marked(option)\n                  ? `${STATE_LABELS[option]}, has values`\n                  : STATE_LABELS[option]\n              }\n              title={STATE_HINTS[option]}\n              onSelect={() => onSelect(option)}\n            >\n              <span className=\"nx-state-menu__tick\" aria-hidden=\"true\">\n                {option === state ? <Check size={12} /> : null}\n              </span>\n              {STATE_LABELS[option]}\n              {marked(option) ? <StateDot /> : null}\n            </DropdownMenuItem>\n          ))}\n        </DropdownMenuContent>\n      </DropdownMenu>\n      {/*\n       * The states with values the canvas is not showing, in words beside the\n       * trigger rather than as a dot on it, where a dot would read as the\n       * shown state having values. The trigger's name already says which.\n       * One state is named, so the words say where to look; several are\n       * counted, since naming each would outgrow the bar's line.\n       */}\n      {elsewhere.length > 0 ? (\n        <span className=\"nx-state-menu__elsewhere\" aria-hidden=\"true\">\n          {elsewhereWords(elsewhere)}\n        </span>\n      ) : null}\n    </>\n  );\n}\n\n/** The words beside the trigger for the other states with values. */\nfunction elsewhereWords(elsewhere: readonly StyleState[]): string {\n  const [only] = elsewhere;\n  return elsewhere.length === 1 && only !== undefined\n    ? `· ${STATE_LABELS[only]} set`\n    : `· ${elsewhere.length} more set`;\n}\n\n/**\n * The dot beside a state with values. Coloured `currentColor`, a CSS keyword\n * rather than a theme lookup, so it takes the colour of the words beside it in\n * either theme and in the selected item alike.\n */\nfunction StateDot(): React.JSX.Element {\n  return (\n    <span\n      aria-hidden=\"true\"\n      data-nx-state-marked=\"true\"\n      className=\"nx-state-menu__dot\"\n    />\n  );\n}\n\n/**\n * Props for StyleStateField.\n * @experimental\n */\nexport interface StyleStateFieldProps {\n  /** The state currently being edited. `base` when the host says nothing. */\n  state?: StyleState | undefined;\n  /**\n   * Choose a different state, or `undefined` where nothing can act on the\n   * choice — which is what withholds the control.\n   */\n  onSelect?: ((state: StyleState) => void) | undefined;\n  /**\n   * The selected node, whose stored styles the markers are read from.\n   *\n   * The NODE rather than its styles, so the one place that knows a marker is\n   * about stored styles is also the place that reaches for them — a caller\n   * handed a styles-shaped prop has to know that much itself, and every caller\n   * then knows it separately.\n   */\n  node?: { styles?: NodeStyles } | null | undefined;\n  /** The site's breakpoints, so a marker counts only tiers the sheet has. */\n  breakpoints?: BreakpointSet | undefined;\n}\n\n/**\n * The switcher as a style panel mounts it, including whether to mount it.\n *\n * The condition lives with the CONTROL rather than at the call site, because it\n * is a property of the control: this switcher's state and `Canvas.forcedState`\n * are one value, so a host that cannot carry the choice to its canvas would get\n * a switcher reporting a state the author is not looking at. Deciding that\n * where the control is defined also keeps the panel free of a branch per\n * optional prop, which is how a panel already rendering three tabs becomes one\n * nobody can read.\n *\n * Both props accept an explicit `undefined` so a caller can forward whatever it\n * holds without a conditional spread at every call site.\n */\nexport function StyleStateField({\n  state = \"base\",\n  onSelect,\n  node,\n  breakpoints,\n}: StyleStateFieldProps): React.JSX.Element | null {\n  if (onSelect === undefined) return null;\n  return (\n    <span className=\"nx-inspector__state\">\n      <StateSwitcher\n        state={state}\n        onSelect={onSelect}\n        styles={node?.styles}\n        breakpoints={breakpoints}\n      />\n    </span>\n  );\n}\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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * \"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 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 * Typing into a component's exposed text on the canvas.\n *\n * A component is inlined at render: the element an author double-clicks\n * belongs to a re-identified node that the page document does not hold, so the\n * ordinary inline edit, which finds its node in the page, finds nothing. The\n * value it shows comes from the placement, through one of the component's\n * exposures, and that is where an edit has to go.\n *\n * The editor's composition carries the resolver's exposure map\n * (`exposedProps`): which exposure feeds each prop of a composed node, for the\n * host placement's own component only. So the answer is read, never rebuilt:\n * the composed node names its placement (`instanceOf`) and the exposure, and\n * the edit is the placement's own value under that exposure's id — one op, so\n * one undo step, exactly what the panel's field writes.\n *\n * Text the component does not expose is part of the component's design. A\n * double-click there selects the placement and says so, rather than doing\n * nothing.\n *\n * @module exposed-inline\n */\nimport {\n  authoredText,\n  findNode,\n  getBlock,\n  isComponentInstance,\n  isRichTextValue,\n  oneParagraphLines,\n  registryBlockSource,\n  type BlockDocument,\n  type BlockNode,\n  type ResolvedBlockNode,\n  type RichTextValue,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { setOverrideOp } from \"../inspector/instance-inspector\";\nimport { lockBlockingEdit } from \"../locking\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport { composedHolds } from \"./component-holds\";\nimport { inlinePropKind } from \"./inline-prop-kind\";\nimport { richTextChanged } from \"./inline-rich-text\";\n\n/** An exposed value the canvas may edit in place, addressed through its placement. */\nexport interface ExposedTextTarget {\n  /** The composed node the element belongs to, as the canvas addresses it. */\n  readonly nodeId: string;\n  readonly prop: string;\n  /** The placement the value is stored on, a node of the page document. */\n  readonly placementId: string;\n  /** The exposure id the value is stored under. */\n  readonly exposureId: string;\n  readonly multiline: boolean;\n  /** The value the page shows now. */\n  readonly value: string;\n}\n\n/**\n * An exposed passage the canvas may edit in place, addressed through its\n * placement. The passage itself is read when the editor opens and again when\n * it closes ({@link exposedPassage}), never carried, so a change made to it\n * meanwhile is seen.\n */\nexport interface ExposedRichTarget {\n  /** The composed node the element belongs to, as the canvas addresses it. */\n  readonly nodeId: string;\n  readonly prop: string;\n  /** The placement the passage is stored on, a node of the page document. */\n  readonly placementId: string;\n  /** The exposure id the passage is stored under. */\n  readonly exposureId: string;\n}\n\n/** What a double-click on a component's text means. */\nexport type ComposedTextAnswer =\n  | { readonly kind: \"exposed\"; readonly target: ExposedTextTarget }\n  | { readonly kind: \"exposed-rich\"; readonly target: ExposedRichTarget }\n  /**\n   * Not editable here: the text belongs to the component's design, or, with\n   * `heldExposureId`, the exposure feeding it is held by a lock the component\n   * sets, whose row in the panel says why.\n   */\n  | {\n      readonly kind: \"part-of\";\n      readonly placementId: string;\n      readonly heldExposureId?: string;\n    };\n\n/**\n * What the canvas may do with a value of a composed node, or `null` when the\n * node is the page's own and the ordinary inline edit answers for it.\n *\n * Text a `text` exposure feeds, and a passage a `richText` exposure feeds, on\n * an unlocked placement, are editable. Anything else in a component is \"part\n * of\" it: text it does not expose, a placement locked in Layers, and a value\n * the component's own locks hold (a block it locks in Layers, or a prop that\n * is not content inside an area locked to its content; the panel holds that\n * row read-only, with the reason).\n *\n * @param document - the page document, which holds the placement\n * @param composed - the editor's composition of it, with the exposure map\n * @param nodeId - the composed node's id, as the element carries it\n * @param prop - the prop the element renders\n * @param locks - the block definitions the editor judges locks by\n */\nexport function composedTextAt(\n  document: BlockDocument,\n  composed: BlockDocument | undefined,\n  nodeId: string,\n  prop: string,\n  locks: SlotDefaultSource = registryBlockSource()\n): ComposedTextAnswer | null {\n  if (composed === undefined) return null;\n  const found = placedNode(document, composed, nodeId);\n  if (found === null) return null;\n  const { node, placement } = found;\n  const schema = getBlock(node.type)?.props?.[prop];\n  const kind = inlinePropKind(schema);\n  // Free text through a text exposure, a passage through a rich-text one: an\n  // exposure of another type aimed at the prop is edited in the panel, where\n  // its control keeps the value valid.\n  const exposureId = exposureOf(\n    document,\n    node,\n    prop,\n    placement,\n    kind === \"rich\" ? \"richText\" : \"text\"\n  );\n  // The judgement the panel's rows are held by, so the canvas offers exactly\n  // the text the panel lets change.\n  if (\n    exposureId !== undefined &&\n    composedHolds(composed, locks)(node, prop, false) !== undefined\n  ) {\n    return {\n      kind: \"part-of\",\n      placementId: placement.id,\n      heldExposureId: exposureId,\n    };\n  }\n  // Bound to data, the prop shows the field whatever is typed, so it is\n  // changed through the binding in the panel.\n  if (exposureId === undefined || kind === null || isBound(node, prop)) {\n    return { kind: \"part-of\", placementId: placement.id };\n  }\n  if (kind === \"rich\") {\n    return {\n      kind: \"exposed-rich\",\n      target: { nodeId, prop, placementId: placement.id, exposureId },\n    };\n  }\n  // The text the page draws for this value, through the projection every\n  // reader shares, so an untouched edit compares equal and writes nothing.\n  // A one-paragraph value is drawn with its marks and line breaks, and read\n  // back as the element's text, which holds its words and no breaks.\n  const own = (node.props as Record<string, unknown> | undefined)?.[prop];\n  const shown = kind === \"line\" ? oneParagraphLines(own) : authoredText(own);\n  return {\n    kind: \"exposed\",\n    target: {\n      nodeId,\n      prop,\n      placementId: placement.id,\n      exposureId,\n      multiline: schema?.type === \"textarea\",\n      value: shown,\n    },\n  };\n}\n\n/**\n * The composed node and the page's placement it came from, or `null` when the\n * node is not one a placement contributed.\n */\nfunction placedNode(\n  document: BlockDocument,\n  composed: BlockDocument,\n  nodeId: string\n): { node: ResolvedBlockNode; placement: BlockNode } | null {\n  // Read as a composed node: the composition is the resolver's output, whose\n  // nodes carry `instanceOf` and the exposure map.\n  const node: ResolvedBlockNode | undefined = findNode(composed.nodes, nodeId);\n  const placementId = node?.instanceOf;\n  if (node === undefined || typeof placementId !== \"string\") return null;\n  const placement = findNode(document.nodes, placementId);\n  if (placement === undefined || !isComponentInstance(placement)) return null;\n  return { node, placement };\n}\n\n/** Whether the composed node's prop is bound, as a placement's binding lands. */\nfunction isBound(node: ResolvedBlockNode, prop: string): boolean {\n  const bindings: unknown = node.bindings;\n  return (\n    typeof bindings === \"object\" &&\n    bindings !== null &&\n    Object.hasOwn(bindings, prop)\n  );\n}\n\n/**\n * The id of the exposure of this type feeding this prop, when the placement\n * may change it.\n */\nfunction exposureOf(\n  document: BlockDocument,\n  node: ResolvedBlockNode,\n  prop: string,\n  placement: BlockNode,\n  type: \"text\" | \"richText\"\n): string | undefined {\n  const fed = node.exposedProps;\n  const exposure =\n    fed !== undefined && Object.hasOwn(fed, prop) ? fed[prop] : undefined;\n  // The placement's Layers lock, its own or one around it: either holds every\n  // value the placement stores.\n  if (\n    exposure?.type !== type ||\n    lockBlockingEdit(document, placement.id) !== undefined\n  ) {\n    return undefined;\n  }\n  return exposure.id;\n}\n\n/**\n * The op that stores what the author typed as the placement's value, or\n * `null` when nothing changed or the placement is gone.\n *\n * An emptied value CLEARS the field (`$unset`), as the panel's field does:\n * the author took the text away, which inheriting would put back.\n */\nexport function exposedTextOp(\n  document: BlockDocument,\n  target: ExposedTextTarget,\n  next: string\n): BuilderOp | null {\n  if (next === target.value) return null;\n  const placement: BlockNode | undefined = findNode(\n    document.nodes,\n    target.placementId\n  );\n  if (\n    placement === undefined ||\n    lockBlockingEdit(document, placement.id) !== undefined\n  ) {\n    return null;\n  }\n  return setOverrideOp(\n    placement,\n    target.exposureId,\n    next === \"\" ? { $unset: true } : next\n  );\n}\n\n/**\n * The passage an exposed target shows now, raw as the composition holds it, or\n * `null` once it is no longer editable in place (the placement was locked or\n * removed, or the exposure stopped feeding it). Judged by\n * {@link composedTextAt}, the one answer the canvas opens a passage by, so the\n * editor closes on exactly the rules it opened on.\n */\nexport function exposedPassage(\n  document: BlockDocument,\n  composed: BlockDocument | undefined,\n  target: ExposedRichTarget,\n  locks: SlotDefaultSource = registryBlockSource()\n): {\n  readonly stored: unknown;\n  readonly value: RichTextValue | undefined;\n} | null {\n  const answer = composedTextAt(\n    document,\n    composed,\n    target.nodeId,\n    target.prop,\n    locks\n  );\n  if (\n    answer?.kind !== \"exposed-rich\" ||\n    answer.target.placementId !== target.placementId ||\n    answer.target.exposureId !== target.exposureId ||\n    composed === undefined\n  ) {\n    return null;\n  }\n  const node = findNode(composed.nodes, target.nodeId);\n  const stored = node?.props?.[target.prop];\n  return { stored, value: isRichTextValue(stored) ? stored : undefined };\n}\n\n/**\n * The op that stores an edited passage as the placement's value, or `null`\n * when there is nothing to write: the passage is unchanged, the editor did not\n * return a passage, it is no longer editable, or the page's copy changed while\n * it was open (the older copy is never written over the newer). One op, the\n * same the panel's field writes, so one undo step.\n *\n * @param next - what the editor read when the edit finished\n * @param before - what it read when the passage opened\n * @param opened - the raw passage the session was handed\n */\nexport function exposedRichOp(\n  document: BlockDocument,\n  composed: BlockDocument | undefined,\n  target: ExposedRichTarget,\n  next: unknown,\n  before: unknown,\n  opened: unknown,\n  locks: SlotDefaultSource = registryBlockSource()\n): BuilderOp | null {\n  const now = exposedPassage(document, composed, target, locks);\n  if (now === null || richTextChanged(opened, now.stored)) return null;\n  if (!isRichTextValue(next) || !richTextChanged(before, next)) return null;\n  const placement: BlockNode | undefined = findNode(\n    document.nodes,\n    target.placementId\n  );\n  if (placement === undefined) return null;\n  return setOverrideOp(placement, target.exposureId, next);\n}\n","/**\n * What became of an attempt to edit a value in place.\n *\n * A commit used to answer with the document it wrote, or `null`. That `null`\n * carried four different outcomes, and two of them are opposites: \"the author\n * changed nothing, let go\" and \"this could not be written, and their words\n * exist only in the editor that is still holding them\". Every caller read it as\n * the first, so the ones that meant the second closed the editor over unsaved\n * text, re-pointed the shared editor at another passage, or handed the form a\n * document the author's paragraph never reached.\n *\n * So the outcome is stated rather than encoded in an absence. A host that\n * ignores {@link InlineEditRefused} does not compile, which is the only\n * version of this that stays true as surfaces are added.\n *\n * @module inline-edit-outcome\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\n\n/** Why a finished edit could not be written. */\nexport type InlineEditRefusal =\n  /**\n   * The document's own copy of the value changed while the caret was in it —\n   * another surface, an undo, or an op from anywhere else.\n   */\n  | \"moved-on\"\n  /**\n   * The op layer refused the write. A cap the edit would exceed is the case an\n   * author can act on; a node that went while they typed is the case they\n   * cannot.\n   */\n  | \"rejected\"\n  /**\n   * The value stopped being editable while the caret was in it — a lock\n   * arrived, or it is no longer a shape this surface can store — and its\n   * element is still on the page. The words stay there to be copied, and a\n   * second Escape lets them go.\n   */\n  | \"no-longer-editable\";\n\n/** The edit produced a document. */\nexport interface InlineEditWritten {\n  readonly status: \"written\";\n  readonly document: BlockDocument;\n}\n\n/** There was nothing to write: no edit was open, or none of it changed. */\nexport interface InlineEditUnchanged {\n  readonly status: \"unchanged\";\n}\n\n/**\n * The author changed the value, it could not be stored, and the surface has\n * been given back.\n *\n * The value stopped being editable while the caret was in it and its element\n * has left the page, so there is nothing to keep the words in: the block was\n * deleted, or the canvas re-rendered without it. Their typing is gone, and a\n * host that can say so should: nothing else will mention it. While the element\n * is still on the page the edit is {@link InlineEditRefused} instead, except\n * where the host itself finished a line of text: a host finishing an edit is\n * closing or opening something else, so the line cannot stay open, and its\n * unwritten words are reported here.\n *\n * Distinct from {@link InlineEditRefused} in the one way that matters to a\n * host: there is nothing left to protect, so this must not stop it closing.\n */\nexport interface InlineEditDiscarded {\n  readonly status: \"discarded\";\n}\n\n/**\n * The edit could not be written and is STILL OPEN, holding the author's words.\n *\n * The surface deliberately kept itself mounted, because letting go is what\n * destroys the text — it lives in the editor and nowhere else, and the page\n * would put the older copy back in its place with nothing said.\n *\n * A host must not close, navigate, or open another value on this. What it\n * should do is leave the caret where it is and tell the author, so the text\n * they can still see is text they can still copy.\n */\nexport interface InlineEditRefused {\n  readonly status: \"refused\";\n  readonly reason: InlineEditRefusal;\n}\n\n/**\n * The edit never opened, because the shared editor is holding another one.\n *\n * There is ONE editor behind every surface, and a passage kept open because its\n * words exist nowhere else refuses to give it up. So this is not a failure of\n * the value the author just asked for — it is the previous edit still being\n * protected, and the only thing that resolves it is finishing that one.\n *\n * Reported through the same channel as the outcomes above rather than a second\n * one, because a host that told the author about a refused write in one voice\n * and a refused OPEN in another would be two messages about one editor.\n */\nexport interface InlineEditUnavailable {\n  readonly status: \"unavailable\";\n}\n\n/** What became of an attempt to edit a value in place. */\nexport type InlineEditOutcome =\n  | InlineEditWritten\n  | InlineEditUnchanged\n  | InlineEditDiscarded\n  | InlineEditRefused\n  | InlineEditUnavailable;\n\n/** The shared editor was busy protecting an edit that could not be written. */\nexport const INLINE_EDIT_UNAVAILABLE: InlineEditUnavailable = {\n  status: \"unavailable\",\n};\n\n/** Nothing was open, or nothing about the value changed. */\nexport const INLINE_EDIT_UNCHANGED: InlineEditUnchanged = {\n  status: \"unchanged\",\n};\n\n/** The author's typing could not be stored and the surface has been released. */\nexport const INLINE_EDIT_DISCARDED: InlineEditDiscarded = {\n  status: \"discarded\",\n};\n\n/**\n * The document a host should hold after a commit.\n *\n * `held` is what it had before — the right answer for every outcome that did\n * not produce a new one, including a refusal, where the document genuinely has\n * not changed and the edit is still live.\n *\n * @param outcome - what the commit did\n * @param held - the document the host was holding\n * @returns the document to carry forward\n */\nexport function documentAfter(\n  outcome: InlineEditOutcome,\n  held: BlockDocument\n): BlockDocument {\n  return outcome.status === \"written\" ? outcome.document : held;\n}\n","/**\n * Which of a block's values an author may type directly on the canvas, and the\n * op a finished edit produces.\n *\n * Pure, like every rule in this package, and for the same reason: whether a\n * value is editable in place, and whether a finished edit changed anything, are\n * derivations — and a component test in jsdom cannot separate a correct answer\n * from a plausible wrong one, because both render a caret.\n *\n * **The block decides, not this module.** A prop is offered here only when its\n * schema declares `inline`, which is the same declaration the renderer reads\n * when it marks the element holding the value. Two lists would be two answers\n * to one question, and the failure is quiet: an editor that offers a value the\n * canvas never marked leaves an author double-clicking text that never becomes\n * editable.\n *\n * @module inline-text\n */\n\nimport {\n  findNode,\n  itemOfPropName,\n  itemPropName,\n  type BlockDocument,\n  type BlockNode,\n  type PropSchema,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { propPatch } from \"../inspector/inspector\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport { inlinePropsOfKind } from \"./inline-target\";\n\n/** One value a canvas may let an author type into. */\nexport interface InlineTextTarget {\n  readonly nodeId: string;\n  readonly prop: string;\n  /**\n   * Whether the value may hold line breaks, which is what decides where Enter\n   * goes: into the text for a paragraph, and out of the edit for a heading.\n   *\n   * Read from the schema's own `type` rather than from a list of prop names\n   * kept here, so a block that changes a field from one to the other changes\n   * this with it.\n   */\n  readonly multiline: boolean;\n  /** The value as the document holds it, normalised to a string. */\n  readonly value: string;\n}\n\n/**\n * A stored value as text.\n *\n * Anything that is not a string reads as empty rather than as `\"undefined\"` or\n * `\"[object Object]\"`. A stored document holds whatever a migration, an import\n * or a hand-edited row left there, and putting one of those spellings into an\n * editable element would let an author \"keep\" a value they never typed.\n */\nfunction asText(value: unknown): string {\n  return typeof value === \"string\" ? value : \"\";\n}\n\nfunction targetFor(\n  node: BlockNode,\n  prop: string,\n  schema: PropSchema | undefined\n): InlineTextTarget {\n  return {\n    nodeId: node.id,\n    prop,\n    multiline: schema?.type === \"textarea\",\n    value: asText(valueAt(node, prop)),\n  };\n}\n\n/**\n * What a node holds under a canvas value's name: the prop's value, or one item\n * of a list of words (`items.2`).\n */\nfunction valueAt(node: BlockNode, name: string): unknown {\n  const props = node.props as Record<string, unknown> | undefined;\n  const item = itemOfPropName(name);\n  if (item === null) return props?.[name];\n  const items = props?.[item.prop];\n  return Array.isArray(items) ? items[item.index] : undefined;\n}\n\n/**\n * The op writing a node's list of words with one change made to a copy of\n * it. The whole list is written, as the panel writes it, so an item has no\n * second way to be stored.\n */\nfunction itemsOp(\n  node: BlockNode,\n  prop: string,\n  change: (items: unknown[]) => void\n): BuilderOp {\n  const stored = (node.props as Record<string, unknown> | undefined)?.[prop];\n  const items = Array.isArray(stored) ? [...stored] : [];\n  change(items);\n  return { kind: \"update\", id: node.id, patch: propPatch(node, prop, items) };\n}\n\n/**\n * Every value on this node that may be typed on the canvas, in the order the\n * block declared them.\n *\n * Empty for a LOCKED block, and for a node whose type is not registered. A lock\n * is what an author set to stop the block changing, and inline editing is a\n * change — the lock has to be honoured at every entry point or it is honoured\n * at none, which is the state where an author believes a block is protected.\n *\n * @param document - the document being edited\n * @param nodeId - the node to ask about\n * @returns the editable values, empty when there are none\n */\nexport function inlineTargets(\n  document: BlockDocument,\n  nodeId: string\n): readonly InlineTextTarget[] {\n  const found = inlinePropsOfKind(document, nodeId, \"plain\");\n  if (found === null) return [];\n  return found.entries.map(([name, schema]) =>\n    targetFor(found.node, name, schema)\n  );\n}\n\n/**\n * One named value, or `null` when it is not editable on the canvas.\n *\n * Derived from {@link inlineTargets} rather than repeating its rules, so a\n * block that is locked, unregistered or has not declared the prop answers the\n * same way to both.\n *\n * @param document - the document being edited\n * @param nodeId - the node to ask about\n * @param prop - the value's name\n * @returns the target, or `null`\n */\nexport function inlineTarget(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string\n): InlineTextTarget | null {\n  return inlineTargets(document, nodeId).find(t => t.prop === prop) ?? null;\n}\n\n/**\n * The op a finished edit produces, or `null` when there is nothing to write.\n *\n * `null` for an unchanged value, deliberately: an author who enters an edit and\n * leaves without typing has made no edit, and recording one would put an entry\n * on the undo stack that appears to do nothing — which reads as the history\n * being broken rather than as an empty change.\n *\n * `null` also when the value stopped being editable while the edit was open. A\n * node can be deleted or locked from the layers panel, from a keyboard action,\n * or by another surface entirely, and writing the text back then would either\n * address a node that is gone or defeat a lock that was applied after the\n * caret went in.\n *\n * @param document - the document as it stands NOW, not when the edit began\n * @param nodeId - the node being edited\n * @param prop - the value being edited\n * @param next - the text the author left behind\n * @returns one op, or `null`\n */\nexport function inlineTextOp(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string,\n  next: string\n): BuilderOp | null {\n  const target = inlineTarget(document, nodeId, prop);\n  if (target === null || target.value === next) return null;\n  const node = findNode(document.nodes, nodeId);\n  if (node === undefined) return null;\n  const item = itemOfPropName(prop);\n  if (item !== null) {\n    return itemsOp(node, item.prop, items => {\n      items[item.index] = next;\n    });\n  }\n  return { kind: \"update\", id: nodeId, patch: propPatch(node, prop, next) };\n}\n\n/**\n * The item being typed and its node, while it is still editable here: the\n * same refusals as any other canvas value (gone, locked, not declared).\n */\nfunction editableItem(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string\n): { node: BlockNode; prop: string; index: number } | null {\n  const item = itemOfPropName(prop);\n  if (item === null || inlineTarget(document, nodeId, prop) === null) {\n    return null;\n  }\n  const node = findNode(document.nodes, nodeId);\n  return node === undefined ? null : { node, ...item };\n}\n\n/** An edit to a list of words, and the item the caret goes to after it. */\nexport interface ItemEdit<Next> {\n  readonly op: BuilderOp;\n  readonly next: Next;\n}\n\n/**\n * Enter in an item: the words before the caret stay, the words after it start\n * a new item after this one, and the caret goes there. One op, so one undo\n * takes the new item back with the words it took. `null` when the item is no\n * longer editable here.\n *\n * @param head - the item's words before the caret\n * @param tail - its words after the caret, empty at its end\n */\nexport function splitItemOp(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string,\n  head: string,\n  tail: string\n): ItemEdit<string> | null {\n  const found = editableItem(document, nodeId, prop);\n  if (found === null) return null;\n  return {\n    op: itemsOp(found.node, found.prop, items => {\n      items.splice(found.index, 1, head, tail);\n    }),\n    next: itemPropName(found.prop, found.index + 1),\n  };\n}\n\n/** Where the caret goes in the item an edit moved it to. */\nexport interface ItemCaret {\n  readonly prop: string;\n  readonly caret: \"start\" | \"end\";\n}\n\n/**\n * Backspace in an empty item: the item goes, and the caret goes to the end of\n * the item before it, or to the start of the one that followed when it was\n * the first. `next` is `null` when it was the only item. `null` when the item\n * is no longer editable here.\n */\nexport function removeItemOp(\n  document: BlockDocument,\n  nodeId: string,\n  prop: string\n): ItemEdit<ItemCaret | null> | null {\n  const found = editableItem(document, nodeId, prop);\n  if (found === null) return null;\n  let left = 0;\n  const op = itemsOp(found.node, found.prop, items => {\n    items.splice(found.index, 1);\n    left = items.length;\n  });\n  const next: ItemCaret | null =\n    found.index > 0\n      ? { prop: itemPropName(found.prop, found.index - 1), caret: \"end\" }\n      : left > 0\n        ? { prop: itemPropName(found.prop, 0), caret: \"start\" }\n        : null;\n  return { op, next };\n}\n","\"use client\";\n\n/**\n * Typing a block's text directly on the canvas.\n *\n * The DOM half of {@link module:inline-text}, which decides WHAT may be edited;\n * this decides how. The split is the same one the rest of this package makes,\n * and here it earns its keep twice over: the rules are asserted without a\n * browser, and the parts that genuinely need one are small enough to read.\n *\n * ## The element is left UNCONTROLLED while the caret is in it\n *\n * No op is dispatched per keystroke. React renders the canvas from the\n * document, so an edit that wrote through on every character would re-render\n * the element the author is typing into and move the caret out from under\n * them — the standard failure of `contentEditable` inside a framework that\n * owns the DOM. Every editor that does this well hands the element over for\n * the duration: Gutenberg, Lexical and Puck all do.\n *\n * So the document is untouched until the edit finishes, and finishing writes\n * ONE op. That also gives the behaviour an author expects from undo: a\n * sentence typed and then undone comes back as a sentence, not as forty\n * characters.\n *\n * The visible cost is that the inspector shows the value the document holds\n * rather than the letters being typed, until the edit is committed. That is\n * the same rule the blocks field itself follows when it commits its document\n * on exit, and one editor with two answers about when a change counts is\n * worse than a panel that updates a moment later.\n *\n * ## `plaintext-only`, with a fallback that still cannot store markup\n *\n * The values here are plain text, and `contenteditable=\"plaintext-only\"` is\n * what stops a paste bringing markup, a bold shortcut inserting a `<b>`, and\n * Enter inserting a `<div>`. Where a browser does not support it the attribute\n * falls back to ordinary editing, so the commit reads the element's text — which is\n * text whatever the element ended up containing.\n *\n * @module use-inline-text\n */\n\nimport { itemOfPropName, type BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { isElement } from \"./dom-kind\";\nimport {\n  composedTextAt,\n  exposedTextOp,\n  type ExposedTextTarget,\n} from \"./exposed-inline\";\nimport {\n  INLINE_EDIT_DISCARDED,\n  type InlineEditOutcome,\n  type InlineEditRefusal,\n} from \"./inline-edit-outcome\";\nimport { namedTarget } from \"./inline-target\";\nimport {\n  inlineTarget,\n  inlineTargets,\n  inlineTextOp,\n  removeItemOp,\n  splitItemOp,\n  type ItemCaret,\n  type ItemEdit,\n} from \"./inline-text\";\n\n/** The attribute naming the element an author is currently typing into. */\nexport const EDITING_ATTRIBUTE = \"data-nx-editing\";\n\n/** Which value is being edited. */\nexport interface InlineTextEditing {\n  readonly nodeId: string;\n  readonly prop: string;\n  /**\n   * Set when the value is a component's exposed text: the node is composed,\n   * and the edit is stored on the placement under the exposure's id.\n   */\n  readonly exposure?: ExposedTextTarget;\n}\n\n/**\n * The op a finished edit of exposed text writes, asked again of the editor as\n * it stands: the component library may have changed while the caret was in\n * the text, and a prop no longer fed by the same text exposure takes nothing.\n */\nfunction exposedCommitOp(\n  editor: EditorState,\n  started: ExposedTextTarget,\n  next: string\n) {\n  const now = exposedTarget(editor, started.nodeId, started.prop);\n  if (now === undefined || now.exposureId !== started.exposureId) return null;\n  return exposedTextOp(editor.document, started, next);\n}\n\n/**\n * What the document holds for this edit now, or `undefined` when the value\n * stopped being editable here: its block locked or removed, or the text no\n * longer fed by the same exposure.\n */\nfunction liveValueOf(\n  editor: EditorState,\n  current: InlineTextEditing\n): string | undefined {\n  if (current.exposure === undefined) {\n    return inlineTarget(editor.document, current.nodeId, current.prop)?.value;\n  }\n  const now = exposedTarget(\n    editor,\n    current.exposure.nodeId,\n    current.exposure.prop\n  );\n  return now?.exposureId === current.exposure.exposureId\n    ? now.value\n    : undefined;\n}\n\n/** How an edit would finish: a write, a refusal, or nothing to write. */\ntype Finish =\n  | { readonly op?: BuilderOp }\n  | { readonly refused: InlineEditRefusal };\n\nconst NOTHING_TO_WRITE: Finish = {};\n\n/** A composed node's exposed text, when that is what this value is. */\nfunction exposedTarget(\n  editor: EditorState,\n  nodeId: string,\n  prop: string\n): ExposedTextTarget | undefined {\n  const answer = composedTextAt(\n    editor.document,\n    editor.composed(),\n    nodeId,\n    prop,\n    editor.lockDefinitions\n  );\n  return answer?.kind === \"exposed\" ? answer.target : undefined;\n}\n\nexport interface UseInlineTextResult {\n  /** The value being edited, or `null` when none is. */\n  editing: InlineTextEditing | null;\n  /**\n   * Start editing a value, reporting whether it could be.\n   *\n   * `prop` defaults to the block's FIRST declared inline value, which is what\n   * a keyboard caller wants: it has a selected block and no element.\n   */\n  begin: (nodeId: string, prop?: string) => boolean;\n  /**\n   * Finish, writing whatever the author left behind.\n   *\n   * Returns the document the write produced, or `null` when there was nothing\n   * to write — a caller about to hand the document elsewhere holds the one from\n   * before this commit.\n   */\n  commit: () => BlockDocument | null;\n  /** Finish, discarding it. */\n  cancel: () => void;\n  /**\n   * Enter an edit from a double-click on the canvas.\n   *\n   * Handed to `Canvas` rather than attached here, because the canvas owns its\n   * own root and a second listener on the same tree would be a second place\n   * the gesture is decided.\n   */\n  onDoubleClick: (event: { target: EventTarget | null }) => void;\n}\n\n/**\n * The element the author is typing into, found from what they double-clicked.\n *\n * Walks UP from the event target rather than reading it: a click lands on\n * whatever leaf is under the pointer, and the element carrying the mark may be\n * an ancestor of it.\n */\n/**\n * The words an element holds, as the value it edits: its text, with each\n * `<br>` read as the `\\n` it stands for. `textContent` alone drops a line\n * break drawn as an element, so a line of a Text's one paragraph edited here\n * would come back joined to the next.\n */\nexport function elementWords(element: Node): string {\n  const parts: string[] = [];\n  const stack: Node[] = [...element.childNodes].reverse();\n  while (stack.length > 0) {\n    const node = stack.pop();\n    if (node === undefined) continue;\n    if (isElement(node) && node.localName === \"br\") {\n      parts.push(\"\\n\");\n      continue;\n    }\n    if (node.nodeType === node.TEXT_NODE) {\n      parts.push(node.nodeValue ?? \"\");\n      continue;\n    }\n    for (let i = node.childNodes.length - 1; i >= 0; i--) {\n      const child = node.childNodes[i];\n      if (child !== undefined) stack.push(child);\n    }\n  }\n  return parts.join(\"\");\n}\n\nexport function editableFrom(target: EventTarget | null): {\n  element: HTMLElement;\n  prop: string;\n  nodeId: string;\n} | null {\n  // By node kind: a double-click inside a canvas in a frame targets an\n  // element that frame's window built.\n  if (!isElement(target)) return null;\n  const element = target.closest<HTMLElement>(\"[data-nx-prop]\");\n  if (element === null) return null;\n  const prop = element.getAttribute(\"data-nx-prop\");\n  const owner = element.closest(\"[data-nx-node]\");\n  const nodeId = owner?.getAttribute(\"data-nx-node\") ?? null;\n  if (prop === null || nodeId === null) return null;\n  return { element, prop, nodeId };\n}\n\n/**\n * The element carrying a value, found from the rendered tree rather than from a\n * click.\n *\n * For a keyboard caller, which has a selected node and no element. The node id\n * is compared in JavaScript rather than interpolated into the selector: it\n * reaches this from stored data, and putting it in a selector makes any\n * character CSS treats specially either throw or match something else. The prop\n * name is a key from the block's own schema and is escaped rather than\n * compared, because it addresses an element that may have no other handle.\n *\n * Exported for its own test. Which element holds a value is the part of this\n * module that varies per block, and it is not observable from the hook's\n * result — a wrong answer here shows up as an edit that quietly never starts.\n */\nexport function editableElement(\n  root: ParentNode,\n  editing: InlineTextEditing\n): HTMLElement | null {\n  const owners = root.querySelectorAll<HTMLElement>(\"[data-nx-node]\");\n  let found: HTMLElement | 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  owners.forEach(owner => {\n    if (found !== null) return;\n    if (owner.getAttribute(\"data-nx-node\") !== editing.nodeId) return;\n    // The owner ITSELF first. A block whose text is its own root element — an\n    // unlinked heading is exactly this, carrying both attributes on one `<h2>`\n    // — is missed entirely by a descendant search, and the failure is silent:\n    // the edit never begins and the key reads as broken.\n    if (owner.getAttribute(\"data-nx-prop\") === editing.prop) {\n      found = owner;\n      return;\n    }\n    owner.querySelectorAll<HTMLElement>(\"[data-nx-prop]\").forEach(candidate => {\n      if (found !== null) return;\n      if (candidate.getAttribute(\"data-nx-prop\") !== editing.prop) return;\n      // Not a value belonging to a block nested inside this one. Blocks nest,\n      // so without this a container answers with its child's text and the\n      // caret lands in a block the author did not select.\n      if (candidate.closest(\"[data-nx-node]\") !== owner) return;\n      found = candidate;\n    });\n  });\n  return found;\n}\n\n/**\n * Where the caret goes as an edit opens: across the whole value, so typing\n * replaces it, as a double-click or a key opens one; or at its start or end,\n * as Enter and Backspace move it from one item of a list to the next.\n */\ntype CaretPlace = \"all\" | ItemCaret[\"caret\"];\n\nfunction placeCaret(element: HTMLElement, at: CaretPlace): void {\n  const selection = element.ownerDocument.defaultView?.getSelection();\n  if (!selection) return;\n  const range = element.ownerDocument.createRange();\n  range.selectNodeContents(element);\n  if (at !== \"all\") range.collapse(at === \"start\");\n  selection.removeAllRanges();\n  selection.addRange(range);\n}\n\n/**\n * An element's words either side of the caret, a selection's words dropped as\n * typing over them would drop them. All of them before it when the caret is\n * not in the element.\n */\nfunction wordsAroundCaret(element: HTMLElement): [string, string] {\n  const selection = element.ownerDocument.defaultView?.getSelection();\n  const range =\n    selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;\n  if (\n    range === null ||\n    !element.contains(range.startContainer) ||\n    !element.contains(range.endContainer)\n  ) {\n    return [withoutPlaceholder(element, elementWords(element)), \"\"];\n  }\n  const before = element.ownerDocument.createRange();\n  before.selectNodeContents(element);\n  before.setEnd(range.startContainer, range.startOffset);\n  const after = element.ownerDocument.createRange();\n  after.selectNodeContents(element);\n  after.setStart(range.endContainer, range.endOffset);\n  // Read as the element is, a `<br>` as the line break it stands for, so a\n  // split changes nothing either side of the caret; the placeholder an\n  // emptied line holds is the element's last node, so it ends whichever side\n  // reaches the element's end, and is no line break in either.\n  const head = elementWords(before.cloneContents());\n  const tail = elementWords(after.cloneContents());\n  return range.collapsed && tail === \"\" && !before.collapsed\n    ? [withoutPlaceholder(element, head), tail]\n    : [head, withoutPlaceholder(element, tail)];\n}\n\n/**\n * Words read up to an element's end, without the `<br>` a browser leaves as\n * its last node to hold an emptied line open. Judged by the element's last\n * node, not by the words: a line break stored as text is kept.\n */\nfunction withoutPlaceholder(element: Node, words: string): string {\n  return endsInBreak(element) && words.endsWith(\"\\n\")\n    ? words.slice(0, -1)\n    : words;\n}\n\n/**\n * The words an open edit holds. A browser holds an emptied line open with a\n * `<br>` as its last node; in an item of a list, which is one line, that\n * placeholder is not a line break, so an item emptied that way holds\n * nothing. Judged by the element's last node, not by the words: a line break\n * the item stores is text, and opening and leaving it keeps it.\n */\nfunction editedWords(element: Node, editing: InlineTextEditing): string {\n  const words = elementWords(element);\n  return itemOfPropName(editing.prop) !== null\n    ? withoutPlaceholder(element, words)\n    : words;\n}\n\n/** Whether an element's last node, however deep, is a `<br>`. */\nfunction endsInBreak(element: Node): boolean {\n  let last = element.lastChild;\n  while (last !== null && isElement(last) && last.localName !== \"br\") {\n    last = last.lastChild;\n  }\n  return last !== null && isElement(last) && last.localName === \"br\";\n}\n\n/** An edit to a list's items, planned against the document as it stands. */\ntype ItemPlan = () => ItemEdit<ItemCaret | null> | null;\n\n/**\n * What Enter or Backspace does in an item of a list, or `null` when the key\n * is not the list's: Enter adds the next item with the words after the caret,\n * and Backspace in an empty item removes it. Read when the key is pressed;\n * planned when it is written, against the document then.\n */\nfunction itemKeyPlan(\n  event: KeyboardEvent,\n  element: HTMLElement,\n  editing: InlineTextEditing,\n  documentNow: () => BlockDocument\n): ItemPlan | null {\n  if (editing.exposure !== undefined || event.isComposing) return null;\n  if (itemOfPropName(editing.prop) === null) return null;\n  const { nodeId, prop } = editing;\n  if (event.key === \"Enter\") {\n    const [head, tail] = wordsAroundCaret(element);\n    return () => {\n      const split = splitItemOp(documentNow(), nodeId, prop, head, tail);\n      return split === null\n        ? null\n        : { op: split.op, next: { prop: split.next, caret: \"start\" } };\n    };\n  }\n  if (event.key !== \"Backspace\" || editedWords(element, editing) !== \"\") {\n    return null;\n  }\n  return () => removeItemOp(documentNow(), nodeId, prop);\n}\n\n/**\n * Why the open value may not be written now, or `null`: it stopped being\n * editable here (a lock arrived, so there is nowhere to write it), or it moved\n * on while it was typed (writing would replace newer words with older ones).\n * Every write an edit makes asks this first.\n *\n * @param opened - the value as it was when the caret went in\n */\nfunction stalenessOf(\n  editor: EditorState,\n  current: InlineTextEditing,\n  opened: string | null\n): InlineEditRefusal | null {\n  const live = liveValueOf(editor, current);\n  if (live === undefined) return \"no-longer-editable\";\n  return opened !== null && live !== opened ? \"moved-on\" : null;\n}\n\n/**\n * The edit's side of moving through a list's items, read afresh each time a\n * key lands, so a key is judged against the editor and the session as they\n * stand then.\n */\nfunction itemMoveHostOf(\n  editor: { readonly current: EditorState },\n  editing: InlineTextEditing,\n  session: {\n    readonly current: {\n      readonly finished?: ((outcome: InlineEditOutcome) => void) | undefined;\n      readonly opened: string | null;\n    };\n  },\n  edit: ItemEditHandles\n): () => ItemMoveHost {\n  return () => itemMoveHost(editor.current, editing, session.current, edit);\n}\n\n/** What the edit hands over to open the next item. */\ninterface ItemEditHandles {\n  readonly release: () => void;\n  readonly session: { current: { caretAt: CaretPlace } };\n  readonly setEditing: (next: InlineTextEditing) => void;\n}\n\n/** The edit's side of moving through a list's items, as it stands now. */\nfunction itemMoveHost(\n  editor: EditorState,\n  editing: InlineTextEditing,\n  session: {\n    readonly finished?: ((outcome: InlineEditOutcome) => void) | undefined;\n    readonly opened: string | null;\n  },\n  edit: ItemEditHandles\n): ItemMoveHost {\n  return {\n    editor,\n    stale: stalenessOf(editor, editing, session.opened),\n    refused: reason => session.finished?.({ status: \"refused\", reason }),\n    release: edit.release,\n    open: next => {\n      edit.session.current.caretAt = next.caret;\n      edit.setEditing({ nodeId: editing.nodeId, prop: next.prop });\n    },\n  };\n}\n\n/** What moving through a list's items needs of the edit it moves from. */\ninterface ItemMoveHost {\n  readonly editor: EditorState;\n  /** Why the open value may not be written now, or `null`. */\n  readonly stale: InlineEditRefusal | null;\n  /** Told when the write is refused, the line staying open with its words. */\n  readonly refused: (reason: InlineEditRefusal) => void;\n  /** Ends the open edit. */\n  readonly release: () => void;\n  /** Opens the item the caret goes to. */\n  readonly open: (next: ItemCaret) => void;\n}\n\n/**\n * A planned edit to a list's items, written, then the caret moved on: the\n * refusal said when it cannot be written (the value moved on or stopped being\n * editable, or the page refused the write). The item the caret goes to is\n * asked of the document the write produced: the editor's own holds it only\n * from its next render, and an item Enter added is not in it yet.\n */\nfunction moveThroughItems(\n  host: ItemMoveHost,\n  element: HTMLElement,\n  editing: InlineTextEditing,\n  plan: ItemPlan\n): void {\n  if (host.stale !== null) return host.refused(host.stale);\n  const planned = plan();\n  if (planned === null) return host.refused(\"no-longer-editable\");\n  const written = host.editor.apply(planned.op);\n  if (written === null) return host.refused(\"rejected\");\n  // The element the author typed into, given back holding what its item now\n  // holds. Its item's stored words may not have changed (a split at the end\n  // of words typed after them), and then nothing redraws it: the words after\n  // the caret would show in it and in the item that took them.\n  element.textContent =\n    inlineTarget(written, editing.nodeId, editing.prop)?.value ?? \"\";\n  host.release();\n  const { next } = planned;\n  if (next === null) return;\n  if (inlineTarget(written, editing.nodeId, next.prop) === null) return;\n  host.open(next);\n}\n\n/**\n * Listen for Enter and Backspace in an item of a list being typed, and move\n * through its items by them. A key the list takes goes no further, so the\n * edit's own keys (Enter leaving a line) never see it. Returns the way to\n * stop listening.\n */\nfunction listenForItemKeys(\n  element: HTMLElement,\n  editing: InlineTextEditing,\n  host: () => ItemMoveHost\n): () => void {\n  const onKey = (event: KeyboardEvent) => {\n    const current = host();\n    const plan = itemKeyPlan(\n      event,\n      element,\n      editing,\n      () => current.editor.document\n    );\n    if (plan === null) return;\n    event.preventDefault();\n    event.stopImmediatePropagation();\n    // A held Enter's auto-repeat adds no run of empty items.\n    if (event.repeat && event.key === \"Enter\") return;\n    moveThroughItems(current, element, editing, plan);\n  };\n  element.addEventListener(\"keydown\", onKey);\n  return () => element.removeEventListener(\"keydown\", onKey);\n}\n\n/**\n * @param editor - the editor state whose document is being edited\n * @param onFinished - told when a key's way out of the line was refused and\n *   the line stays open with the words in it, so a host can say why\n * @returns the current edit, the ways in and out, and the canvas handler\n */\nexport function useInlineText(\n  editor: EditorState,\n  onFinished?: (outcome: InlineEditOutcome) => void\n): UseInlineTextResult {\n  const [editing, setEditing] = useState<InlineTextEditing | null>(null);\n  /*\n   * The document the canvas is drawn in, which a keyboard caller's edit is\n   * found in: the frame's when the canvas is in one. The editor's own\n   * document holds no block there.\n   */\n  const { document: canvasDocument } = useCanvasFrame();\n  /** The element handed over for the duration, so the exit can find it again. */\n  const elementRef = useRef<HTMLElement | null>(null);\n\n  /*\n   * Read through refs inside the listeners below rather than captured as\n   * dependencies. The listeners are attached once per edit, and closing over\n   * these would pin the document they saw when the caret went in — so a commit\n   * would be decided against a document that may have changed underneath.\n   */\n  const editorRef = useRef(editor);\n  editorRef.current = editor;\n  const editingRef = useRef(editing);\n  editingRef.current = editing;\n  /*\n   * The host's ear, and the value as it was when the caret went in. The\n   * second tells a write that replaces it from one that would replace a NEWER\n   * value another surface, an undo or a remote change put there meanwhile. It\n   * is recorded once per edit (`openedFor`), so a frame replacing its\n   * document mid-edit keeps the same baseline.\n   */\n  const session = useRef<{\n    finished?: (outcome: InlineEditOutcome) => void;\n    opened: string | null;\n    openedFor: InlineTextEditing | null;\n    /*\n     * Where the caret goes in the next edit opened: across its value, unless\n     * Enter or Backspace moved it there from the item beside it.\n     */\n    caretAt: CaretPlace;\n  }>({ opened: null, openedFor: null, caretAt: \"all\" });\n  session.current.finished = onFinished;\n\n  /** Take the element back, whatever else happens. */\n  const release = useCallback(() => {\n    const element = elementRef.current;\n    elementRef.current = null;\n    setEditing(null);\n    if (element === null) return;\n    element.removeAttribute(\"contenteditable\");\n    element.removeAttribute(EDITING_ATTRIBUTE);\n    return element;\n  }, []);\n\n  /**\n   * The op that stores what the element holds, or `null` when there is\n   * nothing to store: an unchanged value, or one that stopped being editable\n   * while the caret was in it — see `inlineTextOp`.\n   */\n  const commitOp = useCallback(\n    (current: InlineTextEditing, next: string): BuilderOp | null =>\n      current.exposure === undefined\n        ? inlineTextOp(\n            editorRef.current.document,\n            current.nodeId,\n            current.prop,\n            next\n          )\n        : exposedCommitOp(editorRef.current, current.exposure, next),\n    []\n  );\n\n  /**\n   * What finishing the edit would do, decided ONCE for every way out — a key,\n   * a click away, or the host — so no exit writes what another refuses:\n   *\n   * - nothing to write: nothing typed, or the element has left the page with\n   *   nothing to hold the words in;\n   * - refused, because the value moved on while it was typed (writing would\n   *   replace newer words with older ones) or stopped being editable (a lock\n   *   arrived, so there is nowhere to write it);\n   * - otherwise the write.\n   */\n  const decide = useCallback((): Finish => {\n    const element = elementRef.current;\n    const current = editingRef.current;\n    if (element === null || current === null) return NOTHING_TO_WRITE;\n    // The element's text (`elementWords`, with a `<br>` read as `\\n`) rather\n    // than `innerText` or `innerHTML`: the first is what\n    // the value IS regardless of what the element ended up containing, and the\n    // last would store markup this value cannot hold.\n    const next = editedWords(element, current);\n    const opened = session.current.opened;\n    if (next === opened || !element.isConnected) return NOTHING_TO_WRITE;\n    const refused = stalenessOf(editorRef.current, current, opened);\n    if (refused !== null) return { refused };\n    const op = commitOp(current, next);\n    return op === null ? NOTHING_TO_WRITE : { op };\n  }, [commitOp]);\n\n  /**\n   * The host's way out. It cannot leave the line open, because it is closing\n   * or opening something else, so a refused or rejected write gives the line\n   * back unwritten and says the words were lost.\n   */\n  const commit = useCallback(() => {\n    const finish = decide();\n    release();\n    if (\"refused\" in finish) {\n      session.current.finished?.(INLINE_EDIT_DISCARDED);\n      return null;\n    }\n    if (finish.op === undefined) return null;\n    const written = editorRef.current.apply(finish.op);\n    if (written === null) session.current.finished?.(INLINE_EDIT_DISCARDED);\n    return written;\n  }, [decide, release]);\n\n  /**\n   * The author's way out, by a key or a click away: the write is made first\n   * and the edit ends only once the page has taken it. The refusal's reason\n   * when the line stays open with the words in it, because they are the\n   * author's only copy: {@link decide}'s refusals, and the page refusing the\n   * write (a size cap).\n   */\n  const commitOrHold = useCallback((): InlineEditRefusal | null => {\n    const finish = decide();\n    if (\"refused\" in finish) return finish.refused;\n    if (\n      finish.op !== undefined &&\n      editorRef.current.apply(finish.op) === null\n    ) {\n      return \"rejected\";\n    }\n    release();\n    return null;\n  }, [decide, release]);\n\n  const cancel = useCallback(() => {\n    const element = elementRef.current;\n    const current = editingRef.current;\n    // Put back what the document holds before letting go. Without it the\n    // abandoned text stays on screen until something else re-renders the\n    // canvas, and the author sees an edit they explicitly discarded.\n    if (element !== null && current !== null) {\n      // The opened value where the document's is no longer editable here, so\n      // a line held after a lock arrived still shows what the page holds.\n      const restored =\n        liveValueOf(editorRef.current, current) ?? session.current.opened;\n      if (restored !== null) element.textContent = restored;\n    }\n    release();\n  }, [release]);\n\n  const begin = useCallback((nodeId: string, prop?: string) => {\n    const target = namedTarget(\n      inlineTargets(editorRef.current.document, nodeId),\n      prop\n    );\n    if (target !== undefined) {\n      setEditing({ nodeId: target.nodeId, prop: target.prop });\n      return true;\n    }\n    // Not a node of the page: a component's exposed text, reached through\n    // its placement, when it is one.\n    if (prop === undefined) return false;\n    const exposure = exposedTarget(editorRef.current, nodeId, prop);\n    if (exposure === undefined) return false;\n    setEditing({ nodeId, prop, exposure });\n    return true;\n  }, []);\n\n  const onDoubleClick = useCallback(\n    (event: { target: EventTarget | null }) => {\n      const found = editableFrom(event.target);\n      if (found === null) return;\n      if (begin(found.nodeId, found.prop)) elementRef.current = found.element;\n    },\n    [begin]\n  );\n\n  /*\n   * Hand the element over, and take it back on the way out.\n   *\n   * In an effect rather than in `begin` so the handover happens after React has\n   * finished rendering: setting `contentEditable` and focusing mid-render\n   * fights whatever the renderer is about to commit.\n   */\n  useEffect(() => {\n    if (editing === null) return;\n    /*\n     * The element a press handed over, while it is still the page's: a frame\n     * that replaces its document mid-edit leaves it in the discarded page, and\n     * the value is then found again in the page the canvas now draws.\n     */\n    const held = elementRef.current;\n    const current =\n      held !== null &&\n      held.isConnected &&\n      (canvasDocument === null || held.ownerDocument === canvasDocument)\n        ? held\n        : null;\n    const element =\n      current ??\n      (canvasDocument === null\n        ? null\n        : editableElement(canvasDocument, editing));\n    if (element === null) {\n      // Nothing on screen carries this value. The node may have been removed\n      // between the request and this effect; dropping the edit is the honest\n      // answer, and leaving `editing` set would show a caret nobody can see.\n      setEditing(null);\n      return;\n    }\n    // The page it was typed into is gone, but the typing is not committed:\n    // it goes on in the new page's element rather than being lost with it.\n    if (held !== null && held !== element) {\n      element.textContent = held.textContent;\n    }\n    elementRef.current = element;\n    if (session.current.openedFor !== editing) {\n      session.current.openedFor = editing;\n      session.current.opened = liveValueOf(editorRef.current, editing) ?? null;\n    }\n\n    element.setAttribute(\"contenteditable\", \"plaintext-only\");\n    element.setAttribute(EDITING_ATTRIBUTE, editing.prop);\n    element.focus();\n    placeCaret(element, session.current.caretAt);\n    session.current.caretAt = \"all\";\n\n    /*\n     * The words a keyboard exit's write was refused with, while the line\n     * stays open. The next deliberate Escape over the SAME words lets them\n     * go: the author's way out of a write the page will not take. Words\n     * revised since are a new write, tried again.\n     */\n    let refusedWith: string | null = null;\n    const tryToLeave = () => {\n      const words = elementWords(element);\n      const refusal = commitOrHold();\n      refusedWith = refusal === null ? null : words;\n      if (refusal !== null) {\n        session.current.finished?.({ status: \"refused\", reason: refusal });\n      }\n    };\n    const exitByKey = () => {\n      const words = elementWords(element);\n      if (refusedWith !== null && words === refusedWith) {\n        cancel();\n        return;\n      }\n      tryToLeave();\n    };\n    /*\n     * Enter and Backspace in an item of a list: a listener of their own,\n     * added before the one below so a key the list takes goes no further.\n     */\n    const stopItemKeys = listenForItemKeys(\n      element,\n      editing,\n      itemMoveHostOf(editorRef, editing, session, {\n        release,\n        session,\n        setEditing,\n      })\n    );\n    const onKeyDown = (event: KeyboardEvent) => {\n      // Escape keeps what was typed and ends the edit, as Enter does on a\n      // line: the editor's design asks for it, and an author pressing Escape\n      // to get out of the text expects their words to stay. Stopped here, so\n      // it is the NEXT Escape that selects the block's parent. A held key's\n      // auto-repeat is not a second press, so it neither writes nor discards.\n      if (event.key === \"Escape\") {\n        event.preventDefault();\n        event.stopPropagation();\n        if (event.repeat) return;\n        exitByKey();\n        return;\n      }\n      if (event.key !== \"Enter\") return;\n      const target =\n        editing.exposure ??\n        inlineTarget(editorRef.current.document, editing.nodeId, editing.prop);\n      // Enter belongs to the VALUE: a line break in a paragraph, and the way\n      // out of a heading. The schema says which, so a block changing a field\n      // from one type to the other changes this with it.\n      if (target?.multiline === true) return;\n      event.preventDefault();\n      if (event.repeat) return;\n      tryToLeave();\n    };\n    /*\n     * Stopped at the element rather than by teaching the canvas about editing.\n     * Selection and dragging both listen on the canvas root, so a press inside\n     * the text would start a drag instead of placing the caret — and the rule\n     * belongs to the element that is currently something else.\n     */\n    const swallow = (event: Event) => event.stopPropagation();\n\n    /*\n     * A value typed inside a disclosure's `<summary>` (a Question's title):\n     * the summary opens and closes its `<details>` on a click, and on the\n     * click the browser makes for Space and Enter, whatever inside it was\n     * pressed. Refused while the title is being typed, so a space or a click\n     * placing the caret leaves the question as it is.\n     */\n    const summary = element.closest(\"summary\");\n    const keepDisclosure = (event: Event) => event.preventDefault();\n    // In the capture phase: the element below stops a click's propagation.\n    summary?.addEventListener(\"click\", keepDisclosure, true);\n\n    element.addEventListener(\"keydown\", onKeyDown);\n    element.addEventListener(\"blur\", tryToLeave);\n    element.addEventListener(\"pointerdown\", swallow);\n    element.addEventListener(\"click\", swallow);\n    element.addEventListener(\"dblclick\", swallow);\n    return () => {\n      summary?.removeEventListener(\"click\", keepDisclosure, true);\n      stopItemKeys();\n      element.removeEventListener(\"keydown\", onKeyDown);\n      element.removeEventListener(\"blur\", tryToLeave);\n      element.removeEventListener(\"pointerdown\", swallow);\n      element.removeEventListener(\"click\", swallow);\n      element.removeEventListener(\"dblclick\", swallow);\n    };\n  }, [editing, cancel, commit, commitOrHold, canvasDocument, release]);\n\n  return { editing, begin, commit, cancel, onDoubleClick };\n}\n","\"use client\";\n\n/**\n * The marks drawn over blocks: the selection, the editable parts of a selected\n * component placement, the block a Layers row points at, and during a drag the\n * container a drop would land in or the one refusing it.\n *\n * The canvas decides WHICH elements are marked and says so with attributes on\n * them (`useCanvasMarkers` in `canvas.tsx`): every rendering of a selected\n * node, the outermost element of a component placement, the drop container.\n * This draws a box over each of those elements, in the editor's chrome rather\n * than as a style of the element, so the site's CSS cannot restyle or hide the\n * mark and the mark keeps its width at any zoom. Reading the attributes rather\n * than resolving the ids again keeps one answer to \"what is marked\".\n *\n * @module canvas-marks\n */\n\nimport type { BreakpointSet } from \"@nextlyhq/blocks-engine\";\nimport { INSTANCE_ATTRIBUTE, NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\nimport { AlertCircle, CircleCheck, Split } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { Rect } from \"../geometry\";\nimport { LOOK_REACH_ATTRIBUTE } from \"../inspector/style-inspector/look-reach\";\nimport { UNNAMED_COMPONENT } from \"../panels/layers/layers\";\nimport { deviceLabel } from \"../shell/breakpoint-switcher\";\n\nimport {\n  outsetCornerRadii,\n  scaleCornerRadii,\n  SQUARE_CORNERS,\n  type CornerRadii,\n} from \"./border-radii\";\nimport {\n  CANVAS_ROOT_CLASS,\n  CONDITIONED_ATTRIBUTE,\n  ENTRY_CONTENT_ATTRIBUTE,\n  CONDITIONED_OWN_ATTRIBUTE,\n  DROP_PARENT_ATTRIBUTE,\n  DROP_REFUSED_ATTRIBUTE,\n  isOutermostForAddress,\n  LOCKED_ATTRIBUTE,\n  nodeAddressOf,\n  SELECTED_ATTRIBUTE,\n} from \"./canvas\";\nimport { DEVICE_HIDDEN_ATTRIBUTE } from \"./canvas-device-hidden\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport {\n  OVERLAY_OUTPUT_ATTRIBUTE,\n  watchCanvasFor,\n  watchScreenBand,\n} from \"./canvas-geometry-watch\";\nimport {\n  tabBoardOf,\n  useTabPost,\n  type TabAt,\n  type TabDraft,\n  type TabPlacement,\n} from \"./canvas-tab-places\";\nimport { EXPOSED_ATTRIBUTE } from \"./exposed-outline\";\nimport {\n  canvasContentRect,\n  CHROME_BLEED,\n  clippedByAncestor,\n  onScreenOf,\n  overlaySpaceOf,\n  renderedScale,\n  usedRadiiOf,\n  visiblePartOf,\n  type OverlaySpace,\n} from \"./geometry-dom\";\nimport { useHoveredBlock } from \"./hovered-block\";\nimport {\n  TOOLBAR_GAP_PX,\n  toolbarPlacement,\n  type ToolbarPlacement,\n} from \"./toolbar-actions\";\nimport { EDITING_ATTRIBUTE } from \"./use-inline-text\";\n\n/**\n * The marks that are the marked element's outline and nothing more, by the\n * attribute that asks for each: a block an edit to the look being edited\n * reaches, and a drop's parent and refused target. Each with how far its\n * outline is drawn outside its box, the stylesheet's offset and width\n * together (`canvas.css`), which it is kept that far inside the page by.\n */\nconst OUTLINE_MARKS = [\n  [LOOK_REACH_ATTRIBUTE, \"look-reach\", 5],\n  [DROP_PARENT_ATTRIBUTE, \"drop-parent\", 4],\n  [DROP_REFUSED_ATTRIBUTE, \"drop-refused\", 4],\n] as const;\n\n/**\n * `rect` pulled in from the page's edges by `reach` on each side where an\n * outline that far outside it would run past them: the page meets the canvas\n * region's edges, which cut off anything drawn past them.\n */\nfunction pulledInFrom(page: Rect, rect: Rect, reach: number): Rect {\n  const kept = withinRect(\n    {\n      x: rect.x - reach,\n      y: rect.y - reach,\n      width: rect.width + 2 * reach,\n      height: rect.height + 2 * reach,\n    },\n    page\n  );\n  return {\n    x: kept.x + reach,\n    y: kept.y + reach,\n    width: Math.max(0, kept.width - 2 * reach),\n    height: Math.max(0, kept.height - 2 * reach),\n  };\n}\n\n/**\n * The marks drawn over an element's box alone that it asks for, drawn as\n * `box`: its outline-only marks, kept on the `page`, and the stripes and tag\n * of a block the page hides on the device shown. Those are drawn here, over the canvas, rather\n * than by an overlay inside the block, which would need the block to hold it\n * and so move what its fixed or absolutely placed blocks are laid out against.\n */\nfunction outlineMarksOf(\n  marked: Element,\n  box: Omit<Mark, \"kind\">,\n  page: Rect\n): Mark[] {\n  const marks: Mark[] = OUTLINE_MARKS.filter(([attribute]) =>\n    marked.hasAttribute(attribute)\n  ).map(([, kind, reach]) => ({\n    ...box,\n    rect: pulledInFrom(page, box.rect, reach),\n    kind,\n  }));\n  const deviceTag = marked.getAttribute(DEVICE_HIDDEN_ATTRIBUTE);\n  if (deviceTag !== null) {\n    marks.push({ ...box, kind: \"device-hidden\", deviceTag });\n  }\n  return marks;\n}\n\n/** One box to draw, in the chrome's coordinates. */\ninterface Mark {\n  readonly kind:\n    | \"selected\"\n    | \"hovered\"\n    | \"exposed\"\n    | \"look-reach\"\n    | \"drop-parent\"\n    | \"drop-refused\"\n    | \"device-hidden\"\n    | \"at-rest\";\n  /** The rest of a multi-block selection, drawn thinner than the primary. */\n  readonly secondary: boolean;\n  /** A component placement, drawn in the component colour. */\n  readonly component: boolean;\n  /** A block locked in Layers, by its own lock or one around it: dashed. */\n  readonly locked: boolean;\n  /**\n   * An exposed part being edited in place on the canvas: a solid ring, so the\n   * passage the caret is in reads apart from the placement's other parts.\n   */\n  readonly editing?: boolean;\n  /** Another exposed part of a placement while one of its parts is edited. */\n  readonly dimmed?: boolean;\n  /** A block the page hides on the device shown: the tag its stripes carry. */\n  readonly deviceTag?: string;\n  /**\n   * A selected block the page hides on the device shown, drawn because it is\n   * selected: hatched, and tagged as hidden.\n   */\n  readonly hidden: boolean;\n  /**\n   * Where a hidden block's tag sits: below the ring, above it when the ring\n   * ends at the bottom of what is on screen, where the canvas would cut a tag\n   * below it off, or inside it when neither fits, as on a block that fills\n   * the screen.\n   */\n  readonly tag: \"below\" | \"above\" | \"inside\";\n  /**\n   * For a tag inside the ring, how far in from the ring's bottom and side\n   * edges it sits, so it stays on screen when the ring runs past the screen.\n   */\n  readonly tagInset: { readonly bottom: number; readonly side: number };\n  /**\n   * Which of the ring's edges the tag lines up with: its right edge, so the\n   * tag runs leftwards, or its left edge when there is no room on screen for\n   * it to the left of the ring's right edge.\n   */\n  readonly tagEdge: \"right\" | \"left\";\n  /** Cut to the part a clipping ancestor leaves visible, with no halo band. */\n  readonly clipped: boolean;\n  /**\n   * Around a block its own `clip-path` shapes: no halo band, the ring still\n   * outside the box.\n   */\n  readonly shaped?: boolean;\n  /** The placement a component frame is drawn around, by its address. */\n  readonly placement?: string;\n  /**\n   * A placement's tag is drawn inside its frame: the frame's top is too\n   * close to the top of what is on screen for a tag above it to show.\n   */\n  readonly placementTagInside?: boolean;\n  /** The block a hovered mark points at, by its address, for its name tag. */\n  readonly hoveredAddress?: string;\n  /**\n   * The hovered block is marked never to be quoted, read off the element the\n   * page renders (`data-nosnippet`), so its tag says so.\n   */\n  readonly notQuoted?: boolean;\n  /**\n   * A hovered block's tag is drawn inside its outline: the outline's top is\n   * too close to the top of what is on screen for a tag above it to show.\n   */\n  readonly hoverTagInside?: boolean;\n  /**\n   * An at-rest mark's condition tab: a conditioned block's, conditional,\n   * with conditions it can't check, or, while conditions are applied, shown\n   * for the previewed entry.\n   */\n  readonly condition?: ConditionMarkKind;\n  /**\n   * An at-rest mark's Entry content tab, by its words: an Entry content\n   * block's, naming the field it draws (\"Entry content · Body\").\n   */\n  readonly entryContent?: string;\n  /** Where an at-rest mark's tabs go: above the block, below it, or inside its top. */\n  readonly tabsAt?: TabAt;\n  /** Whether the block is selected, so its ring stands for the outline. */\n  readonly atRestSelected?: boolean;\n  readonly rect: Rect;\n  /** The block's own corners, in the chrome's coordinates, as `border-radius`. */\n  readonly radius: string;\n}\n\nconst NO_MARKS: readonly Mark[] = [];\n\nconst NO_IDS: readonly string[] = [];\n\n/** The height a hidden block's tag takes outside its ring, with its gap. */\nconst TAG_ROOM = 24;\n\n/** The gap between a tag inside the ring and the ring's edges. */\nconst TAG_GAP = 4;\n\nconst NO_INSET = { bottom: TAG_GAP, side: TAG_GAP } as const;\n\n/**\n * About how wide a tag of `label` is drawn: its 11px face runs under 7px a\n * character, plus its padding. An estimate erring wide, since a tag judged to\n * fit that does not is the one the canvas cuts off.\n */\nfunction tagWidthOf(label: string): number {\n  return label.length * 7 + 12;\n}\n\n/** The room a condition tab's icon and its gap take beside the words. */\nconst CONDITION_ICON_ROOM = 16;\n\n/** @experimental */\nexport interface CanvasMarksProps {\n  /**\n   * Selected blocks the page hides on the device being shown, which the\n   * canvas draws anyway while they are selected. Their ring is hatched and\n   * tagged, so a block a visitor will not see is never mistaken for one they\n   * will.\n   */\n  readonly revealed?: readonly string[];\n  /**\n   * The site's breakpoints and the device being shown, which names the tag\n   * on such a ring: \"Hidden on Mobile\".\n   */\n  readonly device?: { breakpoints: BreakpointSet | undefined; id: string };\n  /**\n   * A block's name by its address, for the tag on a component placement's\n   * frame: the name its author gave it, or its component's. A placement it\n   * does not name is tagged as a component.\n   */\n  readonly nameOf?: (address: string) => string | undefined;\n  /**\n   * What a block shown for the previewed entry is badged with while\n   * conditions are applied: \"Shown for this post\".\n   */\n  readonly shownLabel?: string;\n}\n\n/**\n * How far outside a block its selection ring is drawn: the ring and the halo\n * band inside it, each 2px. Outside, so the ring never covers the block's own\n * content, the first glyph of a heading set flush with its box. The layer\n * reaches as far past the frame (`CHROME_BLEED`), so the ring of a block\n * flush with the page's edge is drawn too.\n */\nconst RING_OUTSIDE = CHROME_BLEED;\n\n/**\n * The height of a mark's tag (a placement's, a hovered block's), drawn above\n * its outline. An outline closer than\n * this to the top of what is on screen has its tag drawn inside instead,\n * where it still shows.\n */\nconst MARK_TAG_HEIGHT = 18;\n\n/** Everything that decides how a mark is drawn, as one comparable value. */\nfunction markKey(mark: Mark): string {\n  const {\n    kind,\n    secondary,\n    component,\n    locked,\n    hidden,\n    tag,\n    tagEdge,\n    tagInset,\n    clipped,\n    shaped,\n    editing,\n    dimmed,\n    placement,\n    placementTagInside,\n    hoveredAddress,\n    hoverTagInside,\n    notQuoted,\n    condition,\n    entryContent,\n    tabsAt,\n    atRestSelected,\n    radius,\n    deviceTag,\n    rect,\n  } = mark;\n  return JSON.stringify([\n    kind,\n    secondary,\n    component,\n    locked,\n    hidden,\n    tag,\n    tagEdge,\n    tagInset.bottom,\n    tagInset.side,\n    clipped,\n    shaped === true,\n    editing === true,\n    dimmed === true,\n    placement,\n    placementTagInside,\n    hoveredAddress,\n    hoverTagInside,\n    notQuoted === true,\n    condition,\n    entryContent,\n    tabsAt,\n    atRestSelected === true,\n    radius,\n    // The tag a hidden block's stripes carry, which a renamed device or\n    // another device of the same size changes while its box stays put.\n    deviceTag,\n    rect.x,\n    rect.y,\n    rect.width,\n    rect.height,\n  ]);\n}\n\n/** Whether two lists of marks would draw the same boxes. */\nfunction sameMarks(a: readonly Mark[], b: readonly Mark[]): boolean {\n  if (a.length !== b.length) return false;\n  return a.every((mark, index) => {\n    const other = b[index];\n    return other !== undefined && markKey(mark) === markKey(other);\n  });\n}\n\n/**\n * A mark's box, and for a tag inside the ring the insets the stylesheet places\n * it by: custom properties, read only under `data-tag=\"inside\"`.\n */\nfunction markStyle(mark: Mark): React.CSSProperties {\n  const box: React.CSSProperties = {\n    left: mark.rect.x,\n    top: mark.rect.y,\n    width: mark.rect.width,\n    height: mark.rect.height,\n    borderRadius: mark.radius,\n  };\n  if (mark.kind === \"hovered\" || mark.kind === \"at-rest\") {\n    // The hovered block's name tag, and an at-rest mark's tabs, move in\n    // from the side the screen cuts.\n    return {\n      ...box,\n      \"--nx-tag-inset-side\": `${String(mark.tagInset.side)}px`,\n    } as React.CSSProperties;\n  }\n  if (!mark.hidden) return box;\n  return {\n    ...box,\n    // Every tag moves in from the side the screen cuts; only a tag inside the\n    // ring is placed from the bottom.\n    \"--nx-tag-inset-side\": `${String(mark.tagInset.side)}px`,\n    ...(mark.tag === \"inside\"\n      ? { \"--nx-tag-inset-bottom\": `${String(mark.tagInset.bottom)}px` }\n      : {}),\n  } as React.CSSProperties;\n}\n\n/** Corner radii as the `border-radius` shorthand writes them, both axes. */\nfunction borderRadiusOf(radii: CornerRadii): string {\n  const { topLeft, topRight, bottomRight, bottomLeft } = radii;\n  const px = (value: number): string => `${String(value)}px`;\n  return (\n    `${px(topLeft.x)} ${px(topRight.x)} ${px(bottomRight.x)} ${px(bottomLeft.x)} / ` +\n    `${px(topLeft.y)} ${px(topRight.y)} ${px(bottomRight.y)} ${px(bottomLeft.y)}`\n  );\n}\n\n/** A marked element's box and corners, in the chrome's coordinates. */\ninterface Outline {\n  readonly rect: Rect;\n  /** The corners as `border-radius`. */\n  readonly radius: string;\n  readonly radii: CornerRadii;\n  readonly clipped: boolean;\n  /** Shaped by the block's own `clip-path`: no halo band, ring outside. */\n  readonly shaped?: boolean;\n}\n\n/**\n * A marked element's box and corners, in the chrome's coordinates.\n *\n * The corners follow the block's own curve, so the ring and its halo hug a\n * rounded card rather than squaring its corners off. Square where the corners\n * cannot be read — a block transformed out of its axes, or radii a computed\n * style leaves unresolved: over a frame the mark is the only ring the block\n * has, so a block whose shape cannot be described keeps a square one rather\n * than none.\n *\n * A block an ancestor clips (`overflow: hidden` or `clip`) is marked over the\n * part left visible, square and `clipped`: the page draws nothing of it past\n * the clip, and a ring drawn there would mark what the reader cannot see.\n * A block the clip hides entirely has no outline (`null`), and where the clip\n * cannot be described, the whole box keeps a square ring.\n */\nfunction outlineOf(\n  marked: Element,\n  root: HTMLElement,\n  space: OverlaySpace\n): Outline | null {\n  const own = canvasContentRect(marked, root);\n  const style = marked.ownerDocument.defaultView?.getComputedStyle(marked);\n  const scale = renderedScale(marked, root);\n  const radii =\n    style === undefined || !scale.describable\n      ? undefined\n      : usedRadiiOf(style, own, scale);\n  // In the root's coordinates, where the clip is asked about.\n  const inRoot =\n    radii === undefined\n      ? SQUARE_CORNERS\n      : scaleCornerRadii(radii, { x: scale.x, y: scale.y });\n  if (clippedByAncestor(marked, root, inRoot)) {\n    const visible = visiblePartOf(marked, root) ?? own;\n    if (visible === \"hidden\") return null;\n    return {\n      rect: space.place(visible),\n      radius: borderRadiusOf(SQUARE_CORNERS),\n      radii: SQUARE_CORNERS,\n      clipped: true,\n    };\n  }\n  /*\n   * A block its OWN `clip-path` shapes — a circle cut from a square box —\n   * draws nothing of the box outside that shape. A halo band hugging the box\n   * would frame corners that show the page behind, so the ring is drawn\n   * square around the box with no band. Unlike an ancestor's clip, the\n   * block's own shape does not cut the overlay, so the ring stays OUTSIDE\n   * the box, where it covers nothing the shape shows.\n   */\n  const shape = style?.clipPath;\n  if (shape !== undefined && shape !== \"\" && shape !== \"none\") {\n    return {\n      rect: space.place(own),\n      radius: borderRadiusOf(SQUARE_CORNERS),\n      radii: SQUARE_CORNERS,\n      clipped: false,\n      shaped: true,\n    };\n  }\n  const drawn = scaleCornerRadii(inRoot, { x: space.scale, y: space.scale });\n  return {\n    rect: space.place(own),\n    radius: borderRadiusOf(drawn),\n    radii: drawn,\n    clipped: false,\n  };\n}\n\n/**\n * Where a selection ring is drawn for an outline: outside the block by\n * {@link RING_OUTSIDE}, with its rounded corners grown to stay concentric,\n * and never past the page's edges (`page`, in the chrome's coordinates).\n *\n * The page meets the canvas region's edges, and the region cuts off whatever\n * is drawn past them, so a ring outside a block flush with the page's edge\n * lost that side. On such a side the ring stays on the page, over the\n * block's edge, so all four of its sides are on screen.\n *\n * A clipped outline is drawn where it is: the page shows nothing past the\n * clip, so a ring outside it would ring what the reader cannot see.\n */\nfunction ringOf(outline: Outline, page: Rect): Outline {\n  if (outline.clipped) return outline;\n  const { x, y, width, height } = outline.rect;\n  const radii = outsetCornerRadii(outline.radii, RING_OUTSIDE);\n  return {\n    rect: withinRect(\n      {\n        x: x - RING_OUTSIDE,\n        y: y - RING_OUTSIDE,\n        width: width + 2 * RING_OUTSIDE,\n        height: height + 2 * RING_OUTSIDE,\n      },\n      page\n    ),\n    radius: borderRadiusOf(radii),\n    radii,\n    clipped: false,\n    ...(outline.shaped === true ? { shaped: true } : {}),\n  };\n}\n\n/**\n * `rect` cut to `bounds` on each side it runs past them; left as it is where\n * it lies inside them. A rectangle wholly outside keeps no area.\n */\nfunction withinRect(rect: Rect, bounds: Rect): Rect {\n  const left = Math.max(rect.x, bounds.x);\n  const top = Math.max(rect.y, bounds.y);\n  const right = Math.min(rect.x + rect.width, bounds.x + bounds.width);\n  const bottom = Math.min(rect.y + rect.height, bounds.y + bounds.height);\n  return {\n    x: left,\n    y: top,\n    width: Math.max(0, right - left),\n    height: Math.max(0, bottom - top),\n  };\n}\n\n/** The smallest rectangle holding every one given. */\nfunction unionOf(rects: readonly Rect[]): Rect {\n  const left = Math.min(...rects.map(rect => rect.x));\n  const top = Math.min(...rects.map(rect => rect.y));\n  const right = Math.max(...rects.map(rect => rect.x + rect.width));\n  const bottom = Math.max(...rects.map(rect => rect.y + rect.height));\n  return { x: left, y: top, width: right - left, height: bottom - top };\n}\n\n/**\n * The outline around every part of one placement: their union, square unless\n * there is one part, whose corners it keeps, and cut by a clip where any part\n * is.\n */\nfunction placementOutline(parts: readonly Outline[]): Outline {\n  const [only] = parts;\n  if (parts.length === 1 && only !== undefined) return only;\n  return {\n    rect: unionOf(parts.map(part => part.rect)),\n    radius: borderRadiusOf(SQUARE_CORNERS),\n    radii: SQUARE_CORNERS,\n    clipped: parts.some(part => part.clipped),\n    ...(parts.some(part => part.shaped === true) ? { shaped: true } : {}),\n  };\n}\n\n/** A selected placement's parts, gathered to draw one frame around them. */\ninterface SelectedPlacement {\n  /** The placement's address, which its tag names. */\n  readonly placement: string;\n  readonly parts: Outline[];\n  readonly secondary: boolean;\n  readonly locked: boolean;\n  readonly hidden: boolean;\n}\n\n/** How a selected ring is drawn, decided by its element. */\ninterface RingLook {\n  readonly secondary: boolean;\n  readonly locked: boolean;\n  readonly hidden: boolean;\n}\n\n/** Where a hidden block's tag goes on a ring, decided by `marksOf`. */\ntype TagPlacer = (\n  rect: Rect,\n  primary: boolean\n) => Pick<Mark, \"tag\" | \"tagEdge\" | \"tagInset\">;\n\n/** A selected block's mark, drawn over its ring; a placement's carries it. */\nfunction selectedMark(\n  ring: Outline,\n  look: RingLook,\n  placeTag: TagPlacer,\n  placement?: string\n): Mark {\n  return {\n    rect: ring.rect,\n    radius: ring.radius,\n    clipped: ring.clipped,\n    ...(ring.shaped === true ? { shaped: true } : {}),\n    kind: \"selected\",\n    component: placement !== undefined,\n    ...look,\n    ...placeTag(ring.rect, !look.secondary),\n    ...(placement === undefined ? {} : { placement }),\n  };\n}\n\n/**\n * Add one selected part to its placement's gathered parts.\n *\n * Gathered per rendered COPY as well as per placement: a block that renders\n * its slot more than once, as a loop does once per entry, draws a placement's\n * parts once in each copy, all with the placement's address. A copy's parts\n * are siblings, so their parent tells the copies apart; one frame around every\n * copy would ring whatever lies between them.\n */\nfunction gatherPlacement(\n  placements: Map<string, SelectedPlacement>,\n  copies: Map<Element | null, number>,\n  marked: Element,\n  placement: string,\n  part: Outline,\n  look: RingLook\n): void {\n  const key = `${String(copyOf(copies, marked))}\\u0000${placement}`;\n  const gathered = placements.get(key);\n  if (gathered === undefined) {\n    placements.set(key, { placement, parts: [part], ...look });\n  } else gathered.parts.push(part);\n}\n\n/** The tag on a placement's frame: a component's mark and its name. */\nfunction placementTag(\n  placement: string,\n  nameOf: CanvasMarksProps[\"nameOf\"]\n): string {\n  const name = nameOf?.(placement)?.trim();\n  return `◇ ${name === undefined || name === \"\" ? UNNAMED_COMPONENT : name}`;\n}\n\n/**\n * Whether the block toolbar takes the place above a block: above it, or\n * pinned over its top at the top of the screen, where a tag above would\n * collide with it either way. A bar drawn inside the block leaves it free.\n */\nfunction takesTheTop(side: ToolbarPlacement[\"side\"]): boolean {\n  return side !== \"inside\";\n}\n\n/** What a conditioned block's badge says about who sees it. */\ntype ConditionMarkKind = \"conditional\" | \"unchecked\" | \"shown\";\n\n/** Whether a conditioned block's attribute names a kind its tab can say. */\nfunction isConditionMarkKind(value: string | null): value is ConditionMarkKind {\n  return value === \"conditional\" || value === \"unchecked\" || value === \"shown\";\n}\n\n/** The words on a conditioned block's badge. */\nfunction conditionWords(\n  condition: ConditionMarkKind,\n  shownLabel: string\n): string {\n  if (condition === \"unchecked\") return \"Can’t be checked\";\n  return condition === \"shown\" ? shownLabel : \"Conditional\";\n}\n\n/** What the marks are drawn for besides what the canvas marks on the page. */\ninterface MarkInputs {\n  /** The block a Layers row points at, or `null`. */\n  readonly hovered: string | null;\n  /**\n   * Selected blocks shown although the page hides them on this device, as a\n   * set: asked once per marked element, and a selection can hold thousands.\n   */\n  readonly revealed: ReadonlySet<string>;\n  /** About how wide a hidden block's tag is drawn, in the chrome's pixels. */\n  readonly tagWidth: number;\n  /** What a shown block's badge says while conditions are applied. */\n  readonly shownLabel: string;\n}\n\n/**\n * What a measure of the canvas finds: the marks drawn as measured, and the\n * at-rest marks, whose tabs the board places with every other layer's\n * (`placedAtRest`), over the canvas drawn at `root`.\n */\ninterface Measured {\n  readonly root: HTMLElement | null;\n  /** Every mark but the hovered block's. */\n  readonly marks: readonly Mark[];\n  /** The block the hover marks were measured for, or `null`. */\n  readonly hoveredFor: string | null;\n  /**\n   * The hovered block's marks, held apart so a hover change measures them\n   * alone and keeps the rest.\n   */\n  readonly hovered: readonly Mark[];\n  readonly atRest: readonly AtRestDraft[];\n}\n\nconst NOTHING_MEASURED: Measured = {\n  root: null,\n  marks: NO_MARKS,\n  hoveredFor: null,\n  hovered: NO_MARKS,\n  atRest: [],\n};\n\n/** The marked elements of a canvas root, as the boxes to draw over them. */\nfunction marksOf(element: HTMLElement, inputs: MarkInputs): Measured {\n  const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n  if (space === null) return NOTHING_MEASURED;\n  const { root } = space;\n  const onScreen = onScreenOf(space);\n  const screenBottom = onScreen.y + onScreen.height;\n  const screenRight = onScreen.x + onScreen.width;\n  // From the ring's right edge as far as the screen shows it.\n  const roomLeft = (rect: Rect): boolean =>\n    Math.min(rect.x + rect.width, screenRight) - inputs.tagWidth >= onScreen.x;\n  // The block toolbar, drawn beside these marks over the same canvas, which\n  // takes the place above the primary block when it sits there.\n  const toolbar =\n    element.parentElement?.querySelector<HTMLElement>(\".nx-block-toolbar\");\n  const pageBox = space.place(canvasContentRect(root, root));\n  const toolbarAbove = (rect: Rect): boolean =>\n    toolbar !== null &&\n    toolbar !== undefined &&\n    takesTheTop(\n      toolbarPlacement(rect, space.sizeOf(toolbar), pageBox, TOOLBAR_GAP_PX, {\n        top: onScreen.y,\n        bottom: onScreen.y + onScreen.height,\n      }).side\n    );\n  // Below if it fits on screen, above if that does and the toolbar is not\n  // there, and otherwise inside the ring, which is always on screen.\n  const tagSide = (rect: Rect, primary: boolean): Mark[\"tag\"] => {\n    if (rect.y + rect.height + TAG_ROOM <= screenBottom) return \"below\";\n    if (rect.y - TAG_ROOM >= onScreen.y && !(primary && toolbarAbove(rect))) {\n      return \"above\";\n    }\n    return \"inside\";\n  };\n  // A tag moves in as far as the ring runs past the screen, so it is never\n  // drawn where the canvas cuts it off; inside the ring it also keeps a small\n  // gap from the ring's edges.\n  const insetOf = (\n    rect: Rect,\n    edge: Mark[\"tagEdge\"],\n    tag: Mark[\"tag\"]\n  ): Mark[\"tagInset\"] => {\n    const gap = tag === \"inside\" ? TAG_GAP : 0;\n    return {\n      bottom: gap + Math.max(0, rect.y + rect.height - screenBottom),\n      side:\n        gap +\n        (edge === \"right\"\n          ? Math.max(0, rect.x + rect.width - screenRight)\n          : Math.max(0, onScreen.x - rect.x)),\n    };\n  };\n  const placedTag = (\n    rect: Rect,\n    primary: boolean\n  ): Pick<Mark, \"tag\" | \"tagEdge\" | \"tagInset\"> => {\n    const tagEdge = roomLeft(rect) ? \"right\" : \"left\";\n    const tag = tagSide(rect, primary);\n    return { tag, tagEdge, tagInset: insetOf(rect, tagEdge, tag) };\n  };\n  const found: Mark[] = [];\n  // In the order their first part is met, which is document order.\n  const placements = new Map<string, SelectedPlacement>();\n  const copies = new Map<Element | null, number>();\n  root\n    .querySelectorAll(\n      `[${SELECTED_ATTRIBUTE}], [${EXPOSED_ATTRIBUTE}], [${LOOK_REACH_ATTRIBUTE}], [${DROP_PARENT_ATTRIBUTE}], [${DROP_REFUSED_ATTRIBUTE}], [${DEVICE_HIDDEN_ATTRIBUTE}]`\n    )\n    .forEach(marked => {\n      // A canvas rendered inside a block of this one marks its own elements.\n      if (marked.closest(`.${CANVAS_ROOT_CLASS}`) !== root) return;\n      const outline = outlineOf(marked, root, space);\n      // Wholly cut away by a clipping ancestor: the page shows none of it.\n      if (outline === null) return;\n      const plain = {\n        secondary: false,\n        component: false,\n        locked: false,\n        hidden: false,\n        tag: \"below\" as const,\n        tagEdge: \"right\" as const,\n        tagInset: NO_INSET,\n      };\n      const selected = marked.getAttribute(SELECTED_ATTRIBUTE);\n      // A part of a placement, by the placement's address: the canvas marks\n      // only the outermost elements, so each of these is one whole part, and\n      // a selected placement is drawn as one frame around them all.\n      const placement = marked.getAttribute(INSTANCE_ATTRIBUTE) ?? \"\";\n      if (selected !== null) {\n        const address = nodeAddressOf(marked);\n        const look = {\n          secondary: selected !== \"primary\",\n          locked: marked.hasAttribute(LOCKED_ATTRIBUTE),\n          hidden: address !== null && inputs.revealed.has(address),\n        };\n        if (placement !== \"\") {\n          gatherPlacement(placements, copies, marked, placement, outline, look);\n        } else {\n          found.push(selectedMark(ringOf(outline, pageBox), look, placedTag));\n        }\n      }\n      // An exposed part keeps its dash inside its placement's frame. A block\n      // that is itself ringed keeps its ring alone: one element draws one\n      // outline, and the ring says more there.\n      if (\n        marked.hasAttribute(EXPOSED_ATTRIBUTE) &&\n        (selected === null || placement !== \"\")\n      ) {\n        found.push({\n          ...outline,\n          ...plain,\n          kind: \"exposed\",\n          ...(marked.hasAttribute(EDITING_ATTRIBUTE) ? { editing: true } : {}),\n        });\n      }\n      // The marks drawn as the element's outline alone, one per attribute.\n      found.push(...outlineMarksOf(marked, { ...outline, ...plain }, pageBox));\n    });\n  placements.forEach(({ placement, parts, ...look }) => {\n    const ring = ringOf(placementOutline(parts), pageBox);\n    found.push({\n      ...selectedMark(ring, look, placedTag, placement),\n      // Measured from the top of what is on screen rather than of the page:\n      // a placement scrolled to the top keeps its tag in view.\n      placementTagInside: ring.rect.y - onScreen.y < MARK_TAG_HEIGHT,\n    });\n  });\n  return {\n    root,\n    marks: dimmedBesideEditing(stripesFirst(found)),\n    hoveredFor: inputs.hovered,\n    hovered: hoveredMarksOf(root, space, onScreen, inputs.hovered),\n    atRest: atRestMarks(root, space, onScreen, toolbarAbove, inputs.shownLabel),\n  };\n}\n\n/**\n * The last measure with the hover's marks measured again for `hovered`, and\n * nothing else measured: the other marks stay as the last full measure left\n * them, which the canvas's watchers keep current. `undefined` when the layer\n * no longer sits over the canvas last measured, which wants a full measure.\n */\nfunction withHoverOf(\n  element: HTMLElement,\n  last: Measured,\n  hovered: string | null\n): Measured | undefined {\n  if (last.root === null) return undefined;\n  if (hovered === null) return { ...last, hoveredFor: null, hovered: NO_MARKS };\n  const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n  if (space === null || space.root !== last.root) return undefined;\n  return {\n    ...last,\n    hoveredFor: hovered,\n    hovered: hoveredMarksOf(space.root, space, onScreenOf(space), hovered),\n  };\n}\n\n/** The marks of the block pointed at, measured; none when none is. */\nfunction hoveredMarksOf(\n  root: HTMLElement,\n  space: OverlaySpace,\n  onScreen: Rect,\n  hovered: string | null\n): readonly Mark[] {\n  if (hovered === null) return NO_MARKS;\n  const found: Mark[] = [];\n  /*\n   * Every rendering of the hovered block, found by its ADDRESS and the\n   * outermost element standing for it, as the selection is: a placement's\n   * component draws no element of its own, and a block drawn twice is\n   * pointed at twice. A block already selected keeps its ring alone.\n   */\n  root.querySelectorAll(`[${NODE_ID_ATTRIBUTE}]`).forEach(candidate => {\n    if (candidate.closest(`.${CANVAS_ROOT_CLASS}`) !== root) return;\n    if (candidate.hasAttribute(SELECTED_ATTRIBUTE)) return;\n    if (nodeAddressOf(candidate) !== hovered) return;\n    if (!isOutermostForAddress(candidate, hovered, root)) return;\n    const outline = outlineOf(candidate, root, space);\n    if (outline === null) return;\n    found.push({\n      ...outline,\n      kind: \"hovered\",\n      secondary: false,\n      component: candidate.hasAttribute(INSTANCE_ATTRIBUTE),\n      locked: false,\n      hidden: false,\n      tag: \"below\",\n      tagEdge: \"left\",\n      // In from the screen's left edge as far as the outline runs past it,\n      // so a block scrolled partly off the side keeps its name in view. Not\n      // for one wholly off it: there is nothing on screen to tag.\n      tagInset: {\n        bottom: 0,\n        side:\n          outline.rect.x + outline.rect.width > onScreen.x\n            ? Math.max(0, onScreen.x - outline.rect.x)\n            : 0,\n      },\n      hoveredAddress: hovered,\n      // From the top of what is on screen, as the placement's tag is.\n      hoverTagInside: outline.rect.y - onScreen.y < MARK_TAG_HEIGHT,\n      notQuoted: candidate.hasAttribute(NOT_QUOTED_ATTRIBUTE),\n    });\n  });\n  return found;\n}\n\n/** What an element asks an at-rest mark to say, read off its attributes. */\ninterface AtRestTabs {\n  readonly condition?: ConditionMarkKind;\n  readonly entryContent?: string;\n}\n\n/**\n * The at-rest tabs an element asks for: a conditioned block's condition, and\n * an Entry content block's words. Nothing where it asks for neither.\n */\nfunction atRestTabsOf(element: Element): AtRestTabs | undefined {\n  const condition = element.getAttribute(CONDITIONED_ATTRIBUTE);\n  const entry = element.getAttribute(ENTRY_CONTENT_ATTRIBUTE);\n  const tabs: AtRestTabs = {\n    ...(isConditionMarkKind(condition) ? { condition } : {}),\n    ...(entry !== null && entry !== \"\" ? { entryContent: entry } : {}),\n  };\n  return tabs.condition === undefined && tabs.entryContent === undefined\n    ? undefined\n    : tabs;\n}\n\n/**\n * The at-rest mark on every block the canvas says something about whether or\n * not it is selected: a conditioned block, which the canvas draws whoever the\n * page would show it to, and an Entry content block, which draws the entry's\n * own content rather than the template's. One faint dashed outline round the\n * block with its tabs on the outline's edge, a block that is both carrying\n * both tabs on the one outline. Placed outside the block, above it where\n * there's room and below it where there isn't, so the tabs never cover what\n * the block draws; where they go apart from every other tab drawn over the\n * canvas is the board's to say (`placedAtRest`).\n */\nfunction atRestMarks(\n  root: HTMLElement,\n  space: OverlaySpace,\n  onScreen: Rect,\n  toolbarAbove: (rect: Rect) => boolean,\n  shownLabel: string\n): AtRestDraft[] {\n  const badges = new Map<string, ConditionBadge>();\n  const copies = new Map<Element | null, number>();\n  root\n    .querySelectorAll(\n      `[${CONDITIONED_ATTRIBUTE}], [${ENTRY_CONTENT_ATTRIBUTE}]`\n    )\n    .forEach(element => {\n      if (element.closest(`.${CANVAS_ROOT_CLASS}`) !== root) return;\n      const tabs = atRestTabsOf(element);\n      if (tabs === undefined) return;\n      const outline = outlineOf(element, root, space);\n      if (outline === null) return;\n      const key = badgeKey(element, copies, badges.size);\n      const selected = element.getAttribute(SELECTED_ATTRIBUTE);\n      const gathered = badges.get(key);\n      if (gathered === undefined) {\n        badges.set(key, {\n          tabs,\n          parts: [outline],\n          selected: selected !== null,\n          primary: selected === \"primary\",\n          placement: (element.getAttribute(INSTANCE_ATTRIBUTE) ?? \"\") !== \"\",\n        });\n      } else {\n        gathered.parts.push(outline);\n        gathered.selected ||= selected !== null;\n        gathered.primary ||= selected === \"primary\";\n      }\n    });\n  return [...badges.values()].map(badge =>\n    atRestMark(badge, onScreen, toolbarAbove, shownLabel)\n  );\n}\n\n/** A marked block's parts, gathered to draw one outline and its tabs. */\ninterface ConditionBadge {\n  readonly tabs: AtRestTabs;\n  readonly parts: Outline[];\n  selected: boolean;\n  primary: boolean;\n  readonly placement: boolean;\n}\n\n/**\n * Which badge an element's outline joins: a block of a placed component's\n * definition its own, by its composed id within one drawn copy; the roots of one copy of a\n * conditioned placement one together, as one frame is drawn round a selected\n * one; any other block its own.\n */\nfunction badgeKey(\n  element: Element,\n  copies: Map<Element | null, number>,\n  index: number\n): string {\n  if (element.hasAttribute(CONDITIONED_OWN_ATTRIBUTE)) {\n    // By copy as well: a list drawing the component once per entry draws\n    // the block once per entry, each with the same composed id.\n    // The roots of one placement nested in a component share its badge, as\n    // a page placement's roots share theirs.\n    const nested = element.getAttribute(CONDITIONED_OWN_ATTRIBUTE) ?? \"\";\n    const id =\n      nested === \"\"\n        ? (element.getAttribute(NODE_ID_ATTRIBUTE) ?? String(index))\n        : `placed\\u0000${nested}`;\n    return `own\\u0000${String(copyOf(copies, element))}\\u0000${id}`;\n  }\n  const placement = element.getAttribute(INSTANCE_ATTRIBUTE) ?? \"\";\n  return placement === \"\"\n    ? `block\\u0000${String(index)}`\n    : `${String(copyOf(copies, element))}\\u0000${placement}`;\n}\n\n/**\n * One marked block's at-rest mark before its tabs are placed: the mark, and\n * its tabs as the board places them (`canvas-tab-places.ts`).\n */\ninterface AtRestDraft {\n  readonly mark: Mark;\n  readonly tab: TabDraft;\n}\n\n/** One marked block's at-rest mark: its outline and where its tabs may go. */\nfunction atRestMark(\n  badge: ConditionBadge,\n  onScreen: Rect,\n  toolbarAbove: (rect: Rect) => boolean,\n  shownLabel: string\n): AtRestDraft {\n  const outline = placementOutline(badge.parts);\n  // The top is taken by a selected placement's name, or by the block\n  // toolbar above the primary block: the tab then takes the bottom edge.\n  const topTaken =\n    (badge.selected && badge.placement) ||\n    (badge.primary && toolbarAbove(outline.rect));\n  const places = tabPlacesOf(outline.rect, onScreen, topTaken);\n  const side = tabInset(outline.rect, onScreen, badge.tabs, shownLabel);\n  return {\n    mark: {\n      ...outline,\n      kind: \"at-rest\",\n      secondary: false,\n      component: false,\n      locked: false,\n      hidden: false,\n      tag: \"below\",\n      tagEdge: \"right\",\n      tagInset: { bottom: 0, side },\n      ...badge.tabs,\n      tabsAt: places[0] ?? \"inside\",\n      ...(badge.selected ? { atRestSelected: true } : {}),\n    },\n    tab: {\n      block: outline.rect,\n      edge: outline.rect,\n      places,\n      side,\n      // No wider than the outline, as the stylesheet keeps them.\n      width: Math.min(tabsWidthOf(badge.tabs, shownLabel), outline.rect.width),\n      height: AT_REST_TAB_HEIGHT,\n      // Measured from the edge they stand on: their foot shares the dash.\n      foot: 0,\n      leftmost: onScreen.x,\n    },\n  };\n}\n\n/**\n * The height an at-rest mark's tabs take, as the stylesheet draws them: a\n * 16px line, with 1px of padding and a 1px border above and below it.\n */\nconst AT_REST_TAB_HEIGHT = 20;\n\n/**\n * The at-rest marks with their tabs where the board places them: apart from\n * each other, from the \"Visitors won't see this\" badges and from the block\n * toolbar, all placed by the one pass (`tabsApart` in `canvas-tab-places.ts`).\n * With no board (no canvas), each keeps its tabs where they go alone.\n */\nfunction placedAtRest(\n  drafts: readonly AtRestDraft[],\n  placements: readonly TabPlacement[]\n): Mark[] {\n  return drafts.map(({ mark, tab }, index) => {\n    const { at, side } = placements[index] ?? {\n      at: tab.places[0] ?? \"inside\",\n      side: tab.side,\n    };\n    return { ...mark, tabsAt: at, tagInset: { ...mark.tagInset, side } };\n  });\n}\n\n/**\n * How far the right-anchored tab moves in from the block's right edge so it\n * is on screen: in by what the screen cuts off the right, or out past the\n * edge, a negative inset, when the screen cuts the block's left so little of\n * it shows that the tab would run off the left.\n */\nfunction tabInset(\n  rect: Rect,\n  onScreen: Rect,\n  tabs: AtRestTabs,\n  shownLabel: string\n): number {\n  const right = rect.x + rect.width;\n  // A block wholly off the screen to either side keeps its tab with it,\n  // rather than leaving one stranded at the screen's edge.\n  if (right <= onScreen.x || rect.x >= onScreen.x + onScreen.width) return 0;\n  const cutRight = Math.max(0, right - (onScreen.x + onScreen.width));\n  const width = tabsWidthOf(tabs, shownLabel);\n  const fitsLeft = right - onScreen.x - width;\n  return Math.min(cutRight, fitsLeft);\n}\n\n/** About how wide an at-rest mark's tabs are drawn, side by side. */\nfunction tabsWidthOf(\n  { condition, entryContent }: AtRestTabs,\n  shownLabel: string\n): number {\n  const conditionWidth =\n    condition === undefined\n      ? 0\n      : tagWidthOf(conditionWords(condition, shownLabel)) + CONDITION_ICON_ROOM;\n  const entryWidth = entryContent === undefined ? 0 : tagWidthOf(entryContent);\n  return conditionWidth + entryWidth;\n}\n\n/** Which copy of a placement an element is part of: its parent, numbered. */\nfunction copyOf(copies: Map<Element | null, number>, element: Element): number {\n  const parent = element.parentElement;\n  let copy = copies.get(parent);\n  if (copy === undefined) {\n    copy = copies.size;\n    copies.set(parent, copy);\n  }\n  return copy;\n}\n\n/**\n * Where an at-rest mark's tabs may go, in order of preference: above the\n * block where there's room on screen and nothing else takes that corner,\n * below it where there's room, and inside its top edge, which is always on\n * screen. The first is where they go alone, so a block taller than what's on\n * screen carries them inside; `tabsApart` takes a later one where another\n * block's tabs, a visitor badge or the block toolbar are in the way.\n */\nfunction tabPlacesOf(\n  rect: Rect,\n  onScreen: Rect,\n  topTaken: boolean\n): readonly TabAt[] {\n  const above = !topTaken && rect.y - onScreen.y >= MARK_TAG_HEIGHT;\n  const below =\n    rect.y + rect.height + MARK_TAG_HEIGHT <= onScreen.y + onScreen.height;\n  return [\n    ...(above ? ([\"above\"] as const) : []),\n    ...(below ? ([\"below\"] as const) : []),\n    \"inside\",\n  ];\n}\n\n/**\n * An at-rest mark's tabs, side by side on the outline's edge: what the canvas\n * says about the block, the Entry content block's words before a condition's.\n * A block shown for the previewed entry while conditions are applied says so\n * (`shownLabel`) with a tick.\n */\nfunction AtRestTabsView({\n  mark,\n  shownLabel,\n}: {\n  mark: Mark;\n  shownLabel: string;\n}): React.JSX.Element {\n  const { condition, entryContent } = mark;\n  const Icon =\n    condition === \"unchecked\"\n      ? AlertCircle\n      : condition === \"shown\"\n        ? CircleCheck\n        : Split;\n  return (\n    <span className=\"nx-canvas-mark__tabs\">\n      {entryContent === undefined ? null : (\n        <span className=\"nx-canvas-mark__tab\" data-tab=\"entry-content\">\n          {entryContent}\n        </span>\n      )}\n      {condition === undefined ? null : (\n        <span className=\"nx-canvas-mark__tab\" data-tab={condition}>\n          <Icon aria-hidden=\"true\" size={12} />\n          {conditionWords(condition, shownLabel)}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/** An at-rest mark's state, as the stylesheet reads it. */\nfunction atRestAttributes(mark: Mark): Record<string, string> {\n  return {\n    ...(mark.condition === undefined\n      ? {}\n      : { \"data-condition\": mark.condition }),\n    ...(mark.tabsAt === undefined ? {} : { \"data-tab-at\": mark.tabsAt }),\n    ...(mark.atRestSelected === true ? { \"data-at-rest-selected\": \"\" } : {}),\n  };\n}\n\n/** An exposed part's editing state, as the stylesheet reads it. */\nfunction editingAttributes(mark: Mark): Record<string, string> {\n  return {\n    ...(mark.editing === true ? { \"data-editing\": \"\" } : {}),\n    ...(mark.dimmed === true ? { \"data-dimmed\": \"\" } : {}),\n  };\n}\n\n/**\n * The stripes over hidden blocks first, so every other mark, a ring on a block\n * inside a hidden section among them, is drawn over them rather than under.\n */\nfunction stripesFirst(marks: Mark[]): Mark[] {\n  const stripes = marks.filter(mark => mark.kind === \"device-hidden\");\n  if (stripes.length === 0) return marks;\n  return [...stripes, ...marks.filter(mark => mark.kind !== \"device-hidden\")];\n}\n\n/**\n * The marks with every other exposed part dimmed while one is being edited,\n * so the passage the caret is in is the one that stands out.\n */\nfunction dimmedBesideEditing(marks: Mark[]): Mark[] {\n  if (!marks.some(mark => mark.editing === true)) return marks;\n  return marks.map(mark =>\n    mark.kind === \"exposed\" && mark.editing !== true\n      ? { ...mark, dimmed: true }\n      : mark\n  );\n}\n\n/** The attribute a block marked never to be quoted carries on the page. */\nconst NOT_QUOTED_ATTRIBUTE = \"data-nosnippet\";\n\n/**\n * A hovered block's tag: its name, and for a block marked never to be\n * quoted, that it is not quoted in search. None without a name.\n */\nfunction hoverLabel(\n  name: string | undefined,\n  notQuoted: boolean | undefined\n): string | undefined {\n  const named = name?.trim();\n  if (named === undefined || named === \"\") return undefined;\n  return notQuoted === true ? `${named} · not quoted in search` : named;\n}\n\n/**\n * The marks over the canvas's blocks.\n *\n * Re-measured whenever the canvas may have moved or been re-marked —\n * `watchCanvasFor` hears the attributes change as well as the layout — and\n * when the frame's zoom or page changes, which moves every block on screen\n * while nothing inside the frame changes size.\n *\n * @experimental\n */\nexport function CanvasMarks({\n  revealed = NO_IDS,\n  device,\n  nameOf,\n  shownLabel = \"Shown for this entry\",\n}: CanvasMarksProps = {}): React.JSX.Element {\n  const shownOn =\n    device === undefined\n      ? undefined\n      : deviceLabel(device.breakpoints, device.id);\n  const hiddenLabel = shownOn === undefined ? \"Hidden\" : `Hidden on ${shownOn}`;\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const [marks, setMarks] = React.useState<readonly Mark[]>(NO_MARKS);\n  const canvasFrame = useCanvasFrame();\n  const hovered = useHoveredBlock();\n  // Keyed by value, so a host handing a new array of the same ids on every\n  // render does not re-measure every block. JSON, which spells any id\n  // unambiguously.\n  const revealedKey = JSON.stringify(revealed);\n  // What a measure reads, kept current after each render, so the measure and\n  // the watchers built on it stay the same functions through every hover and\n  // selection: a new measure would rebuild each watcher, observing every\n  // block on the page again.\n  const inputs = React.useRef({\n    hovered,\n    revealedKey,\n    hiddenLabel,\n    shownLabel,\n  });\n  React.useLayoutEffect(() => {\n    inputs.current = { hovered, revealedKey, hiddenLabel, shownLabel };\n  });\n\n  // The last measure, which placing the at-rest tabs again reads: another\n  // layer's post moves where they go, not what the canvas marks.\n  const measured = React.useRef<Measured>(NOTHING_MEASURED);\n\n  // The marks as last measured, the at-rest tabs where the board puts them\n  // now: placed again whenever another layer's post changes the board.\n  const placeTabs = React.useCallback(() => {\n    const { root, marks: drawn, hovered: pointed, atRest } = measured.current;\n    const next = [\n      ...drawn,\n      ...pointed,\n      ...placedAtRest(\n        atRest,\n        root === null ? [] : tabBoardOf(root).placesOf(\"at-rest\")\n      ),\n    ];\n    setMarks(current => (sameMarks(current, next) ? current : next));\n  }, []);\n  const postTabs = useTabPost(\"at-rest\", placeTabs);\n\n  // The canvas root the last measure found, which the watchers are put on:\n  // a new root moves them, or they would go on hearing a root since removed.\n  const [watchedRoot, setWatchedRoot] = React.useState<HTMLElement | null>(\n    null\n  );\n\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    const now = inputs.current;\n    measured.current =\n      element === null\n        ? NOTHING_MEASURED\n        : marksOf(element, {\n            hovered: now.hovered,\n            revealed: new Set(JSON.parse(now.revealedKey) as string[]),\n            tagWidth: tagWidthOf(now.hiddenLabel),\n            shownLabel: now.shownLabel,\n          });\n    const { root, atRest } = measured.current;\n    setWatchedRoot(root);\n    postTabs(root, { tabs: atRest.map(({ tab }) => tab), taken: [] });\n    placeTabs();\n  }, [postTabs, placeTabs]);\n\n  // Measured in full when the canvas or what the marks say changes, and when\n  // the watchers move to a new root: what the old ones had not yet reported\n  // goes with them.\n  React.useLayoutEffect(() => {\n    measure();\n  }, [measure, canvasFrame, watchedRoot, revealedKey, hiddenLabel, shownLabel]);\n\n  // Measured again whenever the layer finds itself over another canvas root:\n  // the page in a frame can mount the canvas again under a new root while\n  // this layer stays. Checked on every render, as nothing else reports it.\n  React.useLayoutEffect(() => {\n    const element = layer.current;\n    if (element === null) return;\n    const root = overlaySpaceOf(element, CANVAS_ROOT_CLASS)?.root ?? null;\n    if (root !== measured.current.root) measure();\n  });\n\n  // A hover change measures the block pointed at alone. Every other mark is\n  // as the last full measure left it, which the watchers keep current.\n  React.useLayoutEffect(() => {\n    const element = layer.current;\n    if (measured.current.hoveredFor === hovered) return;\n    const next =\n      element === null\n        ? undefined\n        : withHoverOf(element, measured.current, hovered);\n    if (next === undefined) {\n      measure();\n      return;\n    }\n    measured.current = next;\n    placeTabs();\n  }, [hovered, measure, placeTabs]);\n\n  React.useEffect(\n    () => watchCanvasFor(() => layer.current, measure),\n    [measure, canvasFrame, watchedRoot]\n  );\n\n  // And the scrolls that move what of the canvas is on screen, which the tags\n  // keep to: the host's scroller around a zoomed frame among them, which no\n  // listener in the frame hears.\n  React.useEffect(() => {\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) return;\n    return watchScreenBand(space.root, space.frame, measure);\n  }, [measure, canvasFrame, watchedRoot]);\n\n  return (\n    // Hidden from assistive technology: the selection is announced by the\n    // editor's live region and named in the inspector, and a box says nothing.\n    <div\n      ref={layer}\n      className=\"nx-canvas-marks\"\n      aria-hidden=\"true\"\n      // Drawn over the page and moving nothing in it, so no overlay's watch\n      // re-measures for a mark being drawn.\n      {...{ [OVERLAY_OUTPUT_ATTRIBUTE]: \"\" }}\n    >\n      {marks.map((mark, index) => (\n        <div\n          // Position in the list is the identity: the boxes carry no state.\n          key={index}\n          className=\"nx-canvas-mark\"\n          data-mark={mark.kind}\n          data-secondary={mark.secondary ? \"\" : undefined}\n          data-component={mark.component ? \"\" : undefined}\n          data-locked={mark.locked ? \"\" : undefined}\n          {...editingAttributes(mark)}\n          data-hidden={mark.hidden ? \"\" : undefined}\n          data-device-tag={mark.deviceTag}\n          // The tag a hidden block's ring carries, drawn by the stylesheet\n          // from this attribute; the layer is hidden from assistive\n          // technology, and Layers and the inspector say it in words.\n          data-label={mark.hidden ? hiddenLabel : undefined}\n          data-tag={mark.hidden ? mark.tag : undefined}\n          data-tag-edge={mark.hidden ? mark.tagEdge : undefined}\n          data-clipped={mark.clipped ? \"\" : undefined}\n          data-shaped={mark.shaped === true ? \"\" : undefined}\n          // The tag a placement's frame carries, drawn by the stylesheet from\n          // this attribute: the layer is hidden from assistive technology,\n          // and the inspector names the placement in words.\n          data-placement-label={\n            mark.placement === undefined\n              ? undefined\n              : placementTag(mark.placement, nameOf)\n          }\n          data-placement-tag-inside={\n            mark.placementTagInside === true ? \"\" : undefined\n          }\n          // The hovered block's name, drawn by the stylesheet as a small tag\n          // over its outline's corner, as the editor's design draws it.\n          data-hover-label={\n            mark.hoveredAddress === undefined\n              ? undefined\n              : hoverLabel(nameOf?.(mark.hoveredAddress), mark.notQuoted)\n          }\n          data-hover-tag-inside={mark.hoverTagInside === true ? \"\" : undefined}\n          {...atRestAttributes(mark)}\n          style={markStyle(mark)}\n        >\n          {mark.kind === \"at-rest\" ? (\n            <AtRestTabsView mark={mark} shownLabel={shownLabel} />\n          ) : null}\n        </div>\n      ))}\n    </div>\n  );\n}\n","/**\n * One canvas drag's own record and the questions asked of it.\n *\n * `useCanvasDrag` in `canvas-drag.tsx` holds a {@link Gesture} while a press\n * is down. What that record is, which pointer owns it, the target a release\n * would commit to, the locks' verdict on where it aims, the rectangles measured\n * when it began, and how a point from another document reaches the canvas's\n * all live here, so the hook keeps only the wiring of events to these answers.\n *\n * @module canvas-drag-gesture\n */\n\nimport {\n  type BlockNode,\n  COMPONENT_INSTANCE_TYPE,\n  declaredSlotNames,\n  type PlacedNode,\n  type PlacementSources,\n} from \"@nextlyhq/blocks-engine\";\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Point, Rect } from \"../geometry\";\nimport type { LockDropRefusal, LockRefusalFacts } from \"../lock-refusal\";\nimport type { OpPosition } from \"../op-vocabulary\";\n\nimport { isOutermostForAddress, nodeAddressOf } from \"./canvas\";\nimport type { DragSubject } from \"./canvas-drag-types\";\nimport type { CanvasFrame } from \"./canvas-frame-context\";\nimport type {\n  DropRegion,\n  DropResolution,\n  DropTarget,\n  RectSource,\n  RegionVerdicts,\n} from \"./drop-targets\";\nimport {\n  canvasContentRect,\n  framePaintedScale,\n  hostPointInFrame,\n} from \"./geometry-dom\";\nimport type { TargetSwitchState } from \"./target-switch\";\n\n/**\n * Hand the pointer back, when this transport is the one holding it.\n *\n * A node-origin drag captures on the canvas root; a palette drag captures\n * nowhere and passes `null`. Asked of the element rather than tracked, because\n * the browser releases capture itself on some endings and a flag would then\n * describe a capture that is already gone.\n */\nexport function releaseCapture(\n  host: HTMLElement | null,\n  pointerId: number\n): void {\n  if (host !== null && host.hasPointerCapture(pointerId)) {\n    host.releasePointerCapture(pointerId);\n  }\n}\n\n/**\n * The target a release would commit to, or `undefined` when there is none.\n *\n * ONE absent value, not two. Written as `null` for \"nothing committed\" and\n * `undefined` for \"committed to something no longer drawable\", the caller\n * would have to exclude both — and excluding one reads as complete, so a drag\n * released over no target would reach `target.at`.\n */\nexport function committedTarget(drag: Gesture): DropTarget | undefined {\n  const committed = drag.switchState.committed;\n  return committed === null ? undefined : drag.targets.get(committed);\n}\n\n/**\n * The gesture this pointer owns, or `null` when it owns none.\n *\n * The one answer to \"may this event drive the drag\", asked by every transport:\n * the canvas's React handlers for a pointer over the canvas, and the document\n * listeners for one anywhere else. Written once because it was written three\n * times — move, release and cancel each compared the id themselves, and a\n * change to what ownership means would have had to find all three.\n */\nexport function gestureOwnedBy(\n  current: Gesture | null,\n  pointerId: number\n): Gesture | null {\n  if (current === null) return null;\n  return current.owner === pointerId ? current : null;\n}\n\n/**\n * Whether a press may begin a gesture.\n *\n * A drag ALREADY IN FLIGHT keeps the pointer that started it: a second finger\n * must not take it over, or the first gesture is left with no ending of its own\n * — its release unheard, its click never suppressed.\n *\n * An INACTIVE gesture is a different thing and must not block anything. It is a\n * press that has not yet travelled far enough to mean a drag, and one can be\n * stranded: a press beginning within the activation threshold of the canvas\n * edge takes no capture, so if the pointer leaves the root its move and release\n * are delivered somewhere these handlers never see. Refusing later presses\n * because of it would lock dragging until the host unmounted, and there is\n * nothing to protect — no drag was in progress.\n */\nexport function admitsPress(current: Gesture | null): boolean {\n  return current === null || !current.active;\n}\n\n/** Where the pointer aims, with a target the locks refuse turned into a refusal. */\ntype AimResolution =\n  | DropResolution\n  | { readonly kind: \"refused\"; readonly refusal: LockDropRefusal };\n\n/**\n * A resolved target the editor's locks refuse, answered as a refusal that says\n * so. Asked of the editor's own `lockRefusalFor`, the question its apply asks,\n * so the indicator never offers a drop the release would then refuse.\n */\nexport function withLockVerdict(\n  drag: Gesture,\n  editor: Pick<EditorState, \"lockRefusalFor\">,\n  resolution: DropResolution\n): AimResolution {\n  if (resolution.kind !== \"target\") return resolution;\n  const target = resolution.target;\n  let verdict = drag.lockVerdicts.get(target.id);\n  if (verdict === undefined) {\n    verdict = lockVerdictAt(drag.subject, target.at, editor) ?? null;\n    drag.lockVerdicts.set(target.id, verdict);\n  }\n  if (verdict === null) return resolution;\n  return {\n    kind: \"refused\",\n    refusal: {\n      regionId: target.regionId,\n      ...(target.at.parentId === undefined\n        ? {}\n        : { parentId: target.at.parentId }),\n      lock: verdict,\n    },\n  };\n}\n\n/**\n * A thunk that builds its node on the first call and hands back that node\n * after, so one gesture judges and inserts one node. Building twice would\n * judge one subtree and insert another, with ids of its own.\n */\nexport function builtOnce(\n  make: () => BlockNode | null\n): () => BlockNode | null {\n  let built: { node: BlockNode | null } | undefined;\n  return () => (built ??= { node: make() }).node;\n}\n\n/** The lock break dropping the subject at `at` would add. */\nfunction lockVerdictAt(\n  subject: DragSubject,\n  at: OpPosition,\n  editor: Pick<EditorState, \"lockRefusalFor\">\n): LockRefusalFacts | undefined {\n  if (subject.kind === \"move\") {\n    return editor.lockRefusalFor([\n      { kind: \"move\", id: subject.nodeId, to: at },\n    ]);\n  }\n  // The node an insert would place, starting blocks and all: a block whose\n  // own slots are locked is judged as it would land, not as an empty shell.\n  const node = subject.makeNode();\n  return node === null\n    ? undefined\n    : editor.lockRefusalFor([{ kind: \"insert\", node, at }]);\n}\n\n/**\n * A press on a block a Layers lock holds in place: whose pointer, where it\n * began, the block, the lock's facts, and whether its reason is drawn.\n */\nexport interface HeldPress {\n  readonly owner: number;\n  readonly originClient: { readonly x: number; readonly y: number };\n  readonly nodeId: string;\n  readonly blockName: string;\n  readonly lock: LockRefusalFacts;\n  shown: boolean;\n}\n\n/** What a drag needs to remember, none of which renders. */\nexport interface Gesture {\n  readonly subject: DragSubject;\n  /**\n   * The pointer that began this gesture, and the only one that may drive it.\n   *\n   * A node-origin drag takes pointer capture, which retargets one pointer and\n   * leaves the rest alone — so this is redundant there and costs nothing. A\n   * palette drag deliberately takes no capture, because the browser resolves a\n   * click against the capturing element and the row must keep inserting on\n   * click. Its events therefore arrive by two transports, the canvas's own\n   * React handlers and the document listeners, and BOTH see every active\n   * pointer on a touch device.\n   *\n   * Kept on the gesture rather than checked in each transport's closure: the\n   * two entry points below are where every pointer event of either transport\n   * converges, so enforcing it there covers a route a closure check would\n   * miss — a second finger moving over the CANVAS reaches the React handler,\n   * not the document listener.\n   */\n  readonly owner: number;\n  readonly origin: Point;\n  /**\n   * Where the press landed in CLIENT pixels.\n   *\n   * Kept beside {@link origin} rather than derived from it, because the two\n   * answer different questions and a scaled canvas separates them. `origin` is\n   * in the canvas's own content coordinates, which is what a hit test needs;\n   * the thresholds below are about how far a HAND moved, which is a fact about\n   * the person and not about the document's coordinate system.\n   *\n   * Measured in content pixels they shrink with the canvas: at a canvas painted\n   * to 71%, the 4px that separates a click from a drag needs only 2.85px of\n   * real movement, so ordinary click jitter starts committing moves — and the\n   * target hysteresis loosens by the same factor at the same time.\n   *\n   * In the canvas document's client coordinates, like every later point of\n   * the gesture, and turned into the author's pixels by {@link handScale}.\n   */\n  readonly originClient: Point;\n  /**\n   * How many of the author's on-screen pixels one of the canvas document's\n   * client pixels is: `1` in the editor's own document, the frame's painted\n   * scale in a frame. The host paints a frame scaled, and nothing read inside\n   * the frame shows it, so a distance measured there is multiplied by this\n   * before any threshold about the hand is applied to it. Read once at the\n   * press: the scale does not change during a gesture.\n   */\n  readonly handScale: number;\n  readonly regions: readonly DropRegion[];\n  readonly rects: RectSource;\n  readonly forbiddenParents: ReadonlySet<string>;\n  readonly blockName: string;\n  /**\n   * What the placement is judged by: the block's own type, or an instance's\n   * resolved roots. Computed once at the press — the definitions a drag\n   * resolves against do not change mid-gesture.\n   */\n  readonly blockNames: readonly string[];\n  /**\n   * The blocks being placed, with everything inside them, which the one\n   * placement rule judges. Asked only when a region is judged, because an\n   * insert's answer is the node its palette builds, the very node the release\n   * inserts. Empty when the palette builds nothing; the name rules then judge\n   * `blockNames` as before.\n   */\n  readonly placing: () => readonly PlacedNode[];\n  /**\n   * The placement rule's answer for each region, asked once for the gesture's\n   * life, as the lock verdicts are: the document, the blocks and the regions\n   * do not change mid-drag, and every pointer move and autoscroll frame\n   * resolves the drop again.\n   */\n  readonly placementVerdicts: RegionVerdicts;\n  /** False until the pointer has travelled far enough to mean a drag. */\n  active: boolean;\n  switchState: TargetSwitchState;\n  /** Targets by id, so the committed id resolves back to something drawable. */\n  targets: Map<string, DropTarget>;\n  /**\n   * Each target's lock verdict, asked once for the gesture's life: the document\n   * does not change mid-drag, and asking per pointer move would apply the edit\n   * speculatively on every frame.\n   */\n  lockVerdicts: Map<string, LockRefusalFacts | null>;\n  /**\n   * The canvas root, kept so a frame with no pointer event still has it.\n   *\n   * Autoscroll runs between moves — a pointer resting in the edge band produces\n   * no events at all — so the element cannot come from `event.currentTarget`\n   * the way every other read here does.\n   */\n  readonly root: HTMLElement;\n  /**\n   * The element that actually scrolls, or `null` when nothing does.\n   *\n   * Resolved once at drag start rather than per frame: it is a walk up the tree\n   * reading computed styles, and the answer cannot change mid-gesture.\n   */\n  readonly scroller: Element | null;\n  /** The last pointer position, in the canvas document's CLIENT coordinates. */\n  clientX: number;\n  clientY: number;\n  /** The scheduled frame, or `null` when no loop is running. */\n  frame: number | null;\n}\n\n/**\n * The identity half of {@link CanvasDragState}, for whichever subject is in\n * flight.\n *\n * Derived in one place rather than spelled out at each `setState`, so the two\n * fields cannot drift into disagreeing about whether a drag is happening: an\n * insert has no `draggingId`, and a site that set the id alone would report no\n * drag at all to everything gated on the block name.\n */\nexport function drawnSubject(drag: Gesture): {\n  draggingId: string | null;\n  draggingBlockName: string;\n} {\n  return {\n    draggingId: drag.subject.kind === \"move\" ? drag.subject.nodeId : null,\n    draggingBlockName: drag.blockName,\n  };\n}\n\n/**\n * The element standing for each rendered block, by the block's address: the\n * one place that answers which element a block is measured by. The drag\n * measures every one at once (`snapshotRects`); the Add panel's insertion\n * line measures only those it asks for.\n *\n * Compared in JavaScript rather than matched with a selector built from an\n * id: a node id reaches this from stored data, and interpolating it into\n * `querySelector` makes any character CSS treats specially either throw or,\n * worse, match a different element.\n */\nexport function blockElements(root: HTMLElement): Map<string, Element> {\n  const found = new Map<string, Element>();\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    // The ADDRESS a drag asks by, not the raw attribute. `collectRegions`\n    // requests rectangles by the id the document holds, and a definition-owned\n    // element carries a re-minted one — so keying by the attribute leaves every\n    // child of a component unmeasured. `targetsInRegion` then reads a root with\n    // no measured children and collapses it to one index-0 midpoint, so\n    // releasing a drag moves the component to the start whatever was under the\n    // pointer.\n    //\n    // Reachable only since the hit test began answering with instance ids: the\n    // drag used to bail before this, because `findNode` could not resolve the\n    // re-minted id. Making that path work is what exposed this.\n    const id = nodeAddressOf(element);\n    // OUTERMOST only, so an instance is measured as its own box rather than as\n    // whichever element its definition contributed last. A node a block\n    // rendered more than once still measures every copy, because sibling copies\n    // are each outermost — the last one wins there exactly as it did before.\n    if (id !== null && isOutermostForAddress(element, id, root)) {\n      found.set(id, element);\n    }\n  });\n  return found;\n}\n\n/** Every rendered node's rectangle, read once. */\nexport function snapshotRects(root: HTMLElement): RectSource {\n  const measured = new Map<string, Rect>();\n  blockElements(root).forEach((element, id) => {\n    measured.set(id, canvasContentRect(element, root));\n  });\n  // The canvas's own box, measured through the SAME reader as the blocks\n  // inside it. `scrollWidth`/`scrollHeight` describe the whole content rather\n  // than the part on screen, and mixing them with a rectangle read means the\n  // region and its children answer to two different measurements — which is\n  // the disagreement this package keeps its geometry in one place to avoid.\n  //\n  // The visible box is also the correct extent for what it is used for: it\n  // decides whether the POINTER is inside the canvas, and a pointer cannot be\n  // over content that is scrolled out of view.\n  const rootRect: Rect = canvasContentRect(root, root);\n  return {\n    rectOf: id => measured.get(id),\n    rootRect: () => rootRect,\n  };\n}\n\n/**\n * Listen for one event type on every document given, in the capture phase.\n *\n * Returns the function that removes exactly the listeners added, so a caller\n * holding it cannot remove from one document and leave the other listening.\n */\nexport function listenOn<K extends keyof DocumentEventMap>(\n  documents: readonly Document[],\n  type: K,\n  listener: (event: DocumentEventMap[K]) => void\n): () => void {\n  for (const doc of documents) doc.addEventListener(type, listener, true);\n  return () => {\n    for (const doc of documents) doc.removeEventListener(type, listener, true);\n  };\n}\n\n/**\n * The window the canvas root's frame loop runs in.\n *\n * The ROOT's, because a frame's animation callbacks are paced by that frame's\n * own rendering, and a loop scheduled on another window's clock scrolls the\n * frame out of step with what it paints. `null` for a root whose document has\n * no window, where there is no frame to schedule on.\n */\nexport function frameLoopOf(drag: Gesture): Window | null {\n  return drag.root.ownerDocument.defaultView;\n}\n\n/**\n * How many of the author's on-screen pixels one canvas client pixel is.\n *\n * See {@link Gesture.handScale}.\n */\nexport function handScaleOf(canvas: CanvasFrame): number {\n  return canvas.frame === null ? 1 : framePaintedScale(canvas.frame);\n}\n\n/**\n * A point delivered to `doc`, in the canvas document's client coordinates.\n *\n * The canvas's own document, and every document while there is no frame,\n * already reports in them. The editor's document reports in its own, which are\n * carried into the frame's: every rectangle of the canvas is read inside the\n * frame, so a point from the panels means nothing there until it is mapped.\n */\nexport function canvasClientPoint(\n  canvas: CanvasFrame,\n  doc: Document,\n  clientX: number,\n  clientY: number\n): Point {\n  const point = { x: clientX, y: clientY };\n  return canvas.frame === null || doc === canvas.document\n    ? point\n    : hostPointInFrame(canvas.frame, point);\n}\n\n/**\n * The slots a component placement exposes, which its type alone cannot say.\n * Every other block answers undefined, so its regions come from the caller's\n * `slots` source, the one this hook documents as each type's child regions.\n */\nexport function slotsOfNode(\n  sources: PlacementSources\n): (node: BlockNode) => readonly string[] | undefined {\n  return node =>\n    node.type === COMPONENT_INSTANCE_TYPE\n      ? declaredSlotNames(node, sources)\n      : undefined;\n}\n","\"use client\";\n\n/**\n * The line a canvas drag draws where the dragged block would land. Moved out\n * of `canvas-drag.tsx`, which still exports it beside the hook that decides\n * the target it draws.\n *\n * @module drop-indicator\n */\n\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { CANVAS_ROOT_CLASS } from \"./canvas\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { targetLineRect, type DropTarget } from \"./drop-targets\";\nimport { overlaySpaceOf } from \"./geometry-dom\";\n\nexport interface DropIndicatorProps {\n  /** Where a drop would land, or null to draw nothing. */\n  target: DropTarget | null;\n}\n\n/**\n * The line showing where a dropped block will go.\n *\n * The target is in the canvas root's content coordinates, which is what the\n * rectangles were measured in. Where the line is drawn in those coordinates\n * depends on where it is drawn: inside the root over a canvas sharing the\n * editor's document, or in the layer over the canvas's frame, where they are\n * scaled to the frame's zoom while the line keeps its own thickness. Asked of\n * the line's own element, through `overlaySpaceOf`, the one mapping every\n * piece of chrome uses.\n *\n * Written to the element's style before paint rather than rendered: the\n * mapping needs the element in the document, and a render to apply it would\n * draw the line at the unmapped position for a frame on every pointer move.\n *\n * `aria-hidden`, and deliberately: the equivalent keyboard move announces its\n * own outcome through the editor's one live region, and a second element\n * describing the same pointer gesture would be read alongside it. A pointer drag\n * is also self-describing to anyone who can see the line.\n */\nexport function DropIndicator({\n  target,\n}: DropIndicatorProps): React.JSX.Element | null {\n  const line = React.useRef<HTMLDivElement | null>(null);\n  // A zoom, or the frame's page arriving, moves the line on screen while the\n  // target stays where it was.\n  const canvasFrame = useCanvasFrame();\n  useIsomorphicLayoutEffect(() => {\n    const element = line.current;\n    if (element === null || target === null) return;\n    // The line is drawn ACROSS the axis children are separated along: a\n    // region stacking its children downward gets a horizontal rule, a row\n    // gets a vertical one.\n    const rect = targetLineRect(target);\n    const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    const at = space === null ? rect : space.place(rect);\n    element.style.left = `${String(at.x)}px`;\n    element.style.top = `${String(at.y)}px`;\n    // The other dimension is the stylesheet's, so a line that changes axis\n    // does not keep the length it had along the old one.\n    element.style.width = target.axis === \"y\" ? `${String(at.width)}px` : \"\";\n    element.style.height = target.axis === \"x\" ? `${String(at.height)}px` : \"\";\n  }, [target, canvasFrame]);\n\n  if (target === null) return null;\n\n  return (\n    <div\n      ref={line}\n      className=\"nx-drop-indicator\"\n      data-axis={target.axis}\n      aria-hidden=\"true\"\n    />\n  );\n}\n","/**\n * Where the Add panel's highlighted tile would land, as something to draw.\n *\n * The same geometry a canvas drag draws its drop line from: the place's\n * region, measured, and {@link targetsInRegion}'s line at the place's index,\n * which sits in the middle of the gap after the block before it, across the\n * region, and runs down a row's height in a row. One answer for both, so the\n * line a tile shows is where a drag to the same place would show it.\n *\n * Only the place's own region is measured: its container and the blocks in\n * it, never the page around it.\n *\n * @module insertion-line-geometry\n */\nimport { findNode, type BlockDocument } from \"@nextlyhq/blocks-engine\";\n\nimport type { OpPosition } from \"../op-vocabulary\";\n\nimport {\n  rootRegion,\n  slotRegion,\n  targetsInRegion,\n  type DropRegion,\n  type DropTarget,\n  type RectSource,\n} from \"./drop-targets\";\n\n/** What the canvas draws for a place. */\n/**\n * The rendered block a place is shown beside, and which of its sides the\n * place touches: what is scrolled into view to show the place.\n */\nexport interface Neighbour {\n  readonly id: string;\n  /** The place comes after the block, before it, or inside it. */\n  readonly side: \"after\" | \"before\" | \"inside\";\n}\n\nexport type InsertionMark =\n  /** A line at the place, as a drag's drop line, and its neighbour. */\n  | {\n      readonly kind: \"line\";\n      readonly target: DropTarget;\n      readonly near: Neighbour | undefined;\n    }\n  /** An empty container the block goes inside: its outline, not a line. */\n  | { readonly kind: \"empty\"; readonly containerId: string };\n\n/**\n * The region a place is in: the container's slot, or the page's top level,\n * built as a drag builds it. `undefined` when the container is no longer on\n * the page or did not render.\n */\nfunction regionOf(\n  document: BlockDocument,\n  at: OpPosition,\n  rects: RectSource\n): DropRegion | undefined {\n  if (at.parentId === undefined || at.slot === undefined) {\n    return rootRegion(document, rects);\n  }\n  const parent = findNode(document.nodes, at.parentId);\n  return parent === undefined\n    ? undefined\n    : slotRegion(parent, at.slot, 1, rects);\n}\n\n/**\n * What to draw for a block going in at `at`: a line where it will land, or,\n * for an empty container, that container to light up. `undefined` when the\n * place cannot be drawn: its container is gone or drew nothing, or it is the\n * top of an empty page, which the page's own start area already shows.\n */\nexport function insertionMarkOf(\n  document: BlockDocument,\n  at: OpPosition,\n  rects: RectSource\n): InsertionMark | undefined {\n  const region = regionOf(document, at, rects);\n  if (region === undefined) return undefined;\n  if (region.childIds.length === 0) {\n    return region.parentId === undefined\n      ? undefined\n      : { kind: \"empty\", containerId: region.parentId };\n  }\n  const target = lineAt(targetsInRegion(region, rects), at.index);\n  if (target === undefined) return undefined;\n  return { kind: \"line\", target, near: neighbourOf(region, at.index, rects) };\n}\n\n/**\n * The rendered block nearest a place: the closest before it, else the\n * closest after it, else its container. A block that draws nothing has no\n * box to scroll to, so it is passed over.\n */\nfunction neighbourOf(\n  region: DropRegion,\n  index: number,\n  rects: RectSource\n): Neighbour | undefined {\n  const drawn = (id: string | undefined): id is string =>\n    id !== undefined && rects.rectOf(id) !== undefined;\n  const before = region.childIds.slice(0, index).reverse().find(drawn);\n  if (before !== undefined) return { id: before, side: \"after\" };\n  const after = region.childIds.slice(index).find(drawn);\n  if (after !== undefined) return { id: after, side: \"before\" };\n  return region.parentId === undefined\n    ? undefined\n    : { id: region.parentId, side: \"inside\" };\n}\n\n/**\n * The region's line for `index`. A block that rendered nothing has no line of\n * its own and takes no room, so a place beside one is drawn at the next line\n * after it, which is the same gap on screen; where none comes after, at the\n * last line before it.\n */\nfunction lineAt(\n  lines: readonly DropTarget[],\n  index: number\n): DropTarget | undefined {\n  return lines.find(line => line.at.index >= index) ?? lines[lines.length - 1];\n}\n","/**\n * Which edge of a spacing band actually moves when the value grows.\n *\n * It is not a constant, and that is the whole reason this file exists. Measured\n * in Chromium on one ordinary block and one with a fixed height:\n *\n * | block | content edge | border edge |\n * | --- | --- | --- |\n * | height fits its content | stays | **moves outward** |\n * | height is fixed | **moves inward** | stays |\n *\n * So a handle placed on a fixed edge sits still while the block grows away from\n * it, and a drag direction derived from the wrong edge runs backwards. Both were\n * true of `padding-bottom` and `padding-right` on ordinary blocks, which is the\n * common case rather than an exotic one.\n *\n * ## Why this is measured rather than read off the CSS\n *\n * The question is whether the block's size along that axis is decided by its\n * content, and the ways a size becomes definite are open-ended: an explicit\n * `height`, a flex basis, a stretched grid area, an `aspect-ratio`, a fixed\n * parent with `align-items: stretch`. Enumerating them is the kind of list that\n * is complete until the next layout feature ships, and every gap is a handle\n * that runs backwards for a reason nobody can see. Asking the element is\n * complete by construction.\n *\n * MARGINS look exempt, on the reasoning that one lies outside the border box\n * and never moves it. That reasoning fails the way any table of layout cases\n * fails — by arguing about layout instead of asking it. Measured in Chromium on\n * a block in normal flow, and again in a flex column:\n *\n * | band | border edge | outer margin edge |\n * | --- | --- | --- |\n * | `margin-top` | moves INWARD | pinned by what precedes it |\n * | `margin-left` | moves INWARD | pinned by the container |\n * | `margin-right`, auto width | moves INWARD | pinned by the container |\n * | `margin-right`, fixed width | pinned | moves outward |\n * | `margin-bottom` | pinned | moves outward |\n *\n * Exactly one of a margin band's two edges moves, so asking whether the BORDER\n * edge moved answers it: if it did, the outer edge is the pinned one. And the\n * question is not which SIDE — `margin-right` answers both ways depending on\n * whether the width is settled — which is why no table can stand in for asking.\n *\n * The two boxes therefore read the probe differently, and the difference is the\n * geometry rather than an inconsistency. A padding band's far edge from the\n * block's middle IS the border edge, and a padding can only push it outward, so\n * a padding is answered by SIGNED outward movement. A margin band's far edge is\n * the other one, and a margin drives the border edge either way, so a margin is\n * answered by whether it moved AT ALL.\n *\n * @module spacing-response\n */\n\nimport { boxAcross } from \"./geometry-dom\";\nimport type { SpacingBox, SpacingSide } from \"./spacing-bands\";\n\n/** An element whose inline `style` this can write and put back. */\nexport type StyleCapableElement = Element & ElementCSSInlineStyle;\n\n/**\n * Whether this element can be probed at all.\n *\n * Asked as a CAPABILITY rather than as `instanceof HTMLElement`, because the\n * blocks needing an answer are not all HTML: `isReplaced` counts `<svg>` among\n * the replaced boxes and `drawableBoxes` draws its margins, so an HTML-only\n * test answered every SVG-rooted block with a fallback instead of a\n * measurement — and a fallback is a direction supplied without measuring, which\n * is the thing this module exists to stop. An inline `style` is the whole\n * requirement, and HTML, SVG and MathML elements all carry one.\n */\nexport function styleCapable(element: Element): element is StyleCapableElement {\n  return \"style\" in element;\n}\n\n/** How far the probe pushes the padding, in CSS pixels. */\nconst PROBE_PX = 10;\n\n/**\n * The same property as a computed-style key.\n *\n * Read this way rather than through `getPropertyValue`, because that is how\n * every other reader in this package asks a computed style — `boxesOf` in the\n * overlay takes `style.paddingTop` — and asking a second way would be a second\n * shape for a test double to satisfy.\n */\nconst COMPUTED = {\n  padding: {\n    top: \"paddingTop\",\n    right: \"paddingRight\",\n    bottom: \"paddingBottom\",\n    left: \"paddingLeft\",\n  },\n  margin: {\n    top: \"marginTop\",\n    right: \"marginRight\",\n    bottom: \"marginBottom\",\n    left: \"marginLeft\",\n  },\n} as const satisfies Record<SpacingBox, Record<SpacingSide, string>>;\n\n/**\n * What to set `transition-property` to while the probe writes.\n *\n * Naming what is RUNNING rather than turning transitions off, because those are\n * different instructions and only one of them is safe. `transition: none` also\n * cancels whatever the block is in the middle of: measured in Chromium, a block\n * 0.28 of the way through an opacity transition jumps straight to 1 and stays\n * there, and restoring the attribute afterwards cannot resume a timeline that\n * has ended. A forced-state change starts exactly such a transition and then\n * mutates a class, which is what asks for a measurement — so the probe would\n * snap the animation it was prompted by.\n *\n * Listing the live transitions minus the probed property keeps each of them and\n * suppresses only the push about to be made. `transition-property: none` when\n * nothing is running cancels nothing, since there is nothing to cancel.\n *\n * Asked of the ELEMENT rather than of its declared `transition-property`, which\n * cannot answer it: `all` covers the probed property along with every other,\n * and no subtraction expresses \"all except this one\".\n */\nfunction transitionsToKeep(block: Element, property: string): string {\n  /* c8 ignore next -- jsdom animates nothing, so it publishes no timelines */\n  if (typeof block.getAnimations !== \"function\") return \"none\";\n  const running = block\n    .getAnimations()\n    .map(animation =>\n      \"transitionProperty\" in animation\n        ? String(animation.transitionProperty)\n        : \"\"\n    )\n    .filter(name => name !== \"\" && name !== property);\n  return running.length === 0 ? \"none\" : [...new Set(running)].join(\", \");\n}\n\n/**\n * Let the browser settle the style written so far, by reading through it.\n *\n * A pair of writes in one task otherwise lands in a single recalculation, and\n * a transition then sees the wrong value as the one it starts from. Computed\n * style rather than a rectangle: it flushes just the same, and a rectangle read\n * belongs to `geometry-dom`, which owns that question for this package.\n */\nfunction settle(\n  view: Window,\n  block: Element,\n  computed: keyof CSSStyleDeclaration\n): void {\n  const styles = view.getComputedStyle(block);\n  // Read into nothing on purpose: the READ is the effect being asked for.\n  if (styles[computed] === undefined) return;\n}\n\n/** How far the border edge on `side` moved away from the block's middle. */\nfunction edgeMovedOut(\n  before: DOMRect,\n  after: DOMRect,\n  side: SpacingSide\n): number {\n  switch (side) {\n    case \"top\":\n      return before.top - after.top;\n    case \"bottom\":\n      return after.bottom - before.bottom;\n    case \"left\":\n      return before.left - after.left;\n    case \"right\":\n      return after.right - before.right;\n  }\n}\n\n/**\n * Ask the element which edge responds, by pushing its padding and looking.\n *\n * The inline value is restored EXACTLY — including the absence of one, and\n * including a priority the author set — so the document is byte-identical after\n * this returns. It has to be: this writes to a node the canvas is rendering, and\n * a probe that left a trace would be an edit nobody made.\n *\n * Synchronous throughout. The write, both reads and the restore happen in one\n * task, so no frame is ever painted with the probe value applied and no\n * `ResizeObserver` sees a size that differs from the one it last delivered.\n *\n * @param block - the rendered element the band was measured from\n * @param side - the physical side being asked about\n * @returns whether the OUTER edge is the one that moves\n */\nexport function spacingRespondsOutward(\n  block: StyleCapableElement,\n  box: SpacingBox,\n  side: SpacingSide,\n  scale: number\n): boolean {\n  const property = `${box}-${side}`;\n  const style = block.style;\n  /*\n   * The WHOLE attribute, restored verbatim.\n   *\n   * Setting and then removing one property leaves `style=\"\"` behind where there\n   * was no attribute at all — invisible to rendering and perfectly visible to\n   * the `MutationObserver` this canvas has watching its own subtree, which is\n   * the difference between a probe and an edit. Saving the attribute also\n   * carries the author's priority and property order for free, which restoring\n   * one declaration by hand does not.\n   */\n  const had = block.getAttribute(\"style\");\n  const view = block.ownerDocument.defaultView;\n  /* c8 ignore next -- an element outside a realm cannot be measured at all */\n  if (view === null) return false;\n  const computed = COMPUTED[box][side];\n  const current =\n    Number.parseFloat(view.getComputedStyle(block)[computed]) || 0;\n  const keep = transitionsToKeep(block, property);\n\n  /** The element's own inline style, exactly as it was found. */\n  const release = (): void => {\n    if (had !== null) {\n      block.setAttribute(\"style\", had);\n      return;\n    }\n    block.removeAttribute(\"style\");\n    /*\n     * Removed TWICE, with a read between, and only the read makes the second\n     * one work.\n     *\n     * Measured in Chromium: an element that had no `style` attribute is left\n     * carrying `style=\"\"` after one removal, because the declaration this probe\n     * dirtied is re-serialised back into the attribute. Calling\n     * `removeAttribute` twice in a row does not help — nothing between them\n     * forces that pending write to happen — while asking whether the attribute\n     * is there does, so the removal after it clears the attribute for real.\n     *\n     * It matters because the canvas watches this subtree: an empty `style`\n     * attribute is invisible to rendering and perfectly visible to a\n     * `MutationObserver`, which is the difference between a probe and an edit\n     * nobody made. jsdom removes the attribute on the first call, so no test in\n     * this package can tell the two apart; only a browser can.\n     */\n    if (block.hasAttribute(\"style\")) block.removeAttribute(\"style\");\n  };\n\n  /*\n   * Read through `geometry-dom`, which is the one module allowed to take a\n   * rectangle off the DOM — `geometry-ownership.test.ts` enforces that, and the\n   * reason is that two readers are each right about their own question and\n   * disagree about the shared one.\n   */\n  const { before, after } = boxAcross(\n    block,\n    () => {\n      /*\n       * The probed property must not transition, and it is the difference\n       * between a measurement and a reading of nothing.\n       *\n       * `transition` is a catalog property, so a block may carry one over the\n       * very side being probed — and then the push does not land, it begins to\n       * animate. Measured in Chromium: with `transition: margin-top 2s`, the\n       * edge moves ZERO pixels in the same task, so the probe reads a block\n       * whose margin responds as one that does not, places the handle on the\n       * pinned edge and inverts the drag. Writing the declaration at important\n       * priority does not help, because priority decides the cascade rather\n       * than whether a transition runs.\n       *\n       * An ANIMATION needs nothing here and gets nothing: measured the same\n       * way, a running keyframe animation over the same property answers\n       * correctly either way, because an author declaration at important\n       * priority outranks an animation in the cascade.\n       *\n       * Restored with everything else: the whole attribute goes back verbatim.\n       */\n      style.setProperty(\"transition-property\", keep, \"important\");\n      // `important`, so an author's own `!important` padding cannot win and\n      // make every block answer \"the outer edge never moves\".\n      style.setProperty(\n        property,\n        `${String(current + PROBE_PX)}px`,\n        \"important\"\n      );\n    },\n    () => {\n      /*\n       * Put the VALUE back while the transition is still suppressed, and only\n       * then let the transition back.\n       *\n       * Restoring both at once starts the very animation the suppression was\n       * for, in reverse. The measurement above has already committed the probed\n       * value — that is what reading the rectangle does — so a restore that\n       * also re-enables the author's transition presents a transitionable change\n       * FROM the probed value back to the real one. Measured in Chromium on a\n       * block with `transition: margin-top 2s`: after one probe the computed\n       * margin reads thirty pixels, and the block spends two seconds sliding\n       * back to twenty from a value nobody wrote. Eight probes make that eight\n       * properties, on nothing more than a selection.\n       */\n      release();\n      style.setProperty(\"transition-property\", keep, \"important\");\n      settle(view, block, computed);\n      // The value is already back, so this changes nothing that can transition.\n      release();\n    }\n  );\n\n  /*\n   * Judged against what the probe SHOULD have moved at this canvas's scale.\n   *\n   * `boxAcross` answers in viewport pixels, and the canvas is painted through a\n   * transform — so ten CSS pixels of padding move the edge by ten times the\n   * scale on screen, which is five at half zoom and two and a half at quarter.\n   * A fixed threshold in viewport pixels therefore reads an ordinary\n   * outward-growing block as stationary on any zoomed canvas, places the handle\n   * on the edge that never moves and inverts the drag: exactly the defect this\n   * module exists to remove, reintroduced by the units it was measured in.\n   *\n   * Half the expected motion separates the two answers cleanly, because the\n   * other one is not a smaller movement — it is no movement at all.\n   */\n  const expected = PROBE_PX * (Number.isFinite(scale) && scale > 0 ? scale : 1);\n  const moved = edgeMovedOut(before, after, side);\n  /*\n   * A padding is asked whether the border edge moved OUTWARD, because that edge\n   * is the far one of its band and a padding cannot pull it inward: growing one\n   * either pushes the border edge out or is absorbed by a size already settled.\n   */\n  if (box === \"padding\") return moved > expected / 2;\n  /*\n   * A margin is asked whether that edge moved AT ALL, and the sign is the trap.\n   * `margin-top` drives the border edge DOWN — inward, which reads NEGATIVE here\n   * — so a SIGNED comparison files it under \"did not move\", concludes the outer\n   * edge is the live one, and puts the handle on the very edge this module\n   * exists to avoid. A border edge that moved means the outer one is pinned, and\n   * so the band grows inward.\n   */\n  return Math.abs(moved) <= expected / 2;\n}\n","\"use client\";\n\n/**\n * The line on the canvas where the Add panel's highlighted tile would land.\n *\n * While a tile is pointed at or has the keyboard's highlight, the panel hands\n * its place and words to the canvas (`insertion-preview`), and this draws\n * them: the drag's drop line at that place, with the panel's words on a small\n * label at its start, so the author sees where a click would put the block\n * before clicking. An empty container the block would go inside is lit\n * instead, in the look an empty container takes when pointed at.\n *\n * **Calm.** It never animates and never scrolls the canvas: a new tile moves\n * it at once, and the panel keeps it a moment after the pointer leaves the\n * tiles, so crossing the gaps between them does not make it blink. A place\n * off screen gets its label alone, pinned to the canvas edge nearest it with\n * an arrow; pressing that label, never pointing at it, scrolls the place into\n * view.\n *\n * Drawn in the canvas's overlay and only re-rendered by the preview: the page\n * is never drawn again for it, and only the place's own region is measured.\n *\n * @module insertion-line\n */\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { Rect } from \"../geometry\";\n\nimport { CANVAS_ROOT_CLASS } from \"./canvas\";\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { blockElements } from \"./canvas-drag-gesture\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport {\n  OVERLAY_OUTPUT_ATTRIBUTE,\n  watchCanvasFor,\n  watchScreenBand,\n} from \"./canvas-geometry-watch\";\nimport { DropIndicator } from \"./drop-indicator\";\nimport {\n  targetLineRect,\n  type DropTarget,\n  type RectSource,\n} from \"./drop-targets\";\nimport { canvasContentRect, onScreenOf, overlaySpaceOf } from \"./geometry-dom\";\nimport { insertionMarkOf, type Neighbour } from \"./insertion-line-geometry\";\nimport {\n  useInsertionPreview,\n  type InsertionPreview,\n} from \"./insertion-preview\";\nimport { styleCapable } from \"./spacing-response\";\n\nexport interface InsertionLineProps {\n  /** The page the place is in, as the panel judged it. */\n  readonly document: BlockDocument;\n}\n\n/** What is drawn for the preview, in the chrome's coordinates. */\ntype Drawn =\n  | {\n      readonly kind: \"line\";\n      readonly target: DropTarget;\n      /** The line's start, where its label sits. */\n      readonly start: { readonly x: number; readonly y: number };\n      /** No room above the line on screen, so the label goes below it. */\n      readonly labelBelow: boolean;\n      /** No room right of a row's line on screen, so the label goes left. */\n      readonly labelBefore: boolean;\n      /** The widest the label may be: the room on its side of the line. */\n      readonly labelRoom: number;\n    }\n  | {\n      readonly kind: \"edge\";\n      /** The block beside the place, scrolled into view to show it. */\n      readonly near: Neighbour | undefined;\n      /** The place itself, in the canvas's content coordinates. */\n      readonly place: Rect;\n      /** Which edge of the canvas the label is pinned to. */\n      readonly edge: Edge;\n      readonly left: number;\n      readonly top: number;\n      /** At the top or bottom, too near the right to fit: grows leftwards. */\n      readonly before: boolean;\n      /** The widest the label may be: the room on its side. */\n      readonly room: number;\n    }\n  | { readonly kind: \"empty\"; readonly rect: Rect };\n\n/** An edge of what the canvas shows. */\ntype Edge = \"top\" | \"bottom\" | \"left\" | \"right\";\n\n/** The arrow an edge label points with. */\nconst ARROWS: Readonly<Record<Edge, string>> = {\n  top: \"↑\",\n  bottom: \"↓\",\n  left: \"←\",\n  right: \"→\",\n};\n\n/** How far an edge label keeps from the canvas's edge, in pixels. */\nconst EDGE_GAP = 8;\n\n/** The room a label above its line needs on screen, in pixels. */\nconst LABEL_ROOM = 22;\n\n/**\n * The widest a label is drawn, in pixels: the stylesheet's `max-width` of\n * 24rem on `.nx-insertion-line__label`, the room a label beside a row's line\n * needs on screen.\n */\nconst LABEL_WIDEST = 384;\n\n/**\n * How long an edge label outlasts the panel letting go of its place: long\n * enough for the pointer to cross from the tiles to the label and press it.\n * Pointed at, it stays for as long as the pointer does.\n */\nexport const EDGE_HOLD_MS = 1500;\n\n/**\n * The rectangles of a canvas's blocks, each measured only when asked for, so\n * the place's region is measured and the rest of the page is not.\n *\n * The element that stands for each block is the drag's own answer\n * (`blockElements`), so the preview and a drag measure the same box.\n */\nfunction lazyRects(\n  root: HTMLElement\n): RectSource & { elementOf: (id: string) => Element | undefined } {\n  const elements = blockElements(root);\n  // Each block read once per measure, however often the geometry asks.\n  const measured = new Map<string, Rect | undefined>();\n  return {\n    rectOf: id => {\n      if (!measured.has(id)) {\n        const element = elements.get(id);\n        measured.set(\n          id,\n          element === undefined ? undefined : canvasContentRect(element, root)\n        );\n      }\n      return measured.get(id);\n    },\n    rootRect: () => canvasContentRect(root, root),\n    elementOf: id => elements.get(id),\n  };\n}\n\n/** Which edge of the screen a place lies past, or `undefined` for none. */\nfunction edgePast(drawnAt: Rect, screen: Rect): Edge | undefined {\n  if (drawnAt.y + drawnAt.height < screen.y) return \"top\";\n  if (drawnAt.y > screen.y + screen.height) return \"bottom\";\n  if (drawnAt.x + drawnAt.width < screen.x) return \"left\";\n  if (drawnAt.x > screen.x + screen.width) return \"right\";\n  return undefined;\n}\n\n/** `value` kept between `low` and `high`. */\nfunction within(value: number, low: number, high: number): number {\n  return Math.min(Math.max(value, low), high);\n}\n\n/**\n * The label pinned to the canvas edge for a place off screen, or `undefined`\n * for one on screen. A canvas zoomed past its region can leave a place off\n * to either side as well as above or below. `drawnAt` and `screen` are in\n * the chrome's coordinates.\n */\nfunction edgeLabelFor(\n  near: Neighbour | undefined,\n  place: Rect,\n  drawnAt: Rect,\n  screen: Rect\n): Drawn | undefined {\n  const edge = edgePast(drawnAt, screen);\n  if (edge === undefined) return undefined;\n  const right = screen.x + screen.width - EDGE_GAP;\n  const bottom = screen.y + screen.height - EDGE_GAP;\n  const across = edge === \"top\" || edge === \"bottom\";\n  const sideways = edge === \"left\" ? screen.x + EDGE_GAP : right;\n  const upright = edge === \"top\" ? screen.y + EDGE_GAP : bottom;\n  return {\n    kind: \"edge\",\n    near,\n    place,\n    edge,\n    left: across ? within(drawnAt.x, screen.x + EDGE_GAP, right) : sideways,\n    top: across ? upright : within(drawnAt.y, screen.y + EDGE_GAP, bottom),\n    before: across && goesLeft(drawnAt.x, screen),\n    room: across ? roomFor(drawnAt.x, screen) : screen.width - 2 * EDGE_GAP,\n  };\n}\n\n/**\n * Whether a row line's label goes on its left: only where its widest size\n * does not fit on the right, and the left has more room than the right.\n */\nfunction goesLeft(x: number, screen: Rect): boolean {\n  const right = screen.x + screen.width - x;\n  const left = x - screen.x;\n  return right < LABEL_WIDEST && left > right;\n}\n\n/**\n * The width a label beside `x` may take: the room on the side it goes, less\n * the gap it keeps from the screen's edge, so even a long label keeps its\n * arrow and its first words on screen.\n */\nfunction roomFor(x: number, screen: Rect): number {\n  const side = goesLeft(x, screen) ? x - screen.x : screen.x + screen.width - x;\n  return Math.max(0, side - EDGE_GAP);\n}\n\n/** The preview's drawing, measured from the layer it is drawn in. */\nfunction drawnFor(\n  layer: HTMLElement,\n  document: BlockDocument,\n  at: Parameters<typeof insertionMarkOf>[1]\n): Drawn | null {\n  const space = overlaySpaceOf(layer, CANVAS_ROOT_CLASS);\n  if (space === null) return null;\n  const rects = lazyRects(space.root);\n  const mark = insertionMarkOf(document, at, rects);\n  if (mark === undefined) return null;\n  // The place in the canvas's own coordinates: the line, or the empty\n  // container it would light.\n  const place =\n    mark.kind === \"empty\"\n      ? rects.rectOf(mark.containerId)\n      : targetLineRect(mark.target);\n  if (place === undefined) return null;\n  const drawnAt = space.place(place);\n  const screen = onScreenOf(space);\n  const edge = edgeLabelFor(\n    mark.kind === \"empty\"\n      ? { id: mark.containerId, side: \"inside\" }\n      : mark.near,\n    place,\n    drawnAt,\n    screen\n  );\n  if (edge !== undefined) return edge;\n  if (mark.kind === \"empty\") return { kind: \"empty\", rect: drawnAt };\n  return {\n    kind: \"line\",\n    target: mark.target,\n    // At the start of the part of the line on screen: a zoomed canvas can\n    // show a line whose own start is off to a side, or above.\n    start: {\n      x: within(drawnAt.x, screen.x, screen.x + screen.width),\n      y: within(drawnAt.y, screen.y, screen.y + screen.height),\n    },\n    labelBelow: drawnAt.y - LABEL_ROOM < screen.y,\n    labelBefore: goesLeft(drawnAt.x, screen),\n    labelRoom: roomFor(\n      within(drawnAt.x, screen.x, screen.x + screen.width),\n      screen\n    ),\n  };\n}\n\n/** How a neighbour is scrolled to bring the place at its side into view. */\nconst ALIGN: Readonly<Record<Neighbour[\"side\"], ScrollLogicalPosition>> = {\n  // The place is at the block's end: that end in view, however tall it is.\n  after: \"end\",\n  before: \"start\",\n  inside: \"center\",\n};\n\n/** Room kept past the place when it is scrolled into view, for its label. */\nconst REVEAL_ROOM = 24;\n\n/**\n * How far past the neighbour's side the place lies, plus room for its label,\n * as a CSS `scroll-margin`: the line sits in the middle of the gap after a\n * block, not on its edge. Along the line's own axis only; every side zero for\n * a place inside an empty container, which is centred.\n */\nfunction revealMargin(near: Neighbour, block: Rect, place: Rect): string {\n  // Centred with every side zero, so none of the block's own margins skews it.\n  if (near.side === \"inside\") return \"0px 0px 0px 0px\";\n  const down = place.height === 0;\n  const past =\n    near.side === \"after\"\n      ? down\n        ? place.y - (block.y + block.height)\n        : place.x - (block.x + block.width)\n      : down\n        ? block.y - place.y\n        : block.x - place.x;\n  const margin = `${String(Math.max(0, past) + REVEAL_ROOM)}px`;\n  const sides = [0, 0, 0, 0].map(() => \"0px\");\n  // top, right, bottom, left\n  const at = near.side === \"after\" ? (down ? 2 : 1) : down ? 0 : 3;\n  sides[at] = margin;\n  return sides.join(\" \");\n}\n\n/**\n * Bring the place into view: the side of the block beside it that the place\n * touches, with the place itself past that side as a scroll margin, scrolled\n * into view by the browser, which moves every scroller that clips it, the\n * frame's page and the region around a zoomed frame alike, in both\n * directions. The block's own style is left as it was.\n */\nfunction revealPlace(\n  layer: HTMLElement,\n  near: Neighbour | undefined,\n  place: Rect\n): void {\n  if (near === undefined) return;\n  const space = overlaySpaceOf(layer, CANVAS_ROOT_CLASS);\n  if (space === null) return;\n  const rects = lazyRects(space.root);\n  const element = rects.elementOf(near.id);\n  const block = rects.rectOf(near.id);\n  // Any element with an inline style: a block drawn as an SVG root has one,\n  // and scrolls into view as any element does.\n  if (element === undefined || !styleCapable(element) || block === undefined) {\n    return;\n  }\n  const align = ALIGN[near.side];\n  // The block's inline style exactly as it was, put back whole afterwards:\n  // read side by side, a shorthand through a variable reads empty and a\n  // side's priority can be lost, so only the attribute keeps everything.\n  const kept = element.getAttribute(\"style\");\n  // Side by side, so no side the block has is read through a shorthand.\n  revealMargin(near, block, place)\n    .split(\" \")\n    .forEach((value, index) => {\n      element.style.setProperty(SCROLL_MARGIN_SIDES[index] ?? \"\", value);\n    });\n  element.scrollIntoView({ block: align, inline: align });\n  if (kept === null) element.removeAttribute(\"style\");\n  else element.setAttribute(\"style\", kept);\n}\n\n/** The longhands of `scroll-margin`, which the temporary margin is written to. */\nconst SCROLL_MARGIN_SIDES = [\n  \"scroll-margin-top\",\n  \"scroll-margin-right\",\n  \"scroll-margin-bottom\",\n  \"scroll-margin-left\",\n] as const;\n\n/**\n * The preview to draw: the panel's, or the one an edge label is holding on\n * to after the panel let go, so the pointer can reach the label and press\n * it. Held for {@link EDGE_HOLD_MS}, and for as long as the label is\n * pointed at; let go of when pressed.\n */\nfunction useHeldPreview(\n  preview: InsertionPreview | null,\n  holdsEdge: boolean\n): {\n  shown: InsertionPreview | null;\n  pointed: (inside: boolean) => void;\n  release: () => void;\n} {\n  const [held, setHeld] = React.useState<InsertionPreview | null>(null);\n  const last = React.useRef<InsertionPreview | null>(null);\n  // Read when the panel lets go, not a reason to run again on its own.\n  const edgeShown = React.useRef(holdsEdge);\n  edgeShown.current = holdsEdge;\n  const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n  const stop = React.useCallback(() => {\n    if (timer.current !== null) clearTimeout(timer.current);\n    timer.current = null;\n  }, []);\n  // Whether the edge label is pointed at now: no hold runs out under it.\n  const over = React.useRef(false);\n  const expire = React.useCallback(() => {\n    stop();\n    timer.current = setTimeout(() => setHeld(null), EDGE_HOLD_MS);\n  }, [stop]);\n  React.useEffect(() => {\n    if (preview !== null) {\n      last.current = preview;\n      stop();\n      setHeld(null);\n    } else if (edgeShown.current && last.current !== null) {\n      setHeld(last.current);\n      if (!over.current) expire();\n    }\n  }, [preview, stop, expire]);\n  React.useEffect(() => stop, [stop]);\n  return {\n    shown: preview ?? held,\n    pointed: inside => {\n      over.current = inside;\n      if (inside) stop();\n      else expire();\n    },\n    release: () => {\n      stop();\n      setHeld(null);\n    },\n  };\n}\n\nexport function InsertionLine({\n  document,\n}: InsertionLineProps): React.JSX.Element {\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  // A zoom, or the frame's page arriving, moves the place on screen.\n  const canvasFrame = useCanvasFrame();\n  const [drawn, setDrawn] = React.useState<Drawn | null>(null);\n  const { shown, pointed, release } = useHeldPreview(\n    useInsertionPreview(),\n    drawn?.kind === \"edge\"\n  );\n\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    setDrawn(\n      element === null || shown === null\n        ? null\n        : drawnFor(element, document, shown.at)\n    );\n  }, [document, shown]);\n\n  useIsomorphicLayoutEffect(measure, [measure, canvasFrame]);\n\n  // Kept where the place is as the page scrolls, resizes or reflows, only\n  // while there is a place to keep; again for a frame's new page, whose\n  // scrolls and sizes the old page's listeners never hear.\n  React.useEffect(() => {\n    if (shown === null) return undefined;\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    const stopGeometry = watchCanvasFor(() => layer.current, measure);\n    const stopBand =\n      space === null\n        ? undefined\n        : watchScreenBand(space.root, space.frame, measure);\n    return () => {\n      stopGeometry?.();\n      stopBand?.();\n    };\n  }, [shown, measure, canvasFrame]);\n\n  const words = shown?.words ?? \"\";\n  return (\n    <div\n      ref={layer}\n      className=\"nx-insertion-line\"\n      // The editor's own chrome: a press on the edge label is not a press on\n      // the page, so it keeps the selection.\n      {...{ [OVERLAY_OUTPUT_ATTRIBUTE]: \"\", [CHROME_ATTRIBUTE]: \"\" }}\n    >\n      {drawn?.kind === \"line\" ? (\n        <>\n          <DropIndicator target={drawn.target} />\n          {/* The panel's line says these words for assistive technology. */}\n          <span\n            className=\"nx-insertion-line__label\"\n            data-axis={drawn.target.axis}\n            {...(drawn.labelBelow ? { \"data-below\": \"\" } : {})}\n            {...(drawn.labelBefore ? { \"data-before\": \"\" } : {})}\n            aria-hidden=\"true\"\n            style={{\n              left: drawn.start.x,\n              top: drawn.start.y,\n              maxWidth: drawn.labelRoom,\n            }}\n          >\n            {words}\n          </span>\n        </>\n      ) : null}\n      {drawn?.kind === \"edge\" ? (\n        <button\n          type=\"button\"\n          className=\"nx-insertion-line__edge\"\n          data-edge={drawn.edge}\n          {...(drawn.before ? { \"data-before\": \"\" } : {})}\n          style={{ left: drawn.left, top: drawn.top, maxWidth: drawn.room }}\n          onPointerEnter={() => pointed(true)}\n          onPointerLeave={() => pointed(false)}\n          onClick={() => {\n            if (layer.current !== null) {\n              revealPlace(layer.current, drawn.near, drawn.place);\n            }\n            release();\n          }}\n        >\n          {`${ARROWS[drawn.edge]} ${words}`}\n        </button>\n      ) : null}\n      {drawn?.kind === \"empty\" ? (\n        <div\n          className=\"nx-insertion-line__container\"\n          aria-hidden=\"true\"\n          style={{\n            left: drawn.rect.x,\n            top: drawn.rect.y,\n            width: drawn.rect.width,\n            height: drawn.rect.height,\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n","/**\n * The canvas's second kind of selection: a region of the page's layout, its\n * header or footer, drawn from another document around the page.\n *\n * Held beside the editor's block selection rather than inside it. A region\n * is no node of the page's document, so the block selection's rules (ids in\n * document order, outermost only, pruned by an edit) have nothing to say\n * about it, and every surface reading the block selection (the toolbar, the\n * block menus, the keyboard's Delete and moves) is left with nothing selected\n * while a region is: none of them can act on a region by accident.\n *\n * The two never hold at once. Selecting a region clears the block selection,\n * and a block selected by any route clears the region on that very render,\n * derived rather than synced, so no surface ever sees both.\n *\n * @module region-selection\n */\nimport type { RegionArea } from \"@nextlyhq/blocks-engine\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\n\n/** What the region selection reads of the editor: its block selection. */\nexport interface RegionSelectionEditor {\n  readonly selectedId: string | null;\n  readonly select: (id: null) => void;\n}\n\n/** The selected region, and the ways to change it. */\nexport interface RegionSelection {\n  /**\n   * The region selected, or `null`: always `null` while a block is selected\n   * or while the region is not drawn.\n   */\n  readonly area: RegionArea | null;\n  /** Select a region, clearing the block selection. */\n  readonly select: (area: RegionArea) => void;\n  /** Select no region. */\n  readonly clear: () => void;\n}\n\n/**\n * The region selection for an editor whose canvas draws `areas`.\n *\n * Its verbs keep one identity, reading the newest editor when called, so a\n * canvas or a Layers row holding them is not drawn again on every edit.\n */\nexport function useRegionSelection(\n  editor: RegionSelectionEditor,\n  areas: readonly RegionArea[]\n): RegionSelection {\n  const [held, setHeld] = useState<RegionArea | null>(null);\n  const latest = useRef(editor);\n  latest.current = editor;\n  const { selectedId } = editor;\n  const blockSelected = selectedId !== null;\n  const drawn = held !== null && areas.includes(held);\n  // Dropped for good once a block is selected or the region goes, so neither\n  // clearing that block nor drawing the region again selects it once more.\n  // Asked when the block selection changes, not of it as it stands: the\n  // press selecting a region clears the block selection in the same breath.\n  useEffect(() => {\n    if (selectedId !== null) setHeld(null);\n  }, [selectedId]);\n  useEffect(() => {\n    if (!drawn) setHeld(null);\n  }, [drawn]);\n  const select = useCallback((area: RegionArea) => {\n    latest.current.select(null);\n    setHeld(area);\n  }, []);\n  const clear = useCallback(() => setHeld(null), []);\n  const area = !blockSelected && drawn ? held : null;\n  return useMemo(() => ({ area, select, clear }), [area, select, clear]);\n}\n","\"use client\";\n\n/**\n * The dim over the rest of the canvas while a region of the page's layout is\n * edited in place: everything above and below the region, the page and the\n * other region, under a see-through wash of the editor's well.\n *\n * Drawn in the chrome layer over the canvas, never on the page: the page\n * keeps its own colours and is only covered, so nothing of a site's design is\n * changed to show it is out of reach. (The page itself is also `inert` and\n * hidden from assistive technology while the region is edited, which the\n * canvas does; this is what a pointer meets.)\n *\n * A press on the dim changes nothing on the page and asks the host to pulse\n * Done (`onPress`), the way back.\n *\n * Placed as the canvas's other overlays are: the region's element found by\n * its area, measured in the canvas's content coordinates and placed in the\n * chrome's, again whenever the canvas's geometry moves.\n *\n * @module region-editing-scrim\n * @experimental Settles with editing a header or footer in place.\n */\n\nimport type { RegionArea } from \"@nextlyhq/blocks-engine\";\nimport {\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type JSX,\n  type SyntheticEvent,\n} from \"react\";\n\nimport type { Rect } from \"../geometry\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport { REGION_ATTRIBUTE } from \"./canvas-regions\";\nimport { canvasContentRect, overlaySpaceOf } from \"./geometry-dom\";\n\nexport interface RegionEditingScrimProps {\n  /** The region edited in place, or `undefined` while the page is edited. */\n  area: RegionArea | undefined;\n  /** A press on the dim: the host pulses Done. */\n  onPress: () => void;\n}\n\nexport function RegionEditingScrim({\n  area,\n  onPress,\n}: RegionEditingScrimProps): JSX.Element | null {\n  const layer = useRef<HTMLDivElement | null>(null);\n  const [boxes, setBoxes] = useState<readonly Rect[]>([]);\n  const measure = useCallback(() => {\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null || area === undefined) {\n      setBoxes(current => (current.length === 0 ? current : []));\n      return;\n    }\n    const { root } = space;\n    const region = root.querySelector(`[${REGION_ATTRIBUTE}=\"${area}\"]`);\n    const whole = canvasContentRect(root, root);\n    const next = dimmedAround(\n      whole,\n      region === null ? undefined : canvasContentRect(region, root)\n    ).map(space.place);\n    setBoxes(current => (sameBoxes(current, next) ? current : next));\n  }, [area]);\n\n  useLayoutEffect(measure, [measure]);\n  useEffect(() => {\n    if (area === undefined) return;\n    return watchCanvasFor(() => layer.current, measure);\n  }, [area, measure]);\n\n  if (area === undefined) return null;\n  // Taken here, so the canvas under it never sees the press as a click on\n  // its ground, which would clear the region's selection.\n  const press = (event: SyntheticEvent): void => {\n    event.stopPropagation();\n    event.preventDefault();\n  };\n  return (\n    <div\n      ref={layer}\n      className=\"nx-region-scrim\"\n      // Chrome, so the canvas's hit-testing and deselect leave it alone; and\n      // a wash, which says nothing to assistive technology.\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n      aria-hidden=\"true\"\n    >\n      {boxes.map(box => (\n        <div\n          key={`${String(box.x)}:${String(box.y)}`}\n          className=\"nx-region-scrim__dim\"\n          style={{\n            left: box.x,\n            top: box.y,\n            width: box.width,\n            height: box.height,\n          }}\n          onPointerDown={press}\n          onClick={event => {\n            press(event);\n            onPress();\n          }}\n        />\n      ))}\n    </div>\n  );\n}\n\n/**\n * The parts of `whole` to dim around `region`: above it and below it, the\n * full width, each left out where it has no height. Without the region\n * drawn, the whole canvas, so nothing of the page is ever left in reach.\n */\nexport function dimmedAround(whole: Rect, region: Rect | undefined): Rect[] {\n  if (region === undefined) return [whole];\n  const top = Math.max(region.y, whole.y);\n  const bottom = Math.min(region.y + region.height, whole.y + whole.height);\n  return [\n    { x: whole.x, y: whole.y, width: whole.width, height: top - whole.y },\n    {\n      x: whole.x,\n      y: bottom,\n      width: whole.width,\n      height: whole.y + whole.height - bottom,\n    },\n  ].filter(box => box.height > 0);\n}\n\n/** Whether two measures draw the same boxes. */\nfunction sameBoxes(before: readonly Rect[], after: readonly Rect[]): boolean {\n  return (\n    before.length === after.length &&\n    before.every((box, index) => {\n      const other = after[index];\n      return (\n        other !== undefined &&\n        box.x === other.x &&\n        box.y === other.y &&\n        box.width === other.width &&\n        box.height === other.height\n      );\n    })\n  );\n}\n","\"use client\";\n\n/**\n * A block that asks for a choice when it is first added, and the editor step\n * that holds \"this block was just added\" while the canvas draws its chooser.\n *\n * The insert places the block at once, so the page is never left waiting on\n * the answer and one undo takes the block away. What the builder holds is\n * which node was just added, in editor state only: nothing is written to the\n * document, so a reload, another editor or the published page never sees it.\n *\n * It holds only while the author is still where the insert left them: the\n * page is the one the insert made and the new block is the one selected. Any\n * other edit, an undo or a redo, a step recorded outside the page, or a\n * selection elsewhere (Escape, a click on another block) ends it, and so do\n * the chooser's own Skip and pick. Because every way the history moves passes\n * through here, a pick knows the insert is still the newest step, and joins\n * it: the insert is taken back and the block placed again as chosen, as ONE\n * step, so one undo still removes the whole block.\n *\n * Which blocks ask stays inside the builder for the core blocks: opening it\n * to other blocks is a later decision.\n *\n * @module first-add\n */\nimport {\n  COLLECTION_LIST_TYPE,\n  findNode,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport { applyOps, type BuilderOp, type OpPosition } from \"../op-vocabulary\";\n\n/** The choosers a block can ask for when it is first added. */\nexport type FirstAddChooser = \"columns-layout\" | \"collection-source\";\n\n/**\n * The core blocks that ask for a choice when they are first added, by type,\n * and the chooser each asks for. Kept here, not on the block's definition:\n * the step is the builder's own until it is opened to other blocks.\n */\nconst FIRST_ADD_CHOOSERS: ReadonlyMap<string, FirstAddChooser> = new Map([\n  [\"core/columns\", \"columns-layout\"],\n  // A Collection list asks which entries it shows, then how they start out.\n  [COLLECTION_LIST_TYPE, \"collection-source\"],\n]);\n\n/** The chooser a block of this type asks for when first added, if any. */\nexport function firstAddChooserOf(type: string): FirstAddChooser | undefined {\n  return FIRST_ADD_CHOOSERS.get(type);\n}\n\n/** A block just added that asks for a choice, while it still does. */\nexport interface FirstAdd {\n  /** The block just added. */\n  readonly nodeId: string;\n  /** The chooser the canvas draws in place of its body. */\n  readonly chooser: FirstAddChooser;\n  /**\n   * Make the author's choice: `ops` on the block as it was added, joined to\n   * the insert as ONE step. Answers whether they landed. Ends the step.\n   */\n  readonly choose: (ops: readonly BuilderOp[]) => boolean;\n  /** Keep the block as it was added, and end the step. */\n  readonly skip: () => void;\n}\n\n/** What the insert left: where it placed the block, and the page it made. */\ninterface Added {\n  readonly nodeId: string;\n  readonly chooser: FirstAddChooser;\n  readonly at: OpPosition;\n  readonly document: EditorState[\"document\"];\n}\n\n/** The parts of the editor this step wraps and reads. */\ntype Host = Pick<\n  EditorState,\n  | \"document\"\n  | \"selectedId\"\n  | \"select\"\n  | \"apply\"\n  | \"applyAll\"\n  | \"undo\"\n  | \"redo\"\n  | \"recordStep\"\n  | \"limits\"\n>;\n\n/** What an applied insert leaves to choose, if its block asks for a choice. */\nfunction addedBy(\n  op: BuilderOp,\n  document: EditorState[\"document\"]\n): Added | undefined {\n  if (op.kind !== \"insert\") return undefined;\n  const chooser = firstAddChooserOf(op.node.type);\n  if (chooser === undefined) return undefined;\n  return { nodeId: op.node.id, chooser, at: op.at, document };\n}\n\n/** The block as `ops` leave it on the page the insert made, if they apply. */\nfunction laidOut(\n  added: Added,\n  ops: readonly BuilderOp[],\n  limits: Host[\"limits\"]\n): BlockNode | undefined {\n  try {\n    const after = applyOps(added.document, ops, limits).document;\n    return findNode(after.nodes, added.nodeId);\n  } catch {\n    // Refused by the op layer: the choice is made as a step of its own below,\n    // where the editor says why.\n    return undefined;\n  }\n}\n\n/**\n * The editor with the first-add step: the history's ways in wrapped so each\n * one ends the step (and an insert of a block that asks starts it), and\n * `firstAdd` while it holds.\n */\nexport function useFirstAdd<T extends Host>(\n  host: T\n): T & { firstAdd?: FirstAdd } {\n  const [added, setAdded] = useState<Added | undefined>(undefined);\n  // Read by the wrappers in the same tick a change is made: an insert and the\n  // select after it run before the next render.\n  const current = useRef<Added | undefined>(undefined);\n  const put = useCallback((next: Added | undefined) => {\n    current.current = next;\n    setAdded(next);\n  }, []);\n\n  const { apply: hostApply, applyAll: hostApplyAll, undo: hostUndo } = host;\n  const { redo: hostRedo, recordStep: hostRecordStep } = host;\n  const { select, limits } = host;\n\n  const apply = useCallback<Host[\"apply\"]>(\n    op => {\n      const result = hostApply(op);\n      // A refused op changed nothing, so the step stands as it was.\n      if (result !== null) put(addedBy(op, result));\n      return result;\n    },\n    [hostApply, put]\n  );\n  const applyAll = useCallback<Host[\"applyAll\"]>(\n    ops => {\n      const result = hostApplyAll(ops);\n      // As for one op: a refused group changed nothing, so the step stands.\n      if (result !== null) put(undefined);\n      return result;\n    },\n    [hostApplyAll, put]\n  );\n  const undo = useCallback<Host[\"undo\"]>(() => {\n    put(undefined);\n    return hostUndo();\n  }, [hostUndo, put]);\n  const redo = useCallback<Host[\"redo\"]>(() => {\n    put(undefined);\n    return hostRedo();\n  }, [hostRedo, put]);\n  const recordStep = useCallback<Host[\"recordStep\"]>(\n    step => {\n      put(undefined);\n      return hostRecordStep(step);\n    },\n    [hostRecordStep, put]\n  );\n\n  const skip = useCallback(() => put(undefined), [put]);\n  const choose = useCallback(\n    (ops: readonly BuilderOp[]): boolean => {\n      const now = current.current;\n      put(undefined);\n      if (now === undefined) return false;\n      const node = laidOut(now, ops, limits);\n      // The insert is the newest step while this holds (every other way the\n      // history moves ended it), so taking it back and placing the block as\n      // chosen is one step in its place.\n      if (node !== undefined && hostUndo() === true) {\n        const placed = hostApplyAll([{ kind: \"insert\", node, at: now.at }]);\n        if (placed !== null) {\n          select(now.nodeId);\n          return true;\n        }\n        // Not placed as chosen: the block comes back as it was added.\n        void hostRedo();\n        select(now.nodeId);\n      }\n      return hostApplyAll(ops) !== null;\n    },\n    [hostApplyAll, hostRedo, hostUndo, limits, put, select]\n  );\n\n  // Holds while the page is the one the insert made and its block is selected.\n  const holding =\n    added !== undefined &&\n    host.document === added.document &&\n    host.selectedId === added.nodeId\n      ? added\n      : undefined;\n  const holds = holding !== undefined;\n  // Once it stops holding it is over: selecting the block again later does\n  // not bring the chooser back.\n  useEffect(() => {\n    if (added !== undefined && !holds) put(undefined);\n  }, [added, holds, put]);\n\n  const firstAdd = useMemo<FirstAdd | undefined>(\n    () =>\n      holding === undefined\n        ? undefined\n        : { nodeId: holding.nodeId, chooser: holding.chooser, choose, skip },\n    [holding, choose, skip]\n  );\n\n  return useMemo(\n    () => ({\n      ...host,\n      apply,\n      applyAll,\n      undo,\n      redo,\n      recordStep,\n      ...(firstAdd === undefined ? {} : { firstAdd }),\n    }),\n    [host, apply, applyAll, undo, redo, recordStep, firstAdd]\n  );\n}\n","\"use client\";\n\n/**\n * The editor's undo history: the two stacks of steps, how deep they go, and\n * a step recorded from outside the document.\n *\n * Kept apart from `editor-state` so the document's state and the history it\n * replays read on their own. Nothing here knows the document: an entry is the\n * op layer's inverses, or a step whose halves say whether they took effect.\n *\n * @module editor-history\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\nimport type { BuilderOp } from \"./op-vocabulary\";\nimport {\n  joinsTyping,\n  typingEpoch,\n  typingRunNow,\n  type TypingStep,\n} from \"./typing-run\";\n\n/** How deep the undo history goes before the oldest step is dropped. */\nexport const MAX_HISTORY = 100;\n\n/**\n * A change made outside the document that the editor's history takes back and\n * puts forward, such as a write to the site's shared styles.\n *\n * Each half resolves whether it took effect. A half that did not (a refused\n * or failed write) leaves the change where it was, so the step is dropped\n * rather than kept as an undo that never clears.\n */\nexport interface HistoryStep {\n  /** Takes the change back. */\n  readonly undo: () => Promise<boolean>;\n  /** Makes the change again. */\n  readonly redo: () => Promise<boolean>;\n}\n\n/**\n * One entry of the history: a group of the op layer's inverses, or a step\n * recorded from outside the document. Both stacks hold the entry to replay\n * next, so a step on the redo stack is the recorded one with its halves\n * swapped.\n */\nexport type HistoryEntry =\n  | { readonly kind: \"ops\"; readonly ops: readonly BuilderOp[] }\n  | {\n      readonly kind: \"step\";\n      readonly step: HistoryStep;\n      /** The step as recorded, kept as it moves between the stacks. */\n      readonly origin: HistoryStep;\n    };\n\n/** The step that replays `step` the other way, for the opposite stack. */\nfunction reversed(step: HistoryStep): HistoryStep {\n  return { undo: step.redo, redo: step.undo };\n}\n\n/** How many entries change the document, which is what a save point counts. */\nfunction documentEntries(stack: readonly HistoryEntry[]): number {\n  return stack.filter(entry => entry.kind === \"ops\").length;\n}\n\n/**\n * The undo and redo stacks, and the depths a render reads from them.\n *\n * READONLY groups. A recorded inverse describes the document as it stood when\n * its op ran, so nothing may append to or reorder one after the fact — the\n * history would then describe an edit that never happened. `applyOps` returns\n * them already in undo order and already frozen to the type.\n */\nexport function useHistoryStacks(): {\n  depths: { undo: number; redo: number; document: number };\n  push: (\n    entry: HistoryEntry,\n    into: \"undo\" | \"redo\" | \"new\"\n  ) => HistoryEntry | undefined;\n  pop: (from: \"undo\" | \"redo\") => HistoryEntry | undefined;\n  remove: (entry: HistoryEntry) => void;\n  /**\n   * Take a run of typing's step back out, as if the run had never been\n   * typed: its entry comes off the undo stack, and the redo branch and the\n   * oldest step its first write ended come back. Answers the entry, whose\n   * ops take the document back, or nothing when `run` is not the newest step.\n   */\n  withdrawTyping: (run: object) => HistoryEntry | undefined;\n  /**\n   * Record a step from outside the document, answering the function that\n   * withdraws it again: a no-op once the history has been cleared since, so\n   * a change refused after its session ended cannot reach the next one.\n   */\n  record: (step: HistoryStep) => () => void;\n  /** A replay of the step took effect; the branch it ended is gone. */\n  settle: (origin: HistoryStep) => void;\n  /** Forget everything: both stacks, and what fell off the old end. */\n  clear: () => void;\n} {\n  const undoStack = useRef<HistoryEntry[]>([]);\n  const redoStack = useRef<HistoryEntry[]>([]);\n  // Mirrors the stack lengths so the flags below are STATE and re-render when\n  // they change. Reading `undoStack.current.length` directly would leave an\n  // undo button disabled after the first edit, because a ref mutation does not\n  // schedule a render.\n  const [depths, setDepths] = useState({ undo: 0, redo: 0, document: 0 });\n  /*\n   * Document edits dropped off the old end. The save point measures the\n   * document's position in its history, and that position does not move\n   * because the history forgets how it got there: counted in, a page saved\n   * before a run of style changes stays saved once its edit falls off.\n   */\n  const forgotten = useRef(0);\n  const sync = useCallback(() => {\n    setDepths({\n      undo: undoStack.current.length,\n      redo: redoStack.current.length,\n      document: documentEntries(undoStack.current) + forgotten.current,\n    });\n  }, []);\n  /*\n   * The redo branch a run of recorded steps ended, with those steps and the\n   * entry below the first, so that withdrawing every one of them before\n   * anything else follows gives the branch back: changes that never took\n   * effect must not cost the author their redo either. Kept while the steps\n   * are recorded one after another, and while any of them only moves between\n   * the stacks unanswered, since each change may still be refused; dropped\n   * once a replay of one takes effect or any other entry is pushed.\n   */\n  const endedBranch = useRef<StepRun | null>(null);\n  // The run of typing the newest step was pushed for (`typing-run.ts`), with\n  // what its first write ended, kept so cancelling the run gives it back.\n  const typing = useRef<TypingHeld | null>(null);\n  const push = useCallback(\n    (entry: HistoryEntry, into: \"undo\" | \"redo\" | \"new\") => {\n      // A later write of a run of typing keeps the run's one step, whose\n      // inverse puts back what was there before the author started.\n      const run = into === \"new\" ? typingRunNow() : null;\n      if (joinsTyping(typing.current, undoStack.current.at(-1), run)) {\n        typing.current = widenedTyping(\n          typing.current,\n          entry,\n          undoStack.current\n        );\n        return;\n      }\n      // Read before this push changes them; the redo stack is replaced, never\n      // emptied in place, so the array kept here stays as it was.\n      const redoBefore = redoStack.current;\n      const endedBefore = endedBranch.current;\n      let dropped: HistoryEntry | undefined;\n      endedBranch.current = runAfterPush(\n        endedBranch.current,\n        entry,\n        into,\n        undoStack.current.at(-1),\n        redoStack.current\n      );\n      if (into === \"redo\") {\n        redoStack.current.push(entry);\n      } else {\n        undoStack.current.push(entry);\n      }\n      if (into === \"new\") {\n        // Bounded from the OLD end. Dropping the newest would make the most\n        // recent edit unrepeatable, which is the one an author is most likely\n        // to want back.\n        if (undoStack.current.length > MAX_HISTORY) {\n          dropped = undoStack.current.shift();\n          if (dropped?.kind === \"ops\") forgotten.current += 1;\n        }\n        // A new edit invalidates the redo branch: those inverses were computed\n        // against a document that no longer exists, so replaying one would\n        // apply an edit derived from a tree that has since changed.\n        redoStack.current = [];\n      }\n      typing.current = beganTyping(run, entry, {\n        redo: redoBefore,\n        ended: endedBefore,\n        dropped,\n      });\n      sync();\n      return dropped;\n    },\n    [sync]\n  );\n  const pop = useCallback(\n    (from: \"undo\" | \"redo\") => {\n      const entry = (from === \"undo\" ? undoStack : redoStack).current.pop();\n      sync();\n      return entry;\n    },\n    [sync]\n  );\n  const remove = useCallback(\n    (entry: HistoryEntry) => {\n      undoStack.current = undoStack.current.filter(held => held !== entry);\n      redoStack.current = redoStack.current.filter(held => held !== entry);\n      sync();\n    },\n    [sync]\n  );\n  /*\n   * Take a recorded step back out, wherever it sits: undone, it is on the\n   * redo stack under another entry. The entry its recording pushed off a full\n   * history comes back to the old end, since a change that never took effect\n   * must not cost the oldest edit.\n   */\n  const withdraw = useCallback(\n    (origin: HistoryStep, dropped: HistoryEntry | undefined) => {\n      const kept = (held: HistoryEntry) =>\n        held.kind !== \"step\" || held.origin !== origin;\n      // With the last step of the run gone, the history as it was before it\n      // began (nothing made since, and nothing else undone): the redo branch\n      // the run ended comes back with that withdrawal. While others of the\n      // run remain, one of them may yet take effect, so the branch waits.\n      const ended = endedBranch.current;\n      ended?.steps.delete(origin);\n      const last = ended !== null && ended.steps.size === 0;\n      if (last) endedBranch.current = null;\n      undoStack.current = undoStack.current.filter(kept);\n      const redo = redoStack.current.filter(kept);\n      const restore =\n        last && undoStack.current.at(-1) === ended.below && redo.length === 0\n          ? ended.branch\n          : [];\n      redoStack.current = [...redo, ...restore];\n      forgotten.current -= giveBack(undoStack.current, dropped);\n      sync();\n    },\n    [sync]\n  );\n  /*\n   * A replay of a step of the run took effect: its change and its undo are\n   * both real, so the branch the run ended is gone for good.\n   */\n  const settle = useCallback((origin: HistoryStep) => {\n    if (endedBranch.current?.steps.has(origin) === true) {\n      endedBranch.current = null;\n    }\n  }, []);\n  /*\n   * A history started again, for a new session of the editor: nothing to undo\n   * or redo, no run of steps or of typing to join, and no edit forgotten, so\n   * the save point counts from the session's own start.\n   */\n  /*\n   * Which history a recorded step belongs to: counted up by every clear, so a\n   * withdrawal from before it finds its history gone rather than putting the\n   * entry it once pushed off back into a new one.\n   */\n  const generation = useRef(0);\n  const record = useCallback(\n    (step: HistoryStep) => {\n      // Bounded and branch-ending exactly as a fresh document edit is.\n      const dropped = push({ kind: \"step\", step, origin: step }, \"new\");\n      const recordedIn = generation.current;\n      return () => {\n        if (generation.current === recordedIn) withdraw(step, dropped);\n      };\n    },\n    [push, withdraw]\n  );\n  // The two that reset the stacks without replaying anything, made together:\n  // each reads only the refs and `sync`, so both keep one identity.\n  const { clear, withdrawTyping } = useMemo(\n    () => ({\n      clear: () => {\n        generation.current += 1;\n        undoStack.current = [];\n        redoStack.current = [];\n        forgotten.current = 0;\n        endedBranch.current = null;\n        typing.current = null;\n        sync();\n      },\n      withdrawTyping: (run: object): HistoryEntry | undefined =>\n        takeTypingBack(\n          { undoStack, redoStack, endedBranch, forgotten, typing },\n          run,\n          sync\n        ),\n    }),\n    [sync]\n  );\n  return { depths, push, pop, remove, withdrawTyping, record, settle, clear };\n}\n\n/** The run of typing a step was pushed for, or nothing for an edit that is not typing. */\nfunction beganTyping(\n  run: object | null,\n  entry: HistoryEntry,\n  before: TypingBefore\n): TypingHeld | null {\n  return run === null ? null : { run, entry, before, epoch: typingEpoch() };\n}\n\n/**\n * The run's step after a later write of it. That write may change what the\n * first did not, as a recognised embed link sets a style, so its inverse\n * joins the step's for the fields the step does not already put back: undo\n * then restores every property the run touched, each to its value from before\n * the run, without replaying every keystroke. A write of fields already\n * covered leaves the step as it is, so a long edit is still one small step.\n * The step stays the newest entry, replaced in place.\n */\nfunction widenedTyping(\n  held: TypingHeld | null,\n  entry: HistoryEntry,\n  undo: HistoryEntry[]\n): TypingHeld | null {\n  if (held === null || entry.kind !== \"ops\" || held.entry.kind !== \"ops\") {\n    return held;\n  }\n  const ops = joinedInverse(held.entry.ops, entry.ops);\n  if (ops === held.entry.ops) return held;\n  const joined: HistoryEntry = { kind: \"ops\", ops };\n  undo[undo.length - 1] = joined;\n  return { ...held, entry: joined };\n}\n\n/**\n * The step's inverse with a later one's uncovered fields joined in, or the\n * step's own when there are none. An update replaces each field it names\n * whole, set or removed (`unset`), so a field the step's inverse names is put\n * back by it, to its earlier value. A field for a node the step already\n * updates joins THAT update rather than standing alone: a later write can name\n * a field it leaves as it was (a link's look that stays the same), and an\n * inverse of only that field would change nothing, which the op layer refuses,\n * failing the whole undo. Any op but an update is kept as it is, ahead of the\n * step's, since what it restores is not a field of one node.\n */\nfunction joinedInverse(\n  step: readonly BuilderOp[],\n  later: readonly BuilderOp[]\n): readonly BuilderOp[] {\n  const covered = coveredFields(step);\n  const merged = [...step];\n  const ahead: BuilderOp[] = [];\n  for (const op of later) {\n    const part = op.kind === \"update\" ? uncoveredPart(op, covered) : op;\n    if (part !== null) placePart(part, merged, ahead);\n  }\n  const changed = ahead.length > 0 || merged.some((op, at) => op !== step[at]);\n  return changed ? [...ahead, ...merged] : step;\n}\n\n/**\n * Put a later inverse's part in the step: into the step's update of the same\n * node where there is one, otherwise ahead of the step's own ops.\n */\nfunction placePart(\n  part: BuilderOp,\n  merged: BuilderOp[],\n  ahead: BuilderOp[]\n): void {\n  if (part.kind === \"update\") {\n    const at = merged.findIndex(\n      held => held.kind === \"update\" && held.id === part.id\n    );\n    const into = merged[at];\n    if (into?.kind === \"update\") {\n      merged[at] = mergedUpdate(into, part);\n      return;\n    }\n  }\n  ahead.push(part);\n}\n\n/** Two updates of one node, over different fields, as one. */\nfunction mergedUpdate(\n  held: Extract<BuilderOp, { kind: \"update\" }>,\n  part: Extract<BuilderOp, { kind: \"update\" }>\n): BuilderOp {\n  const unset = [...(held.unset ?? []), ...(part.unset ?? [])];\n  return {\n    kind: \"update\",\n    id: held.id,\n    patch: { ...held.patch, ...part.patch },\n    ...(unset.length > 0 ? { unset } : {}),\n  };\n}\n\n/** Each node's fields the step's updates already put back. */\nfunction coveredFields(\n  step: readonly BuilderOp[]\n): ReadonlyMap<string, ReadonlySet<string>> {\n  const covered = new Map<string, Set<string>>();\n  for (const op of step) {\n    if (op.kind !== \"update\") continue;\n    const fields = covered.get(op.id) ?? new Set<string>();\n    for (const field of updatedFields(op)) fields.add(field);\n    covered.set(op.id, fields);\n  }\n  return covered;\n}\n\n/** An update cut to the fields not covered yet, or `null` when none are. */\nfunction uncoveredPart(\n  op: Extract<BuilderOp, { kind: \"update\" }>,\n  covered: ReadonlyMap<string, ReadonlySet<string>>\n): Extract<BuilderOp, { kind: \"update\" }> | null {\n  const fields = covered.get(op.id);\n  const fresh = (field: string) => fields?.has(field) !== true;\n  const patch = Object.fromEntries(\n    Object.entries(op.patch).filter(([field]) => fresh(field))\n  );\n  const unset = (op.unset ?? []).filter(fresh);\n  if (Object.keys(patch).length === 0 && unset.length === 0) return null;\n  return {\n    kind: \"update\",\n    id: op.id,\n    patch,\n    ...(unset.length > 0 ? { unset } : {}),\n  };\n}\n\n/** The fields an update writes or removes. */\nfunction updatedFields(\n  op: Extract<BuilderOp, { kind: \"update\" }>\n): readonly string[] {\n  return [...Object.keys(op.patch), ...(op.unset ?? [])];\n}\n\n/** The history's stacks and runs, as `takeTypingBack` reads and resets them. */\ninterface HistoryRefs {\n  readonly undoStack: { current: HistoryEntry[] };\n  readonly redoStack: { current: HistoryEntry[] };\n  readonly endedBranch: { current: StepRun | null };\n  readonly forgotten: { current: number };\n  readonly typing: { current: TypingHeld | null };\n}\n\n/**\n * Take a run of typing's step back out, as `withdrawTyping` describes: only\n * while its step is the newest, so nothing else has been pushed and the step\n * has not been undone. Once either has happened, the run is over and its step\n * is ordinary history, and nothing changes. `sync` runs only on a change.\n */\nfunction takeTypingBack(\n  refs: HistoryRefs,\n  run: object,\n  sync: () => void\n): HistoryEntry | undefined {\n  const last = refs.typing.current;\n  // A run a save ended (`endTypingRuns`) is over: what it wrote was saved.\n  if (last === null || last.run !== run || last.epoch !== typingEpoch()) {\n    return undefined;\n  }\n  const { before } = last;\n  if (refs.undoStack.current.at(-1) !== last.entry) return undefined;\n  refs.undoStack.current.pop();\n  refs.redoStack.current = before.redo;\n  refs.endedBranch.current = before.ended;\n  refs.forgotten.current -= giveBack(refs.undoStack.current, before.dropped);\n  refs.typing.current = null;\n  sync();\n  return last.entry;\n}\n\n/**\n * Put back at the old end the entry a full history dropped for a change that\n * is now withdrawn, where there is room. Answers how many document edits came\n * back, which the count of forgotten edits loses.\n */\nfunction giveBack(\n  undo: HistoryEntry[],\n  dropped: HistoryEntry | undefined\n): number {\n  if (dropped === undefined || undo.length >= MAX_HISTORY) return 0;\n  undo.unshift(dropped);\n  return dropped.kind === \"ops\" ? 1 : 0;\n}\n\n/** A run of typing's step, and what its first write ended. */\ninterface TypingHeld extends TypingStep<HistoryEntry> {\n  readonly before: TypingBefore;\n}\n\n/** What a run of typing's first write ended, given back if it is cancelled. */\ninterface TypingBefore {\n  readonly redo: HistoryEntry[];\n  readonly ended: StepRun | null;\n  readonly dropped: HistoryEntry | undefined;\n}\n\n/** A run of recorded steps, the redo branch it ended, and what lay below it. */\ninterface StepRun {\n  steps: Set<HistoryStep>;\n  below: HistoryEntry | undefined;\n  branch: HistoryEntry[];\n}\n\n/**\n * The run of recorded steps once `entry` is pushed: a new step joins the run\n * or starts one (keeping the branch it ends and what lay below), a step of\n * the run moving between the stacks keeps it, and anything else ends it.\n */\nfunction runAfterPush(\n  run: StepRun | null,\n  entry: HistoryEntry,\n  into: \"undo\" | \"redo\" | \"new\",\n  below: HistoryEntry | undefined,\n  branch: HistoryEntry[]\n): StepRun | null {\n  if (entry.kind !== \"step\") return null;\n  if (into !== \"new\") return run?.steps.has(entry.origin) === true ? run : null;\n  if (run === null) return { steps: new Set([entry.origin]), below, branch };\n  run.steps.add(entry.origin);\n  return run;\n}\n\n/**\n * Replay a recorded step and move it to the other stack at once, so a second\n * press reaches the entry before it rather than waiting on a write. Dropped\n * again if the replay did not take effect, for the reason a refused inverse is\n * not pushed back.\n */\nexport function replayStep(\n  { step, origin }: { step: HistoryStep; origin: HistoryStep },\n  into: \"undo\" | \"redo\",\n  push: (entry: HistoryEntry, into: \"undo\" | \"redo\") => void,\n  remove: (entry: HistoryEntry) => void,\n  settle: (origin: HistoryStep) => void\n): Promise<boolean> {\n  const moved: HistoryEntry = { kind: \"step\", step: reversed(step), origin };\n  push(moved, into);\n  return step.undo().then(\n    took => {\n      if (took) settle(origin);\n      else remove(moved);\n      return took;\n    },\n    () => {\n      remove(moved);\n      return false;\n    }\n  );\n}\n\n/**\n * Run `restart` in the render that sees `session` change, never on the\n * first: for each piece of editor state that belongs to one editing session\n * (its document, its history, what the author asked of it), so a new session\n * starts with none of the old one's. Its updates are the calling component's\n * own state, so React drops that render and renders again at once with them.\n * The session is held through a function, so one named by a function is\n * stored as it is rather than called.\n */\nexport function useRestartOn(session: unknown, restart: () => void): void {\n  const [held, setHeld] = useState(() => session);\n  if (Object.is(held, session)) return;\n  setHeld(() => session);\n  restart();\n}\n","/**\n * What the author asked the inspector to take them to, held beside the\n * editor's document: a list's sort row, from its canvas note, and a block's\n * setting, from a page check's item. Each ask selects the block first, so the\n * inspector answering it is the block's own, and is counted, so a second\n * press on the same thing asks again. Editor state only: never stored, and\n * no step of the history.\n *\n * @module editor-asks\n */\nimport { useCallback, useMemo, useState } from \"react\";\n\nimport { useRestartOn } from \"./editor-history\";\nimport type { SettingTab } from \"./inspector/settings-index\";\n\n/** A setting of a block's panel: its tab, and its id in the settings index. */\nexport interface AskedSetting {\n  readonly tab: SettingTab;\n  readonly id: string;\n}\n\n/** One ask to be taken to a block's setting. */\nexport interface SettingAsked {\n  /** The block's id. */\n  readonly id: string;\n  readonly tab: SettingTab;\n  /** The setting's id, as the settings index names it. */\n  readonly setting: string;\n  readonly seq: number;\n}\n\n/** The asks as the editor's state carries them; an ask not made is absent. */\nexport interface EditorAsks {\n  sortFieldAsked?: { readonly id: string; readonly seq: number };\n  askSortField: (id: string) => void;\n  settingAsked?: SettingAsked;\n  askSetting: (id: string, setting: AskedSetting) => void;\n}\n\n/** The asks, and the way to make each, selecting through `select`. */\nexport function useEditorAsks(\n  select: (id: string) => void,\n  session?: unknown\n): EditorAsks {\n  const [sortFieldAsked, setSortFieldAsked] =\n    useState<EditorAsks[\"sortFieldAsked\"]>(undefined);\n  const [settingAsked, setSettingAsked] = useState<SettingAsked | undefined>(\n    undefined\n  );\n  // An ask is about a block of the session's document: a new session (an\n  // editor state started again on another document) has none.\n  useRestartOn(session, () => {\n    setSortFieldAsked(undefined);\n    setSettingAsked(undefined);\n  });\n  const askSortField = useCallback(\n    (id: string) => {\n      select(id);\n      setSortFieldAsked(current => ({ id, seq: (current?.seq ?? 0) + 1 }));\n    },\n    [select]\n  );\n  const askSetting = useCallback(\n    (id: string, setting: AskedSetting) => {\n      select(id);\n      setSettingAsked(current => ({\n        id,\n        tab: setting.tab,\n        setting: setting.id,\n        seq: (current?.seq ?? 0) + 1,\n      }));\n    },\n    [select]\n  );\n  return useMemo(\n    () => ({\n      ...(sortFieldAsked === undefined ? {} : { sortFieldAsked }),\n      askSortField,\n      ...(settingAsked === undefined ? {} : { settingAsked }),\n      askSetting,\n    }),\n    [sortFieldAsked, askSortField, settingAsked, askSetting]\n  );\n}\n","/**\n * The editor's lock answers, kept per document version and per edit.\n *\n * Whether the locks allow an edit is answered by trying the edit on a copy of\n * the page, which costs a walk of the whole page. The toolbar's menu, the\n * block's context menu, the Layers row menu and a keystroke can each ask the\n * same question of the same page, so the answer is kept against the document\n * it was asked of and the ops it was asked about: one version is tried at most\n * once per edit, whichever surface asks first.\n *\n * Kept by the document object itself. Documents are immutable values in the\n * editor, so an edit makes a new one and the answers for the old one are never\n * read again; they go with it when it is garbage collected. Anything else the\n * answer reads (the saved page, the lock sources, the component definitions)\n * is handed in as `scope`, and a different scope starts afresh.\n *\n * @module kept-lock-answers\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\n\nimport type { LockRefusalFacts } from \"./lock-refusal\";\nimport type { BuilderOp } from \"./op-vocabulary\";\n\n/** One answer kept: `undefined` facts are kept too, as \"no lock refuses it\". */\ninterface Kept {\n  readonly facts: LockRefusalFacts | undefined;\n}\n\n/** The lock answers for one editor, kept until what they read changes. */\nexport interface KeptLockAnswers {\n  /**\n   * The answer for `ops` on `document`, worked out by `work` the first time it\n   * is asked under this `scope`, and read back after that.\n   */\n  answer(\n    document: BlockDocument,\n    ops: readonly BuilderOp[],\n    scope: readonly unknown[],\n    work: () => LockRefusalFacts | undefined\n  ): LockRefusalFacts | undefined;\n}\n\n/** An empty set of kept answers. */\nexport function keptLockAnswers(): KeptLockAnswers {\n  let byDocument = new WeakMap<BlockDocument, Map<string, Kept>>();\n  let keptScope: readonly unknown[] = [];\n  return {\n    answer(document, ops, scope, work) {\n      if (!sameScope(keptScope, scope)) {\n        byDocument = new WeakMap();\n        keptScope = [...scope];\n      }\n      let answers = byDocument.get(document);\n      if (answers === undefined) {\n        answers = new Map();\n        byDocument.set(document, answers);\n      }\n      // The ops as written: two asks about the same edit spell it the same.\n      const key = JSON.stringify(ops);\n      const kept = answers.get(key);\n      if (kept !== undefined) return kept.facts;\n      const facts = work();\n      answers.set(key, { facts });\n      return facts;\n    },\n  };\n}\n\n/** Whether two scopes hold the same values, compared by identity. */\nfunction sameScope(a: readonly unknown[], b: readonly unknown[]): boolean {\n  return a.length === b.length && a.every((value, i) => value === b[i]);\n}\n","/**\n * What the editor's lock questions are judged by: the host's block\n * definitions and nesting rules, or the live registry's where the host gives\n * none.\n *\n * One reading for the store's apply, its lock question and a surface that\n * answers a lock question from the structure alone (the Add panel), so the\n * three cannot judge one edit by two sets of definitions.\n *\n * @module lock-sources\n */\n\nimport {\n  registryBlockSource,\n  registryNestingSource,\n  type BlockDocument,\n  type DocumentLimits,\n  type LockSources,\n  type NestingSource,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\nimport { useMemo } from \"react\";\n\n/** The lock sources a host hands the store, if any. */\nexport type HostLocks =\n  | Pick<LockSources, \"definitions\" | \"nesting\">\n  | undefined;\n\n/**\n * The definitions lock questions are judged by: the host's own, or the live\n * registry. Held per source, so the store keeps its identity across renders.\n */\nexport function useLockDefinitions(locks: HostLocks): SlotDefaultSource {\n  const host = locks?.definitions;\n  return useMemo(() => host ?? registryBlockSource(), [host]);\n}\n\n/**\n * The host's lock sources as the store's options spell them: none without\n * definitions of its own, which then come from the live registry.\n */\nexport function hostLocksOf(\n  definitions: SlotDefaultSource | undefined,\n  nesting: NestingSource | undefined\n): HostLocks {\n  return definitions === undefined ? undefined : { definitions, nesting };\n}\n\n/**\n * What every lock question is judged by: the host's definitions and nesting\n * rules, or the live registry's, the document as last saved, and the caps\n * every edit is applied under, so a lock walk and a repair plan are bounded\n * as the apply they stand for is.\n */\nexport function lockSourcesOf(\n  locks: HostLocks,\n  stored: BlockDocument,\n  limits: DocumentLimits\n): LockSources {\n  return {\n    definitions: locks?.definitions ?? registryBlockSource(),\n    nesting: locks?.nesting ?? registryNestingSource(),\n    stored: [stored],\n    limits,\n  };\n}\n","\"use client\";\n\n/**\n * The editor's document state: what is being edited, what is selected, and how\n * to take an edit back.\n *\n * The op layer already answers \"what does this edit do to the document\" and\n * hands back an inverse with every application. What was missing is the thing\n * that HOLDS the answer — so every consumer that wanted to edit had to keep its\n * own copy of the document, its own idea of the selection, and its own undo\n * stack. Three of those disagree the moment one of them applies an op the\n * others do not see.\n *\n * So this is deliberately the only place a document changes. A panel, a canvas,\n * a keyboard handler and an agent all reach the same `apply`, and undo works\n * for all of them because it is built from what the op layer actually did\n * rather than from what each caller believed it was doing.\n *\n * **Undo is the op layer's inverse, not a snapshot of the document.** Snapshots\n * are the obvious design and they are wrong here for a reason that shows up\n * late: a document is a tree of unbounded size, so a stack of snapshots grows\n * with page size times history depth, and the copies are of a value that is\n * mostly unchanged between steps. An inverse is one op. It also composes with\n * anything else that produces ops — a collaborative stream, a replayed agent\n * edit — which a snapshot stack does not.\n *\n * @module editor-state\n */\n\nimport {\n  componentLayersLocks,\n  componentUsageIn,\n  compositionFaults,\n  DEFAULT_LIMITS,\n  findNode,\n  heldBaselines,\n  keptForSameComponents,\n  lockRefusal,\n  lockRepairRule,\n  placedLockChanges,\n  placementRefusal,\n  placementRepairRule,\n  planRepair as planDocumentRepair,\n  registryBlockSource,\n  registryNestingSource,\n  resolveComponentInstances,\n  type BlockDocument,\n  type CompositionFault,\n  type ResolvedComposition,\n  type ComponentLookup,\n  type DocumentLimits,\n  type LocatedPlacementBreak,\n  type LockSources,\n  type RepairPlan,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\nimport { useFirstAdd, type FirstAdd } from \"./canvas/first-add\";\nimport {\n  EMPTY_SELECTION,\n  applySelection,\n  pruneSelection,\n  type BlockSelection,\n  type SelectionMode,\n} from \"./canvas/selection\";\nimport {\n  useEditorAsks,\n  type AskedSetting,\n  type SettingAsked,\n} from \"./editor-asks\";\nimport {\n  replayStep,\n  useHistoryStacks,\n  useRestartOn,\n  type HistoryEntry,\n  type HistoryStep,\n} from \"./editor-history\";\nimport { keptLockAnswers } from \"./kept-lock-answers\";\nimport {\n  layersLockRefusalFor,\n  lockRefusalWording,\n  savedLockBrokenBy,\n  type LockEditRefusal,\n  type LockRefusalFacts,\n} from \"./lock-refusal\";\nimport { hostLocksOf, lockSourcesOf, useLockDefinitions } from \"./lock-sources\";\nimport { refusalAnnouncement } from \"./move-refusal\";\nimport { applyOps, type BuilderOp } from \"./op-vocabulary\";\nimport {\n  compositionRefusal,\n  type CompositionRefusal,\n} from \"./panels/add/inserter\";\n\n// The history's bound, exported here since this is where it was always read.\nexport { MAX_HISTORY } from \"./editor-history\";\n\nexport interface EditorState {\n  /** The document as it currently stands. */\n  document: BlockDocument;\n  /** The selected node's id, or null when nothing is selected. */\n  selectedId: string | null;\n  /**\n   * Everything selected, in document order, with the primary named.\n   *\n   * `selectedId` IS `selection.primary`, derived rather than stored twice: the\n   * two disagreeing would put an outline on one block and the inspector on\n   * another, and there is no render in which that is what an author meant.\n   */\n  selection: BlockSelection;\n  /** Select a node, or clear the selection with null. */\n  select: (id: string | null, mode?: SelectionMode) => void;\n  /**\n   * Apply an edit. Returns the applied op's outcome, or null when the op was\n   * refused — a caller that needs to know whether its edit landed can ask,\n   * rather than comparing documents afterwards.\n   */\n  apply: (op: BuilderOp) => BlockDocument | null;\n  /**\n   * Apply several ops as ONE action, or nothing at all.\n   *\n   * For an edit whose subject is a multi-block selection. Atomic — a group that\n   * failed halfway would leave a document the author never asked for — and it\n   * costs exactly one undo, because \"delete these six\" is one thing an author\n   * did and six presses to take it back would read as the history being wrong.\n   *\n   * Returns the new document, or `null` when any op was refused and nothing was\n   * committed.\n   */\n  applyAll: (ops: readonly BuilderOp[]) => BlockDocument | null;\n  /**\n   * The lock break `ops` would add, asked BEFORE they are applied, or\n   * undefined when they keep every lock. Nothing is applied.\n   *\n   * The question `apply` asks, with the same baseline, so a surface that\n   * refuses an action ahead of time (a drop indicator, the inserter, a\n   * keyboard move, a toolbar action) can never disagree with the apply that\n   * would follow.\n   */\n  lockRefusalFor: (ops: readonly BuilderOp[]) => LockRefusalFacts | undefined;\n  /**\n   * The repair of everything the document holds that the engine's repair\n   * rules put right (its lock breaks, then its placement breaks), planned by\n   * the engine's one repair planner against the baseline `apply` judges by.\n   * Nothing is applied: a surface shows the plan's steps and, once the\n   * author confirms, applies it as one edit. No steps when there is nothing\n   * to repair.\n   *\n   * Planned for `document` when given, which a surface rendering one passes\n   * so its plan is the one it shows; else for the document as it stands.\n   */\n  planRepair: (document?: BlockDocument) => RepairPlan;\n  /**\n   * The document as it stands with every component placement composed in,\n   * through the composition the edits themselves are judged on (each document\n   * composed once); `undefined` where no component library is known. What a\n   * surface reads to show the locks a placement's content sits under inside\n   * its component, which the page alone does not hold.\n   */\n  composed: () => BlockDocument | undefined;\n  /**\n   * The block definitions lock questions are judged by: the host's own\n   * `locks.definitions`, or the live registry. A surface showing what a lock\n   * holds reads these, so it holds what `apply` refuses.\n   */\n  lockDefinitions: SlotDefaultSource;\n  /**\n   * Take back the newest step, and answer whether it took effect: at once for\n   * a document edit, and as a promise for a recorded step, once its own undo\n   * has answered. So a surface says \"Undone\" only for a change that was undone.\n   */\n  undo: () => boolean | Promise<boolean>;\n  /** Repeat the newest undone step, answering as `undo` does. */\n  redo: () => boolean | Promise<boolean>;\n  /**\n   * Record a change made outside the document as one step of this history,\n   * when the author makes it, so it takes its place in order among the page's\n   * edits even while it is still being stored. It ends the redo branch, as an\n   * edit does. Answers a function that withdraws the step, for a change that\n   * did not take effect after all.\n   * @experimental\n   */\n  recordStep: (step: HistoryStep) => () => void;\n  /**\n   * Put back what a run of typing changed, and record nothing: the document\n   * as it was before the run's first write, with the history as it was then,\n   * redo branch included. For Escape in a field that writes as the author\n   * types. Answers whether there was a run to put back: only while the run's\n   * step is the newest, so once another edit, an undo or a blur has ended\n   * the run it is an ordinary step of the history.\n   * @experimental\n   */\n  cancelTyping: (run: object) => boolean;\n  canUndo: boolean;\n  canRedo: boolean;\n  /**\n   * The caps every edit is judged under: the host's, or the engine's defaults\n   * when the host named none.\n   *\n   * Exposed so a surface that asks the resolver whether a placement fits\n   * BEFORE applying it asks under the same caps the apply will enforce. Two\n   * readings of the site's caps — one here, one handed to the surface — agree\n   * until the day one of them is pointed at a different config; the surface\n   * reading this one cannot disagree with the apply that follows.\n   */\n  limits: DocumentLimits;\n  /**\n   * The document's position in its history: the document edits on the undo\n   * stack, plus those that fell off its old end. A recorded step is not one:\n   * it is stored where it was made, so it is no unsaved work here. The same as\n   * the number on the stack until the history passes its bound.\n   *\n   * Exported because \"did anything change\" is not answerable from the document\n   * alone: an edit and its undo leave a document equal to the original but not\n   * identical to it, so a host comparing references sees a change and a host\n   * comparing values misses a real one. A depth is the honest signal, and a\n   * test can read it — which a boolean derived inside a component cannot.\n   */\n  undoDepth: number;\n  /**\n   * The collection lists the canvas draws in their empty state rather than\n   * their entries, by id: what \"Preview the empty message\" chose, so an author\n   * can design what visitors see when nothing matches. Editor state only,\n   * never stored, and not a step of the history.\n   * @experimental\n   */\n  listsShowingEmpty?: ReadonlySet<string>;\n  /** Draw one list's empty state on the canvas, or its entries again. */\n  showListEmpty?: (id: string, empty: boolean) => void;\n  /**\n   * The collection lists whose author picked a new source that waits for an\n   * input, by id, with the tag the canvas shows over each (\"Still showing\n   * Events\"): the list still draws what it stores. Editor state only, never\n   * stored, and not a step of the history.\n   * @experimental\n   */\n  listsStillShowing?: ReadonlyMap<string, string>;\n  /** Tag one list as still showing what it stores, or `undefined` to clear it. */\n  tagListStillShowing?: (id: string, words: string | undefined) => void;\n  /**\n   * The list whose sort the author last asked to fix, from its canvas note's\n   * \"Choose a field\", with a count that grows on each ask, so the inspector\n   * takes the author to the list's first sort row once per press. Editor\n   * state only, never stored.\n   * @experimental\n   */\n  sortFieldAsked?: { readonly id: string; readonly seq: number };\n  /** Select a list and take the author to its first sort row. */\n  askSortField?: (id: string) => void;\n  /** The setting last asked for, counted per ask (`editor-asks`). @experimental */\n  settingAsked?: SettingAsked;\n  /** Select a block and take the author to one of its settings. */\n  askSetting?: (id: string, setting: AskedSetting) => void;\n  /**\n   * A block just added that asks for a choice, while the canvas draws its\n   * chooser: editor state only, never stored. See `first-add.ts`.\n   * @experimental\n   */\n  firstAdd?: FirstAdd;\n}\n\n/**\n * The editor's state without its selection: what a surface that shows\n * nothing about the selected block reads, such as the top bar.\n *\n * Derived from {@link EditorState} rather than declared beside it, so it\n * gains every field the state gains. Having no `selection` or `selectedId`, a\n * surface handed one cannot read the selection at all, so it can never show\n * a selection that is out of date: the compiler refuses the read.\n * @experimental\n */\nexport type EditorDocumentView = Omit<EditorState, \"selection\" | \"selectedId\">;\n\n/**\n * Every field of the view, each present, held or `undefined`: the type the\n * view is first built as, so a field added to the state and not built into\n * the view fails to compile rather than being silently left out of it.\n */\ntype EveryViewField = {\n  // Over the keys as a plain union rather than `keyof`, so the mapping keeps\n  // no field's `?` and every field must be named.\n  [K in Extract<keyof EditorDocumentView, string>]:\n    | EditorDocumentView[K]\n    | undefined;\n};\n\n/**\n * The view of `editor` without its selection, keeping its identity across a\n * change of the selection alone, so a surface given it and memoised draws\n * nothing again when only the selection moves. A change to any other field\n * (an edit, an undo, a list shown empty) makes a new view.\n *\n * Keyed on each field rather than on `editor`, whose identity changes with\n * every selection. Any editor state can be viewed, the page's or a header's\n * edited in place, so the view is taken where it is needed rather than kept\n * on the state.\n * @experimental\n */\nexport function useDocumentView(\n  editor: EditorDocumentView\n): EditorDocumentView {\n  return useMemo(\n    () =>\n      withoutAbsent({\n        document: editor.document,\n        select: editor.select,\n        apply: editor.apply,\n        applyAll: editor.applyAll,\n        lockRefusalFor: editor.lockRefusalFor,\n        planRepair: editor.planRepair,\n        composed: editor.composed,\n        lockDefinitions: editor.lockDefinitions,\n        undo: editor.undo,\n        redo: editor.redo,\n        recordStep: editor.recordStep,\n        cancelTyping: editor.cancelTyping,\n        canUndo: editor.canUndo,\n        canRedo: editor.canRedo,\n        limits: editor.limits,\n        undoDepth: editor.undoDepth,\n        listsShowingEmpty: editor.listsShowingEmpty,\n        showListEmpty: editor.showListEmpty,\n        listsStillShowing: editor.listsStillShowing,\n        tagListStillShowing: editor.tagListStillShowing,\n        sortFieldAsked: editor.sortFieldAsked,\n        askSortField: editor.askSortField,\n        settingAsked: editor.settingAsked,\n        askSetting: editor.askSetting,\n        firstAdd: editor.firstAdd,\n      }),\n    // Each field rather than `editor`, whose identity a selection changes.\n    [\n      editor.document,\n      editor.select,\n      editor.apply,\n      editor.applyAll,\n      editor.lockRefusalFor,\n      editor.planRepair,\n      editor.composed,\n      editor.lockDefinitions,\n      editor.undo,\n      editor.redo,\n      editor.recordStep,\n      editor.cancelTyping,\n      editor.canUndo,\n      editor.canRedo,\n      editor.limits,\n      editor.undoDepth,\n      editor.listsShowingEmpty,\n      editor.showListEmpty,\n      editor.listsStillShowing,\n      editor.tagListStillShowing,\n      editor.sortFieldAsked,\n      editor.askSortField,\n      editor.settingAsked,\n      editor.askSetting,\n      editor.firstAdd,\n    ]\n  );\n}\n\n/** The view with an optional field the state does not hold left absent, as on it. */\nfunction withoutAbsent(fields: EveryViewField): EditorDocumentView {\n  const view: Partial<Record<keyof EditorDocumentView, unknown>> = {};\n  for (const [key, value] of Object.entries(fields)) {\n    if (value !== undefined) view[key as keyof EditorDocumentView] = value;\n  }\n  return view as EditorDocumentView;\n}\n\nexport interface UseEditorStateArgs {\n  /** The document to start from. */\n  initialDocument: BlockDocument;\n  /** The caps this site holds its documents to. */\n  limits?: DocumentLimits;\n  /**\n   * The definitions the canvas draws component instances from, so an edit is\n   * refused when the page would no longer compose with it in.\n   *\n   * The op layer counts a stored instance as ONE node and cannot see that the\n   * resolver spends a budget across every instance it inlines, in document\n   * order, and nests to a depth counted from the page root. Handed the\n   * definitions, the apply asks the resolver about every accepted group —\n   * an insert, a move that carries an instance ahead of another, a duplicated\n   * or pasted copy, a pattern bringing instances of its own — and refuses the\n   * edit that would leave a placeholder where a component stood. Absent, a\n   * host that resolves nothing keeps the apply it had.\n   */\n  definitions?: ComponentLookup;\n  /**\n   * Told why an edit was refused for room, with the sentence the author\n   * should read. Surfaces already treat a `null` apply as \"nothing happened\";\n   * this is the one place the reason is still known.\n   */\n  onRefused?: (refusal: CompositionRefusal) => void;\n  /**\n   * Told why an edit was refused for a lock, with the sentence the author\n   * should read. Separate from `onRefused`, whose refusals are about room and\n   * keep the shape its callers were written against.\n   */\n  onLockRefused?: (refusal: LockEditRefusal) => void;\n  /**\n   * A component's name by its id, for the refusal of an edit to a block the\n   * component locks: the page cannot unlock it, so the author is told whose\n   * it is. Absent, the refusal names no component.\n   */\n  componentName?: (componentId: string) => string | undefined;\n  /**\n   * Where the locks an edit is held to are read: the block definitions and\n   * nesting rules. Defaults to the live registry, so every host's editor holds\n   * the locks its saves enforce.\n   */\n  locks?: Pick<LockSources, \"definitions\" | \"nesting\">;\n  /**\n   * The document as last saved: the stored form a save keeps `contentOnly`\n   * values against, so the editor keeps exactly what the save would. A host\n   * passes the saved value again after every save; absent, the document as\n   * opened stands for it.\n   */\n  stored?: BlockDocument;\n  /**\n   * Told when an edit was refused because it would put a block where the\n   * placement rule forbids, with the block and the reason. Every editor path\n   * (insert, drag, keyboard, toolbar, paste) ends in an op group here, so this\n   * is the one check none of them can miss, whatever a surface asked first.\n   */\n  onPlacementRefused?: (refusal: LocatedPlacementBreak) => void;\n  /**\n   * Which editing session this is. A different value starts the state again\n   * from `initialDocument`: nothing selected and an empty history, as a fresh\n   * mount would, while the component stays mounted. For a host that edits a\n   * second document for a while (a header in place) and drops its history\n   * when it is done. Absent, the state lives as long as the component.\n   * @experimental\n   */\n  session?: unknown;\n}\n\n/**\n * Whether an edit that turned `before` into `after` puts a block where the\n * placement rule forbids — telling the host which, when it does. A break the\n * page already held is not the edit's, so it is not refused here.\n *\n * Judged on the page itself, without composing its component placements: an\n * edit composes the page once, for room and locks, and composing each\n * placement again here would double that on every keystroke. What a placement\n * draws is judged by the surfaces before they act and by the save.\n */\nfunction refusedForPlacement(\n  before: BlockDocument,\n  after: BlockDocument,\n  { onPlacementRefused }: Pick<UseEditorStateArgs, \"onPlacementRefused\">,\n  limits: DocumentLimits\n): boolean {\n  const refusal = placementRefusal(\n    before,\n    after,\n    { nesting: registryNestingSource(), definitions: registryBlockSource() },\n    limits\n  );\n  if (refusal === undefined) return false;\n  onPlacementRefused?.(refusal);\n  return true;\n}\n\n/**\n * Whether an edit that turned `before` into `after` leaves the page without\n * room for a component it holds — telling the host why, when it does.\n *\n * Nothing to ask without definitions: a host that resolves nothing has no\n * composition to judge, and keeps the apply it had.\n */\nfunction refusedForRoom(\n  before: BlockDocument,\n  after: BlockDocument,\n  {\n    definitions,\n    onRefused,\n  }: Pick<UseEditorStateArgs, \"definitions\" | \"onRefused\">,\n  limits: DocumentLimits,\n  compose: Composer\n): boolean {\n  if (definitions === undefined) return false;\n  const refusal = compositionRefusal(\n    before,\n    after,\n    definitions,\n    limits,\n    compose\n  );\n  if (refusal === undefined) return false;\n  onRefused?.(refusal);\n  return true;\n}\n\n/** A document as composed, under the store's components and limits. */\ntype Composer = (document: BlockDocument) => ResolvedComposition;\n\n/** Compositions already made, by document, and what they were made under. */\ninterface CompositionCache {\n  readonly components: ComponentLookup | undefined;\n  readonly limits: DocumentLimits;\n  readonly byDocument: WeakMap<BlockDocument, ResolvedComposition>;\n}\n\n/**\n * Compose through the cache, so each document is composed once.\n *\n * Every edit asks of three documents: the one before it, the one it makes and\n * the one last saved. The one before is the last edit's result, and the saved\n * one changes only with a save, so both are already composed; an edit\n * composes only the document it makes. Keyed by the document OBJECT, which the\n * store never changes in place, and dropped whole when the components or the\n * limits change, since a composition is made under both.\n */\nfunction composerFrom(\n  cache: { current: CompositionCache },\n  components: ComponentLookup,\n  limits: DocumentLimits\n): Composer {\n  if (\n    cache.current.components !== components ||\n    cache.current.limits !== limits\n  ) {\n    cache.current = { components, limits, byDocument: new WeakMap() };\n  }\n  const { byDocument } = cache.current;\n  return document => {\n    let composed = byDocument.get(document);\n    if (composed === undefined) {\n      // With the exposure map: the editor's composition is never rendered or\n      // saved, and the canvas reaches a value inside a component through it.\n      composed = resolveComponentInstances(document, components, {\n        limits,\n        exposures: true,\n      });\n      byDocument.set(document, composed);\n    }\n    return composed;\n  };\n}\n\n/** What a lock question reads besides the documents. */\ninterface LockJudgement {\n  readonly locks: UseEditorStateArgs[\"locks\"];\n  readonly limits: DocumentLimits;\n  /** The composed page, for the locks a placement reaches inside a component. */\n  readonly compose: Composer | undefined;\n  /** A component's name, for a refusal of a block it locks. */\n  readonly componentName: UseEditorStateArgs[\"componentName\"];\n}\n\n/**\n * Whether an edit that turned `before` into `after` adds a lock break,\n * telling the host why, when it does.\n *\n * Judged as a save judges it, by the engine's `lockRefusal`, with the document\n * as last saved as the stored form, so a value the stored page holds stays\n * allowed after edits in between, and one a saved repair removed does not.\n */\nfunction refusedForLock(\n  before: BlockDocument,\n  after: BlockDocument,\n  stored: BlockDocument,\n  judgement: LockJudgement,\n  onLockRefused: UseEditorStateArgs[\"onLockRefused\"]\n): boolean {\n  const found = lockBreakAdded(before, after, stored, judgement);\n  if (found === undefined) return false;\n  onLockRefused?.({\n    reason: \"locked\",\n    sentence: refusalAnnouncement(lockRefusalWording(found)),\n    lock: found,\n  });\n  return true;\n}\n\n/**\n * The lock break an edit adds, judged against the last-saved document: on the\n * page itself, then on the composed page, where a placement's values and slot\n * content land inside its component's own locked slots.\n */\nfunction lockBreakAdded(\n  before: BlockDocument,\n  after: BlockDocument,\n  stored: BlockDocument,\n  judgement: LockJudgement\n): LockRefusalFacts | undefined {\n  const sources = lockSourcesOf(judgement.locks, stored, judgement.limits);\n  return (\n    lockRefusal(before, after, sources) ??\n    composedLockAdded(before, after, stored, sources, judgement)\n  );\n}\n\n/**\n * A block a placed component locks in Layers that the edit changes through a\n * placement, judged as a save judges it (`placedLockChanges`): the composed\n * page against the same page with every placement as its component holds it,\n * keeping a value the page already gave the block, before this edit or as\n * last saved. Named by the component, since the page cannot unlock it.\n */\nfunction componentLockAdded(\n  after: BlockDocument,\n  composedAfter: BlockDocument,\n  kept: readonly BlockDocument[],\n  {\n    compose,\n    limits,\n    componentName,\n  }: Pick<LockJudgement, \"limits\" | \"componentName\"> & { compose: Composer }\n): LockRefusalFacts | undefined {\n  // Asked of the as-held baseline, not of the page after the edit: an edit\n  // that hides or removes the locked block leaves no lock after it to find,\n  // but the page before it, or as saved, still draws one. A page none of\n  // whose forms draws a component lock composes nothing more.\n  const drawsLock = [composedAfter, ...kept].some(\n    form => componentLayersLocks(form.nodes, limits).size > 0\n  );\n  if (!drawsLock) return undefined;\n  const held = heldBaselines(after, limits).map(level => ({\n    form: compose(level.document).document,\n    placements: level.placements,\n  }));\n  const [change] = placedLockChanges(composedAfter, held, kept, limits);\n  if (change === undefined) return undefined;\n  return componentLockFacts(\n    componentNameOf(after, change.placementId, componentName)\n  );\n}\n\n/** The name of the component a page's placement draws, or \"\" when none is known. */\nfunction componentNameOf(\n  page: BlockDocument,\n  placementId: string | undefined,\n  componentName: LockJudgement[\"componentName\"]\n): string {\n  const placement =\n    placementId === undefined ? undefined : findNode(page.nodes, placementId);\n  const componentId = (\n    placement?.props as { componentId?: unknown } | undefined\n  )?.componentId;\n  return typeof componentId === \"string\"\n    ? (componentName?.(componentId) ?? \"\")\n    : \"\";\n}\n\n/** A refusal for a block a component locks, named by the component. */\nfunction componentLockFacts(name: string): LockRefusalFacts {\n  return {\n    code: \"layers-locked\",\n    label: name,\n    relation: \"component\",\n    verb: \"change\",\n  };\n}\n\n/**\n * The lock break an edit adds to the composed page, judged by the engine's\n * `compositionFaults`, the check a save runs over the same composition.\n *\n * \"Adds\" as on the page itself: a break the composed page already had before\n * the edit is left to the repair, and the document before the edit and as last\n * saved, both composed, are the baselines a `\"contentOnly\"` value may keep.\n */\nfunction composedLockAdded(\n  before: BlockDocument,\n  after: BlockDocument,\n  stored: BlockDocument,\n  sources: LockSources,\n  { compose, limits, componentName }: LockJudgement\n): LockRefusalFacts | undefined {\n  if (compose === undefined) return undefined;\n  // A page placing no component has no composed break to add.\n  const placed = componentUsageIn(after.nodes, limits.maxNodes);\n  if (placed.complete && placed.ids.length === 0) return undefined;\n  const composedBefore = compose(before);\n  const baselines = [composedBefore.document, compose(stored).document];\n  const composedAfter = compose(after);\n  // A value is kept only under the component that gave it: a placement this\n  // edit switches to another component is left out of the forms it keeps.\n  const kept = [before, stored].map((form, index) => {\n    const same = keptForSameComponents(after, form, limits);\n    return same === form ? baselines[index] : compose(same).document;\n  });\n  const held = componentLockAdded(after, composedAfter.document, kept, {\n    compose,\n    limits,\n    componentName,\n  });\n  if (held !== undefined) return held;\n  const lockFaults = (host: BlockDocument, composition: ResolvedComposition) =>\n    compositionFaults(host, composition, {\n      definitions: sources.definitions,\n      nesting: sources.nesting,\n      limits,\n      baselines,\n    }).filter(fault => fault.lock !== undefined);\n  const had = new Set(lockFaults(before, composedBefore).map(composedBreakKey));\n  const added = lockFaults(after, composedAfter).find(\n    fault => !had.has(composedBreakKey(fault))\n  );\n  if (added?.lock === undefined) return undefined;\n  return {\n    code:\n      added.code === \"locked-slot-content-only\"\n        ? \"locked-slot-content-only\"\n        : \"locked-slot-altered\",\n    holderType: added.lock.holderType,\n    lock: added.lock.lock,\n    childType: added.lock.childType,\n    instanceId: added.instanceId,\n  };\n}\n\n/** What the store reads at apply time: the host's sources and its saved copy. */\ninterface AtApply\n  extends Pick<\n    UseEditorStateArgs,\n    | \"definitions\"\n    | \"onRefused\"\n    | \"onLockRefused\"\n    | \"locks\"\n    | \"onPlacementRefused\"\n    | \"componentName\"\n  > {\n  /** The document as last saved; the document as opened when none is given. */\n  readonly stored: BlockDocument;\n}\n\nfunction atApply(\n  host: Pick<\n    UseEditorStateArgs,\n    | \"definitions\"\n    | \"onRefused\"\n    | \"onLockRefused\"\n    | \"locks\"\n    | \"stored\"\n    | \"onPlacementRefused\"\n    | \"componentName\"\n  >,\n  opened: BlockDocument\n): AtApply {\n  return {\n    componentName: host.componentName,\n    definitions: host.definitions,\n    onRefused: host.onRefused,\n    onLockRefused: host.onLockRefused,\n    locks: host.locks,\n    stored: host.stored ?? opened,\n    onPlacementRefused: host.onPlacementRefused,\n  };\n}\n\n/** The rules a repair runs, in order. */\nconst REPAIR_RULES = [lockRepairRule, placementRepairRule] as const;\n\n/**\n * The store's lock questions, asked of the document as it stands and the\n * baseline as last saved, with the composer the room check shares.\n */\nfunction useLockQuestions(\n  latestDocument: { current: BlockDocument },\n  composition: { current: AtApply },\n  limits: DocumentLimits,\n  /** The document as last saved, as this render holds it. */\n  baseline: BlockDocument,\n  locks: UseEditorStateArgs[\"locks\"]\n): {\n  composerNow: () => Composer | undefined;\n  lockRefusalFor: EditorState[\"lockRefusalFor\"];\n  planRepair: EditorState[\"planRepair\"];\n  composed: EditorState[\"composed\"];\n  lockDefinitions: SlotDefaultSource;\n} {\n  const composerNow = useComposer(composition, limits);\n  // The sources and the baseline as values, not through the ref: a host that\n  // swaps either, or a save that changes the baseline without changing the\n  // document, gives these callbacks, and so the store, a new identity, and a\n  // surface asking once per store asks again.\n  const definitions = locks?.definitions;\n  const nesting = locks?.nesting;\n  // Kept per document version and edit, and dropped when anything else the\n  // answer reads changes (the scope below).\n  const [kept] = useState(keptLockAnswers);\n  const lockRefusalFor = useCallback(\n    (ops: readonly BuilderOp[]): LockRefusalFacts | undefined => {\n      // Read at the question, as the apply reads it. The component names\n      // are not part of what is kept by: they only word a refusal, and a host\n      // may hand a new function on every render.\n      const { componentName, definitions: components } = composition.current;\n      const document = latestDocument.current;\n      const scope = [components, baseline, definitions, nesting, limits];\n      return kept.answer(document, ops, scope, () =>\n        lockAnswerFor(document, ops, baseline, {\n          locks: hostLocksOf(definitions, nesting),\n          limits,\n          compose: composerNow(),\n          componentName,\n        })\n      );\n    },\n    [\n      latestDocument,\n      composition,\n      kept,\n      limits,\n      composerNow,\n      baseline,\n      definitions,\n      nesting,\n    ]\n  );\n\n  const planRepair = useCallback(\n    (document: BlockDocument = latestDocument.current): RepairPlan =>\n      // The lock rule first and the placement rule after it, so a block a\n      // lock repair moves is judged where the lock rule put it.\n      planDocumentRepair(\n        document,\n        lockSourcesOf(hostLocksOf(definitions, nesting), baseline, limits),\n        REPAIR_RULES\n      ),\n    [latestDocument, limits, baseline, definitions, nesting]\n  );\n  const composed = useCallback(\n    (): BlockDocument | undefined =>\n      composerNow()?.(latestDocument.current).document,\n    [composerNow, latestDocument]\n  );\n  const lockDefinitions = useLockDefinitions(locks);\n  return { composerNow, lockRefusalFor, planRepair, composed, lockDefinitions };\n}\n\n/**\n * The composer for the components the store holds at the moment it is asked,\n * or none without them; the compositions the room and lock checks share. See\n * `composerFrom`.\n */\nfunction useComposer(\n  composition: { current: Pick<UseEditorStateArgs, \"definitions\"> },\n  limits: DocumentLimits\n): () => Composer | undefined {\n  const compositions = useRef<CompositionCache>({\n    components: undefined,\n    limits,\n    byDocument: new WeakMap(),\n  });\n  return useCallback((): Composer | undefined => {\n    const components = composition.current.definitions;\n    return components === undefined\n      ? undefined\n      : composerFrom(compositions, components, limits);\n  }, [composition, limits]);\n}\n\n/**\n * Whether a fresh edit is refused: it deletes a block the saved page still\n * holds locked, the page no longer composes, or the edit adds a lock break.\n * The host is told why, in that order.\n */\nfunction refusedAsFresh(\n  before: BlockDocument,\n  after: BlockDocument,\n  {\n    stored,\n    current,\n    limits,\n    compose,\n    ops,\n  }: {\n    stored: BlockDocument;\n    current: Pick<\n      UseEditorStateArgs,\n      \"definitions\" | \"onRefused\" | \"onLockRefused\" | \"locks\" | \"componentName\"\n    >;\n    limits: DocumentLimits;\n    compose: Composer | undefined;\n    /** The edit's ops, for the saved page's Layers lock on what it deletes. */\n    ops: readonly BuilderOp[];\n  }\n): boolean {\n  // A delete of a block the SAVED page still holds locked, though the author\n  // has unlocked it since: a save would refuse it, so the edit is refused now,\n  // with the way forward.\n  if (reportLayersLock(before, ops, current.onLockRefused, after, stored)) {\n    return true;\n  }\n  if (\n    compose !== undefined &&\n    refusedForRoom(before, after, current, limits, compose)\n  ) {\n    return true;\n  }\n  return refusedForLock(\n    before,\n    after,\n    stored,\n    judgementOf(current, limits, compose),\n    current.onLockRefused\n  );\n}\n\n/**\n * The lock `ops` would break in `document`, applied only to ask: a block\n * locked in Layers first, now or on the saved page for a delete, then the\n * slot locks a block declares. Ops the document cannot take for another\n * reason are the apply's to refuse; they add no lock break, because they add\n * nothing.\n */\nfunction lockAnswerFor(\n  document: BlockDocument,\n  ops: readonly BuilderOp[],\n  stored: BlockDocument,\n  judgement: LockJudgement\n): LockRefusalFacts | undefined {\n  const layers = layersLockRefusalFor(document, ops, stored);\n  if (layers !== undefined) return layers;\n  let group;\n  try {\n    group = applyOps(document, ops, judgement.limits);\n  } catch {\n    return undefined;\n  }\n  if (group.inverses.length === 0) return undefined;\n  return lockBreakAdded(document, group.document, stored, judgement);\n}\n\n/**\n * Tell the host which Layers lock refused an edit, and answer whether one did.\n *\n * With `after` and `stored`, the edit applied and only the saved page's lock\n * on a block it deletes is asked (`savedLockBrokenBy`); without them, the\n * edit was refused by the op layer and the lock it broke is found again.\n */\nfunction reportLayersLock(\n  before: BlockDocument,\n  ops: readonly BuilderOp[],\n  onLockRefused: UseEditorStateArgs[\"onLockRefused\"],\n  after?: BlockDocument,\n  stored?: BlockDocument\n): boolean {\n  const found =\n    after === undefined || stored === undefined\n      ? layersLockRefusalFor(before, ops)\n      : savedLockBrokenBy(before, after, stored, ops);\n  if (found === undefined) return false;\n  onLockRefused?.({\n    reason: \"locked\",\n    sentence: refusalAnnouncement(lockRefusalWording(found)),\n    lock: found,\n  });\n  return true;\n}\n\n/** The lock judgement from what the store reads at apply time. */\nfunction judgementOf(\n  current: Pick<UseEditorStateArgs, \"locks\" | \"componentName\">,\n  limits: DocumentLimits,\n  compose: Composer | undefined\n): LockJudgement {\n  return {\n    locks: current.locks,\n    limits,\n    compose,\n    componentName: current.componentName,\n  };\n}\n\n/**\n * A composed break by its rule, its placement, its locked slot and, for the\n * blocks a slot holds, which blocks those are: so a slot already broken may\n * keep its blocks, as on the page itself, but not change them further.\n */\nfunction composedBreakKey(fault: CompositionFault): string {\n  const { lock } = fault;\n  if (lock === undefined) return `${fault.code}\\u0000${fault.instanceId}`;\n  return [\n    fault.code,\n    fault.instanceId,\n    lock.holderId,\n    lock.slot,\n    lock.heldCount,\n    heldKey(lock),\n  ].join(\"\\u0000\");\n}\n\n/**\n * The blocks a locked slot holds, as a key: in order where the lock fixes the\n * order, and as a set of types where it only fixes membership (`\"insert\"`).\n */\nfunction heldKey(lock: NonNullable<CompositionFault[\"lock\"]>): string {\n  const held = lock.held.map(type => type ?? \"\\u0001\");\n  if (lock.lock === \"insert\") held.sort();\n  return held.join(\"\\u0002\");\n}\n\n/**\n * Hold a document and the edits made to it.\n *\n * The document is state and the history is a ref: history changes on every edit\n * but nothing RENDERS from the stacks themselves, only from whether they are\n * empty, so keeping them in state would re-render every consumer on each edit\n * to deliver a value none of them read.\n */\n/**\n * Which lists the canvas shows empty, and the way to change it: a new set\n * only when one changes, so the canvas, which draws per set, draws again only\n * then.\n */\nfunction useListsShowingEmpty(session: unknown): {\n  listsShowingEmpty: ReadonlySet<string>;\n  showListEmpty: (id: string, empty: boolean) => void;\n} {\n  const [listsShowingEmpty, setListsShowingEmpty] = useState<\n    ReadonlySet<string>\n  >(() => new Set());\n  useRestartOn(session, () => setListsShowingEmpty(new Set()));\n  const showListEmpty = useCallback((id: string, empty: boolean) => {\n    setListsShowingEmpty(current => toggled(current, id, empty));\n  }, []);\n  return { listsShowingEmpty, showListEmpty };\n}\n\n/**\n * Which lists the canvas tags as still showing what they store, and the way\n * to change it: a new map only when one changes, as for the empty state.\n */\nfunction useListsStillShowing(session: unknown): {\n  listsStillShowing: ReadonlyMap<string, string>;\n  tagListStillShowing: (id: string, words: string | undefined) => void;\n} {\n  const [listsStillShowing, setListsStillShowing] = useState<\n    ReadonlyMap<string, string>\n  >(() => new Map());\n  useRestartOn(session, () => setListsStillShowing(new Map()));\n  const tagListStillShowing = useCallback(\n    (id: string, words: string | undefined) => {\n      setListsStillShowing(current => {\n        if (current.get(id) === words) return current;\n        const next = new Map(current);\n        if (words === undefined) next.delete(id);\n        else next.set(id, words);\n        return next;\n      });\n    },\n    []\n  );\n  return { listsStillShowing, tagListStillShowing };\n}\n\n/** `current` with `id` in it or not, the same set when nothing changes. */\nfunction toggled(\n  current: ReadonlySet<string>,\n  id: string,\n  present: boolean\n): ReadonlySet<string> {\n  if (current.has(id) === present) return current;\n  const next = new Set(current);\n  if (present) next.add(id);\n  else next.delete(id);\n  return next;\n}\n\n/**\n * The editor's state: the document and its history, with which lists the\n * canvas shows empty and which list's sort the author asked to fix beside\n * them, which are editor state and no step of the history.\n */\nexport function useEditorState(args: UseEditorStateArgs): EditorState {\n  // With the step that holds a block just added while it asks for a choice.\n  const state = useFirstAdd(useDocumentState(args));\n  // Each of these belongs to the session's document, so a new session starts\n  // with none of them (`session`).\n  const { listsShowingEmpty, showListEmpty } = useListsShowingEmpty(\n    args.session\n  );\n  const { listsStillShowing, tagListStillShowing } = useListsStillShowing(\n    args.session\n  );\n  // What the author asked the inspector to take them to (`editor-asks`).\n  const asks = useEditorAsks(state.select, args.session);\n  return useMemo(\n    () => ({\n      ...state,\n      listsShowingEmpty,\n      showListEmpty,\n      listsStillShowing,\n      tagListStillShowing,\n      ...asks,\n    }),\n    [\n      state,\n      listsShowingEmpty,\n      showListEmpty,\n      listsStillShowing,\n      tagListStillShowing,\n      asks,\n    ]\n  );\n}\n\n/**\n * The document and its selection, started again in the render that sees\n * `session` change (never on the first), with the history `clearHistory`\n * forgets. During that render rather than after it, so no surface ever reads\n * the old document under the new session: the updates are this component's\n * own, so React drops that render and renders again at once with them.\n */\nfunction useSessionDocument(\n  initialDocument: BlockDocument,\n  session: unknown,\n  clearHistory: () => void\n) {\n  const [document, setDocument] = useState<BlockDocument>(initialDocument);\n  const [selection, setSelection] = useState<BlockSelection>(EMPTY_SELECTION);\n  useRestartOn(session, () => {\n    setDocument(initialDocument);\n    setSelection(EMPTY_SELECTION);\n    clearHistory();\n  });\n  return { document, setDocument, selection, setSelection };\n}\n\n/** The document, its selection and its history: see {@link useEditorState}. */\nfunction useDocumentState({\n  initialDocument,\n  limits = DEFAULT_LIMITS,\n  definitions,\n  onRefused,\n  onLockRefused,\n  locks,\n  stored,\n  onPlacementRefused,\n  componentName,\n  session,\n}: UseEditorStateArgs): EditorState {\n  // Read at apply time rather than closed over, so a library that reloads or\n  // a host that swaps its callback does not rebuild `apply` and everything\n  // keyed on it.\n  // The document as last saved is read the same way, so a save the host\n  // reports takes effect on the very next edit.\n  const host = {\n    definitions,\n    onRefused,\n    onLockRefused,\n    locks,\n    stored,\n    onPlacementRefused,\n    componentName,\n  };\n  const composition = useRef(atApply(host, initialDocument));\n  composition.current = atApply(host, initialDocument);\n  const { depths, push, pop, remove, withdrawTyping, record, settle, clear } =\n    useHistoryStacks();\n  const { document, setDocument, selection, setSelection } = useSessionDocument(\n    initialDocument,\n    session,\n    clear\n  );\n\n  /**\n   * The document as it stands NOW, for everything a LATER event reaches.\n   *\n   * Every callback below closes over the render it was made in. Most callers\n   * take theirs from the current render and the distinction never shows, but\n   * two paths do not, and both read this ref rather than the state.\n   *\n   * `select`, because a gesture is handled by whatever handler the last render\n   * bound and the selection rules need the document that is current when the\n   * click lands. Closing over it resolves a range against a stale tree, which\n   * is a wrong selection rather than a missing one.\n   *\n   * `run`, because a panel that commits from an unmount cleanup necessarily\n   * holds an older callback: the component going away does not render again, so\n   * its closure predates the very edit that removed it. Folding onto that older\n   * document did not merely apply a stale edit — it SUCCEEDED where it should\n   * have been refused, the node still being present in that copy, and then\n   * wrote the whole document back. Deleting a block with an unsaved panel open\n   * restored the block and discarded everything since. Read through the ref the\n   * same call is refused, which is what callers are already written to handle.\n   *\n   * The hazard was named here for `select` alone and left on the op path, which\n   * is the more expensive of the two.\n   */\n  const latestDocument = useRef(document);\n  const { composerNow, lockRefusalFor, planRepair, composed, lockDefinitions } =\n    useLockQuestions(\n      latestDocument,\n      composition,\n      limits,\n      composition.current.stored,\n      locks\n    );\n  latestDocument.current = document;\n\n  /**\n   * Run an op and record its inverse on the given stack.\n   *\n   * Shared by `apply`, `undo` and `redo` because all three are the same\n   * operation with a different destination for the inverse — undo pushes onto\n   * redo and vice versa. Written once so the three cannot disagree about what\n   * a refused op does, which is nothing at all: no state change, no history\n   * entry, and the caller told.\n   */\n  /**\n   * Apply a GROUP of ops as one action.\n   *\n   * ## Atomic, and that is the point\n   *\n   * Every op is folded onto a WORKING document and nothing is committed until\n   * all of them have succeeded. A group that failed halfway would leave the\n   * document in a state the author never asked for and no single undo could\n   * leave — deleting four of six blocks because the fifth was locked is worse\n   * than deleting none.\n   *\n   * ## One group, one undo\n   *\n   * The inverses are collected in REVERSE order and pushed as a single stack\n   * entry. Undo granularity belongs to the history rather than to the document\n   * format: the op vocabulary stays four flat kinds, which matters because ops\n   * are persisted in a `json()` column and a nested \"batch\" op would make every\n   * reader of that column understand recursion.\n   *\n   * A single op is a group of one, so there is one code path rather than a fast\n   * path and a batch path that can drift.\n   */\n  const run = useCallback(\n    (\n      ops: readonly BuilderOp[],\n      // \"none\": applied and recorded nowhere, for a run of typing put back.\n      into: \"undo\" | \"redo\" | \"new\" | \"none\"\n    ): BlockDocument | null => {\n      let group;\n      try {\n        // ONE call rather than a fold here, so the group's atomicity and its\n        // inverse ordering live in one place: `applyOps` returns the inverses\n        // in undo order and answers with none at all when the group left the\n        // document as it found it.\n        //\n        // It does NOT make the caps a group-level decision. Every op is still\n        // judged against the document as it stands when that op runs, which is\n        // what keeps an accepted edit undoable — a group allowed to exceed the\n        // cap in passing can hand back an inverse the cap then refuses, and\n        // `undo` pops its entry before replaying it.\n        //\n        // So a group's outcome can depend on the order its ops arrive in, and\n        // nothing below this line changes that. A caller whose ops are known to\n        // be independent could order them; none does today.\n        group = applyOps(latestDocument.current, ops, limits);\n      } catch {\n        // A refused group is an ordinary outcome, not a crash: an insert past a\n        // cap, a move onto a node that no longer exists, an update to a node\n        // a concurrent edit removed. The caller decides what to say about it.\n        // Nothing is committed — see the atomicity note above.\n        //\n        // A block locked in Layers is the one refusal the host is told the\n        // reason for here, in the lock's own words, whichever surface sent the\n        // edit: nothing on the canvas explains it otherwise.\n        if (into === \"new\") {\n          reportLayersLock(\n            latestDocument.current,\n            ops,\n            composition.current.onLockRefused\n          );\n        }\n        return null;\n      }\n\n      // NO inverses is the ONE answer to \"is there anything to record\", and it\n      // covers both ways of arriving at nothing: a group with no ops, and a\n      // group whose ops left the document as they found it. Either would be a\n      // history entry whose undo has no visible effect, which reads as the\n      // history being broken.\n      //\n      // Asked of `applyOps` rather than answered here from `ops.length`, so\n      // one place decides what an empty group means. Answering here would\n      // answer before the op layer has seen the group at all, while a direct\n      // `applyOps` caller would still get the op layer's answer — one group\n      // with two verdicts.\n      if (group.inverses.length === 0) return latestDocument.current;\n\n      // Whether the page still composes and keeps its locks, asked of a\n      // fresh edit only. An undo or a redo returns the page to a state that\n      // was accepted when it was made, and a library that grew or a cap that\n      // shrank since must not strand the history.\n      if (\n        into === \"new\" &&\n        refusedAsFresh(latestDocument.current, group.document, {\n          stored: composition.current.stored,\n          current: composition.current,\n          limits,\n          compose: composerNow(),\n          ops,\n        })\n      ) {\n        return null;\n      }\n      // A fresh edit only, for the reason room is: an undo or a redo returns\n      // the page to a state that was accepted when it was made.\n      if (\n        into === \"new\" &&\n        refusedForPlacement(\n          latestDocument.current,\n          group.document,\n          composition.current,\n          limits\n        )\n      ) {\n        return null;\n      }\n\n      const applied = { document: group.document, inverse: group.inverses };\n      const entry: HistoryEntry = { kind: \"ops\", ops: applied.inverse };\n\n      if (into !== \"none\") push(entry, into);\n      // Ahead of `setDocument`, which does not take effect until the next\n      // render: two ops applied in one tick must see each other, or the second\n      // is folded onto the document the first already replaced.\n      latestDocument.current = applied.document;\n      setDocument(applied.document);\n\n      // A selection pointing at a node this edit removed would leave every\n      // panel describing something the author cannot see. Cleared by asking the\n      // NEW document whether the id is still there, rather than by inspecting\n      // the op — an op that removes a container removes its subtree too, and\n      // the op names only the container.\n      setSelection(current => pruneSelection(applied.document, current));\n\n      return applied.document;\n    },\n    // NOT `document`: it is read through the ref above, so depending on it here\n    // would rebuild these callbacks every edit for a value none of them close\n    // over. Stable identity is also the point — a stale `run` is now the same\n    // `run`, folding onto the tree as it stands.\n    // The setters too, stable, listed since they arrive from a hook here.\n    [limits, composerNow, push, setDocument, setSelection]\n  );\n\n  const apply = useCallback((op: BuilderOp) => run([op], \"new\"), [run]);\n\n  const applyAll = useCallback(\n    (ops: readonly BuilderOp[]) => run(ops, \"new\"),\n    [run]\n  );\n\n  /**\n   * Take the newest entry off one stack and replay it, recording what takes\n   * it back on the other.\n   *\n   * Popped before running, and NOT pushed back on failure. A refused undo\n   * means the inverse no longer applies to this document, so keeping it would\n   * leave a step that fails every time it is reached — an undo button that\n   * does nothing and never clears.\n   */\n  const replay = useCallback(\n    (from: \"undo\" | \"redo\"): boolean | Promise<boolean> => {\n      const entry = pop(from);\n      if (entry === undefined) return false;\n      const into = from === \"undo\" ? \"redo\" : \"undo\";\n      if (entry.kind === \"step\") {\n        return replayStep(entry, into, push, remove, settle);\n      }\n      return run(entry.ops, into) !== null;\n    },\n    [pop, push, remove, run, settle]\n  );\n  const undo = useCallback(() => replay(\"undo\"), [replay]);\n  const redo = useCallback(() => replay(\"redo\"), [replay]);\n  // Recorded by the history, which knows the session it belongs to.\n  const recordStep = record;\n  const cancelTyping = useCallback(\n    (typingRun: object): boolean => {\n      const entry = withdrawTyping(typingRun);\n      // A typing run's step is always a document edit; the guard keeps the\n      // type honest rather than assuming it.\n      if (entry === undefined || entry.kind !== \"ops\") return false;\n      return run(entry.ops, \"none\") !== null;\n    },\n    [withdrawTyping, run]\n  );\n\n  const select = useCallback(\n    (id: string | null, mode: SelectionMode = \"replace\") =>\n      setSelection(current =>\n        applySelection(latestDocument.current, current, id, mode)\n      ),\n    // Stable setter, listed since it arrives from a hook of this module.\n    [setSelection]\n  );\n\n  return useMemo(\n    () => ({\n      document,\n      selectedId: selection.primary,\n      selection,\n      select,\n      apply,\n      applyAll,\n      lockRefusalFor,\n      planRepair,\n      composed,\n      lockDefinitions,\n      undo,\n      redo,\n      recordStep,\n      cancelTyping,\n      canUndo: depths.undo > 0,\n      canRedo: depths.redo > 0,\n      limits,\n      undoDepth: depths.document,\n    }),\n    [\n      document,\n      selection,\n      select,\n      apply,\n      applyAll,\n      lockRefusalFor,\n      planRepair,\n      composed,\n      lockDefinitions,\n      undo,\n      redo,\n      recordStep,\n      cancelTyping,\n      depths,\n      limits,\n    ]\n  );\n}\n","\"use client\";\n\n/**\n * Which document the editor is editing: the page, or a region of its layout\n * (a header or footer) drawn from another document and edited in place, the\n * page staying on screen under it.\n *\n * Two editor states, never merged. The page's stays mounted and frozen while a\n * region is edited: nothing routes an edit, an undo or a recorded step to it,\n * because everything that edits reads the ACTIVE state this hands out. The\n * region's is a second `useEditorState` of its own, started from the region's\n * document with an empty history on entering and started again empty on\n * leaving, so its history is dropped whatever leaving chose. An undo after\n * leaving can never reach into a header that may already be published.\n *\n * Generic on purpose: the host supplies the region's document, its\n * definitions and every word said about it (the bar, Done, the announcements,\n * the name Layers and the inspector use). The builder knows nothing of what\n * the region comes from or how it is saved.\n *\n * The verbs are plain commands (`enter`, `leave`, `pulseDone`) so a keyboard\n * route, a button, a command palette or an agent all reach the same switch.\n *\n * @module editing-target\n * @experimental Settles with editing a header or footer in place.\n */\n\nimport type {\n  BlockDocument,\n  DefinitionsById,\n  RegionArea,\n} from \"@nextlyhq/blocks-engine\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\nimport {\n  useEditorState,\n  type EditorState,\n  type UseEditorStateArgs,\n} from \"../editor-state\";\n\n/** What the host says about a region while it is edited. */\nexport interface RegionEditingWords {\n  /** The bar above the canvas: \"Editing the site header · changes show on 11 pages\". */\n  readonly bar: string;\n  /** The bar's button that ends the editing: \"Done\". */\n  readonly done: string;\n  /** Announced on entering: \"Editing the site header. Changes show on 11 pages.\" */\n  readonly entered: string;\n  /** Announced on leaving: \"Back to the page.\" */\n  readonly left: string;\n}\n\n/** A region of the page's layout to edit in place, as the host hands it over. */\nexport interface RegionEditing {\n  /** Which region: the header or the footer. */\n  readonly area: RegionArea;\n  /** Its document as editing starts: the latest version of what fills it. */\n  readonly document: BlockDocument;\n  /** The definitions that document's component placements are drawn from. */\n  readonly definitions?: DefinitionsById;\n  /** Its name, \"Site header\": \"Layers · Site header\", \"Navigation · in Site header\". */\n  readonly label: string;\n  /** What is said about it while it is edited. */\n  readonly words: RegionEditingWords;\n}\n\n/** What the editor edits: the page, or a region of its layout in place. */\nexport type EditingTarget =\n  | { readonly kind: \"page\" }\n  | ({ readonly kind: \"region\" } & RegionEditing);\n\n/** The editing target, the state that edits it, and the ways to switch. */\nexport interface EditingTargetState {\n  /** What is being edited now. */\n  readonly target: EditingTarget;\n  /**\n   * The state of the document being edited: the region's while one is edited,\n   * else the page's. Everything that edits or reads \"the document being\n   * edited\" (the inspector, Layers, the Add panel, the keyboard, the palette,\n   * the toolbar, the canvas marks, Undo and Redo, a recorded site-style step)\n   * is handed this, so one switch routes them all.\n   */\n  readonly active: EditorState;\n  /** Edit `region` in place, with a history of its own that starts empty. */\n  readonly enter: (region: RegionEditing) => void;\n  /** Back to the page, dropping the region's history. */\n  readonly leave: () => void;\n  /**\n   * How many times the dimmed page was pressed this session: each press\n   * briefly highlights Done, the one way back, and changes nothing else.\n   */\n  readonly pulse: number;\n  /** Count one press on the dimmed page. */\n  readonly pulseDone: () => void;\n  /**\n   * What a live region says now: the region's `entered` words after entering,\n   * its `left` words after leaving, empty before either.\n   */\n  readonly announcement: string;\n  /**\n   * The definitions the region is drawn from now, while one is edited: the\n   * host's current ones, else those it was entered with.\n   */\n  readonly definitions?: DefinitionsById;\n}\n\n/** The arguments the region's state takes beyond its own document. */\nexport type RegionStateArgs = Omit<\n  UseEditorStateArgs,\n  \"initialDocument\" | \"definitions\" | \"stored\" | \"session\"\n> & {\n  /**\n   * The definitions the host draws component placements from now, which a\n   * region edited in place is drawn and judged by over the ones it was\n   * entered with: a component made or loaded while it is edited is known to\n   * it at once, its history kept.\n   */\n  readonly definitions?: DefinitionsById;\n};\n\n/** The page as the target: one value, so a render compares it by identity. */\nconst PAGE_TARGET: EditingTarget = { kind: \"page\" };\n\n/** The region state's document while no region is edited. */\nconst NO_REGION: BlockDocument = {\n  formatVersion: 1,\n  kind: \"component\",\n  nodes: [],\n};\n\n/**\n * The editing target for an editor whose page state is `page`.\n *\n * The region's state is always mounted, so entering and leaving change which\n * state is active without mounting anything: each entry is a new session of\n * it (`useEditorState`'s `session`), started from the region's document with\n * nothing selected and an empty history, and leaving starts it again on an\n * empty document, which drops that history. The page's selection is never\n * touched, so it is as it was when the author comes back.\n *\n * `args` are what the region's edits are judged by beside its own document:\n * the host's caps, refusal reporting and locks, as the page's are.\n */\nexport function useEditingTarget(\n  page: EditorState,\n  args: RegionStateArgs = {}\n): EditingTargetState {\n  const [target, setTarget] = useState<EditingTarget>(PAGE_TARGET);\n  const [pulse, setPulse] = useState(0);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const editing = target.kind === \"region\" ? target : undefined;\n  const { definitions: current, ...judged } = args;\n  const definitions =\n    editing === undefined ? undefined : (current ?? editing.definitions);\n  const region = useEditorState({\n    ...judged,\n    initialDocument: editing?.document ?? NO_REGION,\n    ...(definitions === undefined ? {} : { definitions }),\n    // The target itself names the session: every entry is a new object, so\n    // entering again, even the same region, starts from an empty history.\n    session: target,\n  });\n\n  const enter = useCallback((next: RegionEditing) => {\n    setTarget({ kind: \"region\", ...next });\n    setPulse(0);\n    setAnnouncement(current => said(current, next.words.entered));\n  }, []);\n  // Read when leaving rather than closed over, so a Done bound by an older\n  // render still says the words of the region being left.\n  const latestTarget = useRef(target);\n  latestTarget.current = target;\n  const leave = useCallback(() => {\n    const leaving = latestTarget.current;\n    if (leaving.kind !== \"region\") return;\n    setTarget(PAGE_TARGET);\n    setAnnouncement(current => said(current, leaving.words.left));\n  }, []);\n  const pulseDone = useCallback(() => setPulse(count => count + 1), []);\n\n  const active = editing === undefined ? page : region;\n  return useMemo(\n    () => ({\n      target,\n      active,\n      enter,\n      leave,\n      pulse,\n      pulseDone,\n      announcement,\n      ...(definitions === undefined ? {} : { definitions }),\n    }),\n    [target, active, enter, leave, pulse, pulseDone, announcement, definitions]\n  );\n}\n\n/**\n * `message` as a live region's next text. A live region does not say text\n * that did not change, so the same words twice running (leaving the header,\n * then the footer) differ by a zero-width space that is not read aloud.\n */\nfunction said(previous: string, message: string): string {\n  return previous.replace(/​$/, \"\") === message ? `${message}​` : message;\n}\n\n/**\n * What the canvas draws as the region being edited: its area, the region\n * state's LIVE document and its definitions, or nothing while the page is\n * the target. Derived from the editing target, so the canvas cannot draw one\n * region while the panels edit another.\n */\nexport function canvasEditingOf(\n  editing: Pick<EditingTargetState, \"target\" | \"active\" | \"definitions\">\n):\n  | {\n      readonly area: RegionArea;\n      readonly document: BlockDocument;\n      readonly definitions?: DefinitionsById;\n    }\n  | undefined {\n  const { target } = editing;\n  if (target.kind !== \"region\") return undefined;\n  const definitions = editing.definitions ?? target.definitions;\n  return {\n    area: target.area,\n    document: editing.active.document,\n    ...(definitions === undefined ? {} : { definitions }),\n  };\n}\n\n/**\n * What Escape does once nothing inside the region is selected and no popover\n * is open (the keyboard's Escape has already cleared those, innermost\n * first): it ends the region's editing as Done does, the host's `done` where\n * it asks first about unsaved changes, else at once. While the page is the\n * target it runs the host's own `otherwise`.\n *\n * For `BlockKeyboardActions`'s `onEscapeWithoutSelection`.\n */\nexport function regionEscape(\n  editing: Pick<EditingTargetState, \"target\" | \"leave\">,\n  {\n    done,\n    otherwise,\n  }: { readonly done?: () => void; readonly otherwise?: () => void }\n): () => void {\n  return () => {\n    if (editing.target.kind === \"region\") (done ?? editing.leave)();\n    else otherwise?.();\n  };\n}\n","\"use client\";\n\n/**\n * The bar above the canvas while a region of the page's layout is edited in\n * place, for the shell's `canvasStrip` slot: the host's words for what is\n * edited and how far a change reaches (\"Editing the site header · changes\n * show on 11 pages\"), and Done, the one way back to the page.\n *\n * A press on the dimmed page changes nothing there, and briefly highlights\n * Done instead (`pulse`), so an author who clicked the page sees how to get\n * back to it.\n *\n * It holds the live region that announces entering and leaving, drawn\n * whether or not a region is edited: a live region that appears with its\n * first words is often not read at all. So the host draws this part always,\n * and it draws no bar while the page is edited.\n *\n * @module region-editing-bar\n * @experimental Settles with editing a header or footer in place.\n */\n\nimport { useEffect, useId, useState, type JSX } from \"react\";\n\nimport type { EditingTargetState } from \"./editing-target\";\n\n/** How long Done stays highlighted after a press on the dimmed page. */\nconst PULSE_MS = 900;\n\nexport interface RegionEditingBarProps {\n  /** The editing target, from `useEditingTarget`. */\n  editing: Pick<\n    EditingTargetState,\n    \"target\" | \"leave\" | \"pulse\" | \"announcement\"\n  >;\n  /**\n   * What Done runs: the host's, where it asks first about unsaved changes.\n   * Absent, Done leaves at once.\n   */\n  onDone?: () => void;\n}\n\nexport function RegionEditingBar({\n  editing,\n  onDone,\n}: RegionEditingBarProps): JSX.Element {\n  const { target } = editing;\n  const wordsId = useId();\n  const pulsing = usePulsing(editing.pulse);\n  return (\n    <>\n      <div\n        role=\"status\"\n        aria-live=\"polite\"\n        className=\"nx-sr-only\"\n        data-nx-region-announcer=\"\"\n      >\n        {editing.announcement}\n      </div>\n      {target.kind !== \"region\" ? null : (\n        <div className=\"nx-region-bar\" data-nx-region-bar={target.area}>\n          <p className=\"nx-region-bar__words\" id={wordsId}>\n            {target.words.bar}\n          </p>\n          <button\n            type=\"button\"\n            className=\"nx-region-bar__done\"\n            // So a screen reader on Done hears what it ends.\n            aria-describedby={wordsId}\n            data-pulsing={pulsing ? \"\" : undefined}\n            onClick={onDone ?? editing.leave}\n          >\n            {target.words.done}\n          </button>\n        </div>\n      )}\n    </>\n  );\n}\n\n/**\n * Whether Done is highlighted now: for a moment after each new press counted\n * in `pulse`, and not before the first.\n */\nfunction usePulsing(pulse: number): boolean {\n  const [shown, setShown] = useState(0);\n  // Highlighted in the render that sees a new press, rather than an effect\n  // later, so the highlight never lags the press by a frame.\n  const [seen, setSeen] = useState(pulse);\n  if (seen !== pulse) {\n    setSeen(pulse);\n    setShown(pulse);\n  }\n  useEffect(() => {\n    if (shown === 0) return;\n    const timer = setTimeout(() => setShown(0), PULSE_MS);\n    return () => clearTimeout(timer);\n  }, [shown]);\n  return shown !== 0;\n}\n","/**\n * The component placement's exposed passage the canvas is editing in place,\n * as the inspector is told it.\n *\n * One rich-text editor serves the canvas and the inspector's fields, so a\n * field opened on the passage the canvas holds would take it from under the\n * author's caret. The inspector holds that field instead, and says where the\n * passage is being edited.\n *\n * @module canvas-passage\n */\nimport * as React from \"react\";\n\n/** A placement's exposed passage, by the placement and the exposure. */\nexport interface CanvasPassage {\n  readonly placementId: string;\n  readonly exposureId: string;\n}\n\n/** The passage the canvas is editing, or `null` while it edits none. */\nexport const CanvasPassageContext: React.Context<CanvasPassage | null> =\n  React.createContext<CanvasPassage | null>(null);\n","/**\n * The selected block's text sizes as the canvas draws them: the computed\n * font size and line height of the element it renders as, at the device\n * being edited.\n *\n * What a size field shows for a size reaching it from elsewhere when that\n * size reads a variable (Site text's `var(--…-font-size-h2)`): the size the\n * variable comes to where the author is looking, never its CSS. Carried by\n * context because only the fields that show an inherited value read it, and\n * the field table passes every field the same props.\n *\n * @module rendered-lengths\n */\nimport * as React from \"react\";\n\n/**\n * The text sizes the canvas reads, by CSS property, with the style\n * declaration's name for each: the one list both the reading and the fields\n * showing it go by.\n */\nexport const RENDERED_TEXT_SIZES = {\n  \"font-size\": \"fontSize\",\n  \"line-height\": \"lineHeight\",\n} as const;\n\n/**\n * Computed values by CSS property, as the canvas resolved them, for the\n * properties in `RENDERED_TEXT_SIZES`. A property absent here was not read.\n */\nexport type RenderedLengthsValue = Readonly<Record<string, string>>;\n\nexport const RenderedLengths: React.Context<RenderedLengthsValue> =\n  React.createContext<RenderedLengthsValue>({});\n","/**\n * The node a provenance question is asked about, and the ancestors whose rules\n * can reach it.\n *\n * `styleProvenance` needs a {@link StyleSubject} rather than a node id, because\n * deciding which recorded declaration a control is showing takes more than the\n * node: a value can arrive from the block type's defaults, from a named class\n * the node applies, or from an ANCESTOR's rule carrying a descendant selector.\n * The engine settles which of those wins; it cannot settle which of them exist\n * without being told what the node is and what is above it.\n *\n * Built here rather than at the call site because the panel renders one of these\n * per control, and a subject assembled per control is the document walked per\n * control — the same shape as the cascade walk the panel's own comments say must\n * not happen. One subject per selected node is enough: every control on the\n * panel is asking about the same node.\n *\n * **Ancestors are OUTERMOST FIRST**, which is what `styleOrigin` documents and\n * not what walking up produces. The walk collects nearest-first and the order is\n * reversed once, here, so no caller has to remember which way round it goes.\n *\n * **Only the ancestors' own identity travels, not their ancestors.** The engine\n * types the list as `Omit<StyleSubject, \"ancestors\">`: an ancestor's ancestors\n * are already in the same flat list, and nesting them would present one node\n * twice with nothing to say which copy a rule attached to.\n *\n * @module style-subject\n */\n\nimport type { BlockNode, StyleSubject } from \"@nextlyhq/blocks-engine\";\nimport {\n  MAX_CLASSES_PER_NODE,\n  findNode,\n  locateNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { nodeElement } from \"../canvas/canvas\";\n\n/** One node's own identity, without the chain above it. */\ntype SubjectNode = Omit<StyleSubject, \"ancestors\">;\n\n/**\n * The identity a rule can attach to, taken from a node.\n *\n * `classes` is passed through rather than defaulted to an empty array: the\n * engine reads `classIds` as optional, and an empty array and an absent one are\n * the same answer expressed twice.\n *\n * The SHAPE is checked rather than trusted, and that is not defensive habit. A\n * stored document is untrusted, and the compiler treats a `classes` that is not\n * an array as referencing no classes at all. Forwarded raw, a string would reach\n * `styleOrigin`, whose membership test is `.includes(origin.id)` — which a\n * STRING also answers, by substring. A node storing `classes: \"card-primary\"`\n * would then report `.card` as the winning origin for a class the canvas emitted\n * no token for.\n *\n * WHICH members survive follows the compiler, in both directions, because the\n * question this answers is \"did the rendered element carry this token\" and only\n * the compiler decides that.\n *\n * Read to `MAX_CLASSES_PER_NODE` BY INDEX, not filtered then capped. The\n * compiler's window counts malformed members toward the limit, so a node whose\n * 30th entry is a number has a different 64th applied class than one whose\n * entries are all strings. Taking the cap after filtering would silently shift\n * that window and admit a class the canvas emitted no token for.\n *\n * Malformed members are skipped INDIVIDUALLY rather than voiding the array. An\n * earlier version required every member to be a string and dropped all of them\n * otherwise — which turned one bad entry, from a forgiving import or a hand\n * edit, into a block whose every class-sourced value reported as set by nobody\n * while the canvas plainly showed `.card` winning. The compiler skips what it\n * cannot read and applies the rest, and this has to agree with it.\n *\n * Over-long ids are left in rather than filtered: the compiler keeps them too,\n * and a string too long to name a class matches no class id, so the membership\n * test answers the same either way.\n */\nfunction identityOf(node: BlockNode): SubjectNode {\n  const subject: { -readonly [K in keyof SubjectNode]: SubjectNode[K] } = {\n    nodeId: node.id,\n    blockType: node.type,\n  };\n  const classes = node.classes;\n  if (Array.isArray(classes)) {\n    subject.classIds = classes\n      .slice(0, MAX_CLASSES_PER_NODE)\n      .filter((id): id is string => typeof id === \"string\");\n  }\n  return subject;\n}\n\n/**\n * The subject for one node of a document, or `undefined` when it holds no such\n * node.\n *\n * Undefined is a real answer rather than a failure: a selection can outlive the\n * node it names — an undo, or an edit applied from another surface — and a\n * caller that received an empty subject instead would ask about a node that is\n * not there and be told, confidently, that every control is unset.\n */\nexport function styleSubjectFor(\n  nodes: readonly BlockNode[],\n  nodeId: string\n): StyleSubject | undefined {\n  const editable = nodes as BlockNode[];\n  const node = findNode(editable, nodeId);\n  if (node === undefined) return undefined;\n\n  const ancestors: SubjectNode[] = [];\n  /*\n   * The ids already visited, the node's own included, so this loop cannot\n   * revisit a node however the document is shaped. The same guard\n   * `contrastObscuredAbove` uses for the same walk: two cycle guards written\n   * differently in one package are two answers to whether a document\n   * terminates.\n   *\n   * It does NOT make this function safe on a cyclic document, and the\n   * distinction is worth stating rather than implying. `locateNode` walks the\n   * whole tree to find a parent, and that walk recurses — measured, a slot cycle\n   * raises `RangeError: Maximum call stack size exceeded` inside it, before this\n   * loop runs at all. Terminating on a malformed document is the engine's\n   * traversal to guarantee, not this module's, and it is being fixed there.\n   */\n  const seen = new Set<string>([nodeId]);\n  let current = nodeId;\n  for (;;) {\n    const parent = locateNode(editable, current)?.parent;\n    if (parent === undefined || seen.has(parent.id)) break;\n    seen.add(parent.id);\n    ancestors.push(identityOf(parent));\n    current = parent.id;\n  }\n\n  // Reversed once, here: the walk produces nearest-first and the engine reads\n  // outermost-first.\n  return { ...identityOf(node), ancestors: ancestors.reverse() };\n}\n\n/**\n * The element a node's own box is rendered as, read off the canvas.\n *\n * The typographic baseline compiles to `:where(h1)` — a rule on the ELEMENT —\n * so nothing else in a subject can say whether one reaches this node. The\n * document cannot answer it either: the tag lives inside a block's render, and\n * `core/heading` picks it from a PROP while `core/rich-text` renders a plain\n * `div` with its headings INSIDE. A reader that guessed from the block type\n * would get the second case backwards and report a heading baseline as styling\n * a rich-text block's own box.\n *\n * So the canvas answers. It is the page a visitor sees, so its tag cannot\n * disagree with the cascade the browser actually ran, and it needs no new field\n * on the block contract — which every third-party block author would otherwise\n * inherit. `core/rich-text` comes out right for free: its root really is a\n * `div`, so a heading baseline correctly does not reach that block's own\n * font-size control.\n *\n * `undefined` when the node is not drawn. Read AFTER a commit rather than\n * during a render, because the canvas and this panel re-render together and the\n * DOM still holds the previous tag while the panel's body is running — asking\n * then reports the level an author just changed away from.\n */\nexport function renderedTagOf(\n  root: HTMLElement | null | undefined,\n  nodeId: string | null\n): string | undefined {\n  if (root == null || nodeId === null) return undefined;\n  /*\n   * The id NEVER reaches a selector. The elements carrying the attribute are\n   * enumerated and their values compared as ordinary strings, which is the same\n   * shape `canvas-drag.tsx` uses to map painted elements back to nodes.\n   *\n   * Escaping was the wrong instinct and an incomplete one. A node id is author\n   * data — an imported or API-authored document can carry any string, since the\n   * document model imposes no character grammar on ids — and `querySelector`\n   * THROWS on invalid syntax rather than returning nothing. Quoting the value\n   * handles `\"` and `\\`, but a raw line break is not representable in a CSS\n   * string at all, so a single id containing one would take the whole style\n   * inspector down from inside an effect. Comparing strings has no such class of\n   * input.\n   *\n   * The cost is a walk over the marked elements instead of an indexed lookup. It\n   * runs once per commit for one selected node, over the elements of one page.\n   */\n  return markedElementOf(root, nodeId)?.tagName.toLowerCase();\n}\n\n/**\n * The element a node renders as, for a reader that may hold no root or no id.\n *\n * An ADAPTER over {@link nodeElement}, not a second search. That function is\n * the one rule for mapping an id to its element, and it knows what this file\n * once did not: a component instance renders no element carrying its own id —\n * it is replaced by the definition's tree — so a lookup over the node-id\n * attribute alone finds nothing for a selected instance, and the style\n * inspector then reads its tag and orientation as unknown for as long as it is\n * selected. Every reader of \"which element is this node\" goes through the same\n * rule so that answer cannot drift between them.\n */\nexport function markedElementOf(\n  root: HTMLElement | null | undefined,\n  nodeId: string | null\n): Element | undefined {\n  if (root == null || nodeId === null) return undefined;\n  return nodeElement(root, nodeId) ?? undefined;\n}\n","/**\n * Which way the element being edited runs, so a box of sides can be drawn true.\n *\n * A per-side property is stored in LOGICAL terms — block start, inline start —\n * and a box is a PHYSICAL picture. Turning one into the other is not a constant:\n * inline start is the left edge in a left-to-right context and the right edge\n * in Arabic or Hebrew, and in a vertical writing mode the block axis is\n * horizontal, so \"block start\" is a side rather than the top.\n *\n * The admin chrome is not the answer to that question. An author editing an\n * Arabic site in an English admin is looking at a left-to-right panel and a\n * right-to-left page, so a box oriented by the panel points at the opposite\n * edge from the one the value moves.\n *\n * ## The canvas answers, for the same reason it answers about the tag\n *\n * `renderedTagOf` in `style-subject` already takes this position: the canvas is\n * the page a visitor sees, so it cannot disagree with the cascade the browser\n * actually ran, and asking it needs no new field on the block contract. Writing\n * mode is if anything more clearly its question — it is inherited, so nothing\n * about the node alone decides it, and a site style or an ancestor block can\n * set it. Both questions therefore find the element the same way, through\n * `markedElementOf`.\n *\n * ## The CSS does the mapping, so no table of edges lives here\n *\n * The caller puts these values on the BOX so its grid resolves in the same\n * terms the element does: grid columns run along the inline axis and rows along\n * the block axis, so column one is the inline start in either direction and a\n * vertical mode transposes the pair. A hand-written map from logical side to\n * physical edge would be a second implementation of something CSS already does,\n * and would have to be kept in step with it.\n *\n * ## Unresolved is a THIRD answer, and it must not collapse into \"left to right\"\n *\n * The element may not be drawn yet — the canvas mounts after styles load, and a\n * block whose render returns a promise shows a fallback first. A reading that\n * fails is then indistinguishable from one that found a left-to-right element,\n * and the box would draw a confident picture of the wrong edges. So this\n * reports absence, and the caller draws four labelled rows instead, which name\n * their side in words and are true whichever way the element runs.\n *\n * ## A look is edited for the site, so the site's direction answers for it\n *\n * A look (a block style) has no element of its own on the canvas: it is\n * edited for every block that wears it. Its box is drawn in the site's own\n * direction, read from the canvas root, which is the same box a block of that\n * site shows. Only where the canvas cannot say does it fall back to left to\n * right, the direction a site has when it states none. See `siteOrientationOf`.\n *\n * @module side-orientation\n */\nimport { markedElementOf } from \"./style-subject\";\n\n/** How the edited element runs, in the two properties a box grid needs. */\nexport interface SideOrientation {\n  /** The element's `writing-mode`, which decides the axes. */\n  readonly writingMode: string;\n  /** The element's `direction`, which decides which end of the inline axis starts. */\n  readonly direction: string;\n  /**\n   * How the element lays out its children, read in the same measurement, so\n   * alignment icons follow the layout the canvas draws: its `display` and\n   * `flex-direction`. Absent where none was measured.\n   */\n  readonly display?: string;\n  readonly flexDirection?: string;\n}\n\n/**\n * The orientation of the node's drawn element, or `undefined`.\n *\n * @param root - the canvas root the node is drawn under\n * @param nodeId - the block being edited\n * @returns the element's writing mode and direction, or `undefined`\n */\nexport function orientationOf(\n  root: HTMLElement | null | undefined,\n  nodeId: string | null\n): SideOrientation | undefined {\n  return orientationOfElement(markedElementOf(root, nodeId));\n}\n\n/**\n * The orientation of one element, or `undefined` when it cannot be read.\n *\n * @param element - the element to measure\n * @returns its writing mode and direction, or `undefined`\n */\nexport function orientationOfElement(\n  element: Element | null | undefined\n): SideOrientation | undefined {\n  if (element === null || element === undefined) return undefined;\n  const style = element.ownerDocument.defaultView?.getComputedStyle(element);\n  if (style === undefined) return undefined;\n  const writingMode = style.writingMode;\n  const direction = style.direction;\n  /*\n   * A style answering with neither is not a resolved element, and taking those\n   * empty strings as \"horizontal, left to right\" is the silent default this\n   * module exists to refuse. It is also the ordinary case under jsdom, which\n   * computes neither property — so a unit test asserting the box appears is\n   * asserting something only a real browser can produce, and the tests beside\n   * this one stub the computed style rather than pretend otherwise.\n   */\n  if (writingMode === \"\" || direction === \"\") return undefined;\n  return {\n    writingMode,\n    direction,\n    display: style.display,\n    flexDirection: style.flexDirection,\n  };\n}\n\n/** The direction a site has when it states none: horizontal, left to right. */\nconst LEFT_TO_RIGHT: SideOrientation = {\n  writingMode: \"horizontal-tb\",\n  direction: \"ltr\",\n};\n\n/**\n * The site's own direction, read from the canvas root, for editing that has\n * no element of its own on the canvas (a look).\n *\n * Only the axes are taken. The root's layout (`display`, `flex-direction`) is\n * the page's, not the block a look styles, so alignment icons are left to\n * draw as they do with no layout measured.\n *\n * Left to right where the root can't be read (not drawn yet, or no canvas):\n * a look is edited for the whole site, and a site that states no direction\n * runs left to right.\n *\n * @param root - the canvas root the page is drawn under\n * @returns the site's writing mode and direction\n */\nexport function siteOrientationOf(\n  root: HTMLElement | null | undefined\n): SideOrientation {\n  const measured = orientationOfElement(root);\n  if (measured === undefined) return LEFT_TO_RIGHT;\n  return { writingMode: measured.writingMode, direction: measured.direction };\n}\n","/**\n * What the CANVAS says about the selected node, read as one answer.\n *\n * Two questions are asked of the same element and they are asked together: the\n * tag it is drawn as, which decides whether an element-level rule such as the\n * typographic baseline reaches it, and the axes it runs on, which decide which\n * physical edge each logical side of a box is. Both are properties of the\n * rendered page rather than of the document, and neither can be answered from\n * the block type — `core/heading` picks its level from a prop, and writing mode\n * is inherited, so an ancestor or a site style can set it.\n *\n * ONE hook rather than two, and that is not tidiness. Asked separately they\n * attach two `MutationObserver`s to the same canvas and walk its marked\n * elements twice per commit to reach the same element, and the two answers can\n * be a render apart — the panel would then be drawing a box for one reading of\n * the selection while naming the tag from another.\n *\n * Its own module, and owned by the inspector WRAPPER rather than by the style\n * panel: the panel that decides which control shows a value should not also\n * hold a subscription to the DOM. Passed down as an answer, exactly as\n * `cascade` and `breakpoints` are.\n *\n * OBSERVED on two axes, and both are load-bearing. The canvas mounts only after styles have loaded while the\n * inspector stays mounted throughout, and a block whose `render` returns a\n * promise commits a Suspense fallback first and its real root later — in both\n * cases the marked element does not exist when an effect first runs. A one-shot\n * read would report the tag as unknown for the rest of the session, and the box\n * as unorientable, which is the state this whole tier exists to fix.\n *\n * @module use-canvas-reading\n */\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport { RENDERED_TEXT_SIZES } from \"../inspector/style-inspector/rendered-lengths\";\nimport {\n  orientationOfElement,\n  siteOrientationOf,\n  type SideOrientation,\n} from \"../styles/side-orientation\";\nimport { markedElementOf } from \"../styles/style-subject\";\n\nimport { observeRenderedTree } from \"./rendered-tree\";\n\n/**\n * What the panel knows that can change the answer without moving an element.\n *\n * The axes are a COMPUTED property, so they move for reasons no mutation\n * reports: a forced state selects different rules, a breakpoint or preview\n * width changes which queries match, and new site styles change what is\n * inherited. None of those adds, removes or re-marks a node, and watching\n * attributes broadly is not open to us — `rendered-tree` records that both\n * observers here WRITE attributes inside the tree they watch, so a broad filter\n * re-enters for as long as the canvas is mounted.\n *\n * So the signals are taken from the panel, which already models every one of\n * them, rather than inferred from the DOM.\n *\n * One gap remains and is worth naming: a restyle from OUTSIDE this model — a\n * stylesheet swapped by the host, or an ancestor `dir` toggled by something\n * that is not the editor — is not covered, and the box keeps the previous axes\n * until anything else here changes. It is drawn from a reading that was true\n * when taken, which is the reason an unreadable orientation draws rows rather\n * than guessing.\n */\nexport interface RestyleSignals {\n  /** The document, so a commit re-reads. */\n  readonly document: EditorState[\"document\"];\n  /** The forced state being previewed, which selects a different rule set. */\n  readonly state?: string | undefined;\n  /** The breakpoint the canvas is sized to, which changes what queries match. */\n  readonly breakpoint?: string | undefined;\n  /** The site's compiled styles, which decide what the element inherits. */\n  readonly cascade?: unknown;\n  /** The container the preview is measured against, for the same reason. */\n  readonly previewContainer?: string | undefined;\n}\n\n/** Everything the canvas can say about the selected node. */\nexport interface CanvasReading {\n  /** The element the node is drawn as, lowercased, or `undefined` if not drawn. */\n  readonly tag: string | undefined;\n  /**\n   * The element's writing mode and direction, or `undefined` if unreadable.\n   *\n   * `undefined` means NOT KNOWN rather than left-to-right, and a caller must\n   * keep those apart: a box of logical sides drawn on an unknown orientation is\n   * a positional claim with nothing behind it.\n   */\n  readonly orientation: SideOrientation | undefined;\n  /**\n   * The address of the picture the node draws, the node itself or the one\n   * inside it (a link or a figure around an image), or `undefined` for none.\n   * What the canvas really shows, so a control aimed at the picture (a focal\n   * point) shows the same one.\n   */\n  readonly picture?: string | undefined;\n  /** Where the canvas places that picture: its computed `object-position`. */\n  readonly picturePosition?: string | undefined;\n  /**\n   * The words of the quotation the node draws, the node itself or the one\n   * inside it (a figure around a quotation and its caption), or `undefined`\n   * for none. What the canvas really shows, so a bound quotation reads as\n   * its value rather than its stored words.\n   */\n  readonly words?: string | undefined;\n  /**\n   * The text sizes the node is drawn at, computed: `font-size` and\n   * `line-height`, at the device the canvas is sized to. What a size reaching\n   * a field as a variable (Site text's) comes to, which the inspector cannot\n   * read from the stored styles. `undefined` when the node isn't drawn.\n   */\n  readonly lengths?: Readonly<Record<string, string>> | undefined;\n}\n\n/** The node's computed text sizes, or `undefined` when it isn't drawn. */\nfunction lengthsOf(\n  element: Element | undefined | null\n): Readonly<Record<string, string>> | undefined {\n  if (element == null) return undefined;\n  const computed = element.ownerDocument.defaultView?.getComputedStyle(element);\n  if (computed === undefined) return undefined;\n  const lengths: Record<string, string> = {};\n  for (const [property, name] of Object.entries(RENDERED_TEXT_SIZES)) {\n    // Read by name, as the axes are: a declaration missing one gives none.\n    const value: unknown = computed[name];\n    if (typeof value === \"string\" && value !== \"\") lengths[property] = value;\n  }\n  return lengths;\n}\n\n/** Whether two readings of the text sizes agree. */\nfunction sameLengths(\n  a: Readonly<Record<string, string>> | undefined,\n  b: Readonly<Record<string, string>> | undefined\n): boolean {\n  return Object.keys(RENDERED_TEXT_SIZES).every(\n    property => a?.[property] === b?.[property]\n  );\n}\n\n/**\n * Roots that hand their media styles to a picture inside them: a link or a\n * figure around an image, whatever else they hold (a caption).\n */\nconst PICTURE_WRAPPERS: ReadonlySet<string> = new Set([\n  \"A\",\n  \"FIGURE\",\n  \"PICTURE\",\n]);\n\n/**\n * What the rich-text renderer draws a passage's pictures and galleries in:\n * its own figures, which a block's styles never reach, whether or not the\n * passage has words beside them.\n */\nconst RICH_TEXT_MEDIA = '[class*=\"nextly-rich-text\"]';\n\n/**\n * Whether an element shows words of its own, not of a block inside it.\n *\n * Text is what makes a root a passage: a picture among words is an inline one,\n * which no fit or focal point set on the passage reaches.\n */\nfunction hasOwnText(element: Element): boolean {\n  const walker = element.ownerDocument.createTreeWalker(\n    element,\n    NodeFilter.SHOW_TEXT\n  );\n  for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n    const words = (node.textContent ?? \"\").trim() !== \"\";\n    if (words && node.parentElement?.closest(\"[data-nx-node]\") === element) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * The image an element draws as its own picture, if it draws one.\n *\n * A link, a figure or a picture element hands its media styles on by design.\n * Any other root (a custom block's div or span around its picture) counts\n * only when that one picture is all it draws: a passage with an inline\n * picture styles its own root, and two pictures leave a single focal point\n * nothing to be aimed at.\n */\nfunction ownImage(element: Element | undefined | null): Element | undefined {\n  if (element == null) return undefined;\n  if (element.tagName === \"IMG\") return element;\n  // Its own, past any image a block inside it draws, and never one a\n  // passage it holds draws.\n  const owned = [...element.querySelectorAll(\"img\")].filter(\n    candidate =>\n      candidate.closest(\"[data-nx-node]\") === element &&\n      candidate.closest(RICH_TEXT_MEDIA) === null\n  );\n  if (PICTURE_WRAPPERS.has(element.tagName)) return owned[0];\n  return owned.length === 1 && !hasOwnText(element) ? owned[0] : undefined;\n}\n\n/** Where the canvas places a picture, as its window computes it. */\nfunction positionOf(image: Element | undefined): string | undefined {\n  if (image === undefined) return undefined;\n  const view = image.ownerDocument.defaultView;\n  const position = view?.getComputedStyle(image).objectPosition;\n  return position === undefined || position === \"\" ? undefined : position;\n}\n\n/** The address a picture shows: the source it chose, else the one it names. */\nfunction addressOf(image: Element | undefined): string | undefined {\n  if (image === undefined) return undefined;\n  const shown =\n    (image as HTMLImageElement).currentSrc || image.getAttribute(\"src\");\n  return shown === null || shown === \"\" ? undefined : shown;\n}\n\n/** Nothing known yet, shared so an unchanged reading keeps its identity. */\nconst NOTHING: CanvasReading = { tag: undefined, orientation: undefined };\n\n/** Whether two readings say the same thing, so state is left alone when they do. */\nfunction same(a: CanvasReading, b: CanvasReading): boolean {\n  return (\n    a.tag === b.tag &&\n    a.picture === b.picture &&\n    a.picturePosition === b.picturePosition &&\n    a.words === b.words &&\n    sameLengths(a.lengths, b.lengths) &&\n    a.orientation?.writingMode === b.orientation?.writingMode &&\n    a.orientation?.direction === b.orientation?.direction &&\n    // The layout too: alignment icons follow it, and it can change alone.\n    a.orientation?.display === b.orientation?.display &&\n    a.orientation?.flexDirection === b.orientation?.flexDirection\n  );\n}\n\n/**\n * The selected node's reading, measured once: found by its id, then asked\n * for its tag, its axes and its picture.\n */\nfunction readSelected(\n  canvasRoot: HTMLElement | null | undefined,\n  selectedId: string | null\n): CanvasReading {\n  const element = markedElementOf(canvasRoot, selectedId);\n  // Found once: the address and the placement are of the same picture.\n  const image = ownImage(element);\n  return {\n    tag: element?.tagName.toLowerCase(),\n    orientation: orientationOfElement(element),\n    picture: addressOf(image),\n    picturePosition: positionOf(image),\n    words: quotationOf(element),\n    lengths: lengthsOf(element),\n  };\n}\n\n/**\n * The words of the quotation an element draws as its own: itself when it is\n * one, else the one it holds directly (a figure's, beside its caption), and\n * never one a block inside it draws.\n */\nfunction quotationOf(element: Element | undefined | null): string | undefined {\n  if (element == null) return undefined;\n  const quotation =\n    element.tagName === \"BLOCKQUOTE\"\n      ? element\n      : element.querySelector(\":scope > blockquote\");\n  return quotation?.textContent ?? undefined;\n}\n\n/**\n * One answer measured from the canvas, kept current as the canvas changes.\n *\n * The one place the canvas is watched for a reading, so the selected block's\n * reading and the site's direction are re-read on the same events: a change\n * in the drawn tree, a resize of the canvas, and every restyle signal.\n *\n * @param canvasRoot - the canvas root the page is drawn under\n * @param selectedId - the block measured, or `null` for the canvas root itself\n * @param restyledBy - what can restyle the page without moving an element\n * @param measure - the reading, a module-level function so it never changes\n * @param sameAs - whether two readings say the same thing\n * @param initial - the answer on the first render, before the effect measures;\n *   given the root, so a reading cheap enough to take during render can be\n *   right from the first paint\n * @returns the newest reading\n */\nfunction useObservedReading<T>(\n  canvasRoot: HTMLElement | null | undefined,\n  selectedId: string | null,\n  restyledBy: RestyleSignals,\n  measure: (root: HTMLElement | null | undefined, id: string | null) => T,\n  sameAs: (a: T, b: T) => boolean,\n  initial: (root: HTMLElement | null | undefined) => T\n): T {\n  const { document, state, breakpoint, cascade, previewContainer } = restyledBy;\n  const [reading, setReading] = React.useState<T>(() => initial(canvasRoot));\n\n  React.useEffect(() => {\n    /*\n     * ONE walk for every answer. `markedElementOf` compares ids as strings\n     * over the marked elements rather than building a selector, because a\n     * node id is author data and `querySelector` throws on invalid syntax\n     * instead of missing — so finding the element twice would also be paying\n     * that walk twice.\n     *\n     * Compared by VALUE before storing, here and in the observer: the canvas\n     * mutates on every keystroke that reaches it, and storing a fresh object\n     * each time would re-render the whole inspector per character for an answer\n     * that had not moved.\n     */\n    const read = () => {\n      const next = measure(canvasRoot, selectedId);\n      setReading(current => (sameAs(current, next) ? current : next));\n    };\n    read();\n\n    if (canvasRoot == null) return;\n    const stopTree = observeRenderedTree(canvasRoot, read);\n    /*\n     * Also on RESIZE, because the axes can change with nothing in the tree\n     * moving at all. Writing mode and direction are inherited and can be set by\n     * a media or container query, so dragging the canvas across one of its own\n     * breakpoints changes the answer while adding, removing and re-marking no\n     * element — and the tree observer, which watches structure and the node id,\n     * has nothing to report. The box would then keep pointing at the edges the\n     * previous width implied.\n     *\n     * The canvas itself is the box being measured, so its own resize is the\n     * event: a query that matters here is answered by the canvas's width, and\n     * the admin window changing without the canvas changing cannot alter what a\n     * rule inside it matched.\n     */\n    // From the canvas's own window: a canvas rendered in a frame is laid out\n    // by that frame, the realm its observer has to come from.\n    const Sizes = canvasRoot.ownerDocument.defaultView?.ResizeObserver;\n    const sizes = typeof Sizes === \"function\" ? new Sizes(read) : undefined;\n    sizes?.observe(canvasRoot);\n    return () => {\n      stopTree?.();\n      sizes?.disconnect();\n    };\n    /*\n     * Every dependency here is something that can RESTYLE the page without\n     * moving an element, which is the class of change no observer above can\n     * see. A forced state applies a different rule set; a breakpoint or preview\n     * width changes which queries match; new site styles change what is\n     * inherited. Each is already modelled by the panel, so the axes are re-read\n     * from the signal rather than from a guess about the DOM.\n     */\n  }, [\n    canvasRoot,\n    selectedId,\n    document,\n    state,\n    breakpoint,\n    cascade,\n    previewContainer,\n    measure,\n    sameAs,\n  ]);\n\n  return reading;\n}\n\n/**\n * Read the selected node's tag and axes from the canvas, keeping them current.\n *\n * @param canvasRoot - the canvas root the page is drawn under\n * @param selectedId - the block being edited\n * @param restyledBy - what can restyle the page without moving an element\n * @returns the tag and orientation, each `undefined` when unreadable\n */\nexport function useCanvasReading(\n  canvasRoot: HTMLElement | null | undefined,\n  selectedId: string | null,\n  restyledBy: RestyleSignals\n): CanvasReading {\n  return useObservedReading(\n    canvasRoot,\n    selectedId,\n    restyledBy,\n    readSelected,\n    same,\n    // Nothing known until the effect has found the selected element.\n    () => NOTHING\n  );\n}\n\n/** Whether two site orientations name the same axes. */\nfunction sameAxes(a: SideOrientation, b: SideOrientation): boolean {\n  return a.writingMode === b.writingMode && a.direction === b.direction;\n}\n\n/**\n * The site's own direction, read from the canvas root and kept current, for\n * editing with no element of its own on the canvas (a look).\n *\n * @param canvasRoot - the canvas root the page is drawn under\n * @param restyledBy - what can restyle the page without moving an element\n * @returns the site's writing mode and direction, left to right where unread\n */\nexport function useSiteOrientation(\n  canvasRoot: HTMLElement | null | undefined,\n  restyledBy: RestyleSignals\n): SideOrientation {\n  return useObservedReading(\n    canvasRoot,\n    null,\n    restyledBy,\n    siteOrientationOf,\n    sameAxes,\n    // Measured on the first render too: one computed-style read of the root,\n    // so a right-to-left site's box is never first painted left to right.\n    siteOrientationOf\n  );\n}\n","/**\n * The site's looks as the Design panel lists them: one group per block type,\n * the block's own look first, then the looks its blocks can wear.\n *\n * Read from the same views the compiler reads, so a row is listed exactly\n * when its look takes effect: an own look as the engine reads it for its\n * type's base (`ownLooksRead`), and a worn look as the library renders it\n * (`sharedStyleRows`, which reads `usableSiteClasses`).\n *\n * @module block-look-rows\n * @experimental Settles with the Design panel's Block looks group.\n */\n\nimport {\n  blockDefaultsOf,\n  getBlock,\n  overlaidStyles,\n  ownLooksRead,\n  starredLooksOf,\n  type NamedClass,\n  type NodeStyles,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { usableSiteClasses } from \"../../styles/class-library\";\nimport {\n  sharedStyleName,\n  sharedStyleRows,\n  type SharedStyleRow,\n} from \"../../styles/shared-style-library\";\n\n/**\n * Which look is meant: its id and its block type together. Two block types'\n * own looks may share an id, since an own look claims none, so the type is\n * what tells them apart.\n */\nexport interface LookKey {\n  readonly id: string;\n  readonly blockType: string;\n}\n\n/** Whether a row is the look a key names. */\nexport function sameLook(\n  row: LookKey,\n  key: LookKey | null | undefined\n): boolean {\n  return (\n    key !== null &&\n    key !== undefined &&\n    row.id === key.id &&\n    row.blockType === key.blockType\n  );\n}\n\n/**\n * A look's key as one string, for a map keyed by look: its block type and id\n * together, as {@link sameLook} compares them. JSON, since an id is any\n * string and no separator could be told apart from one.\n */\nexport function lookKeyOf(look: LookKey): string {\n  return JSON.stringify([look.blockType, look.id]);\n}\n\n/** One look as the Design panel lists it. */\nexport interface BlockLookRow extends SharedStyleRow {\n  /** The block type the look belongs to. */\n  readonly blockType: string;\n  /**\n   * The block's own look: its styles are the site's edits to the type's\n   * base, it is never a class, so its class name is empty and it has no\n   * usage count of its own.\n   */\n  readonly own: boolean;\n  /**\n   * Another entry in the library carries the own look's id, whether another\n   * type's own look, a worn look or a shared style, so a write by id would\n   * reach both: the look is shown, and held from editing. Always false for a\n   * worn look.\n   */\n  readonly sharedId: boolean;\n  /**\n   * The look carries ★: the one a block of its type has until another is\n   * picked. The worn look the compiler reads as starred, or the block's own\n   * look while no worn look of its type is.\n   */\n  readonly starred: boolean;\n  /** Hidden from the block panel's tiles; a block already wearing it keeps it. */\n  readonly hidden: boolean;\n}\n\n/** One block type's looks, its own look first. */\nexport interface BlockLookGroup {\n  readonly blockType: string;\n  readonly rows: readonly BlockLookRow[];\n}\n\n/**\n * Every block type's looks, in the order their first look sits in the\n * library, each type's own look first and then its worn looks in the order\n * that decides precedence. A type with only an own look is still listed,\n * since its own look is still the site's to edit.\n */\nexport function blockLookGroups(\n  library: readonly NamedClass[],\n  suppliedIds: ReadonlySet<string>\n): BlockLookGroup[] {\n  const ownRead = ownLooksRead(library);\n  const shared = idsHeldTwice(library);\n  // Which look of each type carries ★, as the compiler reads it.\n  const starred = starredLooksOf(usableSiteClasses(library));\n  const own = new Map(\n    ownRead.map(entry => [\n      entry.blockType as string,\n      ownRow(entry, suppliedIds, {\n        sharedId: shared.has(entry.id),\n        starred: !starred.has(entry.blockType as string),\n      }),\n    ])\n  );\n  // The entries the rows are read from, as the compiler keeps them: the\n  // first usable one of an id, so a row's type and marks are its own.\n  const entryOf = new Map<string, NamedClass>();\n  for (const entry of usableSiteClasses(library)) {\n    if (!entryOf.has(entry.id)) entryOf.set(entry.id, entry);\n  }\n  const worn = new Map<string, BlockLookRow[]>();\n  for (const row of sharedStyleRows(library, suppliedIds)) {\n    const entry = entryOf.get(row.id);\n    const blockType = entry?.blockType;\n    if (row.look !== true || blockType === undefined) continue;\n    worn.set(blockType, [\n      ...(worn.get(blockType) ?? []),\n      {\n        ...row,\n        blockType,\n        own: false,\n        sharedId: false,\n        starred: starred.get(blockType)?.id === row.id,\n        hidden: entry?.hidden === true,\n      },\n    ]);\n  }\n  const types: string[] = [];\n  for (const entry of library) {\n    const type = (entry as { blockType?: unknown } | null)?.blockType;\n    if (typeof type !== \"string\" || types.includes(type)) continue;\n    if (own.has(type) || worn.has(type)) types.push(type);\n  }\n  return types.map(blockType => {\n    const first = own.get(blockType);\n    return {\n      blockType,\n      rows: [\n        ...(first === undefined ? [] : [first]),\n        ...(worn.get(blockType) ?? []),\n      ],\n    };\n  });\n}\n\n/**\n * The ids more than one library entry carries, whatever each entry is: a\n * write to the site's classes by id would reach every one of them.\n */\nfunction idsHeldTwice(library: readonly NamedClass[]): Set<string> {\n  const seen = new Set<string>();\n  const twice = new Set<string>();\n  for (const entry of library) {\n    // Stored data: an entry may be malformed, and one with no id shares none.\n    const id = (entry as { id?: unknown } | null)?.id;\n    if (typeof id !== \"string\") continue;\n    if (seen.has(id)) twice.add(id);\n    seen.add(id);\n  }\n  return twice;\n}\n\n/** An own look as a row: no class selects it, so its class name is empty. */\nfunction ownRow(\n  entry: NamedClass,\n  suppliedIds: ReadonlySet<string>,\n  marks: { readonly sharedId: boolean; readonly starred: boolean }\n): BlockLookRow {\n  return {\n    id: entry.id,\n    name: sharedStyleName(entry),\n    slug: entry.slug,\n    className: \"\",\n    locked: entry.locked === true,\n    inCode: suppliedIds.has(entry.id),\n    look: true,\n    styles: entry.styles,\n    blockType: entry.blockType as string,\n    own: true,\n    sharedId: marks.sharedId,\n    starred: marks.starred,\n    // Never hidden: it is what a block of its type is with no look picked.\n    hidden: false,\n  };\n}\n\n/**\n * A block type's base as the site draws it: the block's own base styles with\n * the site's edits to its own look laid over. Every look's specimen of that\n * type is drawn on it, as the canvas draws the blocks.\n */\nexport function siteBaseOf(\n  library: readonly NamedClass[] | undefined,\n  blockType: string\n): NodeStyles | undefined {\n  const base = getBlock(blockType)?.baseStyles;\n  const edit = blockDefaultsOf(library ?? [])[blockType];\n  return edit === undefined ? base : overlaidStyles(base, edit);\n}\n\n/** Who an edit to a look reaches, in the words the editing bar shows. */\nexport function lookReachWords(\n  row: Pick<BlockLookRow, \"own\">,\n  blockTitle: string\n): string {\n  // A block's own look is the base every other look of the type is laid on,\n  // so an edit to it reaches every block of the type.\n  return row.own ? `every ${blockTitle}` : `every ${blockTitle} that wears it`;\n}\n\n/** The Default chip's description: what a block's own look is to its type. */\nexport function ownLookDescription(blockTitle: string): string {\n  return `Default · every ${blockTitle} starts from this look; other looks are laid on top`;\n}\n","\"use client\";\n\n/**\n * Taking the author to a setting someone asked for from outside the panel,\n * as a page check's item asks for the setting that fixes it: the panel shows\n * the setting's tab, opens its section, clears a search that would hide it,\n * and puts the cursor in its field.\n *\n * Once per ask: the editor counts each ask (`settingAsked.seq`), so a press\n * on the same item again asks again, while the panel drawn again for any\n * other reason moves nothing. The setting's section is read from the\n * settings index, the same answer \"Find a setting\" uses, so the section\n * opened is the one the row is drawn in.\n *\n * @module asked-setting\n */\nimport * as React from \"react\";\n\nimport type { SettingAsked } from \"../editor-asks\";\n\nimport { withSectionFold } from \"./panel-folds\";\nimport { usePanelFolds } from \"./panel-folds-context\";\nimport { useFilterState } from \"./settings-filter\";\nimport { filtering, type SettingEntry } from \"./settings-index\";\n\n/** How long the field is looked for while its section opens, in ms. */\nconst LOOK_FOR = 1000;\n/** How often it is looked for meanwhile. */\nconst LOOK_EVERY = 25;\n\n/** The field a setting's row is drawn with, where it is on screen. */\nfunction fieldOf(root: HTMLElement, setting: string): HTMLElement | null {\n  const row = [\n    ...root.querySelectorAll<HTMLElement>(\".nx-setting[data-setting]\"),\n  ].find(each => (each.dataset.setting ?? \"\").split(\" \").includes(setting));\n  if (row === undefined || row.closest(\"[hidden]\") !== null) return null;\n  // A field to type in first, then any control: a bound row's bind button\n  // comes before its field.\n  return (\n    row.querySelector<HTMLElement>(\n      \"textarea:not([disabled]), input:not([type=hidden]):not([disabled]), [contenteditable=true]\"\n    ) ??\n    row.querySelector<HTMLElement>(\n      \"button:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex='-1'])\"\n    )\n  );\n}\n\n/**\n * Put the cursor in the setting's field once it is drawn, looking again\n * while its section opens; `done` is called either way, and the returned\n * function stops the looking.\n */\nfunction focusWhenDrawn(\n  root: React.RefObject<HTMLElement | null>,\n  setting: string,\n  done: () => void\n): () => void {\n  let waited = 0;\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  const look = (): void => {\n    const field = root.current === null ? null : fieldOf(root.current, setting);\n    if (field !== null) {\n      field.scrollIntoView({ block: \"nearest\" });\n      field.focus();\n      done();\n      return;\n    }\n    waited += LOOK_EVERY;\n    if (waited >= LOOK_FOR) {\n      done();\n      return;\n    }\n    timer = setTimeout(look, LOOK_EVERY);\n  };\n  timer = setTimeout(look, 0);\n  return () => clearTimeout(timer);\n}\n\n/** What the panel lends the ask. */\nexport interface AskedSettingHost {\n  /** The ask, where there is one. */\n  readonly asked: SettingAsked | undefined;\n  /** The block the panel shows, or `undefined` while it shows none. */\n  readonly nodeId: string | undefined;\n  /** Show a tab. */\n  readonly choose: (tab: string) => void;\n  /** The block's settings, as the settings index lists them. */\n  readonly entries: () => readonly SettingEntry[];\n  /** The panel, which the setting's field is looked for in. */\n  readonly root: React.RefObject<HTMLElement | null>;\n}\n\n/** Answer an ask for one of the shown block's settings, once per ask. */\nexport function useAskedSetting(host: AskedSettingHost): void {\n  const { change } = usePanelFolds();\n  const filter = useFilterState();\n  // Read at the ask rather than tracked: the panel's own changes are no ask.\n  const latest = React.useRef({ host, change, filter });\n  latest.current = { host, change, filter };\n  const answered = React.useRef<number | undefined>(undefined);\n  const { asked, nodeId } = host;\n  React.useEffect(() => {\n    if (asked === undefined || asked.id !== nodeId) return;\n    if (asked.seq === answered.current) return;\n    const now = latest.current;\n    now.host.choose(asked.tab);\n    if (filtering(now.filter)) {\n      now.filter.setQuery(\"\");\n      now.filter.setOnlyChanged(false);\n    }\n    const entry = now.host\n      .entries()\n      .find(each => each.tab === asked.tab && each.id === asked.setting);\n    if (entry !== undefined && entry.sectionLabel !== \"\") {\n      now.change(folds =>\n        withSectionFold(folds, asked.tab, entry.sectionLabel, true)\n      );\n    }\n    // Answered once the field is reached or given up on, not once looked\n    // for: an effect run again (React's StrictMode does so at once) stops\n    // the looking first, and an ask marked answered then would never be.\n    return focusWhenDrawn(now.host.root, asked.setting, () => {\n      answered.current = asked.seq;\n    });\n  }, [asked, nodeId]);\n}\n","/**\n * The mark drawn beside a block's name, in the palette and in the layers tree.\n *\n * The engine names a CONCEPT — `\"columns\"`, `\"quote\"` — and this file is the\n * only place that decides what that concept looks like. That separation is the\n * whole point of the vocabulary: art direction changes here, and no block\n * definition, no plugin and no stored document changes with it.\n *\n * Every mark is DECORATIVE. A block's name is always rendered beside it as\n * text, so an icon that announced itself would make a screen reader say the\n * same thing twice, and one announcing as an unnamed image would be worse than\n * silence. The same bargain the layers badges already strike.\n */\nimport {\n  AudioLines,\n  Blocks,\n  Calendar,\n  ChevronsUpDown,\n  Code,\n  Columns3,\n  Component,\n  FileText,\n  Frame,\n  Grid3x3,\n  Heading,\n  Image,\n  Images,\n  Link,\n  List,\n  Map,\n  Minus,\n  MousePointerClick,\n  MoveVertical,\n  PanelTop,\n  PanelTopOpen,\n  Quote,\n  RectangleVertical,\n  Repeat,\n  ScanText,\n  Search,\n  ShoppingCart,\n  Square,\n  SquareCheck,\n  SquareStack,\n  Star,\n  StretchVertical,\n  Table2,\n  TrendingUp,\n  Type,\n  User,\n  Video,\n} from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\nimport type React from \"react\";\n\n/**\n * One drawing per concept in the engine's vocabulary.\n *\n * Written out rather than derived, because there is nothing to derive it from:\n * a concept and the glyph that reads as that concept are related by judgement,\n * not by rule. `blockIconsCoverTheVocabulary` in the tests is what holds this\n * table to `BLOCK_ICONS`, so a concept added to the engine and not drawn here\n * fails rather than silently falling back to the generic mark.\n *\n * **Every name here must exist at this package's DECLARED peer floor**, which\n * `package.json` puts at `lucide-react >=0.400.0` — not merely at whatever\n * version is installed while developing. Lucide renames icons and DROPS the old\n * names: `BarChart3`, `CheckSquare` and `Columns` are all gone from 0.544, and\n * `ChartColumn` and `SquareDashed` do not yet exist at 0.400. A name from\n * either end of that range makes the built shell, which keeps lucide external\n * and imports these statically, fail to link before a panel can render — every\n * block in the editor gone, for a decorative glyph.\n *\n * So a concept takes a long-standing name over the current canonical one where\n * they differ, and `everyConceptDrawsAGlyph` in the tests renders all of them.\n * Prefer that to raising the floor: widening what a host must install is a real\n * cost for every consumer, and it is not worth paying for a mark.\n */\nconst ICONS: Record<string, LucideIcon> = {\n  // Structure\n  section: PanelTop,\n  container: Square,\n  columns: Columns3,\n  column: RectangleVertical,\n  card: SquareStack,\n  grid: Grid3x3,\n  accordion: ChevronsUpDown,\n  panel: PanelTopOpen,\n  tabs: StretchVertical,\n  divider: Minus,\n  spacer: MoveVertical,\n  // Content\n  heading: Heading,\n  text: Type,\n  \"rich-text\": FileText,\n  list: List,\n  quote: Quote,\n  code: Code,\n  table: Table2,\n  link: Link,\n  // Media\n  image: Image,\n  gallery: Images,\n  video: Video,\n  audio: AudioLines,\n  embed: Frame,\n  map: Map,\n  // Interactive and data\n  button: MousePointerClick,\n  form: SquareCheck,\n  search: Search,\n  loop: Repeat,\n  chart: TrendingUp,\n  calendar: Calendar,\n  user: User,\n  cart: ShoppingCart,\n  star: Star,\n  component: Component,\n  // An entry's own content, drawn read-only inside its template: a page of\n  // lines inside a frame, the content and the template around it.\n  entry: ScanText,\n};\n\n/**\n * What is drawn for a block that names no icon, or names one this editor has\n * never heard of.\n *\n * The same mark for both, deliberately. An editor cannot tell a plugin author's\n * typo from a concept a newer engine added, and drawing a warning for one would\n * put a defect badge on a block that is merely newer than the editor reading\n * it. A block that draws SOMETHING keeps its row the same shape as every other,\n * which is what makes a list of them scannable at all.\n */\nconst FALLBACK: LucideIcon = Blocks;\n\n/** Props for {@link BlockIconMark}. */\nexport interface BlockIconMarkProps {\n  /** The concept the block named, if it named one. */\n  readonly icon?: string;\n  /** Edge length in pixels. */\n  readonly size?: number;\n}\n\n/**\n * Draw a block's mark.\n *\n * `Object.hasOwn` before the lookup, because the name is a string that reached\n * here from a block definition — a plugin's, in the general case — and this\n * table inherits from `Object.prototype`. An icon named `\"constructor\"` or\n * `\"toString\"` would otherwise resolve to an inherited FUNCTION, which is then\n * used as a JSX element type and throws while rendering the panel. The same\n * hazard the rich-text renderer already guards its node tables against.\n */\nexport function BlockIconMark({\n  icon,\n  size = 16,\n}: BlockIconMarkProps): React.JSX.Element {\n  const Mark =\n    icon !== undefined && Object.hasOwn(ICONS, icon)\n      ? (ICONS[icon] ?? FALLBACK)\n      : FALLBACK;\n  return (\n    <span className=\"nx-block-icon\" aria-hidden=\"true\">\n      <Mark size={size} />\n    </span>\n  );\n}\n\n/** The concepts this editor can draw. Exported for the coverage test. */\nexport const DRAWN_ICONS: readonly string[] = Object.keys(ICONS);\n","/**\n * What the selection's verbs offer, decided in two steps: what every surface\n * shows as the selection changes, and what the locks say once an author opens\n * a menu.\n *\n * Whether a slot's lock allows a verb is answered by trying the verb's edit\n * on a copy of the page, so asking it for every verb on every selection made\n * a click on a long page wait on a dozen trial edits nobody had asked for.\n * The toolbar and the keyboard layer draw from the first list, which asks\n * the locks nothing; a Layers lock, an edge or a missing grant still dims a\n * verb there, because those are read off the page directly. A menu that opens\n * reads the second list, which asks the locks about the verbs it holds. The\n * verbs whose availability is a full plan (saving as a pattern, and the\n * component verbs, which build the document they would store) are planned in\n * that second list too, so a click plans nothing. A pressed verb asks and\n * plans for itself, as it always has, so a lock or a plan still refuses it\n * with its reason. The editor keeps each lock answer for the version of the\n * page it was asked of (`kept-lock-answers`), so a menu, a second menu and a\n * keystroke share one trial per verb.\n *\n * @module selection-offer\n */\n\nimport type {\n  BlockDocument,\n  DocumentLimits,\n  NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { SharedStyleOffer } from \"../styles/shared-style-target\";\n\nimport {\n  depthMoveActions,\n  toolbarActions,\n  type ComponentVerbsOffer,\n  type DepthMoveAction,\n  type MoveJudge,\n  type MovePosition,\n  type ToolbarAction,\n} from \"./toolbar-actions\";\n\n/** The selection's verbs, and the depth moves the block menu adds. */\nexport interface SelectionVerbs {\n  readonly actions: ToolbarAction[];\n  readonly depthMoves: readonly DepthMoveAction[];\n}\n\n/** What a provider publishes for the surfaces below it. */\nexport interface SelectionOffer extends SelectionVerbs {\n  /**\n   * The same verbs with the locks asked, for a menu that is opening: worked\n   * out on the first call for this selection and page, and read back after.\n   */\n  readonly withLocks: () => SelectionVerbs;\n}\n\n/** What the verbs are decided from. */\nexport interface SelectionOfferInputs {\n  readonly document: BlockDocument;\n  readonly selectedId: string | null;\n  readonly selectedIds: readonly string[];\n  readonly nesting: NestingSource;\n  readonly mayCreatePattern: boolean;\n  readonly lockRefusalFor: EditorState[\"lockRefusalFor\"];\n  readonly components: ComponentVerbsOffer | undefined;\n  readonly offersEditComponent: boolean;\n  readonly sharedStyles: SharedStyleOffer | undefined;\n  readonly movePosition: MovePosition;\n  readonly placementRefusal: MoveJudge;\n  /** The editor's size limits, which the \"Turn into\" choices are judged under. */\n  readonly limits?: DocumentLimits;\n}\n\n/**\n * The verbs, with the locks asked and the planned verbs planned when `asked`,\n * or from the cheap rules alone when not.\n */\nfunction selectionVerbs(\n  inputs: SelectionOfferInputs,\n  asked: boolean\n): SelectionVerbs {\n  const ask = asked ? inputs.lockRefusalFor : undefined;\n  return {\n    actions: toolbarActions(\n      inputs.document,\n      inputs.selectedId,\n      inputs.selectedIds,\n      inputs.nesting,\n      inputs.mayCreatePattern,\n      ask,\n      inputs.components,\n      inputs.offersEditComponent,\n      inputs.sharedStyles,\n      asked,\n      inputs.limits\n    ),\n    depthMoves: depthMoveActions(\n      inputs.document,\n      inputs.selectedId,\n      inputs.selectedIds,\n      ask,\n      inputs.movePosition,\n      inputs.placementRefusal\n    ),\n  };\n}\n\n/**\n * The offer for the current selection, rebuilt only when one of its inputs\n * changes. The locks are asked on the first `withLocks` call for those\n * inputs, never while the selection merely changes.\n */\nexport function useSelectionOffer(\n  inputs: SelectionOfferInputs\n): SelectionOffer {\n  const {\n    document,\n    selectedId,\n    selectedIds,\n    nesting,\n    mayCreatePattern,\n    lockRefusalFor,\n    components,\n    offersEditComponent,\n    sharedStyles,\n    movePosition,\n    placementRefusal,\n    limits,\n  } = inputs;\n  return React.useMemo(() => {\n    const read: SelectionOfferInputs = {\n      document,\n      selectedId,\n      selectedIds,\n      nesting,\n      mayCreatePattern,\n      lockRefusalFor,\n      components,\n      offersEditComponent,\n      sharedStyles,\n      movePosition,\n      placementRefusal,\n      ...(limits === undefined ? {} : { limits }),\n    };\n    let locked: SelectionVerbs | undefined;\n    return {\n      ...selectionVerbs(read, false),\n      withLocks: () => (locked ??= selectionVerbs(read, true)),\n    };\n  }, [\n    document,\n    selectedId,\n    selectedIds,\n    nesting,\n    mayCreatePattern,\n    lockRefusalFor,\n    components,\n    offersEditComponent,\n    sharedStyles,\n    movePosition,\n    placementRefusal,\n    limits,\n  ]);\n}\n\n/** No verbs, held as one value so an empty answer keeps its identity. */\nconst NO_VERBS: readonly ToolbarAction[] = [];\n\n/** Tells whoever listens that the offer a provider shares has changed. */\nexport interface OfferSignal {\n  /** Listen for changes; answers the call that stops listening. */\n  readonly subscribe: (listener: () => void) => () => void;\n  readonly notify: () => void;\n}\n\n/** A signal with no listeners yet. */\nexport function offerSignal(): OfferSignal {\n  const listeners = new Set<() => void>();\n  return {\n    subscribe: listener => {\n      listeners.add(listener);\n      return () => listeners.delete(listener);\n    },\n    notify: () => {\n      for (const listener of listeners) listener();\n    },\n  };\n}\n\n/**\n * The shared verbs with the locks asked, for a menu drawn outside the\n * provider (the Layers row menu, the block card's menu) while it is open.\n *\n * Read when the menu opens, read again once the page has settled, and read\n * again whenever the provider's offer changes, without asking the locks in\n * between: a menu opened on a block that was not selected selects it as it\n * opens, and the provider takes in the new selection after this menu has\n * first drawn, and an edit, a save or new lock rules can change the answers\n * while it stays open. Each offer answers with the same list each time, so a\n * reading that has not changed draws nothing more.\n */\nexport function useAskedSharedVerbs(\n  verbs:\n    | {\n        readonly withLocks: () => readonly ToolbarAction[];\n        readonly subscribe?: OfferSignal[\"subscribe\"];\n      }\n    | undefined\n): readonly ToolbarAction[] {\n  const withLocks = verbs?.withLocks;\n  const subscribe = verbs?.subscribe;\n  const [asked, setAsked] = React.useState(() => withLocks?.() ?? NO_VERBS);\n  React.useEffect(() => {\n    const reread = () => setAsked(withLocks?.() ?? NO_VERBS);\n    reread();\n    return subscribe?.(reread);\n  }, [withLocks, subscribe]);\n  return asked;\n}\n","\"use client\";\n\n/**\n * The top of the inspector: which block this is, before anything it holds.\n *\n * Its icon, its type and the author's own label for it, a one-line description\n * from its definition, and a line for each lock that holds it. Rename, Lock or\n * Unlock and the block verbs sit in one \"⋯\" menu, so housekeeping never takes\n * the place at the top of the panel that says what is selected.\n *\n * **Rename** is in the menu and on a double-click of the title. The label is\n * stored on the node as `name` and shown in Layers and here; visitors never\n * see it. One rename is one entry in the history.\n *\n * **A block inside another it belongs to** says so: a picture in a gallery\n * reads \"Picture 2 · in Team photos\", with \"← Back to the gallery\" under it,\n * which selects the gallery.\n *\n * **Two kinds of lock, said apart.** The block's own Layers lock is an edit of\n * the page, so the menu offers Unlock to anyone editing it. A lock set by the\n * block this one sits in is the containing block's own rule, written in code,\n * so the card says what it fixes and who sets it, and offers no Unlock.\n *\n * @module block-card\n */\n\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n  Input,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../block-icon\";\nimport { useAskedSharedVerbs } from \"../canvas/selection-offer\";\nimport type { ToolbarActionId } from \"../canvas/toolbar-actions\";\nimport type { SharedBlockVerbs } from \"../shell/keyboard-actions\";\n\nimport { layersLockChangeable, type BlockLockStatus } from \"./inspector\";\n\n/**\n * The block verbs the card's menu runs, handed in by the host: the SAME verbs\n * and verdicts the toolbar, the context menu and the palette use, rather than\n * a second implementation here. A menu that decided for itself whether Delete\n * was allowed is how one surface comes to offer a verb another refuses.\n */\nexport type CardVerbs = SharedBlockVerbs;\n\n/** The verbs from the shared set that the card's menu offers, in order. */\nconst CARD_VERBS: readonly ToolbarActionId[] = [\n  \"duplicate\",\n  \"save-as-shared-style\",\n  \"turn-into-component\",\n  \"detach-component\",\n  \"duplicate-component\",\n  \"delete\",\n];\n\nexport interface BlockCardProps {\n  /** The block's icon concept, if it names one. */\n  readonly icon: string | undefined;\n  /** What the block is: \"Heading\", \"Image\". */\n  readonly type: string;\n  /** The author's own label for this block, empty when there is none. */\n  readonly name: string;\n  /** One line about the block, from its definition. */\n  readonly description: string;\n  /** Which locks hold it. */\n  readonly lock: BlockLockStatus;\n  /** Store a new label, or remove it with an empty one. Omitted withholds Rename. */\n  readonly onRename?: ((name: string) => void) | undefined;\n  /** Set or lift the Layers lock. Omitted withholds Lock and Unlock. */\n  readonly onLock?: ((locked: boolean) => void) | undefined;\n  /**\n   * Why Lock and Unlock are held here, when they are: shown disabled with\n   * this reason rather than left out, so the menu says why.\n   */\n  readonly lockHeld?: string | undefined;\n  /** The shared block verbs, when the host supplies them. */\n  readonly verbs?: CardVerbs | undefined;\n  /** The id the lock reason takes, so held controls can point at it. */\n  readonly reasonId?: string | undefined;\n  /**\n   * The block it belongs to, where it sits in one that names its children\n   * (a picture in a gallery): the title it reads by while it has no name of\n   * its own, the words after it, and the way back to the block it is in.\n   */\n  readonly placedIn?: PlacedIn | undefined;\n  /**\n   * The region of the page's layout the block is in, while that region is\n   * edited in place (\"Site header\"): the title then reads \"Navigation · in\n   * Site header\", so the author always sees which document they are editing.\n   */\n  readonly inRegion?: string | undefined;\n}\n\n/** A block named by where it sits, and the way back to what it sits in. */\nexport interface PlacedIn {\n  /** Its title while unnamed: \"Picture 2\". */\n  readonly title: string;\n  /** What follows the title: \"in Team photos\". */\n  readonly within: string;\n  /** The button's words: \"← Back to the gallery\". */\n  readonly backLabel: string;\n  readonly onBack: () => void;\n}\n\nexport function BlockCard({\n  icon,\n  type,\n  name,\n  description,\n  lock,\n  onRename,\n  onLock,\n  lockHeld,\n  verbs,\n  reasonId,\n  placedIn,\n  // Where it is while a region is edited in place, which only the title reads.\n  ...where\n}: BlockCardProps): React.JSX.Element {\n  const [renaming, setRenaming] = React.useState(false);\n  const reading = readingOf(name, type, placedIn, where.inRegion);\n  return (\n    <div className=\"nx-block-card\" data-block-card=\"\">\n      <div className=\"nx-block-card__head\">\n        {/* The block's mark on a tile, as the design draws it, so the card\n            reads as the block's own header rather than one more row. */}\n        <span className=\"nx-block-card__icon\">\n          <BlockIconMark icon={icon} size={16} />\n        </span>\n        <div className=\"nx-block-card__text\">\n          {renaming && onRename !== undefined ? (\n            <RenameField\n              name={name}\n              onDone={next => {\n                setRenaming(false);\n                if (next !== undefined && next !== name) onRename(next);\n              }}\n            />\n          ) : (\n            <CardTitle\n              reading={reading}\n              type={type}\n              onRename={\n                onRename === undefined ? undefined : () => setRenaming(true)\n              }\n            />\n          )}\n          {/* One line under the name. Cut short on screen, so the whole\n              sentence stays in the element, where a screen reader reads it,\n              and in its title, for a pointer. */}\n          {description === \"\" ? null : (\n            <p className=\"nx-block-card__description\" title={description}>\n              {description}\n            </p>\n          )}\n        </div>\n        <CardMenu\n          title={reading.own === \"\" ? type : reading.own}\n          locked={lock.layers}\n          onRename={\n            onRename === undefined ? undefined : () => setRenaming(true)\n          }\n          onLock={onLock}\n          lockHeld={lockHeld}\n          verbs={verbs}\n        />\n      </div>\n      {/* Under the head, so the title still says first what is selected. */}\n      {placedIn === undefined ? null : <BackButton placedIn={placedIn} />}\n      <LockLines lock={lock} reasonId={reasonId} />\n    </div>\n  );\n}\n\n/** What a card's title reads: the block's own words, and what follows. */\ninterface TitleReading {\n  /** Its name, else where it sits (\"Picture 2\"), else empty. */\n  readonly own: string;\n  /** What follows it: its type, or where it sits (\"in Team photos\"). */\n  readonly after: string;\n}\n\n/**\n * The block's own name, else where it sits, else nothing but its type. In a\n * region edited in place, its name or its type, then the region it is in.\n */\nfunction readingOf(\n  name: string,\n  type: string,\n  placedIn: PlacedIn | undefined,\n  inRegion: string | undefined\n): TitleReading {\n  if (placedIn === undefined && inRegion !== undefined) {\n    return { own: name === \"\" ? type : name, after: `in ${inRegion}` };\n  }\n  return {\n    own: name === \"\" ? (placedIn?.title ?? \"\") : name,\n    after: placedIn === undefined ? type : placedIn.within,\n  };\n}\n\n/** The title: its type alone, or its own words and what follows them. */\nfunction CardTitle({\n  reading,\n  type,\n  onRename,\n}: {\n  reading: TitleReading;\n  type: string;\n  onRename: (() => void) | undefined;\n}): React.JSX.Element {\n  const { own, after } = reading;\n  return (\n    <h2\n      className=\"nx-block-card__title\"\n      // Cut short on screen like the description below, so the whole\n      // name is in its tooltip for a pointer.\n      title={wholeTitle(own, type, after)}\n      onDoubleClick={onRename}\n    >\n      {own === \"\" ? (\n        type\n      ) : (\n        <>\n          {own}\n          <span className=\"nx-block-card__type\"> · {after}</span>\n        </>\n      )}\n    </h2>\n  );\n}\n\n/** The way back to the block this one sits in. */\nfunction BackButton({ placedIn }: { placedIn: PlacedIn }): React.JSX.Element {\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-block-card__back\"\n      onClick={placedIn.onBack}\n    >\n      {placedIn.backLabel}\n    </button>\n  );\n}\n\n/**\n * The label field, in place of the title while renaming.\n *\n * Committed on Enter and on blur, and dropped on Escape. `onDone` answers the\n * new label, or `undefined` when the author backed out.\n */\nfunction RenameField({\n  name,\n  onDone,\n}: {\n  name: string;\n  onDone: (next: string | undefined) => void;\n}): React.JSX.Element {\n  const [draft, setDraft] = React.useState(name);\n  const id = React.useId();\n  const hintId = `${id}-hint`;\n  // Escape blurs the field on its way out; without this the blur would then\n  // commit the draft the author just backed out of.\n  const cancelled = React.useRef(false);\n  return (\n    <div className=\"nx-block-card__rename\">\n      <label className=\"nx-sr-only\" htmlFor={id}>\n        Label\n      </label>\n      <Input\n        id={id}\n        value={draft}\n        autoFocus\n        placeholder=\"Label\"\n        aria-describedby={hintId}\n        onChange={event => setDraft(event.target.value)}\n        onBlur={() => onDone(cancelled.current ? undefined : draft.trim())}\n        onKeyDown={event => {\n          if (event.key === \"Enter\") {\n            event.preventDefault();\n            event.currentTarget.blur();\n          } else if (event.key === \"Escape\") {\n            event.preventDefault();\n            cancelled.current = true;\n            event.currentTarget.blur();\n          }\n        }}\n      />\n      <p id={hintId} className=\"nx-block-card__hint\">\n        Shown in Layers. Visitors never see it.\n      </p>\n    </div>\n  );\n}\n\n/** The card's \"⋯\" menu: Rename, Lock or Unlock, then the shared block verbs. */\nfunction CardMenu({\n  title,\n  locked,\n  onRename,\n  onLock,\n  lockHeld,\n  verbs,\n}: {\n  title: string;\n  locked: boolean;\n  onRename: (() => void) | undefined;\n  onLock: ((locked: boolean) => void) | undefined;\n  lockHeld: string | undefined;\n  verbs: CardVerbs | undefined;\n}): React.JSX.Element | null {\n  const offered = (verbs?.actions ?? []).filter(action =>\n    CARD_VERBS.includes(action.id)\n  );\n  /* Set when Rename is chosen, and acted on once the menu has closed. */\n  const renameNext = React.useRef(false);\n  if (onRename === undefined && onLock === undefined && offered.length === 0) {\n    return null;\n  }\n  return (\n    // Not modal: a modal menu marks the editor around it aria-hidden while\n    // its controls stay focusable (axe: aria-hidden-focus).\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild>\n        <button\n          type=\"button\"\n          className=\"nx-block-card__menu\"\n          aria-label={`Actions for ${title}`}\n        >\n          <span aria-hidden=\"true\">⋯</span>\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align=\"end\"\n        onCloseAutoFocus={event => {\n          if (!renameNext.current) return;\n          renameNext.current = false;\n          // Opened only now, once the menu has gone: a field mounted while it\n          // was closing lost its focus to the trigger the menu hands focus\n          // back to, and its blur ended the rename as it began.\n          event.preventDefault();\n          onRename?.();\n        }}\n      >\n        {onRename === undefined ? null : (\n          <DropdownMenuItem\n            onSelect={() => {\n              renameNext.current = true;\n            }}\n          >\n            Rename\n          </DropdownMenuItem>\n        )}\n        {onLock === undefined ? null : (\n          <MenuItem\n            label={locked ? \"Unlock\" : \"Lock\"}\n            reason={lockHeld}\n            onSelect={() => onLock(!locked)}\n          />\n        )}\n        <VerbItems offered={offered} verbs={verbs} />\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/**\n * The shared block verbs in the card's menu, after a separator, as the locks\n * answer them: drawn only while the menu is open, so the locks are asked when\n * it opens.\n */\nfunction VerbItems({\n  offered,\n  verbs,\n}: {\n  offered: CardVerbs[\"actions\"];\n  verbs: CardVerbs | undefined;\n}): React.JSX.Element | null {\n  const all = useAskedSharedVerbs(verbs);\n  if (offered.length === 0 || verbs === undefined) return null;\n  const asked = all.filter(action =>\n    offered.some(each => each.id === action.id)\n  );\n  return (\n    <>\n      <DropdownMenuSeparator />\n      {asked.map(action => (\n        <MenuItem\n          key={action.id}\n          label={action.label}\n          reason={action.enabled ? undefined : (action.reason ?? \"\")}\n          onSelect={() => verbs?.run(action.id)}\n        />\n      ))}\n    </>\n  );\n}\n\n/**\n * One item of the card's menu, held with its reason when it may not run.\n *\n * The reason is visible text rather than a tooltip, as the context menu does:\n * a disabled menu item takes no pointer and no keyboard focus, so a tooltip\n * there would reach nobody. An empty reason holds the item and says nothing.\n */\nfunction MenuItem({\n  label,\n  reason,\n  onSelect,\n}: {\n  label: string;\n  /** Why it is held, or `undefined` while it may run. */\n  reason: string | undefined;\n  onSelect: () => void;\n}): React.JSX.Element {\n  return (\n    <DropdownMenuItem disabled={reason !== undefined} onSelect={onSelect}>\n      {label}\n      {reason === undefined || reason === \"\" ? null : (\n        <span className=\"nx-block-card__reason\"> — {reason}</span>\n      )}\n    </DropdownMenuItem>\n  );\n}\n\n/** The card's title as one line: its own words and what follows, or the type. */\nfunction wholeTitle(own: string, type: string, after: string): string {\n  return own === \"\" ? type : `${own} · ${after}`;\n}\n\n/**\n * One line per lock that holds the block, each saying what it fixes and where\n * it is lifted. Words, never a colour or an icon alone.\n */\nfunction LockLines({\n  lock,\n  reasonId,\n}: {\n  lock: BlockLockStatus;\n  /** The id the reason a held control points at takes. */\n  reasonId?: string | undefined;\n}): React.JSX.Element | null {\n  const inherited = lock.layers ? undefined : lock.inheritedFrom;\n  // The reason held controls point at: the Layers lock when it holds, its own\n  // or one around it, which holds everything, and otherwise the slot's.\n  const layersHold = lock.layers || inherited !== undefined;\n  if (!layersHold && lock.slot === undefined) return null;\n  const [layersId, slotId] = layersHold\n    ? [reasonId, undefined]\n    : [undefined, reasonId];\n  return (\n    <ul className=\"nx-block-card__status\">\n      {lock.layers ? <OwnLockLine lock={lock} reasonId={layersId} /> : null}\n      {inherited === undefined ? null : (\n        <InheritedLockLine holder={inherited} reasonId={layersId} />\n      )}\n      {lock.slot === undefined ? null : (\n        <li data-lock={lock.slot.lock}>\n          {/* Its own element, so the sentence a held control points at is\n              exactly the reason. */}\n          <span id={slotId}>{lock.slot.reason}</span> That block sets it itself,\n          so it can&apos;t be unlocked here.\n        </li>\n      )}\n    </ul>\n  );\n}\n\n/** The line for a block locked in Layers itself, and where it is lifted. */\nfunction OwnLockLine({\n  lock,\n  reasonId,\n}: {\n  lock: BlockLockStatus;\n  reasonId: string | undefined;\n}): React.JSX.Element {\n  return (\n    <li data-lock=\"layers\">\n      <span id={reasonId}>\n        <strong>Locked</strong>: it can&apos;t be moved, deleted or edited.\n      </span>\n      {layersLockChangeable(lock) ? \" Unlock it from the block's menu.\" : null}\n    </li>\n  );\n}\n\n/**\n * The line for a block inside one locked in Layers, which is locked with it:\n * the sentence names the block that holds the lock, where it is lifted.\n */\nfunction InheritedLockLine({\n  holder,\n  reasonId,\n}: {\n  holder: string;\n  reasonId: string | undefined;\n}): React.JSX.Element {\n  return (\n    <li data-lock=\"layers-inherited\">\n      <span id={reasonId}>\n        <strong>Locked by {holder}</strong>: this block is inside it, so it\n        can&apos;t be moved, deleted or edited.\n      </span>{\" \"}\n      Unlock {holder} to change it.\n    </li>\n  );\n}\n\n/**\n * The card for several selected blocks: how many, and a menu with the one\n * control well defined across a set, the lock.\n */\nexport function SelectionCard({\n  count,\n  lock,\n  unlocking,\n  held,\n  onLock,\n}: {\n  count: number;\n  /** The lock across the set; `mixed` when some are locked. */\n  lock: \"locked\" | \"unlocked\" | \"mixed\";\n  /** Whether the menu unlocks rather than locks. */\n  unlocking: boolean;\n  /** How many of them sit where their own lock can't change here. */\n  held: number;\n  /** Lock or unlock the blocks it may change; omitted when there are none. */\n  onLock: (() => void) | undefined;\n}): React.JSX.Element {\n  const title = `${count} blocks`;\n  const verb = unlocking ? \"Unlock\" : \"Lock\";\n  return (\n    <div className=\"nx-block-card\" data-block-card=\"many\">\n      <div className=\"nx-block-card__head\">\n        <h2 className=\"nx-block-card__title\">{title}</h2>\n        {/* Not modal, as the single block's card menu above. */}\n        <DropdownMenu modal={false}>\n          <DropdownMenuTrigger asChild>\n            <button\n              type=\"button\"\n              className=\"nx-block-card__menu\"\n              aria-label={`Actions for ${title}`}\n            >\n              <span aria-hidden=\"true\">⋯</span>\n            </button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent align=\"end\">\n            <MenuItem\n              // \"the others\" only while some can change and some can't.\n              label={\n                held === 0 || held === count\n                  ? `${verb} all`\n                  : `${verb} the others`\n              }\n              reason={onLock === undefined ? SELECTION_LOCK_HELD : undefined}\n              onSelect={() => onLock?.()}\n            />\n          </DropdownMenuContent>\n        </DropdownMenu>\n      </div>\n      <SelectionLockLines lock={lock} held={held} count={count} />\n    </div>\n  );\n}\n\n/** Why the selection's lock item is held: no block in it may change its lock. */\nconst SELECTION_LOCK_HELD = \"The area each sits in fixes this.\";\n\n/** The selection's lock state, and how many have their lock fixed by an area. */\nfunction SelectionLockLines({\n  lock,\n  held,\n  count,\n}: {\n  lock: \"locked\" | \"unlocked\" | \"mixed\";\n  held: number;\n  count: number;\n}): React.JSX.Element | null {\n  if (lock === \"unlocked\" && held === 0) return null;\n  return (\n    <ul className=\"nx-block-card__status\">\n      {lock === \"unlocked\" ? null : (\n        <li data-lock={lock}>\n          {lock === \"locked\"\n            ? \"All of them are locked.\"\n            : \"Some of them are locked.\"}\n        </li>\n      )}\n      {held === 0 ? null : <li data-lock=\"held\">{heldWords(held, count)}</li>}\n    </ul>\n  );\n}\n\n/** The held line, in words that agree with how many it is about. */\nfunction heldWords(held: number, count: number): string {\n  if (held === count) {\n    return \"Each sits in an area that fixes its lock, so none can be locked or unlocked here.\";\n  }\n  return held === 1\n    ? \"1 of them sits in an area that fixes its lock, so it can't be locked or unlocked here.\"\n    : `${held} of them sit in areas that fix their lock, so they can't be locked or unlocked here.`;\n}\n","/**\n * What a designer does to a component's fields in its own view: expose a prop,\n * let placements hide a block, rename a field, remove one.\n *\n * Decides and draws nothing: which exposure a prop row holds, whether it can be\n * offered, the op an edit becomes and the sentences an author reads all live\n * here, where they can be asserted without a DOM. `component-fields-panel`\n * draws them.\n *\n * Every edit is asked of the engine's exposure planners, which hold the rules\n * (an id is never reused, a removal prunes the variants, a lock is judged when\n * the field is added), and written as ONE `envelope` op, so an exposure is one\n * undo step like any other edit and reaches autosave and recovery with the rest\n * of the document.\n *\n * @module component-fields\n */\nimport {\n  EXPOSED_PROPERTY_TYPES,\n  exposureTypeForProp,\n  findNode,\n  getBlock,\n  isComponentDocument,\n  isPlainRecord,\n  planExposeProperty,\n  planRemoveExposedSlot,\n  planRemoveExposure,\n  planRenameExposure,\n  sameStoredValue,\n  type BlockDocument,\n  type ComponentDocument,\n  type EnvelopeField,\n  type ExposedProperty,\n  type ExposedPropertyType,\n  type ExposureEdit,\n  type ExposureEditProblem,\n  type ExposureEditResult,\n  type PropSchema,\n  type RetiredExposures,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport { fieldLabel, propLabel } from \"../../inspector/inspector\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { blockLabel } from \"../add/inserter\";\n\n/**\n * What the host knows about the component being edited that its document does\n * not hold.\n *\n * @experimental Settles when the component editor ships.\n */\nexport interface ComponentFieldsHost {\n  /**\n   * Field and slot ids this component must never mint again: those its\n   * PUBLISHED definition holds, and every one it has retired. A draft that\n   * dropped a published field still has placements holding values under its\n   * id, so a new field minted under that id would take them over.\n   *\n   * `unavailable` while the host has not read them, or could not: adding a\n   * field then waits, with that sentence, rather than minting an id the live\n   * definition may still hold. Absent where the host has nothing live to\n   * reserve.\n   */\n  readonly reserved?: RetiredExposures | ReservedUnavailable;\n  /**\n   * How many documents place this component DIRECTLY (pages, Singles, other\n   * components and patterns), for the removal dialog: `complete` false makes\n   * the number a floor, said as \"at least\". Pages reaching it through another\n   * component are not counted, so it is never said as a count of pages.\n   */\n  readonly reach?: { readonly count: number; readonly complete: boolean };\n  /**\n   * How many distinct pages and Singles a change to the component reaches:\n   * placed on them directly, inside another component, or in a Layout that\n   * wraps them. What the banner over the view says; `complete` false makes\n   * it a floor, said as \"at least\". Absent while the host has no count.\n   */\n  readonly pages?: { readonly count: number; readonly complete: boolean };\n  /** The component's name, for the card heading its own view. */\n  readonly name?: string;\n}\n\n/** Why the ids a new field must avoid are not known, said to the author. */\nexport interface ReservedUnavailable {\n  readonly unavailable: string;\n}\n\n/** What an exposure is called in a sentence. The engine's names are code. */\nexport const EXPOSURE_TYPE_LABEL: Readonly<\n  Record<ExposedPropertyType, string>\n> = {\n  text: \"Text\",\n  richText: \"Rich text\",\n  image: \"Image\",\n  link: \"Link\",\n  visibility: \"Visibility\",\n  select: \"Choice\",\n};\n\n/** The component a document is, or `undefined` for a page or a pattern. */\nexport function editedComponent(\n  document: BlockDocument\n): ComponentDocument | undefined {\n  return isComponentDocument(document) ? document : undefined;\n}\n\n/**\n * The fields a component exposes, read as a list whatever is stored.\n *\n * An entry that is not a field (a stored or imported row holding `null`, or\n * one without an id or a type) is left out rather than read: the view has to\n * open on such a component so the author can repair it, and the envelope\n * check names the broken entry on save.\n */\nexport function exposedFields(\n  component: ComponentDocument\n): readonly ExposedProperty[] {\n  if (!Array.isArray(component.exposed)) return [];\n  return component.exposed.filter(isReadableField);\n}\n\nfunction isReadableField(entry: unknown): entry is ExposedProperty {\n  if (\n    !isPlainRecord(entry) ||\n    typeof entry.id !== \"string\" ||\n    typeof entry.label !== \"string\" ||\n    typeof entry.nodeId !== \"string\" ||\n    !(EXPOSED_PROPERTY_TYPES as readonly unknown[]).includes(entry.type)\n  ) {\n    return false;\n  }\n  // Every field but visibility drives a prop, named by its path.\n  return entry.type === \"visibility\" || typeof entry.propPath === \"string\";\n}\n\n/** The ids of the slots a component exposes. */\nexport function exposedSlotIds(\n  component: ComponentDocument\n): readonly string[] {\n  const slots: unknown = component.slots;\n  return slots !== null && typeof slots === \"object\" && !Array.isArray(slots)\n    ? Object.keys(slots)\n    : [];\n}\n\n/** The field exposing one prop of a node, if one does. */\nexport function propExposure(\n  component: ComponentDocument,\n  nodeId: string,\n  propPath: string\n): ExposedProperty | undefined {\n  return exposedFields(component).find(\n    field =>\n      field.type !== \"visibility\" &&\n      field.nodeId === nodeId &&\n      field.propPath === propPath\n  );\n}\n\n/** The field letting placements hide a node, if one does. */\nexport function visibilityExposure(\n  component: ComponentDocument,\n  nodeId: string\n): ExposedProperty | undefined {\n  return exposedFields(component).find(\n    field => field.type === \"visibility\" && field.nodeId === nodeId\n  );\n}\n\n/**\n * Whether a prop can be exposed, by its declared type: the field type it would\n * be, or the sentence saying why not. Shown rather than hidden, so an author\n * learns the prop is not exposable rather than wondering where the switch went.\n */\nexport function exposeOffer(\n  schema: PropSchema\n):\n  | { readonly type: Exclude<ExposedPropertyType, \"visibility\"> }\n  | { readonly reason: string } {\n  const type = exposureTypeForProp(schema);\n  if (type !== undefined) return { type };\n  return {\n    reason: `Pages can’t set a ${String(schema.type)} value, so this stays the same everywhere it is used.`,\n  };\n}\n\n/** Why the engine refused an edit, as an author reads it. */\nconst PROBLEM_SENTENCE: Readonly<Record<ExposureEditProblem, string>> = {\n  \"not-a-component\": \"Fields can only be added in a component’s own view.\",\n  \"unknown-exposure\": \"That field is no longer on this component.\",\n  \"unknown-node\": \"That block is no longer in this component.\",\n  \"unknown-prop\": \"That block no longer has this property.\",\n  \"not-exposable\":\n    \"Pages have no control for this property, so it stays the same everywhere it is used.\",\n  \"content-only\":\n    \"This block is in an area locked to its content, and this property isn’t content, so pages couldn’t change it. Loosen the lock to let each page change it.\",\n  \"invalid-label\": \"Give the field a name.\",\n  \"invalid-exposure\":\n    \"This component’s fields are stored in a shape that can’t be edited here. Remove the broken field first.\",\n  \"exceeds-limits\": \"This change would make the component too large to save.\",\n};\n\n/** The sentence for a refusal. */\nfunction problemSentence(problem: ExposureEditProblem): string {\n  return PROBLEM_SENTENCE[problem];\n}\n\n/**\n * The one op that turns `before`'s envelope into `after`'s, or `undefined`\n * when the two hold the same fields, slots and variants.\n */\nexport function envelopeOpFor(\n  before: ComponentDocument,\n  after: ComponentDocument\n): BuilderOp | undefined {\n  const patch: Record<string, unknown> = {};\n  const unset: EnvelopeField[] = [];\n  for (const field of [\"exposed\", \"slots\", \"variants\"] as const) {\n    const next = Object.hasOwn(after, field) ? after[field] : undefined;\n    const now = Object.hasOwn(before, field) ? before[field] : undefined;\n    if (sameStoredValue(now, next)) continue;\n    if (next === undefined) unset.push(field);\n    else patch[field] = next;\n  }\n  if (Object.keys(patch).length === 0 && unset.length === 0) return undefined;\n  return {\n    kind: \"envelope\",\n    patch,\n    ...(unset.length > 0 ? { unset } : {}),\n  };\n}\n\n/**\n * Every id this component may not mint: what the host reserved, and every id\n * the editing session has seen, so a field removed and then added again under\n * the same name gets a new id rather than the removed one's values.\n */\nexport function reservedIds(\n  host: RetiredExposures | ReservedUnavailable | undefined,\n  seen: RetiredExposures\n): RetiredExposures | ReservedUnavailable {\n  if (host !== undefined && \"unavailable\" in host) return host;\n  return {\n    properties: [...new Set([...(host?.properties ?? []), ...seen.properties])],\n    slots: [...new Set([...(host?.slots ?? []), ...seen.slots])],\n  };\n}\n\n/** The ids a component holds now, to add to what a session has seen. */\nexport function idsIn(component: ComponentDocument): RetiredExposures {\n  return {\n    properties: exposedFields(component)\n      .map(field => field.id)\n      .filter((id): id is string => typeof id === \"string\"),\n    slots: exposedSlotIds(component),\n  };\n}\n\n/** What an edit came to: applied, or refused with the sentence to show. */\nexport type FieldEditOutcome =\n  | { readonly applied: true; readonly edit: ExposureEdit }\n  | { readonly applied: false; readonly reason: string };\n\n/**\n * Apply a planned edit to the editor as one op, or say why it was not.\n *\n * The planner's result is applied as it stands: it is the whole edited\n * definition, judged by the same envelope check the save asks.\n */\nexport function applyFieldEdit(\n  editor: Pick<EditorState, \"apply\">,\n  component: ComponentDocument,\n  result: ExposureEditResult\n): FieldEditOutcome {\n  if (\"problem\" in result) {\n    return { applied: false, reason: problemSentence(result.problem) };\n  }\n  const op = envelopeOpFor(component, result.document);\n  if (op === undefined) return { applied: true, edit: result };\n  return editor.apply(op) === null\n    ? {\n        applied: false,\n        reason: \"This change could not be applied here. Nothing was changed.\",\n      }\n    : { applied: true, edit: result };\n}\n\n/** What the planners read from the editor and the host, gathered once. */\nexport interface FieldEditContext {\n  readonly editor: Pick<EditorState, \"apply\" | \"lockDefinitions\" | \"limits\">;\n  readonly component: ComponentDocument;\n  /** The ids a new field must avoid, or why they are not known yet. */\n  readonly reserved: RetiredExposures | ReservedUnavailable;\n}\n\n/**\n * The ids an addition must avoid, or the refusal to give while they are not\n * known: minting without them could take a live field's id.\n */\nfunction additionRetired(\n  reserved: FieldEditContext[\"reserved\"]\n): RetiredExposures | { readonly applied: false; readonly reason: string } {\n  return \"unavailable\" in reserved\n    ? { applied: false, reason: reserved.unavailable }\n    : reserved;\n}\n\n/** Expose one prop of a node as a new field under `label`. */\nexport function exposeProp(\n  context: FieldEditContext,\n  nodeId: string,\n  propPath: string,\n  label: string\n): FieldEditOutcome {\n  const { editor, component } = context;\n  const retired = additionRetired(context.reserved);\n  if (\"reason\" in retired) return retired;\n  return applyFieldEdit(\n    editor,\n    component,\n    planExposeProperty(\n      component,\n      { nodeId, propPath, label },\n      {\n        definitions: editor.lockDefinitions,\n        retired,\n        limits: editor.limits,\n      }\n    )\n  );\n}\n\n/** Let placements hide a node, through a new visibility field. */\nexport function exposeVisibility(\n  context: FieldEditContext,\n  nodeId: string,\n  label: string\n): FieldEditOutcome {\n  const { editor, component } = context;\n  const retired = additionRetired(context.reserved);\n  if (\"reason\" in retired) return retired;\n  return applyFieldEdit(\n    editor,\n    component,\n    planExposeProperty(\n      component,\n      { nodeId, visibility: true, label },\n      {\n        definitions: editor.lockDefinitions,\n        retired,\n        limits: editor.limits,\n      }\n    )\n  );\n}\n\n/** Rename a field; its id and every placement's value stay. */\nexport function renameField(\n  context: Omit<FieldEditContext, \"reserved\">,\n  id: string,\n  label: string\n): FieldEditOutcome {\n  const { editor, component } = context;\n  return applyFieldEdit(\n    editor,\n    component,\n    planRenameExposure(component, id, label, editor.limits)\n  );\n}\n\n/**\n * The removal of a field or an exposed slot, planned but not applied: the\n * dialog shows what it prunes before the author confirms.\n */\nexport function planFieldRemoval(\n  component: ComponentDocument,\n  removing: { readonly kind: \"field\" | \"slot\"; readonly id: string },\n  limits: EditorState[\"limits\"]\n): ExposureEditResult {\n  return removing.kind === \"field\"\n    ? planRemoveExposure(component, removing.id, limits)\n    : planRemoveExposedSlot(component, removing.id, limits);\n}\n\n/**\n * \"at least 3 documents\", \"1 document\", or nothing when the host could not\n * count. A floor of none says nothing, so it is not said.\n */\nexport function reachPhrase(\n  reach: ComponentFieldsHost[\"reach\"]\n): string | undefined {\n  if (reach === undefined) return undefined;\n  if (reach.count === 0 && !reach.complete) return undefined;\n  const noun = reach.count === 1 ? \"document\" : \"documents\";\n  return reach.complete\n    ? `${reach.count} ${noun}`\n    : `at least ${reach.count} ${noun}`;\n}\n\n/**\n * What the removal dialog says about the placements and variants a removal\n * takes a value from.\n */\nexport function removalSentences(\n  edit: ExposureEdit,\n  removing: { readonly kind: \"field\" | \"slot\" },\n  reach: ComponentFieldsHost[\"reach\"]\n): {\n  readonly placements: string;\n  readonly variants: readonly {\n    readonly variant: string;\n    readonly sentence: string;\n  }[];\n} {\n  const where = reachPhrase(reach);\n  const pages =\n    where === undefined\n      ? \"\"\n      : reach?.count === 0 && reach.complete\n        ? \" No document places this component yet.\"\n        : ` This component is placed directly in ${where}.`;\n  const placements =\n    removing.kind === \"field\"\n      ? `When you publish this component, every use of it that set this field loses its value.${pages}`\n      : `When you publish this component, the blocks each use of it added here are removed.${pages}`;\n  const variants = edit.prunedVariants.map(variant => ({\n    variant: variant.variant,\n    sentence: variant.emptied\n      ? `${variant.label}: loses its value, and with nothing left it shows the defaults`\n      : `${variant.label}: loses its value`,\n  }));\n  return { placements, variants };\n}\n\n/** What a field's source line says of a block that is no longer there. */\nconst MISSING_BLOCK = \"A missing block\";\n\n/**\n * Where a field comes from, in the words an author reads: the block and the\n * property, by the names the block gives them, never a stored prop name or an\n * id. \"Heading text\", \"Button link\"; the block alone where the property is\n * named as the block is (\"Image\"); and \"Heading · level\" where the plain line\n * would only repeat the field's own name. A visibility field says what it\n * does instead, since it drives no property.\n */\nexport function fieldSource(\n  document: BlockDocument,\n  field: ExposedProperty\n): string {\n  const node = findNode(document.nodes, field.nodeId);\n  if (node === undefined) return MISSING_BLOCK;\n  const block = blockLabel(node.type);\n  if (field.type === \"visibility\") return `${block}, shown or hidden`;\n  const prop = inSentence(propWord(node.type, field.propPath));\n  if (prop.toLowerCase() === block.toLowerCase()) return block;\n  const line = `${block} ${prop}`;\n  return line.toLowerCase() === field.label.trim().toLowerCase()\n    ? `${block} · ${prop}`\n    : line;\n}\n\n/** Where an exposed slot sits, and what each placement does with it. */\nexport function slotSource(\n  component: ComponentDocument,\n  slotId: string\n): string {\n  const slots: unknown = component.slots;\n  const slot = isPlainRecord(slots) ? slots[slotId] : undefined;\n  const nodeId = isPlainRecord(slot) ? slot.nodeId : undefined;\n  const node =\n    typeof nodeId === \"string\" ? findNode(component.nodes, nodeId) : undefined;\n  if (node === undefined) return MISSING_BLOCK;\n  return `${blockLabel(node.type)}, filled by each use`;\n}\n\n/**\n * What the block calls the property a path starts at: its own label, or the\n * name spaced when it gives none.\n */\nfunction propWord(type: string, propPath: string): string {\n  const head = propPath.split(\".\", 1)[0] ?? propPath;\n  const schema = getBlock(type)?.props?.[head];\n  return schema === undefined ? fieldLabel(head) : propLabel(head, schema);\n}\n\n/**\n * A label as it reads mid-sentence: its first letter lowered, unless the\n * label opens with an acronym (\"URL\"), which keeps its capitals.\n */\nfunction inSentence(label: string): string {\n  const second = label.charAt(1);\n  if (\n    second !== \"\" &&\n    second === second.toUpperCase() &&\n    /[A-Z]/.test(second)\n  ) {\n    return label;\n  }\n  return label.charAt(0).toLowerCase() + label.slice(1);\n}\n","\"use client\";\n\n/**\n * The component's own view, in the inspector: the icon beside each property\n * that lets each page change it, the same icon on a block's Shown row,\n * the card naming the component over its list of fields, and the dialog that\n * confirms a removal.\n *\n * Draws what `component-fields` decides and decides nothing itself.\n *\n * **A removal always asks first.** Placements that set the field lose their\n * value once the component is published, and variants lose theirs at once, so\n * the dialog names the variants it prunes before anything changes. An\n * exposure added is undone with undo; one removed may already have values on\n * pages, so it is confirmed rather than taken back.\n *\n * A name commits on blur or Enter, as every inspector field does: one rename\n * is one undo step, not one per letter.\n *\n * @module component-fields-panel\n */\nimport {\n  variantOptions,\n  type ComponentDocument,\n  type ExposedProperty,\n  type ExposureEdit,\n  type RetiredExposures,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n  Input,\n  TooltipProvider,\n} from \"@nextlyhq/ui\";\nimport {\n  AlignLeft,\n  Component,\n  Crosshair,\n  Eye,\n  Image as ImageIcon,\n  Link2,\n  List,\n  SquareDashed,\n  Trash2,\n  Type,\n  type LucideIcon,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../chrome-tooltip\";\nimport type { EditorState } from \"../editor-state\";\nimport {\n  editedComponent,\n  EXPOSURE_TYPE_LABEL,\n  exposedFields,\n  exposedSlotIds,\n  exposeOffer,\n  exposeProp,\n  exposeVisibility,\n  fieldSource,\n  idsIn,\n  planFieldRemoval,\n  propExposure,\n  removalSentences,\n  renameField,\n  reservedIds,\n  slotSource,\n  visibilityExposure,\n  applyFieldEdit,\n  type ComponentFieldsHost,\n  type FieldEditContext,\n} from \"../panels/components/component-fields\";\nimport { useStoredDraft } from \"../stored-draft\";\n\nimport { commitOnEnter } from \"./commit-on-enter\";\nimport { propLabel, type EditableProp } from \"./inspector\";\n\n/** A field or an exposed slot the author asked to remove. */\nexport interface FieldRemoval {\n  readonly kind: \"field\" | \"slot\";\n  readonly id: string;\n  /** What the dialog calls it. */\n  readonly label: string;\n}\n\n/** What the inspector hands every control while a component is edited. */\nexport interface ComponentFieldsBinding {\n  readonly context: FieldEditContext;\n  readonly requestRemoval: (removal: FieldRemoval) => void;\n  /** The component's name, for the card heading its view; absent if unknown. */\n  readonly name?: string | undefined;\n  /**\n   * How many pages use the component, as its view counts them, for the\n   * data picker's line over the component's settings; absent while uncounted.\n   */\n  readonly pages?: ComponentFieldsHost[\"pages\"];\n}\n\n/**\n * Every id the session has seen this component hold, kept across edits.\n *\n * A field removed and exposed again under the same name must get a new id: a\n * placement may still hold a value under the old one. The document alone\n * forgets the old id the moment it is removed, so the session remembers it.\n */\nfunction useSeenIds(\n  component: ComponentDocument | undefined\n): RetiredExposures {\n  const seen = React.useRef<{ properties: Set<string>; slots: Set<string> }>({\n    properties: new Set(),\n    slots: new Set(),\n  });\n  if (component !== undefined) {\n    const now = idsIn(component);\n    for (const id of now.properties) seen.current.properties.add(id);\n    for (const id of now.slots) seen.current.slots.add(id);\n  }\n  return {\n    properties: [...seen.current.properties],\n    slots: [...seen.current.slots],\n  };\n}\n\n/**\n * The binding for a component's view, which every control below the scope\n * reads; `undefined` for a page or a pattern.\n */\nexport const ComponentFieldsContext: React.Context<\n  ComponentFieldsBinding | undefined\n> = React.createContext<ComponentFieldsBinding | undefined>(undefined);\n\n/**\n * The component's view around the inspector: the binding its controls read,\n * and the removal dialog any of them may open, drawn once here whichever\n * surface asked for it.\n */\nexport function ComponentFieldsScope({\n  editor,\n  host,\n  children,\n}: {\n  editor: EditorState;\n  host: ComponentFieldsHost | undefined;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const { binding, dialog } = useComponentFields(editor, host);\n  return (\n    <ComponentFieldsContext.Provider value={binding}>\n      {children}\n      {dialog}\n    </ComponentFieldsContext.Provider>\n  );\n}\n\n/**\n * The binding for a component's view, and the removal dialog it opens; no\n * binding for a page or a pattern.\n */\nfunction useComponentFields(\n  editor: EditorState,\n  host: ComponentFieldsHost | undefined\n): {\n  readonly binding: ComponentFieldsBinding | undefined;\n  readonly dialog: React.JSX.Element | null;\n} {\n  const component = editedComponent(editor.document);\n  const seen = useSeenIds(component);\n  const [removal, setRemoval] = React.useState<FieldRemoval | null>(null);\n  const binding: ComponentFieldsBinding | undefined =\n    component === undefined\n      ? undefined\n      : {\n          context: {\n            editor,\n            component,\n            reserved: reservedIds(host?.reserved, seen),\n          },\n          requestRemoval: setRemoval,\n          name: host?.name,\n          pages: host?.pages,\n        };\n  const dialog =\n    component === undefined || removal === null ? null : (\n      <RemoveFieldDialog\n        editor={editor}\n        component={component}\n        removal={removal}\n        reach={host?.reach}\n        onClose={() => setRemoval(null)}\n      />\n    );\n  return { binding, dialog };\n}\n\n/** The refusal or failure an edit came back with, said where it happened. */\nfunction useEditProblem(): [\n  string | undefined,\n  (reason: string | undefined) => void,\n] {\n  return React.useState<string | undefined>(undefined);\n}\n\n/** The type icon a field's row shows, by what a placement sets through it. */\nconst TYPE_ICON: Readonly<Record<ExposedProperty[\"type\"], LucideIcon>> = {\n  text: Type,\n  richText: AlignLeft,\n  image: ImageIcon,\n  link: Link2,\n  visibility: Eye,\n  select: List,\n};\n\n/**\n * What the icon beside a property says, in the author's words: \"page\" where\n * the code says placement, and a one-line tooltip on what pressing it does.\n */\nconst TOGGLE_WORDS = {\n  prop: {\n    label: (property: string) => `Let each page change ${property}`,\n    off: (property: string) =>\n      `Turn this on to let each use of the component, on any page, set its own ${property.toLowerCase()}.`,\n    on: \"Each use can change this. Turn off to use the component’s value everywhere.\",\n  },\n  visibility: {\n    label: (block: string) => `Let each page hide ${block}`,\n    off: (block: string) =>\n      `Turn this on to let each use of the component, on any page, hide this ${block.toLowerCase()}.`,\n    on: \"Each use can hide this. Turn off to show it everywhere.\",\n  },\n} as const;\n\n/**\n * The icon beside a property that lets each page change it: the\n * component mark, pressed while the property is exposed. A button with a\n * pressed state rather than a switch row under every property, as Figma and\n * Webflow bind a property, so a long list stays a list of properties.\n *\n * A property no placement could set keeps its icon HELD rather than disabled:\n * still focusable and hoverable, so the reason can be read, and said aloud\n * when pressed.\n */\nfunction ExposeToggle({\n  label,\n  pressed,\n  held,\n  title,\n  onPress,\n}: {\n  /** The button's name, the same whether pressed or not. */\n  label: string;\n  pressed: boolean;\n  /** Why it cannot be pressed, or nothing when it can. */\n  held: string | undefined;\n  /** What its tooltip says, on hover and on focus. */\n  title: string;\n  onPress: () => void;\n}): React.JSX.Element {\n  return (\n    <TooltipProvider delayDuration={300}>\n      {/* Below the icon, ending at its right edge: the row's own label stays\n          readable beside the icon, and the tip lies over the next row, which\n          the author isn't reading while pointing here. */}\n      <ChromeTooltip\n        side=\"bottom\"\n        align=\"end\"\n        className=\"nx-expose__tip\"\n        content={held ?? title}\n      >\n        <button\n          type=\"button\"\n          className=\"nx-expose__toggle\"\n          aria-label={label}\n          aria-pressed={pressed}\n          aria-disabled={held === undefined ? undefined : true}\n          onClick={onPress}\n        >\n          <Component size={15} aria-hidden=\"true\" />\n        </button>\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/** What the dashed row's \"Field\" label says on hover. */\nconst FIELD_HINT = \"The name each page’s editor shows for this field.\";\n\n/**\n * Under a property, once it is exposed: the dashed row naming the field\n * each page sets it through.\n */\nfunction ExposedFieldName({\n  binding,\n  field,\n  label,\n  inputRef,\n}: {\n  binding: ComponentFieldsBinding;\n  field: ExposedProperty;\n  label: string;\n  inputRef?: React.Ref<HTMLInputElement>;\n}): React.JSX.Element {\n  // The hint is said with the name input as its description, so it reaches\n  // a keyboard or screen-reader user too; the title keeps it on hover.\n  const hintId = `${React.useId()}-hint`;\n  return (\n    <div className=\"nx-expose__field\">\n      <span\n        className=\"nx-expose__field-label\"\n        aria-hidden=\"true\"\n        title={FIELD_HINT}\n      >\n        <Component size={13} />\n        Field\n      </span>\n      <span id={hintId} className=\"nx-sr-only\">\n        {FIELD_HINT}\n      </span>\n      <FieldName\n        inputRef={inputRef}\n        binding={binding}\n        field={field}\n        label={label}\n        describedBy={hintId}\n        className=\"nx-expose__name-input\"\n      />\n    </div>\n  );\n}\n\n/**\n * Beside a prop's control while a component is edited: the icon that lets\n * each page change it, and the field's name under it once it does.\n */\nexport function PropExposeControl({\n  binding,\n  nodeId,\n  prop,\n}: {\n  binding: ComponentFieldsBinding;\n  nodeId: string;\n  prop: EditableProp;\n}): React.JSX.Element {\n  const { context, requestRemoval } = binding;\n  const field = propExposure(context.component, nodeId, prop.name);\n  const offer = exposeOffer(prop.schema);\n  const [problem, setProblem] = useEditProblem();\n  const reasonId = React.useId();\n  const nameRef = React.useRef<HTMLInputElement | null>(null);\n  const focusName = React.useRef(false);\n  const named = propLabel(prop.name, prop.schema);\n\n  React.useEffect(() => {\n    // The name is the next thing an author decides, so a field just exposed\n    // takes the focus straight to it.\n    if (field !== undefined && focusName.current) {\n      focusName.current = false;\n      nameRef.current?.focus();\n      nameRef.current?.select();\n    }\n  }, [field]);\n\n  const unavailable =\n    field === undefined && \"reason\" in offer ? offer.reason : undefined;\n  const press = () => {\n    if (field !== undefined) {\n      requestRemoval({ kind: \"field\", id: field.id, label: field.label });\n      return;\n    }\n    if (unavailable !== undefined) {\n      setProblem(unavailable);\n      return;\n    }\n    const outcome = exposeProp(context, nodeId, prop.name, named);\n    setProblem(outcome.applied ? undefined : outcome.reason);\n    focusName.current = outcome.applied;\n  };\n\n  return (\n    <div\n      className=\"nx-expose\"\n      data-exposed={field === undefined ? undefined : \"\"}\n      data-expose-prop={prop.name}\n      aria-describedby={problem === undefined ? undefined : reasonId}\n    >\n      <ExposeToggle\n        label={TOGGLE_WORDS.prop.label(named)}\n        pressed={field !== undefined}\n        held={unavailable}\n        title={\n          field === undefined\n            ? TOGGLE_WORDS.prop.off(named)\n            : TOGGLE_WORDS.prop.on\n        }\n        onPress={press}\n      />\n      {field === undefined ? null : (\n        <ExposedFieldName\n          inputRef={nameRef}\n          binding={binding}\n          field={field}\n          label={`Name pages see for ${named}`}\n        />\n      )}\n      {problem === undefined ? null : (\n        <p id={reasonId} className=\"nx-expose__reason\" role=\"alert\">\n          {problem}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/**\n * In the Advanced tab's Visibility section while a component is edited: its\n * Shown row, with the same icon, letting each page hide the block.\n */\nexport function VisibilityExposeControl({\n  binding,\n  nodeId,\n  blockName,\n}: {\n  binding: ComponentFieldsBinding;\n  nodeId: string;\n  blockName: string;\n}): React.JSX.Element {\n  const { context, requestRemoval } = binding;\n  const field = visibilityExposure(context.component, nodeId);\n  const [problem, setProblem] = useEditProblem();\n  const reasonId = React.useId();\n\n  const press = () => {\n    if (field !== undefined) {\n      requestRemoval({ kind: \"field\", id: field.id, label: field.label });\n      return;\n    }\n    const outcome = exposeVisibility(\n      context,\n      nodeId,\n      `Show ${blockName.toLowerCase()}`\n    );\n    setProblem(outcome.applied ? undefined : outcome.reason);\n  };\n\n  return (\n    <div className=\"nx-inspector__prop nx-expose-shown\">\n      <div\n        className=\"nx-expose\"\n        data-exposed={field === undefined ? undefined : \"\"}\n        data-expose-visibility=\"\"\n      >\n        <p className=\"nx-expose__shown\">\n          <span className=\"nx-expose__shown-label\">Shown</span>\n          <span className=\"nx-expose__shown-value\">\n            {field === undefined ? \"On every page\" : \"Each use chooses\"}\n          </span>\n        </p>\n        <ExposeToggle\n          label={TOGGLE_WORDS.visibility.label(blockName)}\n          pressed={field !== undefined}\n          held={undefined}\n          title={\n            field === undefined\n              ? TOGGLE_WORDS.visibility.off(blockName)\n              : TOGGLE_WORDS.visibility.on\n          }\n          onPress={press}\n        />\n        {field === undefined ? null : (\n          <ExposedFieldName\n            binding={binding}\n            field={field}\n            label={`Name pages see for hiding ${blockName}`}\n          />\n        )}\n        {problem === undefined ? null : (\n          <p id={reasonId} className=\"nx-expose__reason\" role=\"alert\">\n            {problem}\n          </p>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/** A field's name, renamed on blur or Enter. Its id never changes. */\nfunction FieldName({\n  binding,\n  field,\n  label,\n  inputRef,\n  describedBy,\n  className,\n}: {\n  binding: ComponentFieldsBinding;\n  field: ExposedProperty;\n  label: string;\n  inputRef?: React.Ref<HTMLInputElement>;\n  /** The id of text that says more about the name, read with the input. */\n  describedBy?: string;\n  /** How the name is drawn: flat in the list, dashed under a property. */\n  className: string;\n}): React.JSX.Element {\n  const [draft, setDraft] = useStoredDraft(field.label);\n  const [problem, setProblem] = useEditProblem();\n  const send = () => {\n    if (draft === field.label) return;\n    const outcome = renameField(binding.context, field.id, draft);\n    if (outcome.applied) {\n      setProblem(undefined);\n      return;\n    }\n    // Back to the stored name, with the reason: a blank name is refused, and\n    // leaving the blank on screen would show a name the component does not have.\n    setDraft(field.label);\n    setProblem(outcome.reason);\n  };\n  return (\n    <span className=\"nx-field-name\">\n      <Input\n        ref={inputRef}\n        size=\"sm\"\n        className={className}\n        value={draft}\n        aria-label={label}\n        aria-describedby={describedBy}\n        onChange={event => setDraft(event.target.value)}\n        onBlur={send}\n        onKeyDown={event => {\n          commitOnEnter(event, send);\n        }}\n      />\n      {problem === undefined ? null : (\n        <span className=\"nx-expose__reason\" role=\"alert\">\n          {problem}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/** \"Component · 5 fields · 2 variants\", or \"Component · no fields yet\". */\nfunction holdsSentence(fieldCount: number, variantCount: number): string {\n  const parts = [\"Component\"];\n  parts.push(\n    fieldCount === 0\n      ? \"no fields yet\"\n      : `${fieldCount} ${fieldCount === 1 ? \"field\" : \"fields\"}`\n  );\n  if (variantCount > 0) {\n    parts.push(\n      `${variantCount} ${variantCount === 1 ? \"variant\" : \"variants\"}`\n    );\n  }\n  return parts.join(\" · \");\n}\n\n/**\n * The card heading the component's view: its mark, its name (whole on hover,\n * for a name too long for the panel) and how much it holds.\n */\nfunction ComponentHeader({\n  name,\n  fieldCount,\n  variantCount,\n}: {\n  name: string;\n  fieldCount: number;\n  variantCount: number;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-component-head\">\n      <span className=\"nx-component-head__mark\" aria-hidden=\"true\">\n        <Component size={16} />\n      </span>\n      <div className=\"nx-component-head__text\">\n        <h2 className=\"nx-component-head__name\" title={name}>\n          {name}\n        </h2>\n        <p className=\"nx-component-head__holds\">\n          {holdsSentence(fieldCount, variantCount)}\n        </p>\n      </div>\n    </div>\n  );\n}\n\n/** What the list says before the component has a field. */\nfunction NoFieldsYet(): React.JSX.Element {\n  return (\n    <div className=\"nx-component-fields__empty\">\n      <p className=\"nx-component-fields__empty-title\">No fields yet</p>\n      <p className=\"nx-component-fields__empty-text\">\n        Select a block, then use{\" \"}\n        <span\n          className=\"nx-component-fields__mark\"\n          role=\"img\"\n          aria-label=\"the component mark\"\n        >\n          <Component size={13} aria-hidden=\"true\" />\n        </span>{\" \"}\n        beside a property to let each page change it.\n      </p>\n    </div>\n  );\n}\n\n/**\n * The component's fields and exposed slots, drawn while nothing is selected:\n * the component itself is what the inspector then describes, under a card\n * naming it.\n */\nexport function ExposedFieldsList({\n  binding,\n  editor,\n  children,\n}: {\n  binding: ComponentFieldsBinding;\n  editor: EditorState;\n  /** What the component's view lists under its fields: its variants. */\n  children?: React.ReactNode;\n}): React.JSX.Element {\n  const { component } = binding.context;\n  const fields = exposedFields(component);\n  const slots = exposedSlotIds(component);\n  const headingId = React.useId();\n  return (\n    // No box of its own: drawn inside the panel's frame for the document,\n    // among the host's own rows for it.\n    <div className=\"contents\" data-component-fields=\"\">\n      <ComponentHeader\n        name={binding.name ?? \"This component\"}\n        fieldCount={fields.length + slots.length}\n        variantCount={variantOptions(component).length}\n      />\n      <section aria-labelledby={headingId} className=\"nx-component-fields\">\n        <h3 id={headingId} className=\"nx-inspector__heading\">\n          Fields\n        </h3>\n        {fields.length === 0 && slots.length === 0 ? (\n          <NoFieldsYet />\n        ) : (\n          <ul className=\"nx-component-fields__list\">\n            {fields.map(field => (\n              <ExposedFieldRow\n                key={field.id}\n                binding={binding}\n                editor={editor}\n                field={field}\n              />\n            ))}\n            {slots.map(id => (\n              <ExposedSlotRow\n                key={`slot:${id}`}\n                binding={binding}\n                editor={editor}\n                slotId={id}\n              />\n            ))}\n          </ul>\n        )}\n      </section>\n      {children}\n    </div>\n  );\n}\n\n/** A row's two actions, drawn on hover and focus: show its block, remove it. */\nfunction RowActions({\n  selectLabel,\n  onSelect,\n  removeLabel,\n  removeTitle,\n  onRemove,\n}: {\n  selectLabel: string | undefined;\n  onSelect: () => void;\n  removeLabel: string;\n  removeTitle: string;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-component-field__actions\">\n      {selectLabel === undefined ? null : (\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"icon-sm\"\n          aria-label={selectLabel}\n          title=\"Select its block\"\n          onClick={onSelect}\n        >\n          <Crosshair size={14} aria-hidden=\"true\" />\n        </Button>\n      )}\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"icon-sm\"\n        aria-label={removeLabel}\n        title={removeTitle}\n        onClick={onRemove}\n      >\n        <Trash2 size={14} aria-hidden=\"true\" />\n      </Button>\n    </span>\n  );\n}\n\nfunction ExposedFieldRow({\n  binding,\n  editor,\n  field,\n}: {\n  binding: ComponentFieldsBinding;\n  editor: EditorState;\n  field: ExposedProperty;\n}): React.JSX.Element {\n  const Icon = TYPE_ICON[field.type];\n  return (\n    <li className=\"nx-component-field\" data-field-id={field.id}>\n      <span\n        className=\"nx-component-field__type\"\n        role=\"img\"\n        aria-label={EXPOSURE_TYPE_LABEL[field.type]}\n        title={EXPOSURE_TYPE_LABEL[field.type]}\n      >\n        <Icon size={15} aria-hidden=\"true\" />\n      </span>\n      <span className=\"nx-component-field__text\">\n        <FieldName\n          binding={binding}\n          field={field}\n          label={`Name of the field ${field.label}`}\n          className=\"nx-component-field__name\"\n        />\n        <span className=\"nx-component-field__source\">\n          {fieldSource(editor.document, field)}\n        </span>\n      </span>\n      <RowActions\n        selectLabel={`Select the block ${field.label} comes from`}\n        onSelect={() => editor.select(field.nodeId)}\n        removeLabel={`Remove the field ${field.label}`}\n        removeTitle=\"Remove field\"\n        onRemove={() =>\n          binding.requestRemoval({\n            kind: \"field\",\n            id: field.id,\n            label: field.label,\n          })\n        }\n      />\n    </li>\n  );\n}\n\nfunction ExposedSlotRow({\n  binding,\n  editor,\n  slotId,\n}: {\n  binding: ComponentFieldsBinding;\n  editor: EditorState;\n  slotId: string;\n}): React.JSX.Element {\n  const slot = binding.context.component.slots?.[slotId];\n  const label = typeof slot?.label === \"string\" ? slot.label : slotId;\n  return (\n    <li className=\"nx-component-field\" data-slot-id={slotId}>\n      <span\n        className=\"nx-component-field__type\"\n        role=\"img\"\n        aria-label=\"Blocks each use adds\"\n        title=\"Blocks each use adds\"\n      >\n        <SquareDashed size={15} aria-hidden=\"true\" />\n      </span>\n      <span className=\"nx-component-field__text\">\n        <span className=\"nx-component-field__label\">{label}</span>\n        <span className=\"nx-component-field__source\">\n          {slotSource(binding.context.component, slotId)}\n        </span>\n      </span>\n      <RowActions\n        selectLabel={\n          slot === undefined ? undefined : `Select the block holding ${label}`\n        }\n        onSelect={() => {\n          if (slot !== undefined) editor.select(slot.nodeId);\n        }}\n        removeLabel={`Remove the field ${label}`}\n        removeTitle=\"Remove field\"\n        onRemove={() =>\n          binding.requestRemoval({ kind: \"slot\", id: slotId, label })\n        }\n      />\n    </li>\n  );\n}\n\n/**\n * Confirms a removal, naming what it takes away. Planned when it opens, so the\n * variants it lists are the ones the confirmed edit prunes.\n */\nfunction RemoveFieldDialog({\n  editor,\n  component,\n  removal,\n  reach,\n  onClose,\n}: {\n  editor: EditorState;\n  component: ComponentDocument;\n  removal: FieldRemoval;\n  reach: ComponentFieldsHost[\"reach\"];\n  onClose: () => void;\n}): React.JSX.Element {\n  const planned = planFieldRemoval(component, removal, editor.limits);\n  const [problem, setProblem] = useEditProblem();\n  const noun = removal.kind === \"field\" ? \"field\" : \"slot\";\n  const confirm = () => {\n    const outcome = applyFieldEdit(editor, component, planned);\n    if (outcome.applied) onClose();\n    else setProblem(outcome.reason);\n  };\n  return (\n    <Dialog\n      open\n      onOpenChange={open => {\n        if (!open) onClose();\n      }}\n    >\n      <DialogContent className=\"max-w-md\">\n        <DialogHeader>\n          <DialogTitle>\n            Remove the {noun} “{removal.label}”?\n          </DialogTitle>\n          <DialogDescription>\n            {\"problem\" in planned\n              ? \"This can’t be removed here.\"\n              : removalSentences(planned, removal, reach).placements}\n          </DialogDescription>\n        </DialogHeader>\n        {\"problem\" in planned ? null : (\n          <PrunedVariants edit={planned} removal={removal} />\n        )}\n        {problem === undefined ? null : (\n          <p className=\"nx-inspector__note\" role=\"alert\">\n            {problem}\n          </p>\n        )}\n        <DialogFooter>\n          <Button type=\"button\" variant=\"outline\" onClick={onClose}>\n            Cancel\n          </Button>\n          <Button\n            type=\"button\"\n            variant=\"destructive\"\n            disabled={\"problem\" in planned}\n            onClick={confirm}\n          >\n            Remove {noun}\n          </Button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n\n/** The variants a removal takes a value from, or that none does. */\nfunction PrunedVariants({\n  edit,\n  removal,\n}: {\n  edit: ExposureEdit;\n  removal: FieldRemoval;\n}): React.JSX.Element | null {\n  if (removal.kind === \"slot\") return null;\n  const { variants } = removalSentences(edit, removal, undefined);\n  if (variants.length === 0) {\n    return <p className=\"nx-inspector__note\">No variant sets this field.</p>;\n  }\n  return (\n    <div className=\"nx-remove-field__variants\">\n      <p className=\"nx-inspector__note\">These variants lose their value now:</p>\n      <ul>\n        {variants.map(entry => (\n          <li key={entry.variant}>{entry.sentence}</li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n","/**\n * What a designer does to a component's variants in its own view, and what a\n * placement's variant picker offers.\n *\n * Decides and draws nothing: the op an edit becomes, the sentences an author\n * reads and what a placement's choice resolves to all live here, where they\n * can be asserted without a DOM. `component-variants-panel` and\n * `variant-picker` draw them.\n *\n * Every definition edit is asked of the engine's variant planners, which hold\n * the rules (a key is the variant's id and is never reused, names are unique,\n * an empty variant is kept), and written as ONE `envelope` op, so it is one\n * undo step and reaches autosave and recovery with the rest of the document.\n *\n * @module component-variants\n */\nimport {\n  COMPONENT_INSTANCE_TYPE,\n  instanceExposure,\n  isPlainRecord,\n  planAddVariant,\n  planDeleteVariant,\n  planRenameVariant,\n  planResetVariantValue,\n  planSetVariantValue,\n  variantLabelKey,\n  variantOptions,\n  type BlockNode,\n  type ComponentDocument,\n  type OverrideValue,\n  type VariantEditProblem,\n  type VariantEditResult,\n  type VariantOption,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\n\nimport { envelopeOpFor } from \"./component-fields\";\n\n/**\n * How many placements chose a variant, for the delete dialog.\n *\n * @experimental Settles when the component editor ships.\n */\nexport interface VariantUse {\n  /** Placements that chose it. */\n  readonly placements: number;\n  /** The documents holding them: pages, Singles, components and patterns. */\n  readonly documents: number;\n  /**\n   * False when the count is a floor: the usage index did not list every host,\n   * or a host could not be read. Said as \"at least\".\n   */\n  readonly complete: boolean;\n}\n\n/**\n * What the host knows about a component's variants that its document does not\n * hold.\n *\n * @experimental Settles when the component editor ships.\n */\nexport interface ComponentVariantsHost {\n  /**\n   * Counts the placements that chose a variant, across every document that\n   * places the component. Absent where the host cannot count; the delete\n   * dialog then says the placements fall back without a number.\n   */\n  readonly countUse?: (variantId: string) => Promise<VariantUse>;\n  /**\n   * Which variant is open, held by the host so the canvas can preview it.\n   * Absent, the section holds it alone and the canvas draws the defaults.\n   */\n  readonly preview?: VariantPreviewBinding;\n  /**\n   * The variants are edited in the component's own view alone, and no\n   * section is drawn here: a header or footer edited in place from a page,\n   * whose canvas has no variant of it to preview.\n   */\n  readonly editedInOwnView?: boolean;\n  /**\n   * Opens the component's own view, where its variants are edited: offered\n   * beside the line saying so while `editedInOwnView`. Absent where the host\n   * cannot open it, and the line then stands alone.\n   */\n  readonly onOpenOwnView?: () => void;\n}\n\n/** The open variant, as the host holds it for the canvas to preview. */\nexport interface VariantPreviewBinding {\n  /** The open variant's id, or nothing while none is open. */\n  readonly open: string | undefined;\n  /** Open a variant, or close the open one with `undefined`. */\n  readonly onOpen: (variantId: string | undefined) => void;\n}\n\n/** What the variant edits read from the editor, gathered once. */\nexport interface VariantEditContext {\n  readonly editor: Pick<EditorState, \"apply\" | \"limits\">;\n  readonly component: ComponentDocument;\n  /**\n   * Keys a new variant must not take though the component no longer holds\n   * them: every key this editing session has seen, so a variant deleted and\n   * added again under its old name does not inherit the old one's placements.\n   */\n  readonly taken: readonly string[];\n}\n\n/** What an edit came to: applied, or refused with the sentence to show. */\nexport type VariantEditOutcome =\n  | { readonly applied: true; readonly id: string }\n  | { readonly applied: false; readonly reason: string };\n\n/** The sentence for each refusal, said where the edit was made. */\nfunction problemSentence(\n  problem: VariantEditProblem,\n  clash?: string,\n  needs?: string\n): string {\n  switch (problem) {\n    case \"invalid-value\":\n      return `Not saved: this field ${needs ?? \"needs a different value\"}.`;\n    case \"invalid-label\":\n      return \"A variant needs a name.\";\n    case \"label-taken\":\n      return `There is already a variant called “${clash ?? \"\"}”. Choose another name.`;\n    case \"unknown-variant\":\n      return \"That variant is no longer on this component.\";\n    case \"unknown-exposure\":\n      return \"That field is no longer on this component.\";\n    case \"not-a-component\":\n      return \"Variants belong to components, and this is not one.\";\n    case \"exceeds-limits\":\n      return \"This component is at its size limit, so nothing more can be added.\";\n    case \"invalid-variant\":\n      return \"This component’s variants can’t be read, so they can’t be changed here.\";\n    default:\n      return \"This change could not be made.\";\n  }\n}\n\n/** Apply a planned edit as one op, or say why it was not. */\nfunction applied(\n  context: VariantEditContext,\n  result: VariantEditResult\n): VariantEditOutcome {\n  if (\"problem\" in result) {\n    return {\n      applied: false,\n      reason: problemSentence(result.problem, result.clash, result.needs),\n    };\n  }\n  const op = envelopeOpFor(context.component, result.document);\n  if (op === undefined) return { applied: true, id: result.id };\n  return context.editor.apply(op) === null\n    ? {\n        applied: false,\n        reason: \"This change could not be applied here. Nothing was changed.\",\n      }\n    : { applied: true, id: result.id };\n}\n\n/**\n * A name for a new variant no other variant has: \"Variant 2\" when there is\n * one already, and so on. The designer renames it in place.\n */\nexport function nextVariantName(component: ComponentDocument): string {\n  const taken = new Set(\n    variantOptions(component).map(option => variantLabelKey(option.label))\n  );\n  for (let n = taken.size + 1; ; n += 1) {\n    const name = `Variant ${String(n)}`;\n    if (!taken.has(variantLabelKey(name))) return name;\n  }\n}\n\n/** Define a variant. It presets nothing until it is given values. */\nexport function addVariant(\n  context: VariantEditContext,\n  label: string\n): VariantEditOutcome {\n  return applied(\n    context,\n    planAddVariant(context.component, label, {\n      taken: context.taken,\n      limits: context.editor.limits,\n    })\n  );\n}\n\n/** Rename a variant; every placement that chose it keeps it. */\nexport function renameVariant(\n  context: VariantEditContext,\n  id: string,\n  label: string\n): VariantEditOutcome {\n  return applied(\n    context,\n    planRenameVariant(context.component, id, label, context.editor.limits)\n  );\n}\n\n/** Delete a variant; its placements show the defaults with their own values. */\nexport function deleteVariant(\n  context: VariantEditContext,\n  id: string\n): VariantEditOutcome {\n  return applied(\n    context,\n    planDeleteVariant(context.component, id, context.editor.limits)\n  );\n}\n\n/** Set what a variant presets for one field. */\nexport function setVariantValue(\n  context: VariantEditContext,\n  id: string,\n  fieldId: string,\n  value: OverrideValue\n): VariantEditOutcome {\n  return applied(\n    context,\n    planSetVariantValue(\n      context.component,\n      id,\n      fieldId,\n      value,\n      context.editor.limits\n    )\n  );\n}\n\n/** Take a variant's value for one field away, back to the default. */\nexport function resetVariantValue(\n  context: VariantEditContext,\n  id: string,\n  fieldId: string\n): VariantEditOutcome {\n  return applied(\n    context,\n    planResetVariantValue(context.component, id, fieldId, context.editor.limits)\n  );\n}\n\n/**\n * The component's own value for each exposed field, by field id: what a\n * variant that sets nothing for a field shows.\n *\n * Read from what the resolver itself makes of a placement that sets nothing,\n * once for the whole component, so a visibility field gated by its node's\n * conditions reads as hidden, and a field the resolver cannot use has no\n * value, exactly as a page shows them.\n */\nexport function defaultValues(\n  component: ComponentDocument\n): ReadonlyMap<string, unknown> {\n  const values = new Map<string, unknown>();\n  for (const row of instanceExposure(component, UNPLACED).properties) {\n    if (!values.has(row.property.id)) {\n      values.set(row.property.id, row.cleared ? undefined : row.value);\n    }\n  }\n  return values;\n}\n\n/** A placement that chooses nothing and sets nothing. */\nconst UNPLACED: BlockNode = {\n  id: \"\",\n  type: COMPONENT_INSTANCE_TYPE,\n  version: 1,\n  props: { componentId: \"\" },\n};\n\n/** How many values a variant presets, in words: \"2 changes\", \"No changes yet\". */\nexport function valuesSummary(option: VariantOption): string {\n  if (option.empty) return \"No changes yet\";\n  const count = Object.keys(option.values).length;\n  return count === 1 ? \"1 change\" : `${String(count)} changes`;\n}\n\n/**\n * What the delete dialog says will happen to the variant's placements.\n *\n * `undefined` use is a count still in flight; `null` is one that could not be\n * made, which says what happens without a number rather than \"none\".\n */\nexport function deleteSentence(use: VariantUse | null | undefined): string {\n  const after =\n    \"Each use of this variant will show the component’s defaults, and keep its own changes.\";\n  if (use === undefined) return \"Counting where it is used…\";\n  if (use === null) {\n    return `Where it is used could not be counted. ${after}`;\n  }\n  if (use.placements === 0) {\n    return use.complete\n      ? \"Nothing uses this variant.\"\n      : \"Nothing was found using this variant, though not every page could be checked.\";\n  }\n  const floor = use.complete ? \"\" : \"at least \";\n  const times = `${floor}${String(use.placements)} ${use.placements === 1 ? \"time\" : \"times\"}`;\n  const documents = `${floor}${String(use.documents)} ${use.documents === 1 ? \"document\" : \"documents\"}`;\n  return `Used ${times} in ${documents}. ${after}`;\n}\n\n/**\n * A placement's variant, as its picker shows it.\n *\n * @experimental Settles when the component editor ships.\n */\nexport interface VariantChoice {\n  /** The variants the component offers, in its stored order. */\n  readonly options: readonly VariantOption[];\n  /** The key the placement stores, if any. */\n  readonly chosen?: string;\n  /**\n   * True when the stored key names a variant the component no longer has:\n   * the placement then shows the defaults, and the picker says so.\n   */\n  readonly removed: boolean;\n}\n\n/** What a placement's picker offers and shows, read off the definition. */\nexport function variantChoiceOf(\n  definition: ComponentDocument | undefined,\n  node: BlockNode\n): VariantChoice {\n  const options = variantOptions(definition);\n  const stored = isPlainRecord(node.props) ? node.props.variant : undefined;\n  if (typeof stored !== \"string\" || stored === \"\") {\n    return { options, removed: false };\n  }\n  return {\n    options,\n    chosen: stored,\n    removed: !options.some(option => option.id === stored),\n  };\n}\n\n/**\n * The op that sets a placement's variant, or clears it with `undefined`.\n *\n * The whole props object, as every placement op writes it: `updateNode`\n * merges at the top level, so a patch of the one key would drop the\n * component's id. Clearing removes the key, since absent is \"no variant\".\n */\nexport function chooseVariantOp(\n  node: BlockNode,\n  variantId: string | undefined\n): BuilderOp {\n  const { variant: _stored, ...rest } = isPlainRecord(node.props)\n    ? node.props\n    : {};\n  return {\n    kind: \"update\",\n    id: node.id,\n    patch: {\n      props: variantId === undefined ? rest : { ...rest, variant: variantId },\n    },\n  };\n}\n","\"use client\";\n\n/**\n * A component's variants, in its own view: define one, name it, give it\n * values, delete it.\n *\n * Draws what `component-variants` decides and decides nothing itself.\n *\n * **A variant opens where it is made.** Adding one names it \"Variant 2\" and\n * opens its values with the name selected, so the next keystroke renames it\n * and the fields it can preset are already in view.\n *\n * **A delete always asks first,** with the number of placements that chose\n * the variant: they keep its id and fall back to the component's defaults,\n * which is a change on pages the designer may not be looking at.\n *\n * A name or a text value commits on blur or Enter, as every inspector field\n * does: one rename is one undo step, not one per letter.\n *\n * @module component-variants-panel\n */\nimport {\n  isRichTextValue,\n  isUnsetOverride,\n  oneParagraphLines,\n  variantOptions,\n  type ComponentDocument,\n  type ExposedProperty,\n  type OverrideValue,\n  type VariantOption,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Checkbox,\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n  Input,\n  Textarea,\n  Label,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { ChevronRight, Plus, RotateCcw, Trash2 } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport { exposedFields } from \"../panels/components/component-fields\";\nimport {\n  addVariant,\n  defaultValues,\n  deleteSentence,\n  deleteVariant,\n  nextVariantName,\n  renameVariant,\n  resetVariantValue,\n  setVariantValue,\n  valuesSummary,\n  type ComponentVariantsHost,\n  type VariantEditContext,\n  type VariantPreviewBinding,\n  type VariantUse,\n} from \"../panels/components/component-variants\";\nimport { useStoredDraft } from \"../stored-draft\";\n\nimport { commitOnEnter } from \"./commit-on-enter\";\n\n/**\n * Every variant key this editing session has seen the component hold. A\n * variant deleted and added again must get a new key, since placements may\n * still hold the old one; the document forgets it the moment it is deleted.\n */\nfunction useSeenKeys(component: ComponentDocument): readonly string[] {\n  const seen = React.useRef(new Set<string>());\n  const variants: unknown = component.variants;\n  if (variants !== null && typeof variants === \"object\") {\n    for (const key of Object.keys(variants)) seen.current.add(key);\n  }\n  return [...seen.current];\n}\n\n/**\n * What the host tells the variants section, handed down from the inspector\n * so the surface drawing the component's view need not carry it.\n */\nexport const ComponentVariantsContext: React.Context<\n  ComponentVariantsHost | undefined\n> = React.createContext<ComponentVariantsHost | undefined>(undefined);\n\n/**\n * The variants section of a component's own view, under its exposed fields;\n * where the host keeps them to that view (`editedInOwnView`), one line saying\n * so instead, with the way there when the host offers one.\n *\n * @experimental Settles when the component editor ships.\n */\nexport function ComponentVariantsSection(props: {\n  editor: EditorState;\n  component: ComponentDocument;\n}): React.JSX.Element {\n  const host = React.useContext(ComponentVariantsContext);\n  if (host?.editedInOwnView === true) {\n    return <VariantsInOwnView onOpen={host.onOpenOwnView} />;\n  }\n  return <VariantsSection {...props} host={host} />;\n}\n\n/**\n * Where a header or footer edited in place keeps its variants: said, so the\n * section's absence is not read as a component without any, and opened with\n * the same words the instance inspector uses for that view.\n */\nfunction VariantsInOwnView({\n  onOpen,\n}: {\n  onOpen: (() => void) | undefined;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-inspector__note-row\">\n      <p className=\"nx-inspector__note\">\n        Variants are edited in the component’s own view.\n      </p>\n      {onOpen === undefined ? null : (\n        <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={onOpen}>\n          Edit component\n        </Button>\n      )}\n    </div>\n  );\n}\n\n/** The section itself, given its host. */\nfunction VariantsSection({\n  editor,\n  component,\n  host,\n}: {\n  editor: EditorState;\n  component: ComponentDocument;\n  host: ComponentVariantsHost | undefined;\n}): React.JSX.Element {\n  const taken = useSeenKeys(component);\n  const context: VariantEditContext = { editor, component, taken };\n  const options = variantOptions(component);\n  const fields = exposedFields(component);\n  const headingId = React.useId();\n  // The variant whose values are open, held by the host where it previews\n  // it on the canvas, and the one just added, whose name is selected so\n  // typing renames it.\n  const [open, setOpen] = useOpenVariant(host?.preview);\n  const [fresh, setFresh] = React.useState<string | undefined>(undefined);\n  const [deleting, setDeleting] = React.useState<VariantOption | null>(null);\n  const [problem, setProblem] = React.useState<string | undefined>(undefined);\n\n  const add = () => {\n    const outcome = addVariant(context, nextVariantName(component));\n    if (!outcome.applied) {\n      setProblem(outcome.reason);\n      return;\n    }\n    setProblem(undefined);\n    setOpen(outcome.id);\n    setFresh(outcome.id);\n  };\n\n  return (\n    <section\n      aria-labelledby={headingId}\n      className=\"nx-variants\"\n      data-component-variants=\"\"\n    >\n      <div className=\"nx-variants__header\">\n        <h3 id={headingId} className=\"nx-inspector__heading\">\n          Variants\n        </h3>\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          disabled={fields.length === 0}\n          onClick={add}\n        >\n          <Plus size={14} aria-hidden=\"true\" />\n          Add variant\n        </Button>\n      </div>\n      {fields.length === 0 ? (\n        <p className=\"nx-inspector__note\">\n          Add a field first. A variant is a named set of values for the fields\n          each use of the component can change.\n        </p>\n      ) : options.length === 0 ? (\n        <p className=\"nx-inspector__note\">\n          No variants yet. A variant is a named set of field values, like\n          “Featured” or “Compact”, that each use of the component can choose.\n        </p>\n      ) : null}\n      {/*\n        Listed whether or not any field is left: removing the last field keeps\n        the emptied variants, and placements still offer them, so they stay\n        here to be renamed or deleted.\n      */}\n      {options.length === 0 ? null : (\n        <ul className=\"nx-variants__list\">\n          {options.map(option => (\n            <VariantRow\n              key={option.id}\n              context={context}\n              option={option}\n              fields={fields}\n              open={open === option.id}\n              selectName={fresh === option.id}\n              onToggle={() =>\n                setOpen(open === option.id ? undefined : option.id)\n              }\n              onNameSelected={() => setFresh(undefined)}\n              onDelete={() => setDeleting(option)}\n            />\n          ))}\n        </ul>\n      )}\n      {problem === undefined ? null : (\n        <p className=\"nx-variants__problem\" role=\"alert\">\n          {problem}\n        </p>\n      )}\n      {deleting === null ? null : (\n        <DeleteVariantDialog\n          context={context}\n          option={deleting}\n          host={host}\n          onClose={() => setDeleting(null)}\n        />\n      )}\n    </section>\n  );\n}\n\n/**\n * The open variant: the host's, where it previews it on the canvas, or the\n * section's own otherwise.\n */\nfunction useOpenVariant(\n  preview: VariantPreviewBinding | undefined\n): [string | undefined, (id: string | undefined) => void] {\n  const [own, setOwn] = React.useState<string | undefined>(undefined);\n  return preview === undefined ? [own, setOwn] : [preview.open, preview.onOpen];\n}\n\n/**\n * One variant: its name, how much it presets, and its values when open.\n */\nfunction VariantRow({\n  context,\n  option,\n  fields,\n  open,\n  selectName,\n  onToggle,\n  onNameSelected,\n  onDelete,\n}: {\n  context: VariantEditContext;\n  option: VariantOption;\n  fields: readonly ExposedProperty[];\n  open: boolean;\n  selectName: boolean;\n  onToggle: () => void;\n  onNameSelected: () => void;\n  onDelete: () => void;\n}): React.JSX.Element {\n  // Resolved once for the whole component while the values are open, not\n  // once per field.\n  const defaults = React.useMemo(\n    () =>\n      open ? defaultValues(context.component) : new Map<string, unknown>(),\n    [open, context.component]\n  );\n  const valuesId = React.useId();\n  const problemId = React.useId();\n  const nameRef = React.useRef<HTMLInputElement>(null);\n  // A refused rename's reason, said under the row.\n  const [problem, setProblem] = React.useState<string | undefined>(undefined);\n  React.useEffect(() => {\n    if (!selectName) return;\n    nameRef.current?.focus();\n    nameRef.current?.select();\n    onNameSelected();\n  }, [selectName, onNameSelected]);\n\n  return (\n    <li\n      className=\"nx-variants__item\"\n      data-variant-id={option.id}\n      data-open={open ? \"\" : undefined}\n    >\n      <div className=\"nx-variants__main\">\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          className=\"nx-variants__toggle\"\n          aria-expanded={open}\n          aria-controls={valuesId}\n          aria-label={`${open ? \"Hide\" : \"Show\"} the values of ${option.label}`}\n          onClick={onToggle}\n        >\n          <ChevronRight\n            size={14}\n            aria-hidden=\"true\"\n            className=\"nx-variants__chevron\"\n            data-open={open ? \"\" : undefined}\n          />\n        </Button>\n        <VariantName\n          context={context}\n          option={option}\n          inputRef={nameRef}\n          problemId={problemId}\n          problem={problem}\n          onProblem={setProblem}\n        />\n        <span\n          className=\"nx-variants__summary\"\n          data-empty={option.empty ? \"\" : undefined}\n        >\n          {valuesSummary(option)}\n        </span>\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          aria-label={`Delete the variant ${option.label}`}\n          title=\"Delete variant\"\n          onClick={onDelete}\n        >\n          <Trash2 size={14} aria-hidden=\"true\" />\n        </Button>\n      </div>\n      {problem === undefined ? null : (\n        <p id={problemId} className=\"nx-variants__problem\" role=\"alert\">\n          {problem}\n        </p>\n      )}\n      {open ? (\n        <div id={valuesId} className=\"nx-variants__values\">\n          {fields.length === 0 ? (\n            <p className=\"nx-inspector__note\">\n              This component has no fields, so this variant presets nothing.\n            </p>\n          ) : null}\n          {fields.map(field => (\n            <VariantValueRow\n              key={`${option.id}:${field.id}`}\n              context={context}\n              option={option}\n              field={field}\n              fallback={defaults.get(field.id)}\n            />\n          ))}\n        </div>\n      ) : null}\n    </li>\n  );\n}\n\n/** A variant's name, renamed in place. */\nfunction VariantName({\n  context,\n  option,\n  inputRef,\n  problemId,\n  problem,\n  onProblem,\n}: {\n  context: VariantEditContext;\n  option: VariantOption;\n  inputRef: React.Ref<HTMLInputElement>;\n  /** The id of the row's refusal sentence, which the input points to. */\n  problemId: string;\n  problem: string | undefined;\n  onProblem: (reason: string | undefined) => void;\n}): React.JSX.Element {\n  const [draft, setDraft] = useStoredDraft(option.label);\n  const send = () => {\n    if (draft === option.label) return;\n    const outcome = renameVariant(context, option.id, draft);\n    if (outcome.applied) {\n      onProblem(undefined);\n      return;\n    }\n    // Back to the stored name, with the reason: a blank or taken name is\n    // refused, and leaving it on screen would show a name the variant does not\n    // have.\n    setDraft(option.label);\n    onProblem(outcome.reason);\n  };\n  return (\n    <span className=\"nx-variants__name\">\n      <Input\n        ref={inputRef}\n        size=\"sm\"\n        className=\"nx-variants__name-input\"\n        value={draft}\n        aria-label={`Name of the variant ${option.label}`}\n        aria-describedby={problem === undefined ? undefined : problemId}\n        onChange={event => setDraft(event.target.value)}\n        onBlur={send}\n        onKeyDown={event => {\n          commitOnEnter(event, send);\n        }}\n      />\n    </span>\n  );\n}\n\n/**\n * What a variant presets for one field: the control, whether it is the\n * variant's value or the component's default, and the reset.\n */\nfunction VariantValueRow({\n  context,\n  option,\n  field,\n  fallback,\n}: {\n  context: VariantEditContext;\n  option: VariantOption;\n  field: ExposedProperty;\n  /** The component's own value, shown while the variant sets none. */\n  fallback: unknown;\n}): React.JSX.Element {\n  const id = `${React.useId()}-${field.id}`;\n  const set = Object.hasOwn(option.values, field.id);\n  const value = set ? option.values[field.id] : fallback;\n  const [problem, setProblem] = React.useState<string | undefined>(undefined);\n  const commit = (next: OverrideValue) => {\n    const outcome = setVariantValue(context, option.id, field.id, next);\n    setProblem(outcome.applied ? undefined : outcome.reason);\n  };\n  const reset = () => {\n    const outcome = resetVariantValue(context, option.id, field.id);\n    setProblem(outcome.applied ? undefined : outcome.reason);\n  };\n\n  // The inspector's own row grid, the placement panel's: the label (and its\n  // dot) in the label column, and the value with its Reset slot filling the\n  // rest, so a variant's row lines up with a placement's.\n  return (\n    <div\n      className=\"nx-inspector__field nx-variants__value\"\n      data-set={set ? \"\" : undefined}\n    >\n      <span className=\"nx-variants__value-label\">\n        {/* A dot in the component's hue marks a value this variant sets. */}\n        {set ? (\n          <span\n            className=\"nx-variants__dot\"\n            role=\"img\"\n            aria-label=\"Set by this variant\"\n          />\n        ) : null}\n        <Label htmlFor={id}>{field.label}</Label>\n      </span>\n      <span className=\"nx-variants__value-cell\">\n        <VariantValueControl\n          id={id}\n          field={field}\n          value={shownValue(field, value)}\n          onCommit={commit}\n        />\n        {/* A fixed slot, empty when nothing is set, so values line up. */}\n        <span className=\"nx-variants__reset-slot\">\n          {set ? (\n            <Button\n              type=\"button\"\n              variant=\"ghost\"\n              size=\"icon-sm\"\n              className=\"nx-variants__reset\"\n              aria-label={`Reset ${field.label} to the component’s default in ${option.label}`}\n              title=\"Reset to the component’s value\"\n              onClick={reset}\n            >\n              <RotateCcw size={14} aria-hidden=\"true\" />\n            </Button>\n          ) : null}\n        </span>\n      </span>\n      {problem === undefined ? null : (\n        <p className=\"nx-variants__problem\" role=\"alert\">\n          {problem}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/**\n * What a field's control shows for a stored value. A cleared field shows\n * empty, and a cleared visibility hides its part, as the resolver draws it.\n */\nfunction shownValue(field: ExposedProperty, value: unknown): unknown {\n  if (!isUnsetOverride(value)) return value;\n  return field.type === \"visibility\" ? false : undefined;\n}\n\n/** The control for one field's value, by the field's type. */\nfunction VariantValueControl({\n  id,\n  field,\n  value,\n  onCommit,\n}: {\n  id: string;\n  field: ExposedProperty;\n  value: unknown;\n  onCommit: (next: OverrideValue) => void;\n}): React.JSX.Element {\n  switch (field.type) {\n    case \"visibility\":\n      return <ShownValue id={id} value={value} onCommit={onCommit} />;\n    case \"select\":\n      return (\n        <ChoiceValue id={id} field={field} value={value} onCommit={onCommit} />\n      );\n    case \"text\":\n    case \"link\":\n      return (\n        <TextValue\n          id={id}\n          // A Text's one paragraph, the component's own value, shows its\n          // words; a variant sets plain words in its place.\n          value={\n            typeof value === \"string\"\n              ? value\n              : isRichTextValue(value)\n                ? oneParagraphLines(value)\n                : \"\"\n          }\n          onCommit={onCommit}\n        />\n      );\n    default:\n      return (\n        <p id={id} className=\"nx-variants__hint\">\n          Chosen where the component is used\n        </p>\n      );\n  }\n}\n\n/**\n * Whether the variant shows a part: the placements' own checkbox, saying\n * which, so a part reads the same in both panels.\n */\nfunction ShownValue({\n  id,\n  value,\n  onCommit,\n}: {\n  id: string;\n  value: unknown;\n  onCommit: (next: OverrideValue) => void;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-variants__check\">\n      <Checkbox\n        id={id}\n        checked={value !== false}\n        onCheckedChange={checked => onCommit(checked === true)}\n      />\n      <span>{value === false ? \"Hidden\" : \"Shown\"}</span>\n    </span>\n  );\n}\n\n/** One of a choice field's options. */\nfunction ChoiceValue({\n  id,\n  field,\n  value,\n  onCommit,\n}: {\n  id: string;\n  field: ExposedProperty;\n  value: unknown;\n  onCommit: (next: OverrideValue) => void;\n}): React.JSX.Element {\n  return (\n    <Select\n      value={typeof value === \"string\" ? `=${value}` : undefined}\n      onValueChange={next => onCommit(next.slice(1))}\n    >\n      <SelectTrigger id={id} size=\"sm\">\n        <SelectValue placeholder=\"Choose\" />\n      </SelectTrigger>\n      <SelectContent>\n        {choicesOf(field).map(choice => (\n          // Prefixed, because the primitive reserves the empty string for\n          // \"no selection\" and a choice may be \"\".\n          <SelectItem key={choice.value} value={`=${choice.value}`}>\n            {choice.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\n/**\n * A choice field's options, read defensively: a stored or imported field may\n * hold anything there, and only `{ value, label }` strings can be drawn.\n */\nfunction choicesOf(\n  field: ExposedProperty\n): readonly { value: string; label: string }[] {\n  const options: unknown = field.options;\n  if (!Array.isArray(options)) return [];\n  return options.filter(\n    (option): option is { value: string; label: string } =>\n      typeof option === \"object\" &&\n      option !== null &&\n      typeof (option as { value?: unknown }).value === \"string\" &&\n      typeof (option as { label?: unknown }).label === \"string\"\n  );\n}\n\n/** A text value, committed on blur or Enter. */\nfunction TextValue({\n  id,\n  value,\n  onCommit,\n}: {\n  id: string;\n  value: string;\n  onCommit: (next: OverrideValue) => void;\n}): React.JSX.Element {\n  const [draft, setDraft] = useStoredDraft(value);\n  const send = () => {\n    if (draft !== value) onCommit(draft);\n  };\n  // Words holding lines (a Text's) are edited in a field that keeps them.\n  if (value.includes(\"\\n\")) {\n    return (\n      <Textarea\n        id={id}\n        rows={3}\n        value={draft}\n        onChange={event => setDraft(event.target.value)}\n        onBlur={send}\n      />\n    );\n  }\n  return (\n    <Input\n      id={id}\n      size=\"sm\"\n      value={draft}\n      onChange={event => setDraft(event.target.value)}\n      onBlur={send}\n      onKeyDown={event => {\n        commitOnEnter(event, send);\n      }}\n    />\n  );\n}\n\n/**\n * Confirms a delete, with how many placements chose the variant. Counted when\n * the dialog opens, so the number is the one the designer confirms.\n */\nfunction DeleteVariantDialog({\n  context,\n  option,\n  host,\n  onClose,\n}: {\n  context: VariantEditContext;\n  option: VariantOption;\n  host: ComponentVariantsHost | undefined;\n  onClose: () => void;\n}): React.JSX.Element {\n  const use = useVariantUse(host, option.id);\n  const [problem, setProblem] = React.useState<string | undefined>(undefined);\n  const confirm = () => {\n    const outcome = deleteVariant(context, option.id);\n    if (outcome.applied) onClose();\n    else setProblem(outcome.reason);\n  };\n  return (\n    <Dialog\n      open\n      onOpenChange={next => {\n        if (!next) onClose();\n      }}\n    >\n      <DialogContent className=\"max-w-md\" data-delete-variant=\"\">\n        <DialogHeader>\n          <DialogTitle>Delete the variant “{option.label}”?</DialogTitle>\n          <DialogDescription aria-live=\"polite\">\n            {deleteSentence(use)}\n          </DialogDescription>\n        </DialogHeader>\n        {problem === undefined ? null : (\n          <p className=\"nx-variants__problem\" role=\"alert\">\n            {problem}\n          </p>\n        )}\n        <DialogFooter>\n          <Button type=\"button\" variant=\"outline\" onClick={onClose}>\n            Cancel\n          </Button>\n          <Button\n            type=\"button\"\n            variant=\"destructive\"\n            // Held while the count is out, so the delete is confirmed with\n            // the number in view; a count that failed does not hold it.\n            disabled={use === undefined}\n            onClick={confirm}\n          >\n            Delete variant\n          </Button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n\n/**\n * The host's count of a variant's placements: `undefined` while it is asked,\n * `null` when it cannot be counted.\n */\nfunction useVariantUse(\n  host: ComponentVariantsHost | undefined,\n  variantId: string\n): VariantUse | null | undefined {\n  const count = host?.countUse;\n  const [use, setUse] = React.useState<VariantUse | null | undefined>(\n    count === undefined ? null : undefined\n  );\n  React.useEffect(() => {\n    if (count === undefined) return;\n    let live = true;\n    count(variantId).then(\n      found => {\n        if (live) setUse(found);\n      },\n      () => {\n        if (live) setUse(null);\n      }\n    );\n    return () => {\n      live = false;\n    };\n  }, [count, variantId]);\n  return use;\n}\n","\"use client\";\n\n/**\n * The inspector's controls a lock holds, drawn read-only with the reason.\n *\n * @module held-by-lock\n */\nimport * as React from \"react\";\n\n/**\n * Whether a lock holds the controls drawn here. A disabled fieldset holds\n * every form control inside it but not a `contenteditable`, which reads this.\n */\nexport const HeldHere: React.Context<boolean> =\n  React.createContext<boolean>(false);\n\n/**\n * Controls a lock holds where the block sits, drawn as they are and disabled\n * together, pointing to the sentence that says why.\n *\n * A disabled fieldset rather than a flag threaded into every control: it\n * disables each form control inside it, the Style tab's and Advanced tab's\n * included, so no control can be missed, and a control added later is held\n * without knowing it is. The store refuses the same edits whatever the panel\n * draws; this says so before the author tries.\n */\nexport function HeldByLock({\n  reasonId,\n  children,\n}: {\n  /** The reason's element id; undefined when nothing is held. */\n  reasonId: string | undefined;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  if (reasonId === undefined) return <>{children}</>;\n  return (\n    <fieldset\n      disabled\n      aria-describedby={reasonId}\n      className=\"nx-inspector__held\"\n    >\n      <HeldHere.Provider value={true}>{children}</HeldHere.Provider>\n    </fieldset>\n  );\n}\n","\"use client\";\n\n/**\n * Advanced › Custom CSS: one block's own CSS, for a person who may change the\n * site's code, and the line the Style tab shows about it for everyone.\n *\n * The box holds a draft. Leaving it or pressing Apply checks the draft with\n * the host's checker (`BlockCustomCssAccess.check`, the one the server judges\n * the save by): CSS it accepts is stored on the block in one update, so one\n * undo takes it back; CSS it refuses is stored nowhere, and each refused line\n * is listed under the box with its reason. A change to the block's CSS from\n * anywhere else, an undo among them, puts the box back to what the block\n * holds.\n *\n * The Style tab's line reads only whether the block holds CSS. A person\n * without the permission is told it is there and who can change it, never\n * what it says.\n *\n * @module custom-css-section\n */\nimport { Button, Textarea } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\n\nimport {\n  CUSTOM_CSS_KEY,\n  CUSTOM_CSS_SECTION,\n  CUSTOM_CSS_SETTING,\n  customCssOp,\n  type BlockCustomCssAccess,\n} from \"./custom-css\";\nimport { HeldByLock } from \"./held-by-lock\";\nimport {\n  designReadOnlyReason,\n  lockViewOf,\n  type BlockInspection,\n} from \"./inspector\";\nimport type { PanelSection } from \"./panel-section\";\nimport { SettingSlot } from \"./settings-filter\";\n\n/** Said when the editor refuses the write, as Advanced's other fields say it. */\nconst NOT_SAVED =\n  \"That change could not be saved. A very long value can push the page past its size limit; otherwise the block may have changed since you opened this tab.\";\n\n// design-lint-ok: CSS shown to the author as an example to write, not a\n// colour the panel is drawn with.\nconst SELECTOR_EXAMPLE = \"selector { color: red; }\";\n\n/** What a block stores as its CSS, read as text; anything else is none. */\nfunction storedCss(stored: unknown): string | undefined {\n  return typeof stored === \"string\" ? stored : undefined;\n}\n\n/**\n * Advanced's Custom CSS section, for a person `access` is given to; none for\n * anyone else. The builder's own row, last in the tab: folded until opened\n * even while it holds CSS (its dot still shows), and held like HTML while the\n * design is locked.\n */\nexport function customCssSections({\n  access,\n  block,\n  stored,\n  editor,\n  active,\n  heldBy,\n}: {\n  access: BlockCustomCssAccess | undefined;\n  block: Pick<BlockInspection, \"nodeId\" | \"hasCustomCss\">;\n  /** The block's stored CSS, if it holds any. */\n  stored: unknown;\n  editor: EditorState;\n  /** Whether the Advanced tab is the one showing. */\n  active: boolean;\n  /** The lock reason's id while the design is locked; else undefined. */\n  heldBy: string | undefined;\n}): PanelSection[] {\n  if (access === undefined) return [];\n  return [\n    {\n      key: CUSTOM_CSS_KEY,\n      label: CUSTOM_CSS_SECTION,\n      holdsValue: block.hasCustomCss,\n      opensWithValue: false,\n      body: (\n        <SettingSlot ids={[CUSTOM_CSS_SETTING]}>\n          <HeldByLock reasonId={heldBy}>\n            <CustomCssSection\n              // Keyed by node, so a draft stays with its own block.\n              key={`${block.nodeId}:custom-css`}\n              nodeId={block.nodeId}\n              stored={stored}\n              editor={editor}\n              access={access}\n              active={active}\n            />\n          </HeldByLock>\n        </SettingSlot>\n      ),\n    },\n  ];\n}\n\n/**\n * Stores the box's text on the block if it may be stored, and answers what to\n * list under the box: the refused lines, the reason a write was refused, or\n * nothing once it is stored or nothing changed.\n */\nfunction storeDraft({\n  text,\n  held,\n  access,\n  editor,\n  nodeId,\n}: {\n  text: string;\n  held: string | undefined;\n  access: BlockCustomCssAccess;\n  editor: EditorState;\n  nodeId: string;\n}): readonly string[] {\n  // The box as it was filled: leaving it unchanged writes nothing.\n  if (text === (held ?? \"\")) return [];\n  // White space alone is no CSS: the block holds none.\n  const next = text.trim() === \"\" ? undefined : text;\n  if (next === held) return [];\n  const refused = next === undefined ? [] : access.check(next);\n  if (refused.length > 0) return refused;\n  // Asked of the live document, as every write in the panel asks.\n  const locked = designReadOnlyReason(\n    editor.document,\n    nodeId,\n    lockViewOf(editor)\n  );\n  if (locked !== undefined) return [locked];\n  return editor.apply(customCssOp(nodeId, text)) === null ? [NOT_SAVED] : [];\n}\n\n/**\n * Runs `leave` when the tab holding the box goes off screen, and when the box\n * goes away while it is on screen, with what the box holds then.\n */\nfunction useOnLeave(active: boolean, leave: () => void): void {\n  const latest = React.useRef(leave);\n  latest.current = leave;\n  const onScreen = React.useRef(active);\n  React.useEffect(() => {\n    const was = onScreen.current;\n    onScreen.current = active;\n    if (was && !active) latest.current();\n  }, [active]);\n  React.useEffect(\n    () => () => {\n      if (onScreen.current) latest.current();\n    },\n    []\n  );\n}\n\n/**\n * The box, its hint, Apply and the refused lines, for the block `nodeId`.\n * Keyed by the block where it is drawn, so a draft never moves to another.\n */\nfunction CustomCssSection({\n  nodeId,\n  stored,\n  editor,\n  access,\n  active,\n}: {\n  nodeId: string;\n  /** The block's stored CSS, if it holds any. */\n  stored: unknown;\n  editor: EditorState;\n  access: BlockCustomCssAccess;\n  /** Whether the Advanced tab is the one showing. */\n  active: boolean;\n}): React.JSX.Element {\n  const id = React.useId();\n  const held = storedCss(stored);\n  const [draft, setDraft] = React.useState(held ?? \"\");\n  const [problems, setProblems] = React.useState<readonly string[]>([]);\n  // The block's CSS changed under the box, by an undo, a redo or this box's\n  // own write: the box shows what the block now holds, and nothing it says\n  // about an earlier draft stays.\n  React.useEffect(() => {\n    setDraft(held ?? \"\");\n    setProblems([]);\n  }, [held]);\n\n  const commit = (): void =>\n    setProblems(storeDraft({ text: draft, held, access, editor, nodeId }));\n  // Checked when the author looks away (the tabs move on `mousedown`, before\n  // the blur), and when the box goes away while on screen, as Advanced's\n  // other fields are written.\n  useOnLeave(active, commit);\n\n  const hintId = `${id}-hint`;\n  const problemsId = `${id}-problems`;\n  return (\n    <div className=\"nx-custom-css\">\n      <p id={hintId} className=\"nx-custom-css__hint\">\n        Write <code>selector</code> for this block:{\" \"}\n        <code>{SELECTOR_EXAMPLE}</code>. Applies to this block only, on every\n        device.\n      </p>\n      <Textarea\n        value={draft}\n        aria-label={CUSTOM_CSS_SECTION}\n        aria-describedby={\n          problems.length === 0 ? hintId : `${hintId} ${problemsId}`\n        }\n        aria-invalid={problems.length === 0 ? undefined : true}\n        spellCheck={false}\n        autoCapitalize=\"off\"\n        autoComplete=\"off\"\n        autoCorrect=\"off\"\n        rows={6}\n        className=\"nx-custom-css__box\"\n        onChange={event => setDraft(event.target.value)}\n        onBlur={commit}\n      />\n      {/* Under the box and above the refused lines, so a list appearing as\n          the box is left moves no button the pointer is on its way to. */}\n      <div className=\"nx-custom-css__actions\">\n        <Button type=\"button\" size=\"sm\" variant=\"outline\" onClick={commit}>\n          Apply\n        </Button>\n      </div>\n      {problems.length === 0 ? null : (\n        <div id={problemsId} role=\"alert\" className=\"nx-custom-css__problems\">\n          <ul>\n            {problems.map((problem, at) => (\n              // Two refusals can read the same, so their place keeps them apart.\n              <li key={`${String(at)}:${problem}`}>{problem}</li>\n            ))}\n          </ul>\n        </div>\n      )}\n    </div>\n  );\n}\n\n/**\n * The line at the top of the Style tab while the block holds custom CSS.\n * With the permission it links to the box (\"Edit\" asks the panel for the\n * setting, which shows Advanced, opens the section and focuses the box);\n * without it, it says who can change the CSS, and nothing of what it says.\n */\nexport function CustomCssStyleLine({\n  nodeId,\n  hasCustomCss,\n  access,\n  editor,\n}: {\n  nodeId: string;\n  hasCustomCss: boolean;\n  access: BlockCustomCssAccess | undefined;\n  editor: Pick<EditorState, \"askSetting\">;\n}): React.JSX.Element | null {\n  if (!hasCustomCss) return null;\n  // The way to the box, where the editor can take the author to a setting.\n  const ask = editor.askSetting;\n  if (access === undefined) {\n    return (\n      <p className=\"nx-settings-note nx-custom-css-line\">\n        This block also has custom CSS, set by someone who can change site code.\n      </p>\n    );\n  }\n  if (ask === undefined) {\n    return (\n      <p className=\"nx-settings-note nx-custom-css-line\">\n        This block also has custom CSS.\n      </p>\n    );\n  }\n  return (\n    <p className=\"nx-settings-note nx-custom-css-line\">\n      {\"This block also has custom CSS · \"}\n      <button\n        type=\"button\"\n        className=\"nx-settings-note__link\"\n        onClick={() => ask(nodeId, { tab: \"advanced\", id: CUSTOM_CSS_SETTING })}\n      >\n        Edit\n      </button>\n    </p>\n  );\n}\n","/**\n * What a Layers row's own actions do: hide or show its block on the device\n * being edited, and the keystrokes that reach the row's actions from the\n * keyboard; and where a block is hidden, device by device, as the row, Hide\n * on and the panel's line say it.\n *\n * Pure, so the write each action makes is asserted without a DOM. The panel\n * draws the buttons and the menu; what they write is decided here, and the\n * block's lock is judged by the editor's own question when the op is applied.\n *\n * @module layer-row-actions\n */\n\nimport {\n  deviceVisibility,\n  findNode,\n  hiddenOnDevice,\n  setDeviceVisibility,\n  type BlockDocument,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { DeviceRange } from \"../../inspector/code-hints\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport {\n  deviceOptions,\n  type DeviceOption,\n} from \"../../shell/breakpoint-switcher\";\n\n/** A device the site defines, and whether a block is hidden there. */\nexport interface DeviceState extends DeviceOption {\n  /** Whether a visitor on this device sees nothing of the block. */\n  readonly hidden: boolean;\n  /** The widths the device covers, which hiding it writes `display` at. */\n  readonly widths: DeviceRange;\n}\n\n/**\n * Each device the site defines, widest first, with whether the block is\n * hidden there: its RESOLVED state, read through the engine's cascade, so a\n * device the block is hidden on through a wider one reads as hidden too.\n */\nexport function deviceStates(\n  visibility: unknown,\n  breakpoints: BreakpointSet | undefined\n): DeviceState[] {\n  const shown = new Map(\n    deviceVisibility(visibility, breakpoints).map(device => [\n      device.id,\n      device.visible,\n    ])\n  );\n  const options = deviceOptions(breakpoints);\n  return options.map((option, index) => {\n    // Desktop-first: a device covers from just above the next narrower one's\n    // bound up to its own, and the widest has no upper bound.\n    const narrower = options[index + 1]?.preview;\n    return {\n      ...option,\n      hidden: shown.get(option.id) === false,\n      widths: {\n        from: narrower === undefined ? undefined : narrower + 1,\n        to: index === 0 ? undefined : option.preview,\n      },\n    };\n  });\n}\n\n/** The names of the devices the block is hidden on, widest first. */\nexport function hiddenDeviceNames(\n  visibility: unknown,\n  breakpoints: BreakpointSet | undefined\n): string[] {\n  return deviceStates(visibility, breakpoints)\n    .filter(device => device.hidden)\n    .map(device => device.label);\n}\n\n/** \"Mobile\", \"Tablet and Mobile\", \"Desktop, Tablet and Mobile\". */\nexport function listedNames(names: readonly string[]): string {\n  if (names.length <= 1) return names.join(\"\");\n  return `${names.slice(0, -1).join(\", \")} and ${names[names.length - 1]}`;\n}\n\n/** The device a row's eye acts on: the site's breakpoints and the one edited. */\nexport interface EyeDevice {\n  readonly breakpoints: BreakpointSet | undefined;\n  /** The breakpoint being edited, the one the canvas shows. */\n  readonly id: string;\n}\n\n/**\n * The op that flips a block's visibility on the device being edited, and on\n * that device only: every other device keeps showing what it showed. `null`\n * for a block the document does not hold.\n *\n * Written through the engine's per-device writer, so the stored values are\n * the fewest that resolve to what the author asked for, read by the cascade\n * the published stylesheet is compiled from. A block left visible everywhere\n * stores no visibility at all, its conditions apart.\n */\nexport function toggleOnDeviceOp(\n  document: BlockDocument,\n  id: string,\n  device: EyeDevice\n): BuilderOp | null {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return null;\n  const hidden = hiddenOnDevice(node.visibility, device.breakpoints, device.id);\n  const next = setDeviceVisibility(\n    node.visibility,\n    device.breakpoints,\n    device.id,\n    hidden\n  );\n  return next === undefined\n    ? { kind: \"update\", id, patch: {}, unset: [\"visibility\"] }\n    : { kind: \"update\", id, patch: { visibility: next } };\n}\n\n/** The verbs a row's keystrokes run. */\nexport type RowKeyAction = \"rename\" | \"toggle-hidden\" | \"toggle-lock\";\n\n/**\n * The keystrokes, as the menu shows them beside each verb. F2 renames, as in\n * every file and layer tree; the eye and the lock take the chords Figma gives\n * them, since the icons themselves are pointer-only.\n */\nexport const ROW_KEYS: Readonly<Record<RowKeyAction, string>> = {\n  rename: \"F2\",\n  \"toggle-hidden\": \"mod+shift+h\",\n  \"toggle-lock\": \"mod+shift+l\",\n};\n\n/**\n * Which row verb a key press asks for, or `null`. `mod` is Command on an\n * Apple keyboard and Control elsewhere, as every editor binding reads it.\n */\nexport function rowKeyAction(\n  event: Pick<\n    KeyboardEvent,\n    \"key\" | \"metaKey\" | \"ctrlKey\" | \"shiftKey\" | \"altKey\"\n  >,\n  apple: boolean\n): RowKeyAction | null {\n  if (event.altKey) return null;\n  const mod = apple ? event.metaKey : event.ctrlKey;\n  if (event.key === \"F2\" && !mod && !event.shiftKey) return \"rename\";\n  if (!mod || !event.shiftKey) return null;\n  const key = event.key.toLowerCase();\n  if (key === \"h\") return \"toggle-hidden\";\n  if (key === \"l\") return \"toggle-lock\";\n  return null;\n}\n","\"use client\";\n\n/**\n * \"Hide on\" in the Advanced tab: one toggle per device the site defines, each\n * with its icon and its name, pressed where the block is hidden; and the line\n * at the top of every tab saying where a block is hidden.\n *\n * Each device shows its RESOLVED state, the one a visitor on that device\n * gets, read through the engine's cascade rather than from the stored\n * values: a block hidden from Desktop down is hidden on Tablet too, though\n * nothing is stored for Tablet. A press changes that device alone, as the\n * Layers eye does, so every other device keeps what it showed: hiding on\n * Desktop leaves Tablet and Mobile showing, which the line under the toggles\n * says.\n *\n * @module hide-on\n */\n\nimport { findNode, type BreakpointSet } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport {\n  deviceStates,\n  hiddenDeviceNames,\n  listedNames,\n  toggleOnDeviceOp,\n} from \"../panels/layers/layer-row-actions\";\nimport { tierIcon } from \"../shell/breakpoint-switcher\";\n\nimport { hideOnWrites } from \"./code-hints\";\nimport { CssHint } from \"./css-hint\";\nimport { withSectionFold } from \"./panel-folds\";\nimport { usePanelFolds } from \"./panel-folds-context\";\nimport { useFilterState } from \"./settings-filter\";\n\n/** Whether the site's breakpoints are its own set yet, as the editor reads it. */\nexport type BreakpointsStatus = \"loading\" | \"unavailable\" | \"ready\";\n\n/** The Advanced section Hide on is drawn in, which \"Change\" opens. */\nconst HIDE_ON_SECTION = \"Visibility\";\n\n/** Marks the Hide on field, which \"Change\" moves focus into. */\nconst HIDE_ON_ATTRIBUTE = \"data-hide-on\";\n\nexport interface HideOnProps {\n  readonly editor: EditorState;\n  readonly nodeId: string;\n  /** The site's breakpoints. */\n  readonly breakpoints: BreakpointSet | undefined;\n  /** The device being edited, marked among the others. */\n  readonly editing: string;\n  /**\n   * Whether `breakpoints` is the site's own set: while it is being read, or\n   * when the read failed, the toggles are held, since a change resolved\n   * against a stand-in set is stored wrong, and a sentence says which.\n   */\n  readonly status?: BreakpointsStatus;\n  /**\n   * Why a lock holds the block's design, which includes where it shows, or\n   * `undefined` while nothing does: the inspector's own reading, which holds\n   * every other design control.\n   */\n  readonly heldBy?: string | undefined;\n  /** The id of the element saying why, which held toggles point to. */\n  readonly reasonId?: string;\n}\n\n/** What the control says while it cannot be used, by why. */\nconst STATUS_WORDS: Readonly<\n  Record<Exclude<BreakpointsStatus, \"ready\">, string>\n> = {\n  loading: \"Reading the site's breakpoints…\",\n  unavailable:\n    \"The site's breakpoints could not be read, so where this block shows can't be changed here. Reload to try again.\",\n};\n\n/** Said under the toggles: a press hides that device alone. */\nconst ONLY_THOSE_PICKED =\n  \"Hides only on the devices you pick, not smaller ones.\";\n\nexport function HideOn({\n  editor,\n  nodeId,\n  breakpoints,\n  editing,\n  status = \"ready\",\n  heldBy,\n  reasonId,\n}: HideOnProps): React.JSX.Element | null {\n  const labelId = React.useId();\n  const node = findNode(editor.document.nodes, nodeId);\n  if (node === undefined) return null;\n  const devices = deviceStates(node.visibility, breakpoints);\n  // Held whole while a lock holds the block's design, as every other design\n  // control is, and until the site's breakpoints are known.\n  const held = status !== \"ready\" || heldBy !== undefined;\n  return (\n    <div className=\"nx-inspector__field\" {...{ [HIDE_ON_ATTRIBUTE]: \"\" }}>\n      <p className=\"nx-inspector__field-name\" id={labelId}>\n        Hide on\n      </p>\n      <div\n        className=\"nx-hide-on\"\n        role=\"group\"\n        aria-labelledby={labelId}\n        {...(heldBy === undefined || reasonId === undefined\n          ? {}\n          : { \"aria-describedby\": reasonId })}\n      >\n        {devices.map(device => {\n          const Icon = tierIcon(device.preview);\n          return (\n            <CssHint key={device.id} writes={hideOnWrites(device.widths)}>\n              <button\n                type=\"button\"\n                className=\"nx-hide-on__toggle\"\n                aria-pressed={device.hidden}\n                aria-label={`Hide on ${device.label}`}\n                disabled={held}\n                {...(device.id === editing ? { \"data-editing\": \"\" } : {})}\n                onClick={() => {\n                  const op = toggleOnDeviceOp(editor.document, nodeId, {\n                    breakpoints,\n                    id: device.id,\n                  });\n                  if (op !== null) editor.apply(op);\n                }}\n              >\n                <Icon className=\"nx-hide-on__icon\" />\n                <span className=\"nx-hide-on__name\">{device.label}</span>\n              </button>\n            </CssHint>\n          );\n        })}\n      </div>\n      <p className=\"nx-inspector__note\" aria-live=\"polite\">\n        {status === \"ready\" ? ONLY_THOSE_PICKED : STATUS_WORDS[status]}\n      </p>\n    </div>\n  );\n}\n\n/**\n * The line at the top of a tab while the block is hidden on any device:\n * \"Hidden on Mobile. Visitors on that device won't see it.\" From a tab other\n * than Advanced it ends in \"Change\", which takes the author to Hide on.\n * Nothing while the block shows everywhere.\n */\nexport function HiddenStatus({\n  editor,\n  nodeId,\n  breakpoints,\n  onChoose,\n}: {\n  readonly editor: EditorState;\n  readonly nodeId: string;\n  readonly breakpoints: BreakpointSet | undefined;\n  /**\n   * Show another tab, for \"Change\"; absent on the Advanced tab, where Hide\n   * on is already in view.\n   */\n  readonly onChoose?: ((tab: \"advanced\") => void) | undefined;\n}): React.JSX.Element | null {\n  const node = findNode(editor.document.nodes, nodeId);\n  const toHideOn = useToHideOn(onChoose);\n  if (node === undefined) return null;\n  const names = hiddenDeviceNames(node.visibility, breakpoints);\n  if (names.length === 0) return null;\n  const visitors = names.length === 1 ? \"that device\" : \"those devices\";\n  return (\n    <p className=\"nx-settings-note nx-hidden-status\">\n      {`Hidden on ${listedNames(names)}. Visitors on ${visitors} won't see it.`}\n      {toHideOn === undefined ? null : (\n        <>\n          {\" \"}\n          <button\n            type=\"button\"\n            className=\"nx-settings-note__link\"\n            onClick={toHideOn}\n          >\n            Change\n          </button>\n        </>\n      )}\n    </p>\n  );\n}\n\n/**\n * \"Change\": the Advanced tab shown, its Visibility section opened, and focus\n * on Hide on's first toggle once it is on screen. A search that would keep\n * Hide on out is cleared first; \"Only changed\" keeps it, since a hidden block\n * holds a value there. `undefined` where there is no other tab to go from.\n */\nfunction useToHideOn(\n  onChoose: ((tab: \"advanced\") => void) | undefined\n): ((event: React.MouseEvent<HTMLElement>) => void) | undefined {\n  const { change } = usePanelFolds();\n  const { query, setQuery } = useFilterState();\n  if (onChoose === undefined) return undefined;\n  return event => {\n    if (query !== \"\") setQuery(\"\");\n    // Read now: the tab holding this link may be gone once Advanced shows.\n    const panel = event.currentTarget.closest(\".nx-inspector\");\n    change(folds => withSectionFold(folds, \"advanced\", HIDE_ON_SECTION, true));\n    onChoose(\"advanced\");\n    // A frame later, once the tab and the section are drawn open.\n    requestAnimationFrame(() => {\n      panel\n        ?.querySelector<HTMLElement>(`[${HIDE_ON_ATTRIBUTE}] button`)\n        ?.focus();\n    });\n  };\n}\n","/**\n * The op that sets a block's visibility conditions, for the editor's \"Show\n * when\" controls and the page actions API alike, so both write a block's\n * conditions the one way: the engine's `withConditions`, which keeps the\n * devices a block shows on and stores nothing for a block shown everywhere\n * to everyone.\n *\n * @module condition-ops\n */\nimport {\n  findNode,\n  withConditions,\n  type BlockDocument,\n  type Condition,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\n\n/**\n * The op setting a block's conditions to `conditions`, an OR of AND groups;\n * `null` or no groups removes them. `null` when the document holds no such\n * block.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function conditionsOp(\n  document: BlockDocument,\n  id: string,\n  conditions: readonly (readonly Condition[])[] | null\n): BuilderOp | null {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return null;\n  const next = withConditions(node.visibility, conditions ?? undefined);\n  return next === undefined\n    ? { kind: \"update\", id, patch: {}, unset: [\"visibility\"] }\n    : { kind: \"update\", id, patch: { visibility: next } };\n}\n","\"use client\";\n\n/**\n * \"Show when\": a block's visibility conditions, in the Advanced tab under\n * \"Visible on\". One AND group, edited as the list's filters are: one\n * sentence per condition, opening in place into its field, operator and\n * value. Only fields visitors can see are offered, since whether a block\n * shows would otherwise reveal the field.\n *\n * A block in a list's per-entry slot reads the list's item; every other\n * block reads the entry the page shows. Groups set through the API, which\n * this edits only one of, are shown read-only, with a way to keep the first.\n *\n * @module condition-controls\n */\nimport {\n  CONDITION_MAX,\n  conditionIssues,\n  conditionOp,\n  findNode,\n  outerListOf,\n  readListQuery,\n  type BindingFieldShape,\n  type BlockNode,\n  type Condition,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { AlertCircle, FileText, Plus, Repeat } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport {\n  LoopPicker,\n  useLoopCollections,\n} from \"../inspector/content/collection-loop-controls\";\nimport type {\n  ContentServices,\n  LoopCollection,\n  LoopListField,\n} from \"../inspector/content/content-controls\";\nimport {\n  fieldList,\n  fieldSourceOf,\n  FilterValue,\n  LimitNote,\n  listLimit,\n  PUBLIC_ONLY,\n  useCustomSources,\n  useEntryTitles,\n} from \"../inspector/content/list-query-controls\";\nimport {\n  customSourceLookup,\n  type CustomSource,\n} from \"../inspector/content/named-query-model\";\nimport {\n  SentenceRow,\n  useSentenceRows,\n  type SentenceRows,\n  type ShownRow,\n} from \"../inspector/content/sentence-row\";\n\nimport { storedGroups } from \"./condition-checks\";\nimport { gatedAsStored } from \"./condition-gate\";\nimport {\n  asListField,\n  booleanValueOf,\n  choiceKey,\n  completedCondition,\n  conditionChoices,\n  conditionDraftOf,\n  conditionFieldsOf,\n  conditionFieldsOfShapes,\n  conditionLine,\n  conditionSentence,\n  valueOpFor,\n  type ConditionField,\n  type DraftCondition,\n} from \"./condition-model\";\nimport { conditionsOp } from \"./condition-ops\";\n\nexport interface ShowWhenProps {\n  readonly editor: EditorState;\n  readonly nodeId: string;\n  readonly services: ContentServices | undefined;\n  /** Why a lock holds the block's design, which includes where it shows. */\n  readonly heldBy?: string | undefined;\n  /** The id of the element saying why, which held controls point to. */\n  readonly reasonId?: string;\n}\n\n/** Whose fields a block's conditions read, and how the group names it. */\ninterface ConditionSource {\n  /** The collection read, or `null` for a page with no entry. */\n  readonly collection: string | null | undefined;\n  /**\n   * \"Each post in the list\", \"This post\", \"No entry here\". The panel shows it\n   * only inside a list, or where the page has no entry.\n   */\n  readonly words: string;\n  /** What the conditions must match: \"this post\", \"each post in the list\". */\n  readonly match: string;\n  readonly item: boolean;\n  /**\n   * The fields an item has where the list's source is a named query whose\n   * rows are a schema of their own, which no collection holds.\n   */\n  readonly rowFields?: readonly BindingFieldShape[];\n}\n\n/** One entry's name in a sentence: \"post\", \"page\". */\nfunction oneOf(found: LoopCollection | undefined): string {\n  return (found?.singular ?? found?.label ?? \"entry\").toLowerCase();\n}\n\n/** Where the block's conditions read, as the save judges it. */\nfunction sourceOf(\n  node: BlockNode,\n  nodes: BlockNode[],\n  entryCollection: string | null | undefined,\n  collections: readonly LoopCollection[],\n  customs: readonly CustomSource[] | undefined\n): ConditionSource {\n  const outer = outerListOf(nodes, node.id);\n  if (outer !== undefined) {\n    const { query } = readListQuery(outer.props);\n    // A custom source's items are its query's rows: entries of the\n    // collection they name, or rows of the query's own fields.\n    const rows =\n      query.namedQuery === undefined\n        ? undefined\n        : customs?.find(\n            each => each.declaration.name === query.namedQuery?.name\n          )?.declaration.rows;\n    const collection =\n      rows === undefined\n        ? query.collection\n        : \"collection\" in rows\n          ? rows.collection\n          : undefined;\n    const found = collections.find(each => each.slug === collection);\n    return {\n      collection,\n      words: `Each ${oneOf(found)} in the list`,\n      match: `each ${oneOf(found)} in the list`,\n      item: true,\n      ...(rows !== undefined && \"fields\" in rows\n        ? { rowFields: rows.fields }\n        : {}),\n    };\n  }\n  if (entryCollection === null) {\n    return {\n      collection: null,\n      words: \"No entry here\",\n      match: \"an entry\",\n      item: false,\n    };\n  }\n  const found = collections.find(each => each.slug === entryCollection);\n  return {\n    collection: entryCollection,\n    words: `This ${oneOf(found)}`,\n    match: `this ${oneOf(found)}`,\n    item: false,\n  };\n}\n\n/** What the engine finds wrong with the block's conditions, as a save would. */\nfunction problemsOf(\n  editor: EditorState,\n  nodeId: string,\n  collections: readonly LoopCollection[] | undefined,\n  entryCollection: string | null | undefined,\n  customs: readonly CustomSource[] | undefined\n): { rows: ReadonlyMap<number, string>; whole: readonly string[] } {\n  const found = conditionIssues(editor.document.nodes, {\n    ...(collections === undefined\n      ? {}\n      : { fields: fieldSourceOf(collections) }),\n    ...(entryCollection === undefined ? {} : { entryCollection }),\n    // A custom source's items judged by its query's rows, as the save does.\n    ...(customs === undefined\n      ? {}\n      : { namedQueries: customSourceLookup(customs) }),\n  }).filter(issue => issue.nodeId === nodeId && issue.severity === \"error\");\n  const rows = new Map<number, string>();\n  const whole: string[] = [];\n  for (const issue of found) {\n    // `/…/visibility/conditions/0/2` is the third condition of the group.\n    const index = /\\/visibility\\/conditions\\/0\\/(\\d+)$/.exec(issue.path)?.[1];\n    if (index === undefined) whole.push(issue.message);\n    else rows.set(Number(index), issue.message);\n  }\n  return { rows, whole };\n}\n\n/** A condition row as it stands: what is stored, or the draft over it. */\ntype ShownCondition = ShownRow<DraftCondition>;\n\n/** What a row is drawn with, closed or open. */\ninterface ConditionRowProps {\n  readonly id: string;\n  readonly row: ShownCondition;\n  readonly fields: readonly ConditionField[];\n  readonly open: boolean;\n  readonly disabled: boolean;\n  readonly storedProblem: string | undefined;\n  readonly services: ContentServices | undefined;\n  readonly entryTitle: (id: string) => string | undefined;\n  readonly onOpen: () => void;\n  readonly onClose: () => void;\n  readonly onChange: (draft: DraftCondition) => void;\n  readonly onRemove: () => void;\n}\n\n/** A row's field: picking one starts it on that field's first operator. */\nfunction ConditionFieldPicker({\n  id,\n  labelId,\n  props,\n  field,\n}: {\n  id: string;\n  labelId: string;\n  props: ConditionRowProps;\n  field: ConditionField | undefined;\n}): React.JSX.Element {\n  const { row, fields, disabled, onChange } = props;\n  const name = row.draft.field;\n  return (\n    <LoopPicker\n      id={id}\n      labelId={labelId}\n      value={\n        name === undefined\n          ? { words: \"Choose a field\", state: \"prompt\" }\n          : field === undefined\n            ? { words: `${name} (not offered here)`, state: \"unknown\" }\n            : { words: field.label, state: \"value\" }\n      }\n      disabled={disabled}\n      list={fieldList(fields, name ?? \"\", \"Fields to check\")}\n      around={{ below: PUBLIC_ONLY }}\n      defaultOpen={name === undefined}\n      onPick={choice => {\n        const first = conditionChoices(choice.field.kind)[0];\n        if (choice.field.name === name || first === undefined) return;\n        onChange({ field: choice.field.name, op: first.op });\n      }}\n    />\n  );\n}\n\n/** A row's operator, from those its field's kind offers. */\nfunction ConditionOperatorPicker({\n  id,\n  field,\n  draft,\n  disabled,\n  onChange,\n}: {\n  id: string;\n  field: ConditionField;\n  draft: DraftCondition;\n  disabled: boolean;\n  onChange: (draft: DraftCondition) => void;\n}): React.JSX.Element {\n  const choices = conditionChoices(field.kind, draft.op);\n  return (\n    <Select\n      value={draft.op === undefined ? \"\" : choiceKey(draft.op)}\n      // A lone choice is still offered when the row holds another operator,\n      // so a stored one the field doesn't take can be repaired here.\n      disabled={\n        disabled ||\n        (choices.length === 1 &&\n          draft.op !== undefined &&\n          choices[0]?.key === choiceKey(draft.op))\n      }\n      onValueChange={key => {\n        const choice = choices.find(each => each.key === key);\n        if (choice === undefined) return;\n        // The value carries over where the new operator compares one.\n        onChange({ field: field.name, op: choice.op, value: draft.value });\n      }}\n    >\n      <SelectTrigger\n        id={id}\n        size=\"sm\"\n        aria-label={`How ${field.label} is compared`}\n        className=\"nx-list-filter__op-pick\"\n        data-wide={\n          draft.op !== undefined && valueOpFor(draft.op) === undefined\n            ? \"\"\n            : undefined\n        }\n      >\n        <SelectValue placeholder=\"Compare\" />\n      </SelectTrigger>\n      <SelectContent>\n        {choices.map(choice => (\n          <SelectItem key={choice.key} value={choice.key}>\n            {choice.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\n/** A condition's value, chosen with the list filter's control for it. */\nfunction ConditionValue({\n  props,\n  field,\n  labelId,\n  errorId,\n  problem,\n}: {\n  props: ConditionRowProps;\n  field: ConditionField;\n  labelId: string;\n  errorId: string;\n  problem: string | undefined;\n}): React.JSX.Element | null {\n  const { id, row, disabled } = props;\n  const op = row.draft.op;\n  const valueOp = op === undefined ? undefined : valueOpFor(op);\n  // A field no list filters by takes no value: it is only asked if it has one.\n  const listField = asListField(field);\n  if (op === undefined || valueOp === undefined || listField === undefined) {\n    return null;\n  }\n  return (\n    <FilterValue\n      id={`${id}-value`}\n      labelledBy={labelId}\n      field={listField}\n      draft={{\n        field: field.name,\n        op: valueOp,\n        value: booleanValueOf(op) ?? row.draft.value,\n      }}\n      disabled={disabled}\n      invalid={problem !== undefined}\n      describedBy={problem === undefined ? undefined : errorId}\n      services={props.services}\n      entryTitle={props.entryTitle}\n      onValue={value =>\n        props.onChange(\n          // \"is\" stores Yes or No as its operator; a stored `equals` or\n          // `not_equals` keeps its operator and takes the value.\n          field.kind === \"boolean\" && op !== \"equals\" && op !== \"not_equals\"\n            ? {\n                field: field.name,\n                op: value === false ? \"is_false\" : \"is_true\",\n              }\n            : { ...row.draft, value }\n        )\n      }\n    />\n  );\n}\n\n/** One condition: its sentence, opening in place into its controls. */\nfunction ConditionRow(props: ConditionRowProps): React.JSX.Element {\n  const { id, row, fields, storedProblem, entryTitle, disabled } = props;\n  const field = fields.find(each => each.name === row.draft.field);\n  const sentence = conditionSentence(row.draft, field, entryTitle);\n  const completed = completedCondition(row.draft, field);\n  const missing =\n    row.draft.field !== undefined && \"missing\" in completed\n      ? completed.missing\n      : undefined;\n  const problem = storedProblem ?? missing;\n  return (\n    <SentenceRow\n      id={id}\n      noun=\"condition\"\n      open={props.open}\n      disabled={disabled}\n      sentence={sentence}\n      line={conditionLine(sentence)}\n      problem={problem}\n      field={labelId => (\n        <ConditionFieldPicker\n          id={`${id}-field`}\n          labelId={labelId}\n          props={props}\n          field={field}\n        />\n      )}\n      body={(labelId, errorId) =>\n        field === undefined ? null : (\n          <div className=\"nx-list-filter__body\">\n            <ConditionOperatorPicker\n              id={`${id}-op`}\n              field={field}\n              draft={row.draft}\n              disabled={disabled}\n              onChange={props.onChange}\n            />\n            <ConditionValue\n              props={props}\n              field={field}\n              labelId={labelId}\n              errorId={errorId}\n              problem={problem}\n            />\n          </div>\n        )\n      }\n      onOpen={props.onOpen}\n      onClose={props.onClose}\n      onRemove={props.onRemove}\n    />\n  );\n}\n\n/** Groups set through the API: shown as they read, with a way to keep one. */\nfunction StoredGroups({\n  groups,\n  fields,\n  disabled,\n  entryTitle,\n  onKeepFirst,\n}: {\n  groups: readonly (readonly Condition[])[];\n  fields: readonly ConditionField[];\n  disabled: boolean;\n  entryTitle: (id: string) => string | undefined;\n  onKeepFirst: () => void;\n}): React.JSX.Element {\n  return (\n    <>\n      <p className=\"nx-inspector__note nx-list-query__hint\">\n        Shown when any of these groups match. They were set through the API.\n      </p>\n      <div className=\"nx-show-when__groups\">\n        {groups.map((group, index) => (\n          <React.Fragment key={index}>\n            {index === 0 ? null : <span className=\"nx-show-when__or\">or</span>}\n            <div className=\"nx-show-when__group\">\n              {group.map((condition, at) => {\n                // Related entries by their titles, as an open row names them,\n                // so two groups on different entries read apart.\n                const sentence = conditionSentence(\n                  conditionDraftOf(condition),\n                  fields.find(each => each.name === condition.field),\n                  entryTitle\n                );\n                return (\n                  <span key={at} className=\"nx-show-when__line\">\n                    <span className=\"nx-list-filter__field\">\n                      {sentence.field}\n                    </span>{\" \"}\n                    <span className=\"nx-list-filter__op\">\n                      {sentence.operator}\n                    </span>{\" \"}\n                    {sentence.value}\n                  </span>\n                );\n              })}\n            </div>\n          </React.Fragment>\n        ))}\n      </div>\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        className=\"nx-show-when__keep\"\n        disabled={disabled}\n        onClick={onKeepFirst}\n      >\n        Edit as one group\n      </Button>\n      <p className=\"nx-inspector__hint\">\n        Editing here keeps the first group and removes the others. Undo brings\n        them back.\n      </p>\n    </>\n  );\n}\n\n/** What the engine found wrong, shown once over the whole group. */\ntype ConditionProblems = ReturnType<typeof problemsOf>;\n\n/** Why visitors never see the block, when a condition can't be checked. */\nfunction ShowWhenNotice({\n  problems,\n  unreadable,\n}: {\n  problems: ConditionProblems;\n  /** Conditions stored in a shape no row can show, which the page leaves out. */\n  unreadable: boolean;\n}): React.JSX.Element | null {\n  if (!unreadable && problems.whole.length === 0 && problems.rows.size === 0) {\n    return null;\n  }\n  return (\n    <div className=\"nx-show-when__notice\" role=\"alert\">\n      <AlertCircle aria-hidden=\"true\" size={14} />\n      <p>\n        <strong>Visitors never see this block.</strong>{\" \"}\n        {noticeWords(problems, unreadable)}\n      </p>\n    </div>\n  );\n}\n\n/** Why the page leaves the block out, in the notice's words. */\nfunction noticeWords(problems: ConditionProblems, unreadable: boolean): string {\n  // A shape the condition reader leaves to the format check, which the\n  // engine's own findings therefore don't cover; the page still leaves the\n  // block out, so the notice says so.\n  if (unreadable) {\n    return \"Its conditions can’t be read, so the page leaves it out until they’re removed.\";\n  }\n  return problems.whole.length > 0\n    ? problems.whole.join(\" \")\n    : \"A condition can’t be checked, so the page leaves it out until it’s fixed.\";\n}\n\n/**\n * Said when the site's collections couldn't be listed: no field can be\n * offered, and a stored condition's field can't be named, for that reason\n * rather than any wrong with the conditions.\n */\nfunction FieldsUnavailable({\n  listing,\n}: {\n  listing: ConditionListing;\n}): React.JSX.Element | null {\n  if (listing !== \"unavailable\") return null;\n  return (\n    <p className=\"nx-inspector__note\">\n      The site&apos;s collections could not be listed, so conditions can&apos;t\n      be chosen here.\n    </p>\n  );\n}\n\n/** How the group's edits reach the document: written once a row completes. */\ninterface ConditionWrites {\n  readonly write: (next: readonly Condition[]) => void;\n  readonly change: (row: ShownCondition, draft: DraftCondition) => void;\n  readonly remove: (row: ShownCondition) => void;\n}\n\n/** The writes of the one AND group the inspector edits. */\nfunction conditionWrites(\n  editor: EditorState,\n  nodeId: string,\n  stored: readonly Condition[],\n  state: SentenceRows<DraftCondition>,\n  fields: readonly ConditionField[]\n): ConditionWrites {\n  const write = (next: readonly Condition[]) => {\n    // Stored in the operators' canonical spellings, as the API writes them.\n    const canonical = next.map(each => ({\n      ...each,\n      op: conditionOp(each.op) ?? each.op,\n    }));\n    const op = conditionsOp(\n      editor.document,\n      nodeId,\n      canonical.length === 0 ? null : [canonical]\n    );\n    if (op !== null) editor.apply(op);\n  };\n  const change = (row: ShownCondition, draft: DraftCondition) => {\n    const field = fields.find(each => each.name === draft.field);\n    const completed = completedCondition(draft, field);\n    // Written once complete, and a stored row from there on.\n    const index = state.change(row, draft, \"condition\" in completed);\n    if (\"condition\" in completed) {\n      const next = [...stored];\n      next[index] = completed.condition;\n      write(next);\n    }\n  };\n  const remove = (row: ShownCondition) => {\n    const index = state.remove(row);\n    if (index !== undefined) write(stored.filter((_, at) => at !== index));\n  };\n  return { write, change, remove };\n}\n\n/** What the one editable group is drawn with. */\ninterface OneGroupProps {\n  readonly id: string;\n  readonly state: SentenceRows<DraftCondition>;\n  readonly writes: ConditionWrites;\n  readonly source: ConditionSource;\n  readonly fields: readonly ConditionField[];\n  readonly problems: ConditionProblems;\n  readonly disabled: boolean;\n  readonly services: ContentServices | undefined;\n  readonly entryTitle: (id: string) => string | undefined;\n}\n\n/** The one AND group, a sentence per condition, and the way to add one. */\nfunction OneGroup({\n  id,\n  state,\n  writes,\n  source,\n  fields,\n  problems,\n  disabled,\n  services,\n  entryTitle,\n}: OneGroupProps): React.JSX.Element {\n  // As many as the save takes, so a written row is never one too many.\n  const limit = listLimit(state.rows.length, CONDITION_MAX, id);\n  return (\n    <>\n      <p className=\"nx-inspector__note nx-list-query__hint\">\n        {state.rows.length === 0\n          ? \"Always shown\"\n          : source.item\n            ? `Show this block only when all of these match ${source.match}.`\n            : \"Show this block only when all of these are true.\"}\n      </p>\n      {state.rows.length === 0 ? null : (\n        <ul className=\"nx-list-query__filters\" aria-label=\"Conditions\">\n          {state.rows.map(row => (\n            <ConditionRow\n              key={row.key}\n              id={`${id}-${row.key.replace(\":\", \"-\")}`}\n              row={row}\n              fields={fields}\n              open={state.openKey === row.key}\n              disabled={disabled}\n              // A draft is judged when it is written, not by the stored row.\n              storedProblem={\n                row.index === undefined || row.drafted\n                  ? undefined\n                  : problems.rows.get(row.index)\n              }\n              services={services}\n              entryTitle={entryTitle}\n              onOpen={() => state.setOpenKey(row.key)}\n              onClose={() => state.setOpenKey(null)}\n              onChange={draft => writes.change(row, draft)}\n              onRemove={() => writes.remove(row)}\n            />\n          ))}\n        </ul>\n      )}\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"nx-list-query__add\"\n        disabled={\n          disabled ||\n          source.collection === null ||\n          fields.length === 0 ||\n          limit.full\n        }\n        aria-describedby={limit.describedBy}\n        onClick={state.add}\n      >\n        <Plus aria-hidden=\"true\" size={14} />\n        Add condition\n      </Button>\n      <LimitNote limit={limit}>Up to {CONDITION_MAX} conditions.</LimitNote>\n    </>\n  );\n}\n\n/**\n * Conditions stored in a shape no row can show. The notice above says the\n * page leaves the block out; removing them is the way back to editing.\n */\nfunction UnreadableConditions({\n  disabled,\n  shown,\n  onRemove,\n}: {\n  disabled: boolean;\n  /** Whether the page shows the block anyway, as it does for `null`. */\n  shown: boolean;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <>\n      <p className=\"nx-inspector__note nx-list-query__hint\">\n        {shown\n          ? \"Visitors see this block, but its conditions are stored in a shape the page can’t save. Remove them to save the page, or to set new ones.\"\n          : \"These conditions aren’t stored as groups of conditions, so they can’t be shown here. Remove them to set new ones.\"}\n      </p>\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        className=\"nx-show-when__keep\"\n        disabled={disabled}\n        onClick={onRemove}\n      >\n        Remove conditions\n      </Button>\n    </>\n  );\n}\n\n/** The group's body, by what is stored: unreadable, several groups, or one. */\nfunction GroupBody({\n  groups,\n  stored,\n  gated,\n  ...one\n}: OneGroupProps & {\n  groups: readonly (readonly Condition[])[] | undefined;\n  stored: readonly Condition[];\n  /** Whether the page judges the block by its conditions at all. */\n  gated: boolean;\n}): React.JSX.Element {\n  if (groups === undefined) {\n    return (\n      <UnreadableConditions\n        disabled={one.disabled}\n        shown={!gated}\n        onRemove={() => one.writes.write([])}\n      />\n    );\n  }\n  if (groups.length > 1) {\n    return (\n      <StoredGroups\n        groups={groups}\n        fields={one.fields}\n        disabled={one.disabled}\n        entryTitle={one.entryTitle}\n        onKeepFirst={() => one.writes.write(stored)}\n      />\n    );\n  }\n  return <OneGroup {...one} />;\n}\n\n/** The collections the inspector knows, and where the block's conditions read. */\n/** Whether the site's collections, and so the fields, have been listed. */\ntype ConditionListing = \"loading\" | \"ready\" | \"unavailable\";\n\nfunction useConditionSource(\n  editor: EditorState,\n  node: BlockNode | undefined,\n  services: ContentServices | undefined\n): {\n  listing: ConditionListing;\n  collections: readonly LoopCollection[] | undefined;\n  customs: readonly CustomSource[] | undefined;\n  source: ConditionSource | undefined;\n  fields: readonly ConditionField[];\n  listFields: readonly LoopListField[];\n} {\n  const listed = useLoopCollections(services?.listLoopCollections);\n  const collections = listed?.kind === \"ready\" ? listed.collections : undefined;\n  const customs = useCustomSources(services?.listCustomSources);\n  const source =\n    node === undefined\n      ? undefined\n      : sourceOf(\n          node,\n          editor.document.nodes,\n          services?.entryCollection,\n          collections ?? [],\n          customs\n        );\n  const collection = collections?.find(\n    each => each.slug === source?.collection\n  );\n  // Every field the public may read, not only those a list filters by: a\n  // condition can ask whether any of them has a value.\n  const rowFields = source?.rowFields;\n  const fields = React.useMemo(\n    () =>\n      rowFields !== undefined\n        ? conditionFieldsOfShapes(rowFields)\n        : collection === undefined\n          ? []\n          : conditionFieldsOf(collection),\n    [collection, rowFields]\n  );\n  const listing: ConditionListing =\n    listed === undefined || listed.kind === \"failed\"\n      ? \"unavailable\"\n      : listed.kind;\n  return {\n    listing,\n    collections,\n    customs,\n    source,\n    fields,\n    listFields: collection?.fields ?? [],\n  };\n}\n\n/**\n * Whose fields the conditions read, named only where it changes meaning:\n * inside a list, each item's rather than the page's. And where the page shows\n * no entry, which is why no condition can be added.\n */\nfunction SourceChip({\n  source,\n}: {\n  source: ConditionSource;\n}): React.JSX.Element | null {\n  if (!source.item && source.collection !== null) return null;\n  const SourceIcon = source.item ? Repeat : FileText;\n  return (\n    <span className=\"nx-show-when__source\">\n      <SourceIcon aria-hidden=\"true\" size={12} />\n      {source.words}\n    </span>\n  );\n}\n\n/** The \"Show when\" group of a block's Advanced tab. */\nexport function ShowWhen({\n  editor,\n  nodeId,\n  services,\n  heldBy,\n  reasonId,\n}: ShowWhenProps): React.JSX.Element | null {\n  const id = React.useId();\n  const node = findNode(editor.document.nodes, nodeId);\n  const { listing, collections, customs, source, fields, listFields } =\n    useConditionSource(editor, node, services);\n  const groups = node === undefined ? [] : storedGroups(node);\n  const stored = groups?.[0] ?? [];\n  const state = useSentenceRows<Condition, DraftCondition>(\n    stored,\n    conditionDraftOf,\n    {}\n  );\n  // Every condition shown: the rows being edited, or each API group's.\n  const shownConditions =\n    groups !== undefined && groups.length > 1\n      ? groups.flat().map(each => ({ field: each.field, value: each.value }))\n      : state.rows.map(row => ({\n          field: row.draft.field,\n          value: row.draft.value,\n        }));\n  const entryTitle = useEntryTitles(\n    services?.findEntries,\n    listFields,\n    shownConditions\n  );\n  if (source === undefined) return null;\n\n  const disabled = heldBy !== undefined;\n  const gated = node !== undefined && gatedAsStored(node);\n  const problems = problemsOf(\n    editor,\n    nodeId,\n    collections,\n    services?.entryCollection,\n    customs\n  );\n  const writes = conditionWrites(editor, nodeId, stored, state, fields);\n  const titleId = `${id}-title`;\n  return (\n    <section\n      className=\"nx-list-query__group nx-show-when\"\n      aria-labelledby={titleId}\n      {...(disabled && reasonId !== undefined\n        ? { \"aria-describedby\": reasonId }\n        : {})}\n    >\n      <div className=\"nx-show-when__head\">\n        <h3 id={titleId} className=\"nx-list-query__title\">\n          Show when\n        </h3>\n        <SourceChip source={source} />\n      </div>\n      {/* Red only where the page leaves the block out: a shape it reads as\n          no restriction, such as `null`, is shown to everyone. */}\n      <ShowWhenNotice\n        problems={problems}\n        unreadable={groups === undefined && gated}\n      />\n      <FieldsUnavailable listing={listing} />\n      <GroupBody\n        groups={groups}\n        stored={stored}\n        gated={gated}\n        id={id}\n        state={state}\n        writes={writes}\n        source={source}\n        fields={fields}\n        problems={problems}\n        disabled={disabled}\n        services={services}\n        entryTitle={entryTitle}\n      />\n    </section>\n  );\n}\n","/**\n * What an author may put on a block's root element, and why a row will not land.\n *\n * The engine models two fields beside a node's props: `cssId`, which becomes the\n * element's `id`, and `attributes`, a bag of author-supplied HTML attributes.\n * `blocks-react` already decides which of those reach the DOM and already\n * applies them — this module is the EDITOR's half, and it owns exactly one\n * question: what to tell an author before they save.\n *\n * ## Every rule here is ASKED, never restated\n *\n * The render-safe set lives in the renderer and says so in its own docblock, so\n * `isAllowedAttribute` is imported rather than copied. A second copy would\n * drift, and it drifts in the worse direction: an editor accepting a name the\n * renderer skips lets an author set an attribute, watch it save, and never see\n * it on the page. Nothing here decides what is safe — it decides what to SAY.\n *\n * @module custom-attributes\n */\nimport {\n  isConditionGated,\n  renderedDomId,\n  renderedDomIdIn,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  EDITOR_NAMESPACE,\n  isAllowedAttribute,\n  rendersOwnMarkup,\n  type BlockResolver,\n} from \"@nextlyhq/blocks-react\";\n\n/** One row of the attributes editor, as the author is typing it. */\nexport interface AttributeRow {\n  readonly name: string;\n  readonly value: string;\n  /**\n   * The name this row was LOADED with, when it came from the document.\n   *\n   * Kept so a row that cannot land does not delete what it replaced. Renaming\n   * `data-x` to `onclick` means the author typed something wrong, not that they\n   * want `data-x` gone — and without an origin the only way to avoid deleting\n   * it was to hold the whole write, which then blocked removing an unrelated\n   * row beside it.\n   *\n   * Absent on a row the author added, which has nothing to fall back to.\n   */\n  readonly origin?: string;\n}\n\n/** The id and rows an author is editing, before any of it is written down. */\nexport interface Draft {\n  readonly id: string;\n  readonly rows: readonly AttributeRow[];\n}\n\n/**\n * Whether two drafts hold the same TEXT — what the author typed, character for\n * character.\n *\n * Deliberately not `htmlUpdate`, which compares a NORMALIZED draft against the\n * document and therefore reports a difference nobody made: a stored `\" hero \"`\n * trims and a stored `DATA-X` lowercases, so a panel that had only been looked\n * at wrote a change, added an undo entry, and moved the rendered anchor. The\n * question a commit has to ask first is whether the author edited anything, and\n * that is this one.\n *\n * `origin` is not compared: it records where a row came from so a mistake can\n * fall back to it, and it moves when a write lands rather than when an author\n * types.\n */\nexport function sameDraft(left: Draft, right: Draft): boolean {\n  if (left.id !== right.id) return false;\n  if (left.rows.length !== right.rows.length) return false;\n  return left.rows.every((row, at) => {\n    const other = right.rows[at];\n    return (\n      other !== undefined &&\n      row.name === other.name &&\n      row.value === other.value\n    );\n  });\n}\n\n/** Why a row will not reach the page, or `undefined` when it will. */\nexport type RowProblem =\n  | { readonly kind: \"not-allowed\" }\n  | { readonly kind: \"reserved\" }\n  | { readonly kind: \"duplicate\" }\n  | { readonly kind: \"use-css-id-field\" }\n  | { readonly kind: \"use-css-classes-field\" };\n\n/**\n * HTML attribute names are ASCII case-insensitive; React props are not.\n *\n * The renderer lowercases before writing for exactly that reason — `ID` and\n * `id` would otherwise both survive and land as two id attributes on one\n * element. So two rows differing only in case are ONE attribute here too, and\n * the editor has to say so rather than let an author believe they set two.\n */\nexport function attributeKey(name: string): string {\n  return name.trim().toLowerCase();\n}\n\n/** Whether a row has been started at all. A blank row is not an error. */\nexport function isBlankRow(row: AttributeRow): boolean {\n  return row.name.trim() === \"\";\n}\n\n/**\n * What is wrong with one row, judged against its siblings and the node's id.\n *\n * `cssId` is checked because the renderer resolves the collision in its favour\n * and says so: \"the modelled field wins over an attribute of the same name\".\n * That is not a defect to fix here — a dedicated field beating an escape hatch\n * is the right precedence — but it is invisible from the editor, so an author\n * typing `id` beside a filled CSS id is writing a value that will never be\n * used. Naming it is the whole point of the surface.\n */\nexport function rowProblem(\n  rows: readonly AttributeRow[],\n  index: number\n): RowProblem | undefined {\n  return rowProblems(rows)[index];\n}\n\n/**\n * Every row's verdict, worked out ONCE for the whole set.\n *\n * The verdicts are not independent — who keeps a contested key, and which keys\n * refused rows are holding, are both facts about the set — so asking row by row\n * recomputed both for every row. With the held set settled to a fixed point on\n * top of that, a large imported bag froze the panel: a few hundred permitted\n * `data-*` entries is an ordinary import and was enough.\n *\n * So the set is analysed once and each row reads its answer out. `rowProblem`\n * stays for the single-row callers, and says by its own shape that asking it in\n * a loop is asking for the analysis again each time.\n */\nexport function rowProblems(\n  rows: readonly AttributeRow[]\n): (RowProblem | undefined)[] {\n  const keepers = keepersOf(rows);\n  const held = heldOrigins(rows, keepers);\n  return rows.map((_row, index) => problemGiven(rows, index, keepers, held));\n}\n\n/**\n * One row's verdict, given the set of keys refused rows are already holding.\n *\n * Takes `held` as DATA rather than computing it, because computing it has to\n * ask this question of every row — and a version that reached for the answer\n * itself would be asking itself.\n */\nfunction problemGiven(\n  rows: readonly AttributeRow[],\n  index: number,\n  keepers: ReadonlyMap<string, number>,\n  held: ReadonlySet<string>\n): RowProblem | undefined {\n  const row = rows[index];\n  if (row === undefined || isBlankRow(row)) return undefined;\n  const alone = soloProblem(row);\n  if (alone !== undefined) return alone;\n  const key = attributeKey(row.name);\n  const keeps = keepers.get(key);\n  if (keeps !== undefined && keeps !== index) return { kind: \"duplicate\" };\n  // Asked BEFORE the held keys, so a row the field above owns is told that\n  // rather than being called a duplicate of whatever is holding the name.\n  if (key === \"id\") return { kind: \"use-css-id-field\" };\n  /*\n   * The keys refused rows are HOLDING count as taken too.\n   *\n   * A refused row keeps what it replaced, so its origin is still in the stored\n   * record even though no row on screen carries that name. Judging collisions\n   * on the live names alone accepted a second row renamed onto it — and the\n   * write, which places the preserved value first, was then overwritten by that\n   * row, deleting an attribute nobody asked to lose.\n   *\n   * Reported rather than resolved in the write, because the author is the only\n   * one who can say which of the two they meant. Both rows keep their origins\n   * until they do, so the document is left exactly as it was.\n   */\n  if (held.has(key)) return { kind: \"duplicate\" };\n  return undefined;\n}\n\n/**\n * Among the rows spelling one key, the index of the row that KEEPS it.\n *\n * `undefined` when nobody is displaced, which is the ordinary row.\n *\n * Located by INDEX, never by object identity. A row is a plain value the UI\n * rebuilds on every keystroke, so two rows holding the same name and value are\n * indistinguishable by `===`, and a caller passing an equal-but-separate object\n * had every row reported as a duplicate of itself. Position is what actually\n * decides this — the FIRST row holding a key is the one that lands, matching\n * the renderer's own iteration over the stored record.\n *\n * The one kept is a row that came from the DOCUMENT and still carries its own\n * name — never a row the author has just renamed onto it. First-wins alone got\n * this backwards in one direction: renaming the first row onto a name a later\n * row already held left the edited row looking fine and blamed the untouched\n * one, so on rebuild the untouched row's old value overwrote the edit and the\n * name renamed FROM disappeared. Between two rows that both came from the\n * document — two spellings of one name in an imported bag — first-wins is still\n * the answer.\n */\nfunction keepersOf(rows: readonly AttributeRow[]): Map<string, number> {\n  const sharing = new Map<string, number[]>();\n  rows.forEach((row, at) => {\n    if (isBlankRow(row)) return;\n    const key = attributeKey(row.name);\n    const holders = sharing.get(key);\n    if (holders === undefined) sharing.set(key, [at]);\n    else holders.push(at);\n  });\n  const keepers = new Map<string, number>();\n  for (const [key, holders] of sharing) {\n    // One holder is nobody displaced, which is the ordinary row.\n    if (holders.length <= 1) continue;\n    const settled = holders.filter(at => {\n      const origin = rows[at]?.origin;\n      return origin !== undefined && attributeKey(origin) === key;\n    });\n    const keeps = (settled.length > 0 ? settled : holders)[0];\n    if (keeps !== undefined) keepers.set(key, keeps);\n  }\n  return keepers;\n}\n\n/**\n * What is wrong with a row judged ALONE, before any sibling is looked at.\n *\n * Separated because the answer is needed while deciding what the siblings even\n * occupy, and asking the whole question there would be asking it of itself.\n */\nfunction soloProblem(row: AttributeRow): RowProblem | undefined {\n  const key = attributeKey(row.name);\n  // A class has its own field above, which the block's generated classes\n  // are kept apart from; the bag never carries one.\n  if (key === \"class\") return { kind: \"use-css-classes-field\" };\n  if (!isAllowedAttribute(key)) return { kind: \"not-allowed\" };\n  /*\n   * The editor's own NAMESPACE, asked as a prefix rather than as a list of\n   * the markers that exist today. The renderer drops these while it is\n   * rendering for the editor, so accepting one here would store a name that\n   * never appears — and a list is a thing to keep in sync, which this one\n   * already fell behind on once.\n   */\n  if (key.startsWith(EDITOR_NAMESPACE)) return { kind: \"reserved\" };\n  return undefined;\n}\n\n/**\n * Every stored key a refused row will hold on to, settled.\n *\n * EVERY refused row, not only the malformed ones. `storedAttributes` preserves\n * the origin of any row that cannot land, and counting one kind of refusal but\n * not the other left the same hole one layer along: a row refused as a\n * DUPLICATE also keeps its origin, and a third row renamed onto that origin was\n * accepted and overwrote it.\n *\n * Settled to a FIXED POINT, because holding a key refuses another row, and that\n * row then holds an origin of its own. One pass closes one link of the chain\n * and leaves the next open. Each pass can only ADD — a larger `held` never\n * turns a refused row back into an accepted one — so the loop is monotone and\n * cannot run longer than there are rows to refuse.\n */\nfunction heldOrigins(\n  rows: readonly AttributeRow[],\n  keepers: ReadonlyMap<string, number>\n): Set<string> {\n  const held = new Set<string>();\n  for (let pass = 0; pass < rows.length; pass += 1) {\n    let grew = false;\n    rows.forEach((row, index) => {\n      const origin = row.origin;\n      if (origin === undefined) return;\n      /*\n       * NORMALIZED, because the membership test asks with a normalized key.\n       * A stored `DATA-A` went in raw and was never matched, so a row renamed\n       * onto `data-a` was accepted and both spellings were stored — and the\n       * renderer lowercases and lets the last one win, so the rendered value\n       * changed while another attribute disappeared.\n       */\n      const key = attributeKey(origin);\n      if (held.has(key)) return;\n      if (problemGiven(rows, index, keepers, held) === undefined) return;\n      held.add(key);\n      grew = true;\n    });\n    if (!grew) break;\n  }\n  return held;\n}\n\n/** What to tell the author about a row that will not land. */\nexport function problemMessage(problem: RowProblem): string {\n  switch (problem.kind) {\n    case \"not-allowed\":\n      return \"This site does not put that attribute on a page. Names starting with “data-” or “aria-” are open, along with role, title, lang and dir.\";\n    case \"reserved\":\n      return \"The editor uses that name to find blocks on the canvas, so setting it here would make clicking this block select the wrong one. Pick another name.\";\n    case \"duplicate\":\n      return \"Another row already sets this attribute, and only the first is used. Attribute names ignore capitals, so “Data-X” and “data-x” are one name.\";\n    case \"use-css-id-field\":\n      return \"Set this block’s id in the Anchor (ID) field above. An id written here is not used while that field has a value, and it is the field the rest of the editor reads.\";\n    case \"use-css-classes-field\":\n      return \"Use CSS classes above.\";\n  }\n}\n\n/**\n * The rows an author edits, from what the node stores.\n *\n * Sorted by name so the list does not reorder itself as an author types — a\n * record's key order is its insertion order, and rewriting the record on every\n * keystroke would make rows jump.\n */\nexport function rowsOf(\n  attributes: Readonly<Record<string, string>> | undefined\n): AttributeRow[] {\n  return Object.entries(attributes ?? {})\n    .map(([name, value]) => ({ name, value, origin: name }))\n    .sort((left, right) => left.name.localeCompare(right.name));\n}\n\n/**\n * What to store for a set of rows, or `undefined` to store nothing at all.\n *\n * Blank rows are dropped rather than saved as empty keys, and a row that cannot\n * land is dropped too: storing a value the page will never use is the silent\n * half of the problem this surface exists to make loud. `undefined` rather than\n * `{}` for an empty result, so removing the last attribute leaves the node as\n * it was before any were added rather than carrying an empty bag forever.\n */\nexport function storedAttributes(\n  rows: readonly AttributeRow[],\n  cssId: string,\n  stored: Readonly<Record<string, string>> = {}\n): Record<string, string> | undefined {\n  const kept: Record<string, string> = {};\n  const problems = rowProblems(rows);\n  rows.forEach((row, index) => {\n    /*\n     * Blankness is asked SEPARATELY from correctness, because they are\n     * different questions and `rowProblem` answers only the second. A row an\n     * author has not started typing is not an error to show them — that is why\n     * it has no problem — and it is not something to store either. Reading one\n     * answer for both stored an attribute under the empty name.\n     */\n    if (isBlankRow(row)) return;\n    const problem = problems[index];\n    if (problem === undefined) {\n      kept[attributeKey(row.name)] = row.value;\n      return;\n    }\n    /*\n     * A row that cannot land KEEPS what it replaced, rather than deleting it.\n     * The author has typed something wrong, and the row is on screen with the\n     * reason — removing the attribute underneath it as well would take away\n     * work they never asked to lose. A row they ADDED has no origin, so there\n     * is nothing to keep and nothing is written.\n     *\n     * The one exception is an id the field above now owns: keeping it would let\n     * the renderer fall back to it the moment that field is cleared, which is\n     * the value coming back from the dead.\n     */\n    /*\n     * ANY row that would render as `id`, whichever problem it happened to\n     * draw. A bag holding two spellings gives the first `use-css-id-field`\n     * and every later one `duplicate` — the duplicate check runs earlier —\n     * so keying this on one kind preserved the second, and clearing the CSS\n     * id later made a supposedly removed value render again.\n     */\n    if (cssId.trim() !== \"\" && attributeKey(row.name) === \"id\") return;\n    const origin = row.origin;\n    if (origin === undefined) return;\n    const had = stored[origin];\n    if (had !== undefined) kept[origin] = had;\n  });\n  return Object.keys(kept).length === 0 ? undefined : kept;\n}\n\n/**\n * Every DOM id the document already uses, other than one node's own.\n *\n * A rendered id must be unique across the page: two elements answering to one\n * `id` give a fragment link, a `<label for>` and a CSS selector two possible\n * targets, and which one wins is the document order rather than anything the\n * author chose.\n *\n * The engine already detects this — `validateDomIds` reports `duplicate-dom-id`\n * — but only as a WARNING in forgiving mode, and the field's own validation\n * discards warnings, so a duplicate saves and publishes with nothing said. This\n * is the editor refusing it while the author still has the keyboard, which is\n * the only moment they can act on it.\n *\n * Both sources are read, because both become the same attribute: the modelled\n * `cssId` and the `id` an author can put in the attribute bag.\n */\nexport function domIdsTaken(\n  nodes: readonly BlockNode[],\n  exceptNodeId: string,\n  resolver: BlockResolver\n): Set<string> {\n  const taken = new Set<string>();\n  /*\n   * Every node passes through HERE, which is why the shape is checked here\n   * and not at the two places that call it. A stored document holds what the\n   * database returned: a `null` inside a slot array reaches this, and reading\n   * `.id` off it throws before the tab renders. Guarding the callers instead\n   * would be two guards to keep in step, and the walk gained its second\n   * caller in the same commit that guarded the first.\n   */\n  const visit = (node: unknown): void => {\n    if (typeof node !== \"object\" || node === null) return;\n    const held = node as BlockNode;\n    /*\n     * A node the page replaces with a PLACEHOLDER reserves nothing, and neither\n     * does anything inside it: the renderer prunes the whole subtree, so none\n     * of those ids reach the page. Counting them refuses a healthy block an id\n     * the rendered page would contain exactly once — trading a real anchor for\n     * one nothing was going to use.\n     *\n     * Asked of the renderer's own predicate rather than restated. Whether a\n     * node renders its own markup turns on three things — a failed migration,\n     * an unknown type, and a version ahead of the definition — and a second\n     * copy of that list is a copy to keep in step.\n     */\n    if (!rendersOwnMarkup(held, resolver)) return;\n    /*\n     * A CONDITION-GATED node reserves nothing either, and neither does anything\n     * inside it — `pruneHiddenNodes` drops the subtree before either the render\n     * or the style compile sees it. The gate fails closed because the engine\n     * defines no evaluator yet, so such a node is currently absent from every\n     * page, and the pattern this most affects is the one the feature is for:\n     * personalised variants of a section, each carrying the same anchor,\n     * exactly one of them served.\n     *\n     * Asked of the engine's own predicate, which the renderer and the style\n     * compiler already share. They once derived it separately and disagreed in\n     * both directions; a third copy here would be a third way to disagree.\n     *\n     * What this cannot decide is the day an evaluator arrives and two gated\n     * nodes both match. Nothing here or in `validateDomIds` would catch that,\n     * and it belongs to the evaluator rather than to a scan that has no\n     * conditions to read.\n     */\n    if (isConditionGated(held)) return;\n    if (held.id !== exceptNodeId) {\n      const rendered = renderedDomId(held);\n      if (rendered !== undefined) taken.add(rendered);\n    }\n    for (const child of childNodesOf(held)) visit(child);\n  };\n  for (const node of nodes) visit(node);\n  return taken;\n}\n\n/**\n * The `id` the renderer would emit from an attribute bag, if any.\n *\n * DELEGATED to the engine, which publishes the rule both packages need. It was\n * derived twice — here and there, independently, from the renderer — and the\n * two authors made the same mistakes in the same order before arriving at the\n * same answer. A rule two packages derive separately is one they will\n * eventually derive differently, and the engine is the right home because the\n * builder depends on it and never the reverse.\n *\n * Kept as a named export rather than replaced at its call sites, because what\n * this asks is narrower than \"what does this node render\": `advanced-panel`\n * needs to know whether an empty bag id would SHADOW something, which is a\n * question about the bag alone.\n */\nexport function renderedIdIn(\n  attributes: Readonly<Record<string, string>> | undefined\n): string | undefined {\n  return renderedDomIdIn(attributes);\n}\n\n/** Every node nested inside one, across all of its slots. */\nfunction childNodesOf(node: BlockNode): unknown[] {\n  const slots = node.slots;\n  // `Object.values(null)` throws, and a stored `slots` can be anything —\n  // the same shape check the attribute bag beside it already gets.\n  if (typeof slots !== \"object\" || slots === null) return [];\n  return Object.values(slots).flatMap(held =>\n    Array.isArray(held) ? held : []\n  );\n}\n\n/** What a node should hold, and what it holds now. */\nexport interface HtmlFields {\n  /**\n   * The element's `id`, or `undefined` for a node carrying no such field.\n   *\n   * `\"\"` is a THIRD state and a reachable one: a stored empty string SHADOWS\n   * any `id` in the bag while rendering no id itself, so the element ends up\n   * with none. This editor never writes it — clearing the field is `unset` —\n   * but an import can, and telling it apart from an absent field is what makes\n   * it removable.\n   */\n  readonly cssId: string | undefined;\n  readonly attributes: Readonly<Record<string, string>> | undefined;\n}\n\n/**\n * The id the author is ASKING for, normalized the way it would be stored.\n *\n * Its own function because two questions need the same answer and must not\n * answer it twice: what to write, and — once the write lands — whether what the\n * author asked for is what the node now holds. A collision makes those differ,\n * and the panel has to tell them apart to know whose text belongs in the field.\n *\n * Trimmed only when the author TYPED it. Normalizing a value nobody touched is a\n * change nobody asked for, and the two normalizations are not alike: the\n * renderer lowercases an attribute name itself, so storing `DATA-X` as `data-x`\n * renders the same byte for byte — but it does not trim `cssId`, so tidying a\n * stored `\" hero \"` silently moves the anchor every link to this block points\n * at. What the renderer already does is safe to store; what it does not do is\n * the author's to decide.\n */\nexport function requestedId(draft: Draft, loaded: Draft): string {\n  return draft.id === loaded.id ? draft.id : draft.id.trim();\n}\n\n/** Whether the author has left the id field exactly as it was loaded. */\nfunction untouchedId(draft: Draft, loaded: Draft): boolean {\n  return draft.id === loaded.id;\n}\n\n/**\n * What a draft wants the node to hold — the whole question of what to STORE.\n *\n * Separate from getting the document there, which is the caller's job and a\n * different kind of problem: this one is about attribute rules and knows\n * nothing about ops, refusals or undo.\n *\n * An id another block holds is not written at all: the field keeps showing what\n * the author typed, with the reason beside it, and the document keeps what it\n * had.\n */\nexport function wantedFields(\n  draft: Draft,\n  loaded: Draft,\n  stored: HtmlFields,\n  taken: ReadonlySet<string>\n): HtmlFields {\n  const id = requestedId(draft, loaded);\n  /*\n   * An UNTOUCHED field wants whatever the node already holds, including an\n   * empty-but-present one. Reading an empty box as \"remove it\" made every other\n   * save carry `unset: [\"cssId\"]` along with it — bypassing the explicit\n   * removal the panel offers, and silently unshadowing the bag's `id` so the\n   * rendered anchor changed because an attribute was edited.\n   *\n   * Once the author HAS typed, an empty box means the field should be gone\n   * rather than present and empty: the panel has no gesture that asks for a\n   * field that is present, renders nothing and shadows the bag, so `undefined`\n   * is the only thing a cleared box can honestly mean.\n   */\n  const keptId = untouchedId(draft, loaded)\n    ? stored.cssId\n    : id === \"\"\n      ? undefined\n      : taken.has(id)\n        ? stored.cssId\n        : id;\n  return {\n    cssId: keptId,\n    /*\n     * The shadowed `id` is dropped only when the author has just SET the field,\n     * never merely because it holds something. A node imported with both a\n     * `cssId` and a legacy `id` would otherwise lose the second the moment\n     * anyone opened this tab — and lose it again on a change that was REFUSED,\n     * since a refusal keeps the id the node already had and that is still\n     * non-empty. Nothing the author did not ask for gets deleted.\n     */\n    attributes: storedAttributes(\n      draft.rows,\n      keptId === stored.cssId ? \"\" : (keptId ?? \"\"),\n      stored.attributes ?? {}\n    ),\n  };\n}\n\n/**\n * The rows again, each pointed at the name it is now STORED under.\n *\n * A row keeps the name it was loaded with so a later mistake can fall back to\n * it — but once a rename has landed, that old name is no longer in the document,\n * and falling back to it finds nothing and unsets the value the rename had just\n * saved.\n *\n * Only the origins move. The names and values the author is looking at stay\n * exactly as they are, so nothing shifts under a cursor.\n */\nexport function rebasedRows(\n  rows: readonly AttributeRow[],\n  wanted: HtmlFields\n): AttributeRow[] {\n  const written = wanted.attributes;\n  return rows.map(row =>\n    written !== undefined && written[attributeKey(row.name)] === row.value\n      ? { ...row, origin: attributeKey(row.name) }\n      : row\n  );\n}\n\n/**\n * The smallest update that makes a node hold `wanted`, or nothing to do.\n *\n * Its own question, and a pure one: deciding what an author's draft SHOULD\n * become is about attribute rules, and saying so as an op is about the patch\n * contract. Both live away from the component, which then only has to hand over\n * two values and apply what comes back.\n *\n * Removal is spelled `unset`, never `undefined` as a patch value: `applyOp`\n * refuses that and says why — the key disappears when the op is stored, so a\n * replayed edit would silently do nothing.\n *\n * Only what CHANGED is named. An op that unsets a field the node never had, or\n * rewrites one to the value it already holds, is an undo entry that undoes\n * nothing — and an author pressing undo for their last edit gets a step that\n * does nothing instead.\n */\nexport function htmlUpdate(\n  wanted: HtmlFields,\n  stored: HtmlFields\n): { patch: Record<string, unknown>; unset: string[] } | undefined {\n  const sameId = wanted.cssId === stored.cssId;\n  const sameAttributes = sameRecord(wanted.attributes, stored.attributes);\n  if (sameId && sameAttributes) return undefined;\n\n  const patch: Record<string, unknown> = {};\n  const unset: string[] = [];\n  if (!sameId) {\n    // REMOVED rather than written empty. `applyOp` refuses `undefined` as a\n    // patch value and says why, and an empty string is a different request —\n    // it would leave the field present, rendering no id and shadowing the bag.\n    if (wanted.cssId === undefined) unset.push(\"cssId\");\n    else patch[\"cssId\"] = wanted.cssId;\n  }\n  if (!sameAttributes) {\n    if (wanted.attributes === undefined) unset.push(\"attributes\");\n    else patch[\"attributes\"] = wanted.attributes;\n  }\n  return { patch, unset };\n}\n\n/** Whether two attribute records hold the same names and values. */\nfunction sameRecord(\n  left: Readonly<Record<string, string>> | undefined,\n  right: Readonly<Record<string, string>> | undefined\n): boolean {\n  /*\n   * An EMPTY bag and no bag are the same thing to a reader — the renderer\n   * asks `Object.keys(attributes).length > 0` — so they must compare equal\n   * here too. Treating them as different meant a node stored with `{}` was\n   * rewritten the moment anyone looked at the tab, putting an edit in the\n   * undo history for having opened a panel.\n   */\n  const held = (bag: Readonly<Record<string, string>> | undefined) =>\n    bag === undefined || Object.keys(bag).length === 0 ? undefined : bag;\n  const [a, b] = [held(left), held(right)];\n  if (a === undefined || b === undefined) return a === b;\n  const names = Object.keys(a);\n  if (names.length !== Object.keys(b).length) return false;\n  return names.every(name => a[name] === b[name]);\n}\n","/**\n * The block's HTML surface: its anchor (`id`), its own CSS classes, and the\n * attributes an author may add.\n *\n * ## Why these two sit together, and away from Content and Style\n *\n * Neither is a block PROPERTY — those are the block's own schema and live on\n * the Content tab — and neither is a style. They are the escape hatch: the way\n * an author reaches the rendered element itself, for an anchor to link to, a\n * `data-` attribute an analytics script reads, or an `aria-` attribute the\n * block's own markup does not offer.\n *\n * ## ONE writer for both fields\n *\n * They are written by a single function, because they decide each other. A\n * `cssId` beats an `id` in the attribute bag, so setting one changes whether\n * the other lands — and two commit paths, one per field, disagreed about that:\n * committing rows dropped the shadowed `id` and committing the id did not, so\n * clearing the id later brought a stale one back to life.\n *\n * ## Removal is `unset`, never `undefined`\n *\n * `applyOp` refuses `undefined` as a patch value and says why: the key\n * disappears when the op is stored, so a replayed edit would silently do\n * nothing. Clearing a field is `unset`, which survives being written down.\n *\n * @module advanced-panel\n */\nimport { checkCssClassNames, findNode } from \"@nextlyhq/blocks-engine\";\nimport { registeredBlocks } from \"@nextlyhq/blocks-react\";\nimport type { BlockResolver } from \"@nextlyhq/blocks-react\";\nimport { Button, Input, Label } from \"@nextlyhq/ui\";\nimport { Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport { useDraftFieldEdit } from \"../field-edit\";\n\nimport { BUILT_IN_WRITES } from \"./code-hints\";\nimport { CssHint } from \"./css-hint\";\nimport {\n  domIdsTaken,\n  renderedIdIn,\n  htmlUpdate,\n  type HtmlFields,\n  isBlankRow,\n  problemMessage,\n  rebasedRows,\n  requestedId,\n  rowsOf,\n  rowProblems,\n  sameDraft,\n  wantedFields,\n  type AttributeRow,\n  type Draft,\n  type RowProblem,\n} from \"./custom-attributes\";\nimport { designReadOnlyReason, lockViewOf } from \"./inspector\";\nimport { SettingSlot } from \"./settings-filter\";\n\n/**\n * What a refused write says, wherever it is refused.\n *\n * Names no single cause, because `apply` reports none: it answers `null` for\n * ANY refused op — a value past the document's byte limit, but equally an\n * update to a node a concurrent edit or an undo has removed, or a document\n * carrying duplicate node ids. Telling an author their page is full when their\n * block has gone sends them to fix the wrong thing.\n */\nconst REFUSED =\n  \"That change could not be saved. A very long value can push the page past its size limit; otherwise the block may have changed since you opened this tab.\";\n\nexport interface AdvancedPanelProps {\n  readonly nodeId: string;\n  /**\n   * The element's `id`, or `undefined` when the node carries no such field.\n   *\n   * The two are different states and the rule reads them differently: a stored\n   * `\"\"` is PRESENT, shadows any `id` in the bag below, and renders no id of\n   * its own. The panel has to be able to say which one it is looking at, or the\n   * empty-but-present one can never be removed.\n   */\n  readonly cssId: string | undefined;\n  readonly attributes: Readonly<Record<string, string>> | undefined;\n  readonly editor: EditorState;\n  /**\n   * Whether this is the tab currently on screen.\n   *\n   * The panel stays MOUNTED behind the other tabs — see the commit effect below\n   * — so it no longer learns that the author looked away by being destroyed.\n   * This is how it is told.\n   */\n  readonly active: boolean;\n  /**\n   * The definitions the CANVAS is rendering against.\n   *\n   * Which ids are taken depends on which nodes render, and that turns on the\n   * block set. `Canvas` forwards a `render.blocks` resolver to `PageRenderer`,\n   * so a host that supplies one and a panel that reached for the global\n   * registry would be answering about two different pages: a node the canvas\n   * renders would look like a placeholder here and free its id, and a node it\n   * does not would reserve one.\n   *\n   * Optional, and defaulted to the same registry `PageRenderer` defaults to, so\n   * the ordinary host states nothing and the two still agree.\n   */\n  readonly blocks?: BlockResolver;\n}\n\nexport function AdvancedPanel({\n  nodeId,\n  cssId,\n  attributes,\n  editor,\n  active,\n  blocks,\n}: AdvancedPanelProps): React.JSX.Element {\n  const [draft, setDraft] = React.useState<Draft>(() => ({\n    id: cssId ?? \"\",\n    rows: rowsOf(attributes),\n  }));\n  /*\n   * What the author has FINISHED typing, and the only thing verdicts are read\n   * from. Judging every keystroke tells someone two characters into `data-x`\n   * that `da` is not allowed, and `useDeferredValue` does not prevent that —\n   * it schedules a background render immediately and catches up whenever\n   * React has capacity, so intermediate values are judged and shown exactly as\n   * they would be without it. Settling on blur is the behaviour the panel\n   * actually wanted, and it says what it does.\n   */\n  const [settled, setSettled] = React.useState<Draft>({\n    id: cssId ?? \"\",\n    rows: rowsOf(attributes),\n  });\n\n  /*\n   * What this panel last WROTE, so it can tell its own echo from a real change.\n   *\n   * The stored values must win when they change underneath the panel — an undo,\n   * or an edit from somewhere else — or the fields go on showing what the\n   * document no longer holds. But a write of our own comes back through the\n   * same props, and resetting on that throws away whatever the author has typed\n   * since: a row renamed to a refused name lost its text AND the explanation\n   * beside it, in the same moment the valid attribute it replaced was deleted.\n   */\n  const lastWritten = React.useRef<HtmlFields | null>(null);\n  /*\n   * The draft as last SYNCHRONIZED with the document — what the fields held\n   * when they were filled from it, or when a write of ours landed.\n   *\n   * A commit asks this before it asks anything else, because \"the normalized\n   * draft differs from what is stored\" is not the same question as \"the author\n   * changed something\", and answering the first one for the second wrote an\n   * edit nobody made: a stored `\" hero \"` trims and a stored `DATA-X`\n   * lowercases, so opening Advanced and switching tabs rewrote the document,\n   * added an undo entry, and moved the anchor a link pointed at.\n   */\n  const loaded = React.useRef<Draft>(draft);\n  const [refusal, setRefusal] = React.useState<string | undefined>(undefined);\n  /*\n   * A keystroke in the anchor or an attribute begins the field's edit, as in\n   * every other field of the block: the page counts the draft as unsaved\n   * work, Save pressed with focus still here writes it first (by the field's\n   * own blur, below), and Escape puts back what was loaded.\n   */\n  const edit = useDraftFieldEdit();\n  const typed = (): void => edit.begin(() => setDraft(loaded.current));\n  React.useEffect(() => {\n    const written = lastWritten.current;\n    // Asked through the same function that decides whether a write is needed,\n    // so \"unchanged\" means one thing here and there rather than two.\n    if (\n      written !== null &&\n      htmlUpdate(written, { cssId, attributes }) === undefined\n    ) {\n      /*\n       * CONSUMED, not merely matched. Left in place, the marker goes on\n       * describing a state the document may return to — undo then redo lands\n       * back on it, this branch returns again, and the panel keeps showing the\n       * undone value while a later blur writes from that stale draft and erases\n       * the redone edit. One echo, one write.\n       */\n      lastWritten.current = null;\n      return;\n    }\n    const stored = { id: cssId ?? \"\", rows: rowsOf(attributes) };\n    setDraft(stored);\n    setSettled(stored);\n    loaded.current = stored;\n  }, [cssId, attributes]);\n\n  const taken = React.useMemo(\n    () =>\n      domIdsTaken(editor.document.nodes, nodeId, blocks ?? registeredBlocks()),\n    [editor.document, nodeId, blocks]\n  );\n\n  /*\n   * Read at write time rather than closed over. The panel commits from an\n   * unmount cleanup — see below — which runs after the render that removed it,\n   * so a closure captured earlier would write a draft the author has since\n   * changed.\n   */\n  const latest = React.useRef<Draft>(draft);\n  latest.current = draft;\n  const write = React.useRef<(next: Draft) => void>(() => {});\n\n  /*\n   * The ONE place an op leaves this panel.\n   *\n   * Both things that write — the field commit below and the empty-id removal\n   * beside the CSS id — have to record the same three facts afterwards, and a\n   * second `editor.apply` that recorded none of them is what let a removal\n   * arrive at the effect above looking like an edit from somewhere else. The\n   * effect then replaced the draft with the stored rows, discarding a refused\n   * name and the explanation beside it. The module's own header names this\n   * shape: two commit paths for one pair of fields, disagreeing about what they\n   * had just written.\n   *\n   * Answers whether the op landed, so a caller can stop.\n   */\n  const store = React.useRef<\n    (wanted: HtmlFields, update: { patch: object; unset: string[] }) => boolean\n  >(() => false);\n  store.current = (wanted, update): boolean => {\n    /*\n     * Asked of the live document, as every write path in the inspector asks:\n     * the fields are read-only while the design is locked, but a lock set in\n     * Layers after this panel drew must stop the next write too.\n     */\n    const locked = designReadOnlyReason(\n      editor.document,\n      nodeId,\n      lockViewOf(editor)\n    );\n    if (locked !== undefined) {\n      setRefusal(locked);\n      return false;\n    }\n    const applied = editor.apply({\n      kind: \"update\",\n      id: nodeId,\n      patch: update.patch,\n      ...(update.unset.length > 0 ? { unset: update.unset } : {}),\n    } as Parameters<EditorState[\"apply\"]>[0]);\n    /*\n     * REFUSED ops leave the document alone, and `apply` says so by answering\n     * `null`. Marking the attempt as written before knowing would tell the\n     * effect above that the props it sees are this panel's own echo, so it\n     * would stop re-reading the document and the field would go on showing a\n     * value nothing stored.\n     */\n    if (applied === null) {\n      setRefusal(REFUSED);\n      return false;\n    }\n    setRefusal(undefined);\n    lastWritten.current = wanted;\n    return true;\n  };\n\n  write.current = (next: Draft): void => {\n    /*\n     * NOTHING is written unless the author edited something. Every other test\n     * this could have used compares a NORMALIZED draft against the document,\n     * and normalization is exactly what an untouched panel does to a value it\n     * did not choose — so a panel that had only been looked at wrote a change,\n     * added an undo entry, and moved the anchor a link pointed at.\n     *\n     * The refusal goes with it: a message about a save that failed is about a\n     * pending change, and there is no longer one to fail.\n     */\n    if (sameDraft(next, loaded.current)) {\n      setRefusal(undefined);\n      return;\n    }\n    const stored = { cssId, attributes };\n    // Read BEFORE `loaded` moves below, or it compares the draft against the\n    // value this very write is about to record and always agrees.\n    const asked = requestedId(next, loaded.current);\n    const wanted = wantedFields(next, loaded.current, stored, taken);\n    const update = htmlUpdate(wanted, stored);\n    // Edited, but to something the document already holds — a value typed back\n    // to what it was, or a row whose refusal leaves the stored bag as it was.\n    // Nothing to save, so nothing left to report about saving.\n    if (update === undefined) {\n      setRefusal(undefined);\n      return;\n    }\n    if (!store.current(wanted, update)) return;\n    /*\n     * REBASED onto what landed — the id as well as the rows, because the id is\n     * normalized on the way out and the rows are not.\n     *\n     * Recording the raw draft here left the two disagreeing: the document held\n     * `hero` while the draft still held `\" hero \"`, so the next commit saw an id\n     * unchanged from what was loaded, declined to trim it a second time, and\n     * patched the spaces back — breaking every fragment link to the block. The\n     * rows were already rebased for the same reason; the id was the site this\n     * rule had not reached.\n     */\n    // The DRAFT is text, so an absent field and an empty one are both the empty\n    // box; the difference lives in `wanted` and is settled before this.\n    const landed = wanted.cssId ?? \"\";\n    loaded.current = { id: landed, rows: rebasedRows(next.rows, wanted) };\n    /*\n     * The FIELD only follows when the author's own id is the one that landed.\n     *\n     * A refused id — one another block already holds — is kept out of the write\n     * while staying in the field with its reason beside it, so `wanted.cssId`\n     * is the value the node already had rather than anything the author typed.\n     * Rebasing the field onto that replaced the text they were fixing, and took\n     * the collision message with it, because an unrelated attribute saved.\n     */\n    setDraft(current => ({\n      // Unless the author has typed since, in which case theirs is newer than\n      // anything this write knows about.\n      id: current.id === next.id && landed === asked ? landed : current.id,\n      rows: rebasedRows(current.rows, wanted),\n    }));\n  };\n\n  const settle = (next: Draft): void => {\n    setSettled(next);\n    write.current(next);\n  };\n\n  /*\n   * Read at commit time rather than closed over, for the same reason `latest`\n   * is: both effects below run after a render the author has already moved on\n   * from.\n   */\n  const settleLatest = React.useRef<() => void>(() => {});\n  settleLatest.current = (): void => {\n    settle(latest.current);\n  };\n\n  /*\n   * Committed when the author LOOKS AWAY, and again if the panel goes away.\n   *\n   * The inspector's tabs activate on `mousedown`, so an author who types an\n   * attribute and clicks Style leaves before the browser delivers the blur.\n   * This tab's content is force-mounted for that reason — destroying it took\n   * the draft with it, and took the explanation beside a refused row with it\n   * too: renaming `data-x` to `onclick` and clicking Style correctly declined\n   * to store the name, then discarded the row that said so, so returning to\n   * Advanced showed `data-x` again and the author never learned why.\n   *\n   * Settled rather than merely written, because the verdicts an author needs to\n   * come back to are read from the settled draft.\n   */\n  const shown = React.useRef(active);\n  React.useEffect(() => {\n    if (shown.current === active) return;\n    shown.current = active;\n    if (active) return;\n    settleLatest.current();\n  }, [active]);\n\n  /*\n   * Selecting another block DESTROYS this panel, through the key on it, and\n   * so does closing the inspector. Neither passes through the effect above,\n   * so a panel still on screen commits its draft here as well. One that was\n   * not has already settled it on leaving the screen, and nothing can be\n   * typed in it since: written again from the props it was last drawn with,\n   * it would put back what an undo made since then took away.\n   */\n  React.useEffect(\n    () => () => {\n      if (shown.current) write.current(latest.current);\n    },\n    []\n  );\n\n  const change = (index: number, part: Partial<AttributeRow>): void => {\n    typed();\n    setDraft(current => ({\n      ...current,\n      rows: current.rows.map((row, at) =>\n        at === index ? { ...row, ...part } : row\n      ),\n    }));\n  };\n\n  const remove = (index: number): void => {\n    const next: Draft = {\n      ...draft,\n      rows: draft.rows.filter((_row, at) => at !== index),\n    };\n    setDraft(next);\n    // Immediately: removal is a decision rather than a value being typed, and\n    // there is nothing to coalesce.\n    settle(next);\n  };\n\n  const idProblem = idProblemOf(settled.id, cssId ?? \"\", taken);\n  /*\n   * Analysed ONCE for the settled set, not once per row. Every verdict depends\n   * on the whole set — who keeps a contested key, which keys refused rows are\n   * holding — so asking row by row recomputed all of it for each row, and an\n   * imported bag of a few hundred attributes stopped rendering.\n   */\n  const problems = React.useMemo(() => rowProblems(settled.rows), [settled]);\n  /*\n   * Whether removing the empty id would reveal one. The bag's `id` is dead\n   * while the modelled field is present, so saying so is the difference\n   * between \"this does nothing visible\" and \"this changes the anchor\".\n   *\n   * Asked of the RENDERER's reading rather than of this editor's. The two are\n   * not the same rule: `attributeKey` trims a name on its way to being stored,\n   * so an imported `\" id \"` normalizes to `id` under it while the renderer,\n   * which matches the stored name, emits no id at all — and the note would then\n   * promise to reveal something that was never there.\n   */\n  const emptyIdShadows = renderedIdIn(attributes) !== undefined;\n\n  /*\n   * Written directly rather than through the draft, because the draft cannot\n   * hold the distinction: its id is text, and the box is already empty.\n   */\n  const removeEmptyId = (): void => {\n    const update = htmlUpdate(\n      { cssId: undefined, attributes },\n      { cssId, attributes }\n    );\n    if (update === undefined) return;\n    const wanted = { cssId: undefined, attributes };\n    /*\n     * Through the SAME writer as every other op this panel sends, so the echo\n     * is recorded and the effect above does not mistake this panel's own write\n     * for an edit from elsewhere. Written separately once, it discarded a\n     * refused row and its reason every time an empty id was removed.\n     *\n     * `loaded` moves with it: the field is gone, so the draft is in step with\n     * the document at an empty box, and the next commit has nothing to do\n     * rather than proposing this removal a second time.\n     */\n    if (!store.current(wanted, update)) return;\n    loaded.current = { id: \"\", rows: rebasedRows(latest.current.rows, wanted) };\n  };\n\n  return (\n    <div className=\"nx-inspector__fields\">\n      {refusal === undefined ? null : (\n        <p className=\"nx-attributes__problem\" role=\"alert\">\n          {refusal}\n        </p>\n      )}\n      <SettingSlot ids={[\"anchor\"]}>\n        <div className=\"nx-inspector__field\">\n          <Label htmlFor=\"nx-block-css-id\">Anchor (ID)</Label>\n          {/* What it writes: the root element's `id`. */}\n          <CssHint writes={BUILT_IN_WRITES.anchor}>\n            <Input\n              id=\"nx-block-css-id\"\n              value={draft.id}\n              placeholder=\"none\"\n              aria-describedby={\n                idProblem === undefined ? undefined : \"nx-css-id-problem\"\n              }\n              aria-invalid={idProblem === undefined ? undefined : true}\n              onChange={event => {\n                typed();\n                setDraft(current => ({ ...current, id: event.target.value }));\n              }}\n              onBlur={() => settle(latest.current)}\n              onKeyDown={event => {\n                if (event.key !== \"Enter\") return;\n                event.preventDefault();\n                settle(latest.current);\n              }}\n            />\n          </CssHint>\n          {idProblem === undefined ? (\n            <p className=\"nx-inspector__hint\">\n              Lets a link jump here: #your-id\n            </p>\n          ) : (\n            <p\n              className=\"nx-attributes__problem\"\n              id=\"nx-css-id-problem\"\n              role=\"alert\"\n            >\n              {idProblem}\n            </p>\n          )}\n          {/*\n          The EMPTY-BUT-PRESENT id, which the box above cannot express.\n\n          A field holding `\"\"` shadows any `id` in the bag below and renders\n          none of its own, so the element ends up with no id — and no amount of\n          typing in an already-empty box says \"remove it\", because the draft\n          matches what was loaded and a commit correctly finds nothing to do.\n          This is the gesture that was missing.\n\n          Shown only in that state. Cleaning it up on open would be a write\n          nobody asked for, and folding it into an unrelated save would change\n          the id the page renders as a side effect of editing an attribute:\n          removing the modelled field UNSHADOWS the bag's `id`, so it has to be\n          the author's decision and has to say what it does.\n        */}\n          {cssId !== \"\" ? null : (\n            <p className=\"nx-inspector__note\" role=\"status\">\n              This block has an empty id set, so it renders no id at all\n              {emptyIdShadows\n                ? \" and the id in the attributes below is ignored\"\n                : \"\"}\n              .{\" \"}\n              <Button\n                type=\"button\"\n                variant=\"ghost\"\n                size=\"sm\"\n                onClick={() => removeEmptyId()}\n              >\n                Remove the empty id\n              </Button>\n            </p>\n          )}\n        </div>\n      </SettingSlot>\n\n      <SettingSlot ids={[\"cssClasses\"]}>\n        <CssClassesField\n          nodeId={nodeId}\n          stored={storedClassesOf(editor, nodeId)}\n          editor={editor}\n          active={active}\n        />\n      </SettingSlot>\n\n      <SettingSlot ids={[\"attributes\"]}>\n        <fieldset className=\"nx-attributes\">\n          <legend className=\"nx-attributes__legend\">Attributes</legend>\n          {draft.rows.length === 0 ? (\n            <p className=\"nx-inspector__note\">No attributes on this block.</p>\n          ) : (\n            <>\n              {/*\n              Column headings, shown ONCE. Repeating \"Name\" and \"Value\" against\n              every row is noise to look at, and worse to listen to: each\n              repetition is another control announced with a word that already\n              means the block's own name field above the tabs.\n\n              `aria-hidden` because they label nothing — every input carries its\n              own accessible name, which is unique per row and still contains\n              the word written here.\n            */}\n              <div className=\"nx-attributes__head\" aria-hidden=\"true\">\n                <span>Name</span>\n                <span>Value</span>\n              </div>\n              <ul className=\"nx-attributes__rows\">\n                {draft.rows.map((row, index) => (\n                  <AttributeRowFields\n                    // Keyed by POSITION, not by name: a name is what the author is\n                    // editing, so keying on it would remount the input on every\n                    // keystroke and lose the caret.\n                    key={`${nodeId}:${String(index)}`}\n                    row={row}\n                    index={index}\n                    problem={problemOf(settled, problems, index, draft)}\n                    onChange={change}\n                    onCommit={() => settle(latest.current)}\n                    onRemove={() => remove(index)}\n                  />\n                ))}\n              </ul>\n            </>\n          )}\n          {/* A button that looks like one, with an edge: a ghost button here\n            read as indented text. */}\n          <Button\n            type=\"button\"\n            variant=\"outline\"\n            size=\"sm\"\n            className=\"nx-attributes__add\"\n            onClick={() =>\n              setDraft(current => ({\n                ...current,\n                rows: [...current.rows, { name: \"\", value: \"\" }],\n              }))\n            }\n          >\n            <Plus aria-hidden=\"true\" size={14} />\n            Add attribute\n          </Button>\n        </fieldset>\n      </SettingSlot>\n    </div>\n  );\n}\n\n/** The block's own class text as stored, or `undefined` where it has none. */\nfunction storedClassesOf(\n  editor: EditorState,\n  nodeId: string\n): string | undefined {\n  const value: unknown = findNode(editor.document.nodes, nodeId)?.cssClasses;\n  return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * The names of `text` to judge now: every name once the author has finished\n * the field, and while they type only the names a space has closed, so a name\n * half typed (`nx` on its way to `nxt-card`) is not refused yet.\n */\nfunction finishedText(text: string, finished: boolean): string {\n  return finished ? text : text.replace(/[^\\t\\n\\f\\r ]+$/, \"\");\n}\n\n/**\n * \"CSS classes\": the block's own class names, separated by spaces, added to\n * its root element beside the classes Nextly generates. Judged by the same\n * rule the save and the renderers use, name by name: the valid names are\n * written, and each refused one is listed under the field with the reason,\n * the author's text kept so it can be fixed.\n *\n * Written when the author finishes (Enter, leaving the field, the tab or the\n * block), as the anchor and attributes are, so an undo is one step per edit.\n */\nfunction CssClassesField({\n  nodeId,\n  stored,\n  editor,\n  active,\n}: {\n  nodeId: string;\n  stored: string | undefined;\n  editor: EditorState;\n  active: boolean;\n}): React.JSX.Element {\n  const id = React.useId();\n  const [draft, setDraft] = React.useState(stored ?? \"\");\n  // Whether the field holds what was last finished, so every name is judged.\n  const [finished, setFinished] = React.useState(true);\n  const [refusal, setRefusal] = React.useState<string | undefined>(undefined);\n  // The text the field was filled with or last saved at: leaving a field\n  // nobody changed writes nothing, even where the stored text would tidy.\n  const loaded = React.useRef(stored ?? \"\");\n  // A keystroke begins the field's edit, as the panel's other fields do: Save\n  // pressed from here writes it first, and Escape puts back what was loaded.\n  const edit = useDraftFieldEdit();\n  // What this field last wrote, so its own echo is told from an undo.\n  const lastWritten = React.useRef<string | null>(null);\n  React.useEffect(() => {\n    if (\n      lastWritten.current !== null &&\n      lastWritten.current === (stored ?? \"\")\n    ) {\n      lastWritten.current = null;\n      return;\n    }\n    lastWritten.current = null;\n    setDraft(stored ?? \"\");\n    setFinished(true);\n    loaded.current = stored ?? \"\";\n  }, [stored]);\n\n  const latest = React.useRef(draft);\n  latest.current = draft;\n  const commit = React.useRef<() => void>(() => {});\n  commit.current = (): void => {\n    const text = latest.current;\n    setFinished(true);\n    // Back to what was saved: nothing is pending, so no save failed either.\n    if (text === loaded.current) {\n      setRefusal(undefined);\n      return;\n    }\n    const next = checkCssClassNames(text).valid.join(\" \");\n    if (next === (stored ?? \"\")) {\n      loaded.current = text;\n      setRefusal(undefined);\n      return;\n    }\n    // Asked of the live document, as every write in the panel asks.\n    const locked = designReadOnlyReason(\n      editor.document,\n      nodeId,\n      lockViewOf(editor)\n    );\n    if (locked !== undefined) {\n      setRefusal(locked);\n      return;\n    }\n    const applied = editor.apply(\n      next === \"\"\n        ? { kind: \"update\", id: nodeId, patch: {}, unset: [\"cssClasses\"] }\n        : { kind: \"update\", id: nodeId, patch: { cssClasses: next } }\n    );\n    // A refused save leaves `loaded` where it was, so finishing the field\n    // again tries again once whatever refused it has cleared.\n    if (applied === null) {\n      setRefusal(REFUSED);\n      return;\n    }\n    loaded.current = text;\n    setRefusal(undefined);\n    lastWritten.current = next;\n  };\n\n  // Written when the author looks away (the tabs move on `mousedown`, before\n  // the blur), and when the field goes away while on screen.\n  const shown = React.useRef(active);\n  React.useEffect(() => {\n    if (shown.current === active) return;\n    shown.current = active;\n    if (!active) commit.current();\n  }, [active]);\n  React.useEffect(\n    () => () => {\n      if (shown.current) commit.current();\n    },\n    []\n  );\n\n  const refused = checkCssClassNames(finishedText(draft, finished)).refused;\n  const hintId = `${id}-hint`;\n  const refusedId = `${id}-refused`;\n  return (\n    <div className=\"nx-inspector__field\">\n      <Label htmlFor={id}>CSS classes</Label>\n      {/* What it writes: names on the root element's `class`. */}\n      <CssHint writes={BUILT_IN_WRITES.cssClasses}>\n        <Input\n          id={id}\n          value={draft}\n          placeholder=\"none\"\n          spellCheck={false}\n          autoComplete=\"off\"\n          aria-describedby={refused.length === 0 ? hintId : refusedId}\n          aria-invalid={refused.length === 0 ? undefined : true}\n          onChange={event => {\n            edit.begin(() => {\n              setDraft(loaded.current);\n              setFinished(true);\n            });\n            setDraft(event.target.value);\n            setFinished(false);\n          }}\n          onBlur={() => commit.current()}\n          onKeyDown={event => {\n            if (event.key !== \"Enter\") return;\n            event.preventDefault();\n            commit.current();\n          }}\n        />\n      </CssHint>\n      {refused.length === 0 ? (\n        <p className=\"nx-inspector__hint\" id={hintId}>\n          Separate names with spaces.\n        </p>\n      ) : (\n        <ul\n          className=\"nx-css-classes__refused\"\n          id={refusedId}\n          aria-label=\"Names not added\"\n        >\n          {refused.map((each, at) => (\n            <li\n              key={`${String(at)}:${each.name}`}\n              className=\"nx-attributes__problem\"\n            >\n              {each.reason}\n            </li>\n          ))}\n        </ul>\n      )}\n      {refusal === undefined ? null : (\n        <p className=\"nx-attributes__problem\" role=\"alert\">\n          {refusal}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/** Why the CSS id will not be written, or `undefined`. */\nfunction idProblemOf(\n  id: string,\n  stored: string,\n  taken: ReadonlySet<string>\n): string | undefined {\n  const trimmed = id.trim();\n  if (trimmed === \"\" || trimmed === stored) return undefined;\n  return taken.has(trimmed)\n    ? \"Another block on this page already uses that id. Two elements with one id give a link, a label and a style rule two possible targets.\"\n    : undefined;\n}\n\n/**\n * The verdict for one row, read from the settled draft but keyed to the live one.\n *\n * A row the author is still typing has no verdict yet, so a settled list that\n * no longer matches the live one at this position simply says nothing.\n */\nfunction problemOf(\n  settled: Draft,\n  problems: readonly (RowProblem | undefined)[],\n  index: number,\n  live: Draft\n): string | undefined {\n  const behind = settled.rows[index];\n  const now = live.rows[index];\n  if (behind === undefined || now === undefined) return undefined;\n  if (behind.name !== now.name) return undefined;\n  /*\n   * Every row problem is about the NAME, which is why the reason below is wired\n   * to that input alone. A colliding id used to be the exception — a good name\n   * with a value another block held — and it no longer reaches a row at all:\n   * an id belongs in the field above, and that field carries its own collision\n   * message on the one input whose value it is about.\n   */\n  const problem = problems[index];\n  return problem === undefined ? undefined : problemMessage(problem);\n}\n\nfunction AttributeRowFields({\n  row,\n  index,\n  problem,\n  onChange,\n  onCommit,\n  onRemove,\n}: {\n  row: AttributeRow;\n  index: number;\n  problem: string | undefined;\n  onChange: (index: number, part: Partial<AttributeRow>) => void;\n  onCommit: () => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  /*\n   * Enter COMMITS here; it must not reach the form above. The builder mounts\n   * inside the entry's `<form>`, and a single-line input with nothing\n   * stopping the key implicitly submits it — so typing an attribute and\n   * pressing Enter would save the whole entry.\n   */\n  const onEnter = (event: React.KeyboardEvent): void => {\n    if (event.key !== \"Enter\") return;\n    event.preventDefault();\n    onCommit();\n  };\n  const nameId = `nx-attr-name-${String(index)}`;\n  const valueId = `nx-attr-value-${String(index)}`;\n  const problemId = `nx-attr-problem-${String(index)}`;\n  /*\n   * The visible headings are short because they sit over the columns, and short\n   * words REPEAT: \"Name\" is also the block's own name field above the tabs. So\n   * the accessible name is made unique per row while still CONTAINING the\n   * visible word, which is what lets someone say \"name\" to a voice control and\n   * have it match what they can see.\n   */\n  const position = String(index + 1);\n  return (\n    <li className=\"nx-attributes__row\">\n      <div className=\"nx-attributes__pair\">\n        <Input\n          id={nameId}\n          value={row.name}\n          placeholder=\"data-example\"\n          aria-label={`Name of attribute ${position}`}\n          // Named so a screen reader reaches the reason with the field, rather\n          // than leaving it as text that happens to sit nearby — and only when\n          // the NAME is the thing that is wrong.\n          aria-describedby={problem === undefined ? undefined : problemId}\n          aria-invalid={problem === undefined ? undefined : true}\n          onChange={event => onChange(index, { name: event.target.value })}\n          onBlur={onCommit}\n          onKeyDown={onEnter}\n        />\n        <Input\n          id={valueId}\n          value={row.value}\n          aria-label={`Value of attribute ${position}`}\n          onChange={event => onChange(index, { value: event.target.value })}\n          onBlur={onCommit}\n          onKeyDown={onEnter}\n        />\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          // Named per row, because six identical \"Remove\" buttons give a screen\n          // reader six identical announcements and no way to tell them apart.\n          aria-label={\n            isBlankRow(row) ? \"Remove empty attribute\" : `Remove ${row.name}`\n          }\n          onClick={onRemove}\n        >\n          Remove\n        </Button>\n      </div>\n      {problem === undefined ? null : (\n        <p className=\"nx-attributes__problem\" id={problemId} role=\"alert\">\n          {problem}\n        </p>\n      )}\n    </li>\n  );\n}\n","/**\n * A block's link as the inspector edits it: which props make it up, what is\n * stored in them, and what each pick, switch and flag writes back.\n *\n * A link is one thing to an author and several props to a block: where it\n * goes (`href` or `link`), how it opens (`target`), what it says about the\n * page it points at (`rel`) and, on a button, the entry it points at\n * (`entryCollection` and `entryId`). Drawn one row per prop, the panel showed\n * \"Open link in\" and \"Link relationship\" on a heading with no link at all, and\n * asked for a collection's slug and an entry's id by hand. The group lets the\n * inspector draw them as one control instead, while the block schemas stay as\n * they are.\n *\n * The group is found by prop NAME and type, never by type alone: an image's\n * `src` and a form's `action` are `url` props too, and neither is a link.\n *\n * Pure, so each rule is tested without a panel.\n *\n * @module link-group\n */\nimport { propIsSet, type EditableProp } from \"../inspector\";\n\n/** The props of one block's link, by the names the block declares them under. */\nexport interface LinkGroup {\n  /** Where the link goes: `href` or `link`. */\n  readonly link: string;\n  /** How it opens, when the block declares a target that can be `_blank`. */\n  readonly target?: string;\n  /** Its `rel` tokens, when the block declares them. */\n  readonly rel?: string;\n  /**\n   * The entry it points at, when the block declares both halves of the\n   * reference. An entry beats a typed address where the block renders: it\n   * survives the entry being renamed.\n   */\n  readonly entry?: { readonly collection: string; readonly id: string };\n  /** Every prop drawn inside the group, the link's own included. */\n  readonly drawn: ReadonlySet<string>;\n}\n\n/** The tab a prop is placed in, Content where it names none. */\nfunction tabOf(schema: EditableProp[\"schema\"] | undefined): string {\n  return typeof schema?.group === \"string\" ? schema.group : \"content\";\n}\n\n/** The names a link's own prop is declared under, in the order they are tried. */\nconst LINK_NAMES = [\"href\", \"link\"] as const;\n\n/**\n * Whether a `target` prop is exactly \"this tab or a new tab\": a select whose\n * options are `_self` and `_blank` and nothing else, in either order. Only\n * then does a switch say all it can hold; a target offering `_parent` or a\n * named frame keeps its own menu, since a switch would hide those choices.\n */\nfunction isNewTabTarget(schema: EditableProp[\"schema\"] | undefined): boolean {\n  if (schema?.type !== \"select\" || !Array.isArray(schema.options)) return false;\n  const options = new Set(schema.options);\n  return (\n    schema.options.length === 2 &&\n    options.size === 2 &&\n    options.has(\"_self\") &&\n    options.has(\"_blank\")\n  );\n}\n\n/**\n * The link group of a block's props, or `undefined` when it declares no link.\n *\n * Each sibling joins only in the link's tab and with the type its control\n * writes: a `target` that is not exactly this tab or a new tab is not one a\n * switch can stand for (see {@link isNewTabTarget}), and an entry reference\n * missing either half is not one a pick can complete. A sibling that does\n * not join keeps its own row, in its own tab.\n */\nexport function linkGroupOf(\n  props: ReadonlyArray<Pick<EditableProp, \"name\" | \"schema\">>\n): LinkGroup | undefined {\n  const all = new Map(props.map(prop => [prop.name, prop.schema]));\n  const link = LINK_NAMES.find(name => all.get(name)?.type === \"url\");\n  if (link === undefined) return undefined;\n  // Only the siblings placed in the link's own tab: one the block places\n  // elsewhere (a link relationship in Advanced) is drawn there, on its row.\n  const tab = tabOf(all.get(link));\n  const schemas = new Map(\n    [...all].filter(([, schema]) => tabOf(schema) === tab)\n  );\n  const target = isNewTabTarget(schemas.get(\"target\")) ? \"target\" : undefined;\n  const rel = schemas.get(\"rel\")?.type === \"text\" ? \"rel\" : undefined;\n  const entry =\n    schemas.get(\"entryCollection\")?.type === \"text\" &&\n    schemas.get(\"entryId\")?.type === \"text\"\n      ? { collection: \"entryCollection\", id: \"entryId\" }\n      : undefined;\n  const drawn = new Set<string>([link]);\n  if (target !== undefined) drawn.add(target);\n  if (rel !== undefined) drawn.add(rel);\n  if (entry !== undefined) {\n    drawn.add(entry.collection);\n    drawn.add(entry.id);\n  }\n  return {\n    link,\n    ...(target === undefined ? {} : { target }),\n    ...(rel === undefined ? {} : { rel }),\n    ...(entry === undefined ? {} : { entry }),\n    drawn,\n  };\n}\n\n/**\n * A stored string the inspector counts as set, trimmed, or `undefined`.\n *\n * Asked through `propIsSet`, the one rule the inspector's `onlyWithout` and\n * the renderer read: for the link prop that is the engine's URL policy, so a\n * stored `javascript:` address the page would never follow reads as no link\n * here too, rather than as a link the block does not render.\n */\nfunction storedString(\n  schema: { readonly type: string } | undefined,\n  value: unknown\n): string | undefined {\n  if (typeof value !== \"string\" || !propIsSet(schema, value)) return undefined;\n  const trimmed = value.trim();\n  return trimmed === \"\" ? undefined : trimmed;\n}\n\n/** The link prop's type, which decides what counts as a link that is set. */\nconst URL_PROP = { type: \"url\" } as const;\n\n/** What a block's link holds now. */\nexport type LinkValue =\n  | { readonly kind: \"none\" }\n  | { readonly kind: \"address\"; readonly href: string }\n  | {\n      readonly kind: \"entry\";\n      readonly collection: string;\n      readonly id: string;\n    };\n\n/**\n * What the group's props hold, read the way the block renders them: an entry\n * reference with both halves set wins over an address, as `core/button`\n * resolves it first.\n */\nexport function linkValueOf(\n  group: LinkGroup,\n  values: Readonly<Record<string, unknown>>\n): LinkValue {\n  if (group.entry !== undefined) {\n    const collection = storedString(undefined, values[group.entry.collection]);\n    const id = storedString(undefined, values[group.entry.id]);\n    if (collection !== undefined && id !== undefined) {\n      return { kind: \"entry\", collection, id };\n    }\n  }\n  const href = storedString(URL_PROP, values[group.link]);\n  return href === undefined ? { kind: \"none\" } : { kind: \"address\", href };\n}\n\n/** What kind of address a link is, which decides its icon. */\nexport type LinkKind = \"web\" | \"path\" | \"mail\" | \"phone\" | \"anchor\";\n\n/**\n * The kind of address `value` reads as, or `undefined` when it is not one\n * the control recognises as an address by its shape: a web address\n * (`https://`, or `//host`), a path on this site (`/pricing`), an email\n * (`mailto:`), a phone number (`tel:`) or a place on the page (`#faq`).\n *\n * Recognised text is offered as an address first while searching, since\n * nobody titles a page `https://…`.\n */\nexport function linkKindOf(value: string): LinkKind | undefined {\n  const typed = value.trim();\n  if (/^https?:\\/\\/\\S/i.test(typed) || /^\\/\\/\\S/.test(typed)) return \"web\";\n  if (/^mailto:\\S/i.test(typed)) return \"mail\";\n  if (/^tel:\\S/i.test(typed)) return \"phone\";\n  if (/^#\\S/.test(typed)) return \"anchor\";\n  if (typed.startsWith(\"/\")) return \"path\";\n  return undefined;\n}\n\n/** A host name with no scheme before it: `example.com`, `www.example.com/x`. */\nconst BARE_HOST = /^[a-z0-9-]+(\\.[a-z0-9-]+)*\\.[a-z]{2,}(:\\d+)?([/?#]\\S*)?$/i;\n\n/**\n * What \"Use as a URL\" stores for typed text, or `undefined` when nothing\n * should be offered: empty text, or an address the page could never follow\n * (`javascript:` and the other schemes the engine refuses, which the block\n * would render as no link at all).\n *\n * A bare host name gains `https://`. Stored as typed it would be a path on\n * this site, `/example.com`, which is never what someone typing a domain\n * meant.\n */\nexport function addressFor(typed: string): string | undefined {\n  const trimmed = typed.trim();\n  if (trimmed === \"\") return undefined;\n  const address =\n    linkKindOf(trimmed) === undefined && BARE_HOST.test(trimmed)\n      ? `https://${trimmed}`\n      : trimmed;\n  return propIsSet(URL_PROP, address) ? address : undefined;\n}\n\n/**\n * The `rel` flags offered as checkboxes, in the order they are listed:\n * Nofollow first, as the one most asked for.\n */\nexport const REL_FLAGS: ReadonlyArray<{\n  readonly token: string;\n  readonly label: string;\n}> = [\n  { token: \"nofollow\", label: \"Nofollow\" },\n  { token: \"sponsored\", label: \"Sponsored\" },\n  { token: \"ugc\", label: \"User-generated\" },\n];\n\n/** A stored `rel` as its tokens, in their stored order, each once. */\nexport function relTokens(value: unknown): string[] {\n  if (typeof value !== \"string\") return [];\n  const seen = new Set<string>();\n  return value.split(/\\s+/).filter(token => {\n    const key = token.toLowerCase();\n    if (token === \"\" || seen.has(key)) return false;\n    seen.add(key);\n    return true;\n  });\n}\n\n/** Whether `value` holds `token`. Compared as HTML does: ignoring case. */\nexport function relHas(value: unknown, token: string): boolean {\n  const wanted = token.toLowerCase();\n  return relTokens(value).some(each => each.toLowerCase() === wanted);\n}\n\n/**\n * The stored tokens that are none of the checkboxes', such as a `me` an API\n * write stored: kept by every change here, and shown so they can be removed.\n */\nexport function relOthers(value: unknown): string[] {\n  const flags = new Set(REL_FLAGS.map(flag => flag.token));\n  return relTokens(value).filter(token => !flags.has(token.toLowerCase()));\n}\n\n/**\n * `value` with `token` added or taken out, every other token kept in its\n * place. `undefined` when no token is left, so the prop is removed rather\n * than stored empty.\n */\nexport function relWith(\n  value: unknown,\n  token: string,\n  on: boolean\n): string | undefined {\n  const wanted = token.toLowerCase();\n  const kept = relTokens(value).filter(each => each.toLowerCase() !== wanted);\n  const next = on ? [...kept, wanted] : kept;\n  return next.length === 0 ? undefined : next.join(\" \");\n}\n\n/** What one change to the group writes: a value per prop, `undefined` to remove it. */\nexport type LinkChanges = Readonly<Record<string, unknown>>;\n\n/** Where a pick in the link control goes. */\nexport type LinkPick =\n  | { readonly kind: \"address\"; readonly href: string }\n  | {\n      readonly kind: \"entry\";\n      readonly collection: string;\n      readonly id: string;\n    };\n\n/**\n * What a pick writes.\n *\n * An address (a page's path, or a typed URL) is stored in the link prop and\n * clears an entry reference, which would otherwise win where the block\n * renders and the pick would seem to do nothing. An entry is stored as its\n * reference and clears the address, so the block holds one destination.\n * `undefined` for an entry pick on a block with no entry reference to hold it.\n */\nexport function pickChanges(\n  group: LinkGroup,\n  pick: LinkPick\n): LinkChanges | undefined {\n  if (pick.kind === \"entry\") {\n    if (group.entry === undefined) return undefined;\n    return {\n      [group.entry.collection]: pick.collection,\n      [group.entry.id]: pick.id,\n      [group.link]: undefined,\n    };\n  }\n  return {\n    [group.link]: pick.href,\n    ...(group.entry === undefined\n      ? {}\n      : { [group.entry.collection]: undefined, [group.entry.id]: undefined }),\n  };\n}\n\n/**\n * What clearing the link writes: every prop in the group removed. The target\n * and the `rel` go with it, because they mean nothing without a link and are\n * shown only while one is set: left behind, a new link would arrive opening\n * in a new tab, marked sponsored, with nothing on screen saying so.\n */\nexport function clearChanges(group: LinkGroup): LinkChanges {\n  return Object.fromEntries([...group.drawn].map(name => [name, undefined]));\n}\n\n/**\n * The props `changes` leaves, applied over `props`: a value replaces, and\n * `undefined` removes. One write for several props, so a pick that sets an\n * entry and clears an address is one step to undo.\n */\nexport function withChanges(\n  props: Readonly<Record<string, unknown>>,\n  changes: LinkChanges\n): Record<string, unknown> {\n  const next: Record<string, unknown> = { ...props };\n  for (const [name, value] of Object.entries(changes)) {\n    if (value === undefined) delete next[name];\n    else next[name] = value;\n  }\n  return next;\n}\n","\"use client\";\n\n/**\n * The Content tab's link: one control for where a block goes, and the two\n * settings that only mean something once it goes somewhere.\n *\n * - **The link** is a combobox. Empty, it reads \"Search pages or paste a\n *   URL\". Open, it searches the site's pages and other collections' entries\n *   through the host's `findLinkTargets` and offers what was typed as an\n *   address. Set, it is a chip naming the page, the entry or the address,\n *   with ✕ to clear it.\n * - **Open in a new tab** is a switch row, and **Link options** a disclosure of\n *   `rel` checkboxes. Both are drawn only while a link is set.\n *\n * Which props make up the link, and what each change writes, are decided in\n * `link-group`; this module draws them. Every change is ONE write of the\n * props it touches, through `onCommitMany`, so a pick that sets an entry and\n * clears an address is one step to undo.\n *\n * Without the host's search, the control takes typed addresses only, and\n * says so in the list.\n *\n * @module link-control\n */\n\nimport { findNode, type BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport {\n  Checkbox,\n  Input,\n  Label,\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n  PopoverTrigger,\n  Switch,\n} from \"@nextlyhq/ui\";\nimport {\n  ChevronRight,\n  CornerDownLeft,\n  FileText,\n  Hash,\n  Link2,\n  Mail,\n  Phone,\n  Search,\n  X,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport { HeldByLock } from \"../held-by-lock\";\nimport {\n  lockViewOf,\n  propIsWritable,\n  propLabel,\n  type EditableProp,\n} from \"../inspector\";\n\nimport type { ContentServices, LinkTarget } from \"./content-controls\";\nimport {\n  addressFor,\n  clearChanges,\n  linkKindOf,\n  linkValueOf,\n  pickChanges,\n  REL_FLAGS,\n  relHas,\n  relOthers,\n  relTokens,\n  relWith,\n  withChanges,\n  type LinkChanges,\n  type LinkGroup,\n  type LinkKind,\n  type LinkPick,\n  type LinkValue,\n} from \"./link-group\";\nimport type { BindableOptions, BindableWrapper } from \"./prop-groups\";\n\n/** How long typing pauses before the host is asked again. */\nconst SEARCH_PAUSE_MS = 150;\n\n/** How many pages and entries one search lists. */\nconst TARGETS_SHOWN = 10;\n\n/**\n * How many a lookup of the stored link reads: the host's most, so a page\n * named by its address is found among as many as one read can return.\n */\nconst LOOKUP_LIMIT = 20;\n\ntype FindLinkTargets = NonNullable<ContentServices[\"findLinkTargets\"]>;\n\n/**\n * Write the props `changes` names on one block, as one edit, or none of them.\n *\n * Every prop is asked whether it may change where the block sits, as a single\n * prop's commit asks, and one that may not refuses the whole edit. A pick\n * changes a destination across props (an address and the entry reference it\n * replaces), and writing only the ones a `contentOnly` area allows would leave\n * a destination half saved. The group asks first and sends only what may\n * change; this holds the rule for whatever calls it.\n *\n * @returns the document after the edit, or `null` when it was not applied\n */\nexport function commitLinkChanges(\n  editor: EditorState,\n  nodeId: string,\n  changes: LinkChanges\n): BlockDocument | null {\n  const document = editor.document;\n  const view = lockViewOf(editor);\n  const names = Object.keys(changes);\n  if (names.length === 0) return null;\n  if (!names.every(name => propIsWritable(document, nodeId, name, view))) {\n    return null;\n  }\n  const node = findNode(document.nodes, nodeId);\n  if (node === undefined) return null;\n  return editor.apply({\n    kind: \"update\",\n    id: nodeId,\n    patch: { props: withChanges(node.props, changes) },\n  });\n}\n\n/** The pages and entries for what is typed, while the list is open. */\ntype Targets =\n  | { readonly kind: \"idle\" }\n  | { readonly kind: \"loading\" }\n  | { readonly kind: \"found\"; readonly targets: readonly LinkTarget[] }\n  | { readonly kind: \"failed\" };\n\n/**\n * Read the targets for `search` while `active`, a pause after the last key,\n * cancelling a read a newer one replaces so a slow answer cannot overwrite a\n * later one.\n */\nfunction useTargets(\n  find: FindLinkTargets | undefined,\n  search: string,\n  active: boolean\n): Targets {\n  const [targets, setTargets] = React.useState<Targets>({ kind: \"idle\" });\n  React.useEffect(() => {\n    if (!active || find === undefined) return;\n    const controller = new AbortController();\n    setTargets({ kind: \"loading\" });\n    const timer = setTimeout(() => {\n      find({\n        search: search.trim(),\n        limit: TARGETS_SHOWN,\n        signal: controller.signal,\n      }).then(\n        found => {\n          if (!controller.signal.aborted) {\n            setTargets({ kind: \"found\", targets: found });\n          }\n        },\n        () => {\n          if (!controller.signal.aborted) setTargets({ kind: \"failed\" });\n        }\n      );\n    }, SEARCH_PAUSE_MS);\n    return () => {\n      clearTimeout(timer);\n      controller.abort();\n    };\n  }, [find, search, active]);\n  return targets;\n}\n\n/** The words a path's last part reads as: `/blog/spring-sale` is \"spring sale\". */\nfunction searchWordsOf(path: string): string {\n  const last = path.split(/[?#]/)[0]?.split(\"/\").filter(Boolean).pop() ?? \"\";\n  return last.replace(/[-_]+/g, \" \").trim();\n}\n\n/** A key naming one stored link, so a lookup is made once per link. */\nfunction linkKey(value: LinkValue): string | undefined {\n  if (value.kind === \"entry\") return `entry:${value.collection}:${value.id}`;\n  if (value.kind === \"address\" && linkKindOf(value.href) === \"path\") {\n    return `path:${value.href}`;\n  }\n  return undefined;\n}\n\n/**\n * What is known of the page or entry a stored link names.\n *\n * - `none`: nothing can be looked up, because the link is a typed address,\n *   or because the host lends no search to look it up with.\n * - `loading`, then `found` or `missing`: the lookup ran, and either named it\n *   or found nothing the author can open.\n * - `failed`: the lookup itself failed, which says nothing about the entry,\n *   so it is kept apart from `missing` and tried again.\n */\ntype StoredLookup =\n  | { readonly kind: \"none\" }\n  | { readonly kind: \"loading\" }\n  | { readonly kind: \"found\"; readonly target: LinkTarget }\n  | { readonly kind: \"missing\" }\n  | { readonly kind: \"failed\" };\n\n/**\n * The page or entry the stored link names, looked up once per link: an entry\n * by its collection and id, and a path by its address, first among the pages\n * whose title reads like its last part, then among the first pages listed,\n * since a slug need not read like its page's title.\n *\n * A failed lookup is not repeated on its own, so a host that is down is not\n * asked again on every render. `retry` asks again, once, after a failure: the\n * control calls it when the author comes back to the link.\n */\nfunction useStoredTarget(\n  find: FindLinkTargets | undefined,\n  value: LinkValue\n): { lookup: StoredLookup; retry: () => void } {\n  const key = linkKey(value);\n  const [found, setFound] = React.useState<{\n    key: string;\n    lookup: StoredLookup;\n  }>();\n  // Bumped by `retry`, so the effect below runs again for the same link.\n  const [attempt, setAttempt] = React.useState(0);\n  React.useEffect(() => {\n    if (key === undefined || find === undefined) return;\n    const controller = new AbortController();\n    const [kind, ...rest] = key.split(\":\");\n    const matches = (target: LinkTarget): boolean =>\n      kind === \"entry\"\n        ? `${target.collection}:${target.id}` === rest.join(\":\")\n        : target.path === rest.join(\":\");\n    const settle = (lookup: StoredLookup): void => {\n      if (!controller.signal.aborted) setFound({ key, lookup });\n    };\n    const words = kind === \"entry\" ? \"\" : searchWordsOf(rest.join(\":\"));\n    const searches = words === \"\" ? [\"\"] : [words, \"\"];\n    const lookUp = async (): Promise<LinkTarget | null> => {\n      for (const search of searches) {\n        const targets = await find({\n          search,\n          limit: LOOKUP_LIMIT,\n          signal: controller.signal,\n        });\n        const match = targets.find(matches);\n        if (match !== undefined) return match;\n      }\n      return null;\n    };\n    lookUp().then(\n      target =>\n        settle(\n          target === null ? { kind: \"missing\" } : { kind: \"found\", target }\n        ),\n      () => settle({ kind: \"failed\" })\n    );\n    return () => controller.abort();\n  }, [find, key, attempt]);\n  const lookup: StoredLookup =\n    key === undefined || find === undefined\n      ? { kind: \"none\" }\n      : found === undefined || found.key !== key\n        ? { kind: \"loading\" }\n        : found.lookup;\n  const retry = (): void => {\n    if (lookup.kind !== \"failed\") return;\n    // Shown as loading while it is asked again, and read again only once.\n    setFound(undefined);\n    setAttempt(at => at + 1);\n  };\n  return { lookup, retry };\n}\n\n/** One row of the open list. */\ntype LinkOption =\n  | {\n      readonly key: string;\n      readonly kind: \"target\";\n      readonly target: LinkTarget;\n      /** Why it cannot be chosen here, when it cannot. */\n      readonly unusable?: string;\n    }\n  | { readonly key: string; readonly kind: \"address\"; readonly href: string };\n\n/** Said of a page this block could only link to by an address it lacks. */\nconst NO_ADDRESS = \"No address known for this page\";\n\n/**\n * The open list's rows, in the order they are drawn and stepped through.\n *\n * Text that reads as an address (`https://…`, `/…`, `mailto:`, `tel:`, `#…`)\n * puts \"Use as a URL\" first, so Enter takes what was pasted; otherwise the\n * pages and entries come first and the address after them.\n */\nfunction optionsFor(\n  typed: string,\n  targets: Targets,\n  entryLinks: boolean\n): LinkOption[] {\n  const href = addressFor(typed);\n  const address: LinkOption[] =\n    href === undefined ? [] : [{ key: \"address\", kind: \"address\", href }];\n  const found: LinkOption[] =\n    targets.kind === \"found\"\n      ? targets.targets.map(target => ({\n          key: `target:${target.collection}:${target.id}`,\n          kind: \"target\",\n          target,\n          // A block with an entry reference links to any entry by it; any\n          // other block needs the address the page is served at.\n          ...(target.path === undefined && !entryLinks\n            ? { unusable: NO_ADDRESS }\n            : {}),\n        }))\n      : [];\n  return linkKindOf(typed) === undefined\n    ? [...found, ...address]\n    : [...address, ...found];\n}\n\n/** What a chosen row writes. */\nfunction pickOf(option: LinkOption): LinkPick {\n  if (option.kind === \"address\") return { kind: \"address\", href: option.href };\n  const { target } = option;\n  return target.path === undefined\n    ? { kind: \"entry\", collection: target.collection, id: target.id }\n    : { kind: \"address\", href: target.path };\n}\n\n/** The icon an address is drawn with. */\nfunction AddressIcon({ kind }: { kind: LinkKind }): React.JSX.Element {\n  const Icon =\n    kind === \"mail\"\n      ? Mail\n      : kind === \"phone\"\n        ? Phone\n        : kind === \"anchor\"\n          ? Hash\n          : Link2;\n  return <Icon aria-hidden=\"true\" size={14} className=\"nx-link-pick__icon\" />;\n}\n\n/** What the chip says about the stored link. */\ninterface ChipWords {\n  readonly page: boolean;\n  readonly kind: LinkKind;\n  readonly title: string;\n  readonly detail?: string;\n}\n\n/** The stored entry reference in words, from what is known of it. */\nfunction entryWords(\n  value: { readonly collection: string; readonly id: string },\n  lookup: StoredLookup\n): ChipWords {\n  const as = (title: string, detail: string): ChipWords => ({\n    page: true,\n    kind: \"web\",\n    title,\n    detail,\n  });\n  switch (lookup.kind) {\n    case \"found\":\n      return as(lookup.target.title, lookup.target.group);\n    case \"loading\":\n      return { page: true, kind: \"web\", title: \"Loading the linked entry…\" };\n    case \"missing\":\n      return as(\"An entry you can't open here\", value.collection);\n    case \"failed\":\n      return as(\"The linked entry couldn't be loaded\", value.collection);\n    case \"none\":\n      // No search to name it with: the reference as it is stored, which\n      // still says where the link goes and can still be cleared.\n      return as(`An entry in ${value.collection}`, value.id);\n  }\n}\n\n/** The stored link in words, from what is known of it. */\nfunction chipWords(\n  value: LinkValue,\n  lookup: StoredLookup\n): ChipWords | undefined {\n  if (value.kind === \"none\") return undefined;\n  if (value.kind === \"entry\") return entryWords(value, lookup);\n  if (lookup.kind === \"found\") {\n    return {\n      page: true,\n      kind: \"path\",\n      title: lookup.target.title,\n      detail: value.href,\n    };\n  }\n  // An address that names no page the author can open, or that could not be\n  // looked up, is shown as itself.\n  return {\n    page: false,\n    kind: linkKindOf(value.href) ?? \"web\",\n    title: value.href,\n  };\n}\n\n/** The key a pick's link is looked up and remembered by. */\nfunction pickKey(pick: LinkPick): string | undefined {\n  return linkKey(\n    pick.kind === \"entry\"\n      ? { kind: \"entry\", collection: pick.collection, id: pick.id }\n      : { kind: \"address\", href: pick.href }\n  );\n}\n\n/** What the trigger is announced as: the link it holds, or what it does. */\nfunction triggerLabel(label: string, words: ChipWords | undefined): string {\n  // The placeholder's own words, so someone who says what they see\n  // reaches it; the search field it opens says it in full.\n  if (words === undefined) return `${label}: search or paste a URL`;\n  const detail = words.detail === undefined ? \"\" : `, ${words.detail}`;\n  return `${label}: ${words.title}${detail}. Change`;\n}\n\n/** What the trigger draws: the placeholder, or the chosen link's icon, title and address. */\nfunction TriggerContent({\n  words,\n}: {\n  words: ChipWords | undefined;\n}): React.JSX.Element {\n  if (words === undefined) {\n    return (\n      <>\n        <Link2 aria-hidden=\"true\" size={14} className=\"nx-link-pick__icon\" />\n        <span\n          className=\"nx-link-pick__placeholder\"\n          // Short enough for the control column; the search field it opens\n          // says it in full.\n          title=\"Search pages or paste a URL\"\n        >\n          Search or paste a URL\n        </span>\n      </>\n    );\n  }\n  return (\n    <>\n      {words.page ? (\n        <FileText aria-hidden=\"true\" size={14} className=\"nx-link-pick__icon\" />\n      ) : (\n        <AddressIcon kind={words.kind} />\n      )}\n      <span className=\"nx-link-pick__title\" title={words.title}>\n        {words.title}\n      </span>\n      {words.detail === undefined ? null : (\n        <span className=\"nx-link-pick__detail\" title={words.detail}>\n          {words.detail}\n        </span>\n      )}\n    </>\n  );\n}\n\n/**\n * What the chip says about the stored link: the last row chosen here, so it\n * names it at once rather than after a lookup of what was just picked, and\n * otherwise what a lookup of the stored link found.\n */\nfunction useChipWords(\n  find: FindLinkTargets | undefined,\n  value: LinkValue\n): {\n  words: ChipWords | undefined;\n  remember: (key: string | undefined, target: LinkTarget) => void;\n  retry: () => void;\n} {\n  const [picked, setPicked] = React.useState<{\n    key: string | undefined;\n    target: LinkTarget;\n  } | null>(null);\n  // Only a page or an entry has a key; a typed address is shown as itself.\n  const key = linkKey(value);\n  const pickedHere =\n    picked !== null && picked.key !== undefined && picked.key === key\n      ? picked.target\n      : undefined;\n  const { lookup, retry } = useStoredTarget(\n    pickedHere === undefined ? find : undefined,\n    value\n  );\n  return {\n    words: chipWords(\n      value,\n      pickedHere === undefined ? lookup : { kind: \"found\", target: pickedHere }\n    ),\n    remember: (at, target) => setPicked({ key: at, target }),\n    retry,\n  };\n}\n\ninterface LinkControlProps {\n  /** The trigger's id, which the row's label points at. */\n  readonly id: string;\n  /** What the row is called: the link prop's own label. */\n  readonly label: string;\n  readonly value: LinkValue;\n  /** Whether a page without an address can be linked as an entry reference. */\n  readonly entryLinks: boolean;\n  readonly disabled: boolean;\n  readonly find: FindLinkTargets | undefined;\n  readonly onPick: (pick: LinkPick) => void;\n  readonly onClear: () => void;\n  /**\n   * Whether there is a stored link to clear. A link that applies only as the\n   * block's default has nothing stored, so clearing it would change nothing.\n   */\n  readonly clearable: boolean;\n  /** The id of the words under the row that explain the link, if it has any. */\n  readonly describedBy?: string | undefined;\n}\n\n/** The link combobox: an empty trigger or the chosen link's chip, and the list. */\nfunction LinkControl({\n  id,\n  label,\n  value,\n  entryLinks,\n  disabled,\n  find,\n  onPick,\n  onClear,\n  clearable,\n  describedBy,\n}: LinkControlProps): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const [typed, setTyped] = React.useState(\"\");\n  const { words, remember, retry } = useChipWords(find, value);\n\n  const openWith = (next: boolean): void => {\n    // Opened on a typed address, the field starts from it, so a typo is\n    // fixed rather than typed again; on a page or an entry it starts empty.\n    // A lookup of the stored link that failed is tried again as it opens.\n    if (next) {\n      retry();\n      setTyped(\n        value.kind === \"address\" && words?.page !== true ? value.href : \"\"\n      );\n    }\n    setOpen(next);\n  };\n\n  const choose = (option: LinkOption): void => {\n    const pick = pickOf(option);\n    if (option.kind === \"target\") remember(pickKey(pick), option.target);\n    setOpen(false);\n    onPick(pick);\n  };\n\n  return (\n    <Popover open={open} onOpenChange={openWith} modal={false}>\n      <PopoverAnchor asChild>\n        <div\n          className=\"nx-link-pick\"\n          data-set={words === undefined ? undefined : \"\"}\n        >\n          <PopoverTrigger asChild>\n            <button\n              type=\"button\"\n              id={id}\n              className=\"nx-link-pick__trigger\"\n              disabled={disabled}\n              aria-haspopup=\"listbox\"\n              aria-expanded={open}\n              aria-label={triggerLabel(label, words)}\n              aria-describedby={describedBy}\n              // Coming back to a link whose lookup failed asks again, once.\n              onFocus={retry}\n              onKeyDown={event => {\n                // Down opens the list, as on any combobox.\n                if (event.key === \"ArrowDown\" && !open) {\n                  event.preventDefault();\n                  openWith(true);\n                }\n              }}\n            >\n              <TriggerContent words={words} />\n            </button>\n          </PopoverTrigger>\n          {words === undefined || !clearable ? null : (\n            <button\n              type=\"button\"\n              className=\"nx-link-pick__clear\"\n              disabled={disabled}\n              aria-label={`Remove ${label.toLowerCase()}`}\n              onClick={onClear}\n            >\n              <X aria-hidden=\"true\" size={14} />\n            </button>\n          )}\n        </div>\n      </PopoverAnchor>\n      {/* Aligned to the control's right edge: the list is wider than the\n          control column, and the inspector sits at the window's right edge. */}\n      <PopoverContent\n        align=\"end\"\n        sideOffset={4}\n        className=\"nx-link-pick__popover\"\n      >\n        <LinkList\n          label={label}\n          typed={typed}\n          onType={setTyped}\n          find={find}\n          entryLinks={entryLinks}\n          onChoose={choose}\n        />\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/** One collection's rows, under its heading. */\ninterface OptionGroup {\n  /** The collection's slug, which tells two collections apart. */\n  readonly key: string;\n  /** Its heading: the collection's name, which two collections may share. */\n  readonly name: string;\n  readonly options: LinkOption[];\n}\n\n/**\n * The pages and entries by collection, in the order the host listed them:\n * the site's own pages first.\n */\nfunction groupsOf(options: readonly LinkOption[]): OptionGroup[] {\n  const groups: OptionGroup[] = [];\n  for (const option of options) {\n    if (option.kind !== \"target\") continue;\n    const key = option.target.collection;\n    const group = groups.find(each => each.key === key);\n    if (group === undefined) {\n      groups.push({ key, name: option.target.group, options: [option] });\n    } else {\n      group.options.push(option);\n    }\n  }\n  return groups;\n}\n\n/** What the list says about the search, when it has something to say. */\nfunction listStatus(\n  find: FindLinkTargets | undefined,\n  targets: Targets,\n  typed: string,\n  listed: boolean\n): string | undefined {\n  if (find === undefined) return \"Type or paste an address.\";\n  if (targets.kind === \"loading\") return listed ? undefined : \"Searching…\";\n  if (targets.kind === \"failed\") {\n    return \"Pages couldn't be searched. Try again in a moment.\";\n  }\n  if (targets.kind !== \"found\" || targets.targets.length > 0) return undefined;\n  return typed.trim() === \"\"\n    ? \"No pages yet. Type or paste an address.\"\n    : \"No pages match.\";\n}\n\n/** Where an arrow key moves the active row, or `undefined` for any other key. */\nfunction stepFrom(key: string, at: number, last: number): number | undefined {\n  if (key === \"ArrowDown\") return Math.min(at + 1, last);\n  if (key === \"ArrowUp\") return Math.max(at - 1, 0);\n  return undefined;\n}\n\n/** A row's words: \"Use … as a URL\", or a page's title and its address or the reason it can't be used. */\nfunction OptionWords({ option }: { option: LinkOption }): React.JSX.Element {\n  if (option.kind === \"address\") {\n    return (\n      <>\n        <AddressIcon kind={linkKindOf(option.href) ?? \"web\"} />\n        <span className=\"nx-link-pick__option-title\">\n          Use &ldquo;{option.href}&rdquo; as a URL\n        </span>\n      </>\n    );\n  }\n  const detail = option.unusable ?? option.target.path;\n  return (\n    <>\n      <span className=\"nx-link-pick__option-title\" title={option.target.title}>\n        {option.target.title}\n      </span>\n      {detail === undefined ? null : (\n        <span className=\"nx-link-pick__option-detail\" title={detail}>\n          {detail}\n        </span>\n      )}\n    </>\n  );\n}\n\n/** One row of the open list, chosen by a click unless it cannot be used. */\nfunction OptionRow({\n  option,\n  id,\n  active,\n  pinned,\n  onHover,\n  onChoose,\n}: {\n  option: LinkOption;\n  id: string;\n  active: boolean;\n  /** Kept at the list's foot as it scrolls: the address after the pages. */\n  pinned: boolean;\n  onHover: (option: LinkOption) => void;\n  onChoose: (option: LinkOption) => void;\n}): React.JSX.Element {\n  const usable = option.kind === \"address\" || option.unusable === undefined;\n  return (\n    <li\n      id={id}\n      role=\"option\"\n      aria-selected={active}\n      aria-disabled={usable ? undefined : true}\n      className={\n        pinned\n          ? \"nx-link-pick__option nx-link-pick__option--pinned\"\n          : \"nx-link-pick__option\"\n      }\n      data-kind={option.kind}\n      onMouseMove={() => {\n        if (usable) onHover(option);\n      }}\n      // The search keeps focus while a row is clicked, so typing goes on.\n      onMouseDown={event => event.preventDefault()}\n      onClick={() => {\n        if (usable) onChoose(option);\n      }}\n    >\n      <OptionWords option={option} />\n      {/* Drawn on every row and shown on the active one only: it says\n          which row Enter takes. */}\n      <CornerDownLeft\n        aria-hidden=\"true\"\n        size={12}\n        className=\"nx-link-pick__enter\"\n      />\n    </li>\n  );\n}\n\n/** The open list: the search, the pages and entries by collection, and the address. */\nfunction LinkList({\n  label,\n  typed,\n  onType,\n  find,\n  entryLinks,\n  onChoose,\n}: {\n  label: string;\n  typed: string;\n  onType: (typed: string) => void;\n  find: FindLinkTargets | undefined;\n  entryLinks: boolean;\n  onChoose: (option: LinkOption) => void;\n}): React.JSX.Element {\n  const listId = React.useId();\n  const targets = useTargets(find, typed, true);\n  const options = optionsFor(typed, targets, entryLinks);\n  const usable = options.filter(\n    option => option.kind === \"address\" || option.unusable === undefined\n  );\n  const [activeKey, setActiveKey] = React.useState<string | undefined>();\n  // The active row is kept by key, so a new answer keeps it where it still\n  // is and falls back to the first row that can be chosen where it is not.\n  const active = usable.find(option => option.key === activeKey) ?? usable[0];\n  const optionId = (option: LinkOption): string =>\n    `${listId}-${option.key.replace(/[^a-z0-9-]/gi, \"_\")}`;\n\n  React.useEffect(() => {\n    if (active === undefined) return;\n    document.getElementById(optionId(active))?.scrollIntoView({\n      block: \"nearest\",\n    });\n  });\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>): void => {\n    const at = active === undefined ? -1 : usable.indexOf(active);\n    const next = stepFrom(event.key, at, usable.length - 1);\n    if (next !== undefined) {\n      event.preventDefault();\n      setActiveKey(usable[next]?.key);\n    } else if (event.key === \"Enter\") {\n      event.preventDefault();\n      if (active !== undefined) onChoose(active);\n    }\n  };\n\n  const groups = groupsOf(options);\n  const address = options.find(option => option.kind === \"address\");\n  const addressFirst = address !== undefined && options[0] === address;\n  const status = listStatus(find, targets, typed, groups.length > 0);\n  const row = (option: LinkOption, pinned = false): React.JSX.Element => (\n    <OptionRow\n      key={option.key}\n      option={option}\n      id={optionId(option)}\n      active={option === active}\n      pinned={pinned}\n      onHover={hovered => setActiveKey(hovered.key)}\n      onChoose={onChoose}\n    />\n  );\n\n  return (\n    <div className=\"nx-link-pick__body\">\n      <div className=\"nx-vars__search nx-link-pick__search\">\n        <Search aria-hidden=\"true\" size={16} />\n        <Input\n          type=\"text\"\n          role=\"combobox\"\n          aria-label={`Search pages or paste a URL for ${label.toLowerCase()}`}\n          aria-controls={listId}\n          aria-expanded=\"true\"\n          aria-autocomplete=\"list\"\n          aria-activedescendant={\n            active === undefined ? undefined : optionId(active)\n          }\n          placeholder={\n            find === undefined ? \"Paste a URL\" : \"Search pages or paste a URL\"\n          }\n          autoComplete=\"off\"\n          spellCheck={false}\n          value={typed}\n          onChange={event => {\n            onType(event.target.value);\n            setActiveKey(undefined);\n          }}\n          onKeyDown={onKeyDown}\n        />\n      </div>\n      <ul\n        id={listId}\n        role=\"listbox\"\n        aria-label={`Where ${label.toLowerCase()} goes`}\n        className=\"nx-link-pick__list\"\n      >\n        {addressFirst ? row(address) : null}\n        {groups.map(group => (\n          <OptionGroupList\n            key={group.key}\n            id={`${listId}-group-${group.key.replace(/[^a-z0-9-]/gi, \"_\")}`}\n            group={group}\n            row={row}\n          />\n        ))}\n        {status === undefined ? null : (\n          <li\n            className=\"nx-vars__note nx-link-pick__status\"\n            role=\"presentation\"\n          >\n            <span role=\"status\">{status}</span>\n          </li>\n        )}\n        {/* After the pages, the address stays pinned to the list's foot,\n            ruled off from them, so a long list never scrolls it away. */}\n        {!addressFirst && address !== undefined\n          ? row(address, groups.length > 0)\n          : null}\n      </ul>\n    </div>\n  );\n}\n\n/** One collection's rows under its heading, as a named group of the listbox. */\nfunction OptionGroupList({\n  id,\n  group,\n  row,\n}: {\n  id: string;\n  group: OptionGroup;\n  row: (option: LinkOption) => React.JSX.Element;\n}): React.JSX.Element {\n  return (\n    <li role=\"presentation\">\n      <span id={id} className=\"nx-vars__group-name nx-link-pick__heading\">\n        {group.name}\n      </span>\n      <ul role=\"group\" aria-labelledby={id} className=\"nx-link-pick__group\">\n        {group.options.map(option => row(option))}\n      </ul>\n    </li>\n  );\n}\n\n/**\n * The link \"Link options\" opens: the `rel` checkboxes, and any other stored\n * token as a chip that can be removed. Opened on its own when a token is\n * already stored, so a link marked sponsored says so without a click.\n */\nfunction LinkOptions({\n  rel,\n  disabled,\n  onRel,\n}: {\n  rel: unknown;\n  disabled: boolean;\n  onRel: (next: string | undefined) => void;\n}): React.JSX.Element {\n  const bodyId = React.useId();\n  const [open, setOpen] = React.useState(() => relTokens(rel).length > 0);\n  const others = relOthers(rel);\n  const set = REL_FLAGS.filter(flag => relHas(rel, flag.token));\n  // What is set, said beside the closed disclosure.\n  const summary = [...set.map(flag => flag.label), ...others].join(\", \");\n  return (\n    <div className=\"nx-link-options\">\n      <button\n        type=\"button\"\n        className=\"nx-link-options__toggle\"\n        aria-expanded={open}\n        aria-controls={bodyId}\n        onClick={() => setOpen(was => !was)}\n      >\n        <ChevronRight\n          aria-hidden=\"true\"\n          size={14}\n          className=\"nx-link-options__chevron\"\n        />\n        <span>Link options</span>\n        {open || summary === \"\" ? null : (\n          <span className=\"nx-link-options__summary\">{summary}</span>\n        )}\n      </button>\n      {open ? (\n        <div\n          id={bodyId}\n          role=\"group\"\n          aria-label=\"Link options\"\n          className=\"nx-link-options__body\"\n        >\n          <div className=\"nx-link-options__flags\">\n            {REL_FLAGS.map(flag => (\n              <RelFlag\n                key={flag.token}\n                label={flag.label}\n                checked={relHas(rel, flag.token)}\n                disabled={disabled}\n                onChange={on => onRel(relWith(rel, flag.token, on))}\n              />\n            ))}\n          </div>\n          {others.length === 0 ? null : (\n            <ul\n              className=\"nx-link-options__others\"\n              aria-label=\"Other link relationships\"\n            >\n              {others.map(token => (\n                <li key={token} className=\"nx-link-options__token\">\n                  <span>{token}</span>\n                  <button\n                    type=\"button\"\n                    disabled={disabled}\n                    aria-label={`Remove ${token}`}\n                    onClick={() => onRel(relWith(rel, token, false))}\n                  >\n                    <X aria-hidden=\"true\" size={12} />\n                  </button>\n                </li>\n              ))}\n            </ul>\n          )}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\n/** One `rel` flag: a checkbox and the word that names it. */\nfunction RelFlag({\n  label,\n  checked,\n  disabled,\n  onChange,\n}: {\n  label: string;\n  checked: boolean;\n  disabled: boolean;\n  onChange: (on: boolean) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <div className=\"nx-link-options__flag\">\n      <Checkbox\n        id={id}\n        checked={checked}\n        disabled={disabled}\n        onCheckedChange={next => onChange(next === true)}\n      />\n      <Label htmlFor={id}>{label}</Label>\n    </div>\n  );\n}\n\n/** A field drawn as it is, where the inspector offers no binding controls. */\nconst asDrawn: BindableWrapper = (_name, field) => field;\n\nexport interface LinkGroupFieldProps {\n  readonly group: LinkGroup;\n  /** The block's props, as the inspector reads them. */\n  readonly props: readonly EditableProp[];\n  /** Whether one prop may be set where the block sits. */\n  readonly writable: (name: string) => boolean;\n  /** The id of the lock reason a held control points to. */\n  readonly reasonId: string;\n  readonly services: ContentServices | undefined;\n  /** Write several props as one edit. */\n  readonly onCommitMany: (changes: LinkChanges) => BlockDocument | null | void;\n  /** The link's binding controls, from the inspector; absent, none are drawn. */\n  readonly bindable?: BindableWrapper | undefined;\n  /** The document the block is in, whose bindings say whether the link is bound. */\n  readonly document?: BlockDocument | undefined;\n  /** The block's id. */\n  readonly nodeId?: string | undefined;\n}\n\n/**\n * Whether the link is bound: its address, or its entry. A bound link goes\n * where its field says, so it is a link to qualify even with no address of\n * its own stored.\n */\nexport function isLinkBound(\n  group: LinkGroup,\n  bound: Readonly<Record<string, unknown>> | undefined\n): boolean {\n  if (bound?.[group.link] !== undefined) return true;\n  return group.entry !== undefined && bound?.[group.entry.id] !== undefined;\n}\n\n/** The block's bindings, where the group knows its document and block. */\nfunction bindingsOfBlock(\n  document: BlockDocument | undefined,\n  nodeId: string | undefined\n): Readonly<Record<string, unknown>> | undefined {\n  return document === undefined || nodeId === undefined\n    ? undefined\n    : findNode(document.nodes, nodeId)?.bindings;\n}\n\n/**\n * What binding the link's address says: a button follows a complete entry\n * reference before its address, so binding the address empties the\n * reference in the same edit, or the button would keep going to the entry;\n * and where the block has an entry reference, the picker also offers the\n * entries a relation names, whose pick binds the reference.\n */\nfunction bindOptions(\n  group: LinkGroup,\n  destination: readonly string[],\n  writable: (name: string) => boolean,\n  bound: Readonly<Record<string, unknown>> | undefined\n): BindableOptions {\n  const entry = group.entry;\n  // A related entry's pick removes the address's binding, so where that\n  // binding is held it is not offered either.\n  const addressHeld =\n    bound?.[group.link] !== undefined && !writable(group.link);\n  return {\n    clearsOnBind: destination.filter(name => name !== group.link),\n    ...(entry === undefined\n      ? {}\n      : {\n          entryLink: {\n            link: group.link,\n            ...entry,\n            // A related entry's pick writes both halves, so where either is\n            // held (an area that keeps the block's design) none is offered.\n            writable:\n              writable(entry.collection) && writable(entry.id) && !addressHeld,\n          },\n        }),\n  };\n}\n\n/** The link's hint under it, read as its description, where it has one. */\nfunction LinkHint({\n  id,\n  hint,\n}: {\n  id: string | undefined;\n  hint: string | undefined;\n}): React.JSX.Element | null {\n  if (id === undefined || hint === undefined) return null;\n  return (\n    <p className=\"nx-inspector__note\" id={id}>\n      {hint}\n    </p>\n  );\n}\n\n/** The words a block gives its link to explain it, as any prop's hint. */\nfunction linkHintOf(\n  linkProp: Pick<EditableProp, \"schema\"> | undefined\n): string | undefined {\n  const hint = linkProp?.schema.hint;\n  return typeof hint === \"string\" && hint !== \"\" ? hint : undefined;\n}\n\n/**\n * A block's link group, drawn where its link prop sits: the link, and under\n * a set link its new-tab switch and its Link options. The link's address\n * offers binding through the inspector's wrapper; a bound link counts as set,\n * so how it opens is still offered under its chip.\n */\nexport function LinkGroupField({\n  group,\n  props,\n  writable,\n  reasonId,\n  services,\n  onCommitMany,\n  bindable,\n  document,\n  nodeId,\n}: LinkGroupFieldProps): React.JSX.Element {\n  const id = React.useId();\n  const tabId = React.useId();\n  const ownHintId = React.useId();\n  // Each prop as it applies: what is stored, else the block's default, so a\n  // block that declares a default link reads as linked, and its target and\n  // rel show what applies, as every other control shows a default.\n  const values = Object.fromEntries(\n    props.map(prop => [prop.name, prop.value ?? prop.defaultValue])\n  );\n  const linkProp = props.find(prop => prop.name === group.link);\n  const label =\n    linkProp === undefined ? \"Link\" : propLabel(linkProp.name, linkProp.schema);\n  const hint = linkHintOf(linkProp);\n  const hintId = hint === undefined ? undefined : ownHintId;\n  const value = linkValueOf(group, values);\n  const bound = bindingsOfBlock(document, nodeId);\n  const linkBound = isLinkBound(group, bound);\n  const linked = value.kind !== \"none\" || linkBound;\n  const held = (name: string | undefined): string | undefined =>\n    name === undefined || writable(name) ? undefined : reasonId;\n  // The destination is the link and, on a button, the entry reference that\n  // replaces it: a pick writes them together, so it may change only when all\n  // of them may. Otherwise the link is drawn held, pointing at the reason.\n  const destination = [\n    group.link,\n    ...(group.entry === undefined\n      ? []\n      : [group.entry.collection, group.entry.id]),\n  ];\n  const destinationWritable = destination.every(writable);\n  // Something stored to clear: a link that is only the block's default has\n  // none, and is changed by picking another rather than removed.\n  const clearable = props.some(\n    prop => destination.includes(prop.name) && prop.value != null\n  );\n  return (\n    <div className=\"nx-link-group\" data-link-group={group.link}>\n      {/* The address's bind button sits on its row; bound, the chip stands\n          for the address and the entry pick alike. */}\n      {(bindable ?? asDrawn)(\n        group.link,\n        <HeldByLock reasonId={destinationWritable ? undefined : reasonId}>\n          <div className=\"nx-inspector__field\" data-content-control=\"link\">\n            <Label htmlFor={id}>{label}</Label>\n            <LinkControl\n              id={id}\n              label={label}\n              value={value}\n              entryLinks={group.entry !== undefined}\n              disabled={!destinationWritable}\n              find={services?.findLinkTargets}\n              clearable={clearable}\n              describedBy={hintId}\n              onPick={pick => {\n                const changes = pickChanges(group, pick);\n                if (changes !== undefined && destinationWritable) {\n                  onCommitMany(changes);\n                }\n              }}\n              // Clears the target and the rel with the link: see `clearChanges`.\n              // Where an area holds the target or the rel, the link still\n              // clears and they stay as the area keeps them; the destination\n              // itself is never cleared in part.\n              onClear={() => {\n                if (!destinationWritable) return;\n                onCommitMany(\n                  Object.fromEntries(\n                    Object.entries(clearChanges(group)).filter(\n                      ([name]) => destination.includes(name) || writable(name)\n                    )\n                  )\n                );\n              }}\n            />\n            <LinkHint id={hintId} hint={hint} />\n          </div>\n        </HeldByLock>,\n        bindOptions(group, destination, writable, bound)\n      )}\n      {!linked || group.target === undefined ? null : (\n        <HeldByLock reasonId={held(group.target)}>\n          <div className=\"nx-inspector__field\" data-content-control=\"checkbox\">\n            <Label htmlFor={tabId}>Open in a new tab</Label>\n            <Switch\n              id={tabId}\n              disabled={!writable(group.target)}\n              checked={values[group.target] === \"_blank\"}\n              // Off clears the target rather than storing `_self`: the same\n              // tab is what a link does with none. Unless the block's own\n              // default is a new tab, which a cleared target falls back to:\n              // then off is stored as `_self`, or it would not stay off.\n              onCheckedChange={on => {\n                const target = group.target;\n                if (target === undefined) return;\n                const fallsBackToNewTab =\n                  props.find(prop => prop.name === target)?.defaultValue ===\n                  \"_blank\";\n                const off = fallsBackToNewTab ? \"_self\" : undefined;\n                onCommitMany({ [target]: on ? \"_blank\" : off });\n              }}\n            />\n          </div>\n        </HeldByLock>\n      )}\n      {!linked || group.rel === undefined ? null : (\n        <HeldByLock reasonId={held(group.rel)}>\n          <LinkOptions\n            rel={values[group.rel]}\n            disabled={!writable(group.rel)}\n            onRel={next => {\n              if (group.rel === undefined) return;\n              onCommitMany({ [group.rel]: next });\n            }}\n          />\n        </HeldByLock>\n      )}\n    </div>\n  );\n}\n","/**\n * A label with its indefinite article, for a sentence that names a block or a\n * container. Read off the label's first letter, which is right for the block\n * names these sentences carry.\n *\n * @module with-article\n */\n\n/** \"an Accordion\", \"a Card\"; a namespace's \"any acme block\" as it is. */\nexport function withArticle(label: string): string {\n  if (label.startsWith(\"any \")) return label;\n  return `${/^[aeiou]/i.test(label) ? \"an\" : \"a\"} ${label}`;\n}\n","\"use client\";\n\n/**\n * The Format row of a bound prop: how a date or a number reaches a text prop.\n *\n * A date or a number fills a text prop only through a format (the engine's\n * `fillsUnformatted`), so the row is drawn for exactly that pairing and offers\n * plain presets rather than `Intl`'s whole option list. Which presets are\n * offered is the engine's answer, not a list kept here: each is asked of\n * `checkFormat` against the prop and the bound field, so a field holding a\n * calendar date is never offered a time of day, a month never a day, and a\n * time of day never a date. A stored format is judged by the same check, so\n * one written through the API that a visitor's page would refuse is shown as\n * refused, in the words the engine gives.\n *\n * @module binding-format-field\n */\nimport {\n  bindingFormatEnv,\n  bindingKindOf,\n  checkFormat,\n  createBindingFormatter,\n  type BindablePropKind,\n  type BindingFieldShape,\n  type BindingFormat,\n  type BindingRunInput,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\n/** One choice in the Format menu: its words, and the format it writes. */\ninterface FormatPreset {\n  readonly key: string;\n  readonly label: string;\n  readonly format: BindingFormat;\n}\n\n/** The menu's key for a currency, whose code is typed beside it. */\nconst CURRENCY = \"currency\";\n\n/** The menu's key for a stored format no preset names. */\nconst STORED = \"stored\";\n\n/** What the menu shows for it. */\nconst SET_ELSEWHERE = \"Set elsewhere\";\n\n/**\n * A code `checkFormat` knows on every runtime, used only to ask whether a\n * currency format fits the field at all; the author types the real one.\n */\nconst PROBE_CURRENCY = \"EUR\";\n\n/**\n * The presets, in the order the menu lists them. Dates: `Intl`'s own styles\n * and the parts a month is shown with. Numbers: plain, whole, percent and\n * compact, and a currency, whose code is the author's.\n */\nconst PRESETS: readonly FormatPreset[] = [\n  {\n    key: \"date-long\",\n    label: \"Long date\",\n    format: { type: \"date\", options: { dateStyle: \"long\" } },\n  },\n  {\n    key: \"date-short\",\n    label: \"Short date\",\n    format: { type: \"date\", options: { dateStyle: \"short\" } },\n  },\n  {\n    key: \"date-full\",\n    label: \"Weekday and date\",\n    format: { type: \"date\", options: { dateStyle: \"full\" } },\n  },\n  {\n    key: \"date-time\",\n    label: \"Date and time\",\n    format: {\n      type: \"date\",\n      options: { dateStyle: \"medium\", timeStyle: \"short\" },\n    },\n  },\n  {\n    key: \"time\",\n    label: \"Time\",\n    format: { type: \"date\", options: { timeStyle: \"short\" } },\n  },\n  {\n    key: \"month-year\",\n    label: \"Month and year\",\n    format: { type: \"date\", options: { year: \"numeric\", month: \"long\" } },\n  },\n  { key: \"number\", label: \"Number\", format: { type: \"number\" } },\n  {\n    key: \"number-whole\",\n    label: \"Whole number\",\n    format: { type: \"number\", options: { maximumFractionDigits: 0 } },\n  },\n  {\n    key: \"percent\",\n    label: \"Percent\",\n    format: { type: \"number\", options: { style: \"percent\" } },\n  },\n  {\n    key: \"compact\",\n    label: \"Compact (1.2K)\",\n    format: { type: \"number\", options: { notation: \"compact\" } },\n  },\n  {\n    key: CURRENCY,\n    label: \"Currency\",\n    format: { type: \"currency\", currency: PROBE_CURRENCY },\n  },\n];\n\n/** Whether a value is a plain object, as a stored format and its options are. */\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Whether two option sets hold the same keys with the same values. */\nfunction sameOptions(a: unknown, b: unknown): boolean {\n  const left = isRecord(a) ? a : {};\n  const right = isRecord(b) ? b : {};\n  const keys = Object.keys(left);\n  return (\n    keys.length === Object.keys(right).length &&\n    keys.every(key => Object.is(left[key], right[key]))\n  );\n}\n\n/**\n * The preset a stored format is, or `undefined` for one no preset names. A\n * currency is the currency preset whatever its code, when it sets no options\n * of its own: the code is shown and edited beside the menu.\n */\nfunction presetKeyOf(stored: unknown): string | undefined {\n  if (!isRecord(stored)) return undefined;\n  if (stored.type === CURRENCY) {\n    return sameOptions(stored.options, undefined) ? CURRENCY : undefined;\n  }\n  return PRESETS.find(\n    preset =>\n      preset.key !== CURRENCY &&\n      preset.format.type === stored.type &&\n      sameOptions(preset.format.options, stored.options)\n  )?.key;\n}\n\n/**\n * The presets the engine accepts for this prop and field: a format turns a\n * value into text, so a prop that is not text is offered none, and a field\n * that is neither a date nor a number none either.\n */\nfunction offeredPresets(\n  kind: BindablePropKind | undefined,\n  field: BindingFieldShape\n): readonly FormatPreset[] {\n  return PRESETS.filter(preset => {\n    const check = checkFormat(preset.format, kind, field);\n    return check.ok && check.format !== null && check.unsupported === undefined;\n  });\n}\n\n/**\n * Why a stored format can't be used, in the engine's words, or `undefined`\n * when it can. A format this release does not apply leaves a date or a\n * number unformatted, which a text prop can't hold, so it is refused here too.\n */\nfunction refusalOf(\n  stored: unknown,\n  kind: BindablePropKind | undefined,\n  field: BindingFieldShape\n): string | undefined {\n  if (stored === undefined) return undefined;\n  const check = checkFormat(stored, kind, field);\n  if (!check.ok) return check.message;\n  return check.unsupported === undefined\n    ? undefined\n    : `The “${check.unsupported}” format isn't applied yet, so visitors see the fallback.`;\n}\n\n/** What the bound field holds, as the note under an unset Format says it. */\nfunction heldAs(field: BindingFieldShape): string {\n  return bindingKindOf(field) === \"date\" ? \"A date\" : \"A number\";\n}\n\n/** The preset a bind starts from, for each kind of value that needs one. */\nconst BIND_DEFAULTS: Readonly<Record<string, string>> = {\n  date: \"date-long\",\n  number: \"number\",\n};\n\n/**\n * The format the inspector writes when it binds a text prop to a date or a\n * number, which reaches text only through one: Long date, or Number. Taken\n * from the presets the engine accepts for this field, so a field holding a\n * month, or a time of day, starts from the first it can show instead.\n * `undefined` for a pairing that needs no format, or can take none.\n *\n * The inspector's starting point, not the engine's: a bind written through\n * the API with no format is still refused.\n */\nexport function defaultFormatFor(\n  kind: BindablePropKind | undefined,\n  field: BindingFieldShape\n): { readonly label: string; readonly format: BindingFormat } | undefined {\n  const offered = offeredPresets(kind, field);\n  const wanted = BIND_DEFAULTS[bindingKindOf(field) ?? \"\"];\n  const preset =\n    offered.find(each => each.key === wanted) ??\n    offered.find(each => each.key !== CURRENCY);\n  return preset === undefined\n    ? undefined\n    : { label: preset.label, format: preset.format };\n}\n\n/**\n * A stored preview's value as the formatter reads it: a number's text as a\n * number, a date's as the text it is.\n */\nfunction previewValue(preview: string, field: BindingFieldShape): unknown {\n  if (bindingKindOf(field) !== \"number\") return preview;\n  const number = Number(preview);\n  return preview.trim() === \"\" || !Number.isFinite(number) ? preview : number;\n}\n\n/**\n * A field's preview as a pick would show it: formatted with the format the\n * pick writes, by the engine's formatter, so a date reads \"November 8, 2026\"\n * rather than its stored text. The preview as it is where there is no such\n * format, or where it cannot be formatted, so nothing is lost.\n *\n * Formatted in `formatIn`, the page's language and the site's time zone,\n * resolved by the render's own rule (`bindingFormatEnv`), so the preview\n * reads as the published page shows the value, never in the browser's\n * language or zone. Absent, it is a page with neither: English and UTC.\n */\nexport function previewWithFormat(\n  preview: string,\n  format: BindingFormat,\n  kind: BindablePropKind | undefined,\n  field: BindingFieldShape,\n  formatIn: Pick<BindingRunInput, \"locale\" | \"timeZone\"> | undefined\n): string {\n  const check = checkFormat(format, kind, field);\n  if (!check.ok || check.format === null) return preview;\n  const formatted = createBindingFormatter(\n    bindingFormatEnv(formatIn ?? {}).env\n  ).format(previewValue(preview, field), check.format, field);\n  return formatted.ok ? formatted.value.text : preview;\n}\n\n/**\n * Whether a bound prop gets a Format row: a text prop bound to a date or a\n * number, the pairing that shows nothing without one.\n */\nexport function offersFormat(\n  kind: BindablePropKind | undefined,\n  field: BindingFieldShape | undefined\n): field is BindingFieldShape {\n  return field !== undefined && offeredPresets(kind, field).length > 0;\n}\n\n/** What the Format row is given. */\nexport interface BindingFormatFieldProps {\n  /** The binding's stored format, as the document holds it. */\n  readonly stored: unknown;\n  /** The prop's kind, which a format has to turn the value into. */\n  readonly kind: BindablePropKind | undefined;\n  /** The field the binding reads. */\n  readonly field: BindingFieldShape;\n  readonly disabled: boolean;\n  /** The id of the prop's name, which the row is about. */\n  readonly describedBy: string;\n  /** Write a format to the binding. */\n  readonly onFormat: (format: BindingFormat) => void;\n}\n\n/** The words the menu shows for `value`, or `undefined` for none. */\nfunction shownLabel(\n  value: string,\n  presets: readonly FormatPreset[]\n): string | undefined {\n  if (value === STORED) return SET_ELSEWHERE;\n  return presets.find(preset => preset.key === value)?.label;\n}\n\n/** The currency code a stored currency format names, or `\"\"`. */\nfunction storedCurrencyCode(stored: unknown): string {\n  return isRecord(stored) &&\n    stored.type === CURRENCY &&\n    typeof stored.currency === \"string\"\n    ? stored.currency\n    : \"\";\n}\n\n/**\n * The menu's value: a currency waiting for its code, the stored preset, a\n * stored format no listed preset names, or none.\n */\nfunction menuValue(\n  choosingCurrency: boolean,\n  storedKey: string | undefined,\n  stored: unknown\n): string {\n  if (choosingCurrency) return CURRENCY;\n  if (storedKey !== undefined) return storedKey;\n  return stored === undefined ? \"\" : STORED;\n}\n\n/** A currency's three-letter code, committed when it is left or on Enter. */\nfunction CurrencyCode({\n  storedCode,\n  disabled,\n  focusOnMount,\n  errorId,\n  refused,\n  onCommit,\n}: {\n  storedCode: string;\n  disabled: boolean;\n  /** Take focus when drawn, for a currency just picked from the menu. */\n  focusOnMount: boolean;\n  errorId: string;\n  refused: boolean;\n  onCommit: (typed: string) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  const field = React.useRef<HTMLInputElement>(null);\n  React.useEffect(() => {\n    if (focusOnMount) field.current?.focus();\n  }, [focusOnMount]);\n  return (\n    <>\n      <label className=\"nx-binding__fallback-label\" htmlFor={id}>\n        Code\n      </label>\n      <Input\n        ref={field}\n        id={id}\n        key={storedCode}\n        defaultValue={storedCode}\n        placeholder={PROBE_CURRENCY}\n        maxLength={3}\n        autoCapitalize=\"characters\"\n        spellCheck={false}\n        disabled={disabled}\n        aria-invalid={refused ? true : undefined}\n        aria-describedby={refused ? errorId : undefined}\n        onBlur={event => onCommit(event.currentTarget.value)}\n        onKeyDown={event => {\n          if (event.key !== \"Enter\") return;\n          event.preventDefault();\n          onCommit(event.currentTarget.value);\n        }}\n      />\n    </>\n  );\n}\n\n/** A bound date's or number's Format: a preset menu, and a currency's code. */\nexport function BindingFormatField({\n  stored,\n  kind,\n  field,\n  disabled,\n  describedBy,\n  onFormat,\n}: BindingFormatFieldProps): React.JSX.Element {\n  const id = React.useId();\n  const noteId = React.useId();\n  const errorId = `${id}-error`;\n  const presets = offeredPresets(kind, field);\n  // A stored preset this field can't take (a time on a calendar date) is\n  // shown as set elsewhere, beside the refusal, as the menu doesn't list it.\n  const named = presetKeyOf(stored);\n  const storedKey = presets.some(preset => preset.key === named)\n    ? named\n    : undefined;\n  const refusal = refusalOf(stored, kind, field);\n  // A currency picked from the menu waits for its code before anything is\n  // written: a currency format without one is refused.\n  const [choosingCurrency, setChoosingCurrency] = React.useState(false);\n  const [codeRefusal, setCodeRefusal] = React.useState<string | undefined>();\n  // Set by the pick that draws the Code field, read as the menu closes. A ref\n  // because the menu's last render predates the pick.\n  const codeTakesFocus = React.useRef(false);\n  const value = menuValue(choosingCurrency, storedKey, stored);\n  const storedCode = storedCurrencyCode(stored);\n  // A code is judged by the engine whatever it is, an empty one included:\n  // refused, nothing is written and the reason is said. A currency only\n  // picked, never stored, is let go when its code is left empty, so the menu\n  // shows again what the binding holds rather than a currency it doesn't.\n  const commitCode = (typed: string): void => {\n    const next = typed.trim().toUpperCase();\n    if (next !== \"\" && next === storedCode) {\n      setCodeRefusal(undefined);\n      return;\n    }\n    const format: BindingFormat = { type: \"currency\", currency: next };\n    const check = checkFormat(format, kind, field);\n    if (!check.ok) {\n      setCodeRefusal(check.message);\n      if (next === \"\" && storedKey !== CURRENCY) setChoosingCurrency(false);\n      return;\n    }\n    setCodeRefusal(undefined);\n    setChoosingCurrency(false);\n    onFormat(format);\n  };\n  const choose = (next: string): void => {\n    setCodeRefusal(undefined);\n    if (next === CURRENCY) {\n      codeTakesFocus.current = storedKey !== CURRENCY;\n      setChoosingCurrency(storedKey !== CURRENCY);\n      return;\n    }\n    const preset = presets.find(each => each.key === next);\n    if (preset === undefined) return;\n    setChoosingCurrency(false);\n    onFormat(preset.format);\n  };\n  const message = codeRefusal ?? refusal;\n  // Without a format the value shows nothing, so the row says so rather than\n  // leaving the canvas's fallback unexplained.\n  const noted = message === undefined && stored === undefined;\n  const explainedBy = message !== undefined ? errorId : noted ? noteId : \"\";\n  return (\n    <div className=\"nx-binding__fallback nx-binding__format\">\n      <label className=\"nx-binding__fallback-label\" htmlFor={id}>\n        Format\n      </label>\n      <Select value={value} disabled={disabled} onValueChange={choose}>\n        <SelectTrigger\n          id={id}\n          // The shown value in full, as other cut-off menu values have it.\n          title={shownLabel(value, presets)}\n          aria-invalid={refusal === undefined ? undefined : true}\n          aria-describedby={`${describedBy} ${explainedBy}`.trim()}\n        >\n          <SelectValue placeholder=\"Choose a format\" />\n        </SelectTrigger>\n        <SelectContent\n          // A closing menu hands focus back to its trigger, a moment after\n          // the Code field has taken it. Left to, the field would blur empty\n          // and let the pick go before a code could be typed.\n          onCloseAutoFocus={event => {\n            if (!codeTakesFocus.current) return;\n            codeTakesFocus.current = false;\n            event.preventDefault();\n          }}\n        >\n          {presets.map(preset => (\n            <SelectItem key={preset.key} value={preset.key}>\n              {preset.label}\n            </SelectItem>\n          ))}\n          {value === STORED ? (\n            // Shown, never offered: a format written elsewhere with options\n            // no preset names, kept until the author picks another.\n            <SelectItem value={STORED} disabled>\n              {SET_ELSEWHERE}\n            </SelectItem>\n          ) : null}\n        </SelectContent>\n      </Select>\n      {value === CURRENCY ? (\n        <CurrencyCode\n          storedCode={storedCode}\n          disabled={disabled}\n          focusOnMount={choosingCurrency}\n          errorId={errorId}\n          refused={codeRefusal !== undefined}\n          onCommit={commitCode}\n        />\n      ) : null}\n      <FormatMessage\n        message={message}\n        noted={noted}\n        field={field}\n        errorId={errorId}\n        noteId={noteId}\n      />\n    </div>\n  );\n}\n\n/** Under the row: why a format is refused, or what an unset one means. */\nfunction FormatMessage({\n  message,\n  noted,\n  field,\n  errorId,\n  noteId,\n}: {\n  message: string | undefined;\n  noted: boolean;\n  field: BindingFieldShape;\n  errorId: string;\n  noteId: string;\n}): React.JSX.Element | null {\n  if (message !== undefined) {\n    return (\n      <p className=\"nx-inspector__error\" id={errorId} role=\"alert\">\n        {message}\n      </p>\n    );\n  }\n  if (!noted) return null;\n  return (\n    <p className=\"nx-inspector__note\" id={noteId}>\n      {heldAs(field)} shows as text only through a format; until one is chosen,\n      visitors see the fallback.\n    </p>\n  );\n}\n","/**\n * The ops that bind a block's prop to a field and unbind it, for the\n * inspector's binding controls and the page actions API alike, so both write\n * a binding the one way.\n *\n * Neither decides whether the binding fits: the write is judged as any save\n * is, against the schema of what it reads. An unbind writes what the caller\n * resolved to keep (on the server, as a visitor sees it): the prop's value,\n * or for an image a visitor saw by its address, that address in the block's\n * declared address prop, the media prop then emptied.\n *\n * @module binding-ops\n */\nimport {\n  findNode,\n  isPlainRecord,\n  type Binding,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\n\n/** A node's bindings, as a fresh record; none when it has none. */\nfunction bindingsOf(node: {\n  readonly bindings?: Readonly<Record<string, Binding>>;\n}): Record<string, Binding> {\n  return node.bindings === undefined ? {} : { ...node.bindings };\n}\n\n/**\n * The op binding `prop` of block `id` to `binding`, replacing a binding the\n * prop already had; `null` when the document holds no such block.\n *\n * `clear` names props emptied in the same op, for a prop another prop would\n * win over once bound: a button's entry reference is followed before its\n * address, so binding the address alone would leave the button going to the\n * entry. Only props the block holds are named in the patch, so a bind with\n * nothing to clear writes the bindings alone.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport function bindOp(\n  document: BlockDocument,\n  id: string,\n  prop: string,\n  binding: Binding,\n  clear: readonly string[] = [],\n  more: {\n    /**\n     * Props set in the same edit: what the bound value needs beside it,\n     * such as the collection of the entry a link's bound id names.\n     */\n    readonly set?: Readonly<Record<string, unknown>>;\n    /**\n     * Other props' bindings removed in the same edit: one the block would\n     * follow before this one, such as a link's address bound before the\n     * entry it now points at.\n     */\n    readonly unbind?: readonly string[];\n  } = {}\n): BuilderOp | null {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return null;\n  const kept = Object.entries(bindingsOf(node)).filter(\n    ([name]) => name === prop || !(more.unbind ?? []).includes(name)\n  );\n  const bindings = { ...Object.fromEntries(kept), [prop]: binding };\n  const props: Record<string, unknown> = isPlainRecord(node.props)\n    ? { ...node.props }\n    : {};\n  const held = clear.filter(name => Object.hasOwn(props, name));\n  const setting = Object.entries(more.set ?? {});\n  if (held.length === 0 && setting.length === 0) {\n    return { kind: \"update\", id, patch: { bindings } };\n  }\n  for (const name of held) delete props[name];\n  for (const [name, value] of setting) {\n    // Defined rather than assigned, so a prop's name can't reach the\n    // prototype.\n    Object.defineProperty(props, name, {\n      value,\n      enumerable: true,\n      writable: true,\n      configurable: true,\n    });\n  }\n  return { kind: \"update\", id, patch: { bindings, props } };\n}\n\n/**\n * What an unbind keeps in the block's props: values to set, and props to\n * empty. For an image a visitor saw by its address, the address is set on\n * the declared address prop and the media prop emptied.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport interface KeptProps {\n  readonly set: Readonly<Record<string, unknown>>;\n  readonly empty?: readonly string[];\n}\n\n/**\n * The op unbinding `prop` of block `id`, keeping `kept` in its props; `null`\n * when the document holds no such block. A block left with no binding stores\n * none.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport function unbindOp(\n  document: BlockDocument,\n  id: string,\n  prop: string,\n  kept: KeptProps\n): BuilderOp | null {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return null;\n  const bindings = bindingsOf(node);\n  delete bindings[prop];\n  const props: Record<string, unknown> = {\n    ...(isPlainRecord(node.props) ? node.props : {}),\n    ...kept.set,\n  };\n  for (const name of kept.empty ?? []) delete props[name];\n  return Object.keys(bindings).length === 0\n    ? { kind: \"update\", id, patch: { props }, unset: [\"bindings\"] }\n    : { kind: \"update\", id, patch: { props, bindings } };\n}\n","/**\n * What the binding picker reads through the host, as hooks: the fields a\n * binding can read, one read shared by every control asking at once; the\n * language and zone a value is previewed in; and the values of a list's\n * first entry beside its item's fields.\n *\n * Apart from `binding-controls`, which draws the picker and the chip: the\n * component decides what to show, these decide when the host is asked.\n *\n * @module binding-picker-reads\n */\nimport type { BindingRunInput } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { ContentServices } from \"../inspector/content/content-controls\";\n\nimport type { BindingFieldSource, ListSample } from \"./binding-services\";\nimport type { ItemField } from \"./item-binding-source\";\n\n/** The language and time zone the picker previews a formatted value in. */\nexport type PreviewFormatIn = Pick<BindingRunInput, \"locale\" | \"timeZone\">;\n\n/**\n * The language and zone the picker previews in: the page's language, and the\n * site's zone, asked of the host when the picker opens rather than with the\n * canvas, which reads it only for a page already formatting a date. Until\n * the zone is in, and where the host has none or its read fails, the preview\n * is in UTC, as a page rendered with no zone; it is drawn again once it is.\n */\nexport function usePreviewFormatIn(\n  services: ContentServices | undefined\n): PreviewFormatIn {\n  const locale = services?.bindingLocale;\n  const readZone = services?.readSiteTimeZone;\n  const [read, setRead] = React.useState<{\n    readonly from: () => Promise<string | undefined>;\n    readonly zone: string | undefined;\n  }>();\n  React.useEffect(() => {\n    if (readZone === undefined) return;\n    let current = true;\n    readZone().then(\n      zone => {\n        if (current) setRead({ from: readZone, zone });\n      },\n      () => {\n        // No zone to show: the previews stay in UTC.\n      }\n    );\n    return () => {\n      current = false;\n    };\n  }, [readZone]);\n  // Only the zone this host's read gave, so another host's is never shown.\n  const timeZone = read?.from === readZone ? read?.zone : undefined;\n  return React.useMemo(\n    () => ({\n      ...(locale === undefined ? {} : { locale }),\n      ...(timeZone === undefined ? {} : { timeZone }),\n    }),\n    [locale, timeZone]\n  );\n}\n\n/** The host's read of the fields a binding can read. */\ntype ListBindingFields = () => Promise<readonly BindingFieldSource[]>;\n\n/**\n * The read in flight, per host function, shared only while it runs, as the\n * list controls share theirs (`collection-loop-controls`): the controls drawn\n * together for one block (a bound image's chip and its alt note) make one\n * read and see one answer, so they can't disagree. Dropped once it settles:\n * an answer is one signed-in author's, read with their access.\n */\nconst sourcesInFlight = new WeakMap<\n  ListBindingFields,\n  Promise<readonly BindingFieldSource[]>\n>();\n\n/** The host's binding sources, one read shared by every control asking at once. */\nfunction readBindingSources(\n  list: ListBindingFields\n): Promise<readonly BindingFieldSource[]> {\n  const held = sourcesInFlight.get(list);\n  if (held !== undefined) return held;\n  const answer = list();\n  sourcesInFlight.set(list, answer);\n  const settle = (): void => {\n    if (sourcesInFlight.get(list) === answer) sourcesInFlight.delete(list);\n  };\n  answer.then(settle, settle);\n  return answer;\n}\n\n/** The fields a binding can read, as the host reads them; read once per open. */\nexport function useBindingSources(\n  services: ContentServices | undefined,\n  wanted: boolean\n): readonly BindingFieldSource[] | \"loading\" | \"failed\" {\n  const [sources, setSources] = React.useState<\n    readonly BindingFieldSource[] | \"loading\" | \"failed\"\n  >(\"loading\");\n  const list = services?.listBindingFields;\n  React.useEffect(() => {\n    if (!wanted || list === undefined) return;\n    let current = true;\n    setSources(\"loading\");\n    readBindingSources(list).then(\n      read => {\n        if (current) setSources(read);\n      },\n      () => {\n        if (current) setSources(\"failed\");\n      }\n    );\n    return () => {\n      current = false;\n    };\n  }, [list, wanted]);\n  return sources;\n}\n\n/** One list's sample, asked: its stored props, and the entry clicked. */\nexport interface SampleAsk {\n  readonly props: Readonly<Record<string, unknown>>;\n  /** The entry's place among those the list shows; the first if absent. */\n  readonly entry?: number;\n}\n\n/** No sample read. */\nconst UNREAD: readonly undefined[] = [];\n\n/**\n * The samples of one entry of each list asked (`asks`, nearest first), as\n * the host reads them: the entry the author clicked on the canvas, else the\n * first. Each `undefined` until read, where the host has none, or where its\n * read fails, so that item's fields are then listed with no values. Read\n * again only when a list's stored props or its entry change.\n */\nexport function useListSamples(\n  read: ContentServices[\"readListSample\"],\n  asks: readonly SampleAsk[]\n): readonly (ListSample | undefined)[] {\n  // By value: the document is a new object after every edit elsewhere.\n  const key = JSON.stringify(asks.map(ask => [ask.props, ask.entry ?? null]));\n  const [found, setFound] = React.useState<{\n    readonly read: NonNullable<typeof read>;\n    readonly key: string;\n    readonly samples: readonly (ListSample | undefined)[];\n  }>();\n  React.useEffect(() => {\n    if (read === undefined) return;\n    const asked = JSON.parse(key) as [\n      Readonly<Record<string, unknown>>,\n      number | null,\n    ][];\n    if (asked.length === 0) return;\n    let live = true;\n    void Promise.all(\n      asked.map(([stored, at]) =>\n        // The entry only where one was clicked, so a host reading the first\n        // entry is asked as before; a failed read shows no values.\n        (at === null ? read(stored) : read(stored, at)).catch(() => undefined)\n      )\n    ).then(samples => {\n      if (live) setFound({ read, key, samples });\n    });\n    return () => {\n      live = false;\n    };\n  }, [read, key]);\n  // Only the answer for this host and these lists, never a previous one's.\n  return found !== undefined && found.read === read && found.key === key\n    ? found.samples\n    : UNREAD;\n}\n\n/** A field holding a media item by its id, as a list's entry stores one. */\nfunction holdsMedia(field: ItemField): boolean {\n  return field.type === \"upload\";\n}\n\n/** One list's item fields and the sample read of its entry. */\nexport interface SampledItem {\n  readonly fields: readonly ItemField[];\n  readonly sample: ListSample | undefined;\n}\n\n/**\n * The media ids a list's sample holds, by the field's path: each field\n * holding a media item, and one step into a group or a relation, as far as\n * the picker lists fields (`seo.ogImage`).\n */\nfunction mediaIdsIn(\n  fields: readonly ItemField[],\n  sample: ListSample | undefined,\n  parent?: string\n): [string, string][] {\n  return fields.flatMap((field): [string, string][] => {\n    const path = parent === undefined ? field.name : `${parent}.${field.name}`;\n    const value = sample?.[path];\n    const own: [string, string][] =\n      holdsMedia(field) && typeof value === \"string\" ? [[path, value]] : [];\n    const inside =\n      parent === undefined && field.fields !== undefined\n        ? mediaIdsIn(field.fields, sample, path)\n        : [];\n    return [...own, ...inside];\n  });\n}\n\n/**\n * The pictures each list's sample names by id (`items`, nearest first), by\n * the field's path: each read through the author's own media read\n * (`readMedia`, the one the canvas draws pictures with), its small picture's\n * address. Empty until read, where the host has no read, and for a picture\n * the read does not find.\n */\nexport function useSamplePictures(\n  readMedia: ContentServices[\"readMedia\"],\n  items: readonly SampledItem[]\n): readonly ReadonlyMap<string, string>[] {\n  const ids = items.flatMap(({ fields, sample }, index) =>\n    mediaIdsIn(fields, sample).map(([path, id]): [number, string, string] => [\n      index,\n      path,\n      id,\n    ])\n  );\n  // By value: a new sample object for the same entry asks nothing again.\n  const key = JSON.stringify(ids);\n  const [found, setFound] = React.useState<{\n    readonly key: string;\n    readonly pictures: readonly [number, string, string][];\n  }>();\n  React.useEffect(() => {\n    if (readMedia === undefined) return;\n    const asked = JSON.parse(key) as [number, string, string][];\n    if (asked.length === 0) return;\n    let live = true;\n    void Promise.all(\n      asked.map(\n        async ([index, path, id]): Promise<\n          [number, string, string] | undefined\n        > => {\n          const thumbnail = (await readMedia(id).catch(() => null))?.thumbnail;\n          return thumbnail === undefined ? undefined : [index, path, thumbnail];\n        }\n      )\n    ).then(read => {\n      if (live) {\n        setFound({ key, pictures: read.filter(each => each !== undefined) });\n      }\n    });\n    return () => {\n      live = false;\n    };\n  }, [readMedia, key]);\n  const pictures = found?.key === key ? found.pictures : [];\n  return items.map(\n    (_, index) =>\n      new Map(\n        pictures\n          .filter(([at]) => at === index)\n          .map(([, path, thumbnail]) => [path, thumbnail])\n      )\n  );\n}\n","/**\n * A component's own settings as a source of the data picker, listed first\n * while the component is edited on its own: the settings the prop may\n * follow, each with its default (the value on the setting's own block)\n * beside it, and a pick binding the block to the setting,\n * `{ $bind: \"<setting id>\", source: \"setting\" }`. Which settings fit is the\n * engine's `followableSettingsOf`, the rule the save judges a follower by.\n *\n * Above the list, how many pages use the component, as its view counts them,\n * and what a setting does for them.\n *\n * @module binding-setting-source\n */\nimport {\n  findNode,\n  followableSettingsOf,\n  isPlainRecord,\n  type Binding,\n  type BlockDocument,\n  type ExposedProperty,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { ComponentFieldsContext } from \"../inspector/component-fields-panel\";\nimport type { EditableProp } from \"../inspector/inspector\";\nimport type { ComponentFieldsHost } from \"../panels/components/component-fields\";\n\nimport type {\n  BindingFieldChoice,\n  BindingFieldSource,\n} from \"./binding-services\";\n\n/** What the picker heads the group and the chip names the source. */\nconst COMPONENT_SETTINGS_SOURCE = \"This component's settings\";\n\n/** The component's settings, as a source the picker lists. */\nexport type SettingSource = Omit<BindingFieldSource, \"binding\"> & {\n  readonly binding: { readonly source: \"setting\" };\n};\n\n/**\n * The field type a setting's value is read as, for the controls a bound prop\n * shows under its chip: a text setting's value is text, as a text field's.\n */\nconst READ_AS: Readonly<Record<ExposedProperty[\"type\"], string>> = {\n  text: \"text\",\n  richText: \"richText\",\n  link: \"text\",\n  image: \"upload\",\n  select: \"select\",\n  visibility: \"checkbox\",\n};\n\n/** How much of a default the row shows; the row cuts it shorter still. */\nconst SHOWN_LENGTH = 120;\n\n/**\n * The settings `prop` of block `nodeId` may follow, as a source, or\n * `undefined` where none may: outside a component, for a prop no setting\n * fits, and for a link's entry id (`entryId`), which an id fills, never a\n * setting's value.\n */\nexport function settingSource(\n  document: BlockDocument,\n  nodeId: string,\n  prop: EditableProp,\n  entryId: string | undefined\n): SettingSource | undefined {\n  if (prop.name === entryId) return undefined;\n  const settings = followableSettingsOf(\n    document,\n    nodeId,\n    prop.name,\n    prop.schema\n  );\n  if (settings.length === 0) return undefined;\n  return {\n    binding: { source: \"setting\" },\n    label: COMPONENT_SETTINGS_SOURCE,\n    fields: settings.map(entry => settingChoice(document, entry)),\n  };\n}\n\n/** One setting as a row: its name, and its default beside it. */\nfunction settingChoice(\n  document: BlockDocument,\n  setting: ExposedProperty\n): BindingFieldChoice {\n  return {\n    ...settingField(setting),\n    // A setting is the component's own, shown wherever it is placed.\n    public: true,\n    ...shownDefault(defaultOf(document, setting)),\n  };\n}\n\n/**\n * A setting as a field: its id, its label and the type its value is read as.\n * The one description the picker's row and a bound prop's chip and controls\n * share, so an image setting is read as a file by both.\n */\nfunction settingField(\n  setting: Pick<ExposedProperty, \"id\" | \"label\" | \"type\">\n): { name: string; label: string; type: string } {\n  return {\n    name: setting.id,\n    label: setting.label,\n    type: READ_AS[setting.type],\n  };\n}\n\n/** A stored setting, read only where its id, label and type are usable. */\nfunction readableSetting(\n  entry: unknown\n): Pick<ExposedProperty, \"id\" | \"label\" | \"type\"> | undefined {\n  if (!isPlainRecord(entry)) return undefined;\n  const { id, label, type } = entry;\n  if (typeof id !== \"string\" || typeof label !== \"string\") return undefined;\n  return isSettingType(type) ? { id, label, type } : undefined;\n}\n\n/** Whether a stored value names a kind of setting this editor reads. */\nfunction isSettingType(type: unknown): type is ExposedProperty[\"type\"] {\n  return typeof type === \"string\" && Object.hasOwn(READ_AS, type);\n}\n\n/** The setting's default: the value on its own block, at its path. */\nfunction defaultOf(document: BlockDocument, setting: ExposedProperty): unknown {\n  let value: unknown = findNode(document.nodes, setting.nodeId)?.props;\n  for (const segment of setting.propPath.split(\".\")) {\n    if (!isPlainRecord(value)) return undefined;\n    value = Object.hasOwn(value, segment) ? value[segment] : undefined;\n  }\n  return value;\n}\n\n/**\n * A default as the row says it: its text, \"(empty)\" for none, and nothing\n * for a value that isn't text, such as a picture's reference.\n */\nfunction shownDefault(\n  value: unknown\n): Pick<BindingFieldChoice, \"preview\" | \"empty\"> {\n  if (value === undefined || value === null || value === \"\") {\n    return { empty: true };\n  }\n  return typeof value === \"string\"\n    ? { preview: value.slice(0, SHOWN_LENGTH) }\n    : {};\n}\n\n/**\n * Where a setting binding reads, named for the chip, with the settings by\n * name; `undefined` for any other binding.\n */\nexport function settingBoundFrom(\n  binding: Binding,\n  document: BlockDocument\n):\n  | {\n      readonly name: string;\n      readonly fields: readonly { name: string; type: string; label: string }[];\n      /** A setting is named by its whole id, never read as a path. */\n      readonly whole: true;\n    }\n  | undefined {\n  if (binding.source !== \"setting\") return undefined;\n  const exposed: unknown = isPlainRecord(document) ? document.exposed : [];\n  const fields = (Array.isArray(exposed) ? (exposed as unknown[]) : []).flatMap(\n    entry => {\n      const setting = readableSetting(entry);\n      return setting === undefined ? [] : [settingField(setting)];\n    }\n  );\n  return { name: COMPONENT_SETTINGS_SOURCE, fields, whole: true };\n}\n\n/** What a setting does for the pages using the component. */\nconst SETTINGS_HINT = \"Each page that places it can set its own value.\";\n\n/**\n * How many pages use the component, as its view counts them, then the hint:\n * \"Used on 4 pages. Each page that places it can set its own value.\" A count\n * not yet whole is said as a floor, and no count, the hint alone.\n */\nfunction settingsReachLine(pages: ComponentFieldsHost[\"pages\"]): string {\n  // None counted yet, with the count not whole, says nothing of a floor.\n  if (pages === undefined || (pages.count === 0 && !pages.complete)) {\n    return SETTINGS_HINT;\n  }\n  if (pages.count === 0) return `Not used on any page yet. ${SETTINGS_HINT}`;\n  const noun = pages.count === 1 ? \"page\" : \"pages\";\n  const floor = pages.complete ? \"\" : \"at least \";\n  return `Used on ${floor}${pages.count} ${noun}. ${SETTINGS_HINT}`;\n}\n\n/** The line above the settings, from the component's view. */\nexport function SettingsReach(): React.JSX.Element {\n  const fields = React.useContext(ComponentFieldsContext);\n  return (\n    <p className=\"nx-binding-picker__reach\">\n      {settingsReachLine(fields?.pages)}\n    </p>\n  );\n}\n","/**\n * Where a list item's binding reads: the entries of the collection its list\n * shows, as the host lists that collection's fields for a list, or, for a\n * list fed by a named query, that query's rows: a collection's entries, or\n * the fields the query declares for rows of its own.\n *\n * The list's item is the source nearest a block inside a list: the binding\n * field picker lists its fields first, the inspector names an item binding's\n * field, and judges its Format. All three read the list's items here: a\n * collection's by the fields visitors may read (`LoopCollection.readable`), a\n * named query's own rows by the fields it declares, as a save judges a list's\n * bindings, so a field offered, and a format, is one the save keeps.\n *\n * @module item-binding-source\n */\nimport {\n  namedQueryRowFields,\n  outerListOf,\n  readListQuery,\n  type Binding,\n  type BindingFieldShape,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { useLoopCollections } from \"../inspector/content/collection-loop-controls\";\nimport type {\n  ContentServices,\n  LoopCollection,\n} from \"../inspector/content/content-controls\";\nimport { useCustomSources } from \"../inspector/content/list-query-controls\";\nimport {\n  customSourceLookup,\n  type CustomSource,\n} from \"../inspector/content/named-query-model\";\n\nimport type {\n  BindingFieldChoice,\n  ListSample,\n  ListSampleValue,\n} from \"./binding-services\";\n\n/** One field an item binding can read, with what the admin calls it. */\nexport type ItemField = BindingFieldShape & { readonly label?: string };\n\n/** A list item's source as the chip names it, and the fields it has. */\nexport interface ItemSource {\n  /** \"Each post in the list\". */\n  readonly name: string;\n  /** One of the list's entries, as the name says it: \"post\". */\n  readonly one: string;\n  /** Its fields, once the host has listed the collection; none before. */\n  readonly fields: readonly ItemField[];\n  /**\n   * The list whose entries the item is, as the document stores it; absent\n   * for an item binding left outside every list.\n   */\n  readonly list?: BlockNode;\n  /** Whether the host is still listing the list's collections. */\n  readonly loading: boolean;\n}\n\n/**\n * A collection's fields as an item binding is judged against them: those\n * visitors may read, with a date picked as a day said so, as the list's own\n * fields say it.\n */\nfunction itemFields(found: LoopCollection): readonly ItemField[] {\n  return (found.readable ?? []).map(field => {\n    const listed = found.fields.find(each => each.name === field.name);\n    return listed?.dateOnly === true ? { ...field, dateOnly: true } : field;\n  });\n}\n\n/** What a list's items are, as an item binding reads them. */\ninterface ListItems {\n  /** The collection its items are entries of, where they are one's. */\n  readonly found: LoopCollection | undefined;\n  /** Their fields, once known; none before. */\n  readonly fields: readonly ItemField[];\n}\n\n/**\n * The items of the list whose query is `query`: its collection's entries, or\n * a named query's rows by the engine's one rule for them\n * (`namedQueryRowFields`), the declared fields of rows of its own or the\n * fields of the collection they are entries of. A named query not (yet) read\n * has no fields, so no Format is offered for it until it is.\n */\nfunction listItems(\n  query: ReturnType<typeof readListQuery>[\"query\"] | undefined,\n  collections: readonly LoopCollection[],\n  customs: readonly CustomSource[] | undefined\n): ListItems {\n  const bySlug = (slug: string | undefined) =>\n    collections.find(each => each.slug === slug);\n  const name = query?.namedQuery?.name;\n  if (name === undefined) {\n    const found = bySlug(query?.collection);\n    return { found, fields: found === undefined ? [] : itemFields(found) };\n  }\n  if (customs === undefined) return { found: undefined, fields: [] };\n  const lookup = customSourceLookup(customs);\n  const rows = lookup.declarationOf(name)?.rows;\n  const fields = namedQueryRowFields(lookup, name, slug => {\n    const found = bySlug(slug);\n    return found === undefined ? undefined : itemFields(found);\n  });\n  return {\n    found:\n      rows !== undefined && \"collection\" in rows\n        ? bySlug(rows.collection)\n        : undefined,\n    fields: fields ?? [],\n  };\n}\n\n/** The most lists one block may sit inside, as a document's depth bounds it. */\nconst MOST_LISTS = 64;\n\n/**\n * Every list whose entries `id` is drawn in, innermost first: the list\n * {@link outerListOf} finds, then the one around it, and so on out.\n *\n * @param nodes - the document's nodes\n * @param id - the block\n * @returns the lists, nearest first; none outside every list's entries\n */\nfunction enclosingLists(nodes: BlockNode[], id: string): readonly BlockNode[] {\n  const lists: BlockNode[] = [];\n  // Bounded: each step moves one list out, and no document is this deep.\n  for (\n    let list = outerListOf(nodes, id);\n    list !== undefined && lists.length < MOST_LISTS;\n    list = outerListOf(nodes, list.id)\n  ) {\n    lists.push(list);\n  }\n  return lists;\n}\n\n/** One list's item, named, from the collections and queries read. */\nfunction itemOf(\n  list: BlockNode,\n  collections: ReturnType<typeof useLoopCollections>,\n  customs: readonly CustomSource[] | undefined\n): ItemSource {\n  const query = readListQuery(list.props).query;\n  const { found, fields } = listItems(\n    query,\n    collections?.kind === \"ready\" ? collections.collections : [],\n    customs\n  );\n  const one = (found?.singular ?? found?.label ?? \"entry\").toLowerCase();\n  return {\n    name: `Each ${one} in the list`,\n    one,\n    fields,\n    list,\n    loading: collections?.kind === \"loading\",\n  };\n}\n\n/**\n * The item of every list block `nodeId` sits in, nearest first: none outside\n * every list's entries. Asks the host for the collections, and for its named\n * queries, only while `wanted`, and only for a block in a list.\n *\n * @param document - the document the block is in\n * @param nodeId - the block\n * @param services - the host's reads\n * @param wanted - whether the items are asked for at all\n * @returns each list's item source, named, with its fields once read\n */\nexport function useListItems(\n  document: BlockDocument,\n  nodeId: string,\n  services: ContentServices | undefined,\n  wanted: boolean\n): readonly ItemSource[] {\n  // Found in the document first, so a block outside every list asks the\n  // host for nothing.\n  const lists = wanted ? enclosingLists(document.nodes, nodeId) : [];\n  const listed = useLoopCollections(\n    lists.length === 0 ? undefined : services?.listLoopCollections\n  );\n  // The site's named queries only for a list fed by one: a collection's list\n  // has no need of them, and their read is retried while it fails.\n  const named = lists.some(\n    list => readListQuery(list.props).query.namedQuery !== undefined\n  );\n  const customs = useCustomSources(\n    named ? services?.listCustomSources : undefined\n  );\n  return lists.map(list => itemOf(list, listed, customs));\n}\n\n/**\n * The item of the list block `nodeId` sits in, nearest first, or `undefined`\n * outside every list's entries: the first of {@link useListItems}.\n */\nexport function useListItem(\n  document: BlockDocument,\n  nodeId: string,\n  services: ContentServices | undefined,\n  wanted: boolean\n): ItemSource | undefined {\n  return useListItems(document, nodeId, services, wanted)[0];\n}\n\n/**\n * The source of an item binding on block `nodeId`, or `undefined` for a\n * binding to another source: the item of the list it names (`list`), else\n * of the nearest list, asked for only for an item binding.\n */\nexport function useItemSource(\n  binding: Binding,\n  document: BlockDocument,\n  nodeId: string,\n  services: ContentServices | undefined\n): ItemSource | undefined {\n  const item = binding.source === \"item\";\n  const items = useListItems(document, nodeId, services, item);\n  if (!item) return undefined;\n  const named = \"list\" in binding ? binding.list : undefined;\n  const found =\n    named === undefined\n      ? items[0]\n      : items.find(each => each.list?.id === named);\n  if (found !== undefined) return found;\n  // An item binding outside every list, or naming a list it is not inside,\n  // still names its source, with no fields to name its field from: the save\n  // refuses it there.\n  return {\n    name: \"Each entry in the list\",\n    one: \"entry\",\n    fields: [],\n    loading: false,\n  };\n}\n\n/**\n * A sampled value as a field choice says it: its start as text, a picture's\n * thumbnail, or that the field holds nothing.\n */\nfunction sampled(\n  value: ListSampleValue | undefined,\n  field: ItemField,\n  picture: string | undefined\n): Pick<BindingFieldChoice, \"preview\" | \"thumbnail\" | \"empty\"> {\n  if (picture !== undefined) return { thumbnail: picture };\n  if (value === undefined) return {};\n  // A media item stored by its id: its picture, once read, never the id.\n  if (typeof value === \"string\") {\n    return field.type === \"upload\" ? {} : { preview: value };\n  }\n  return \"thumbnail\" in value\n    ? { thumbnail: value.thumbnail }\n    : { empty: true as const };\n}\n\n/**\n * A list item's fields as the picker lists them: each one visitors may read\n * (only those are listed for an item), with its value in the sampled entry\n * (the one the author clicked, else the first) where the host read one, one\n * step into a group or a relation.\n */\nexport function itemChoices(\n  fields: readonly ItemField[],\n  sample: ListSample | undefined,\n  parent?: string,\n  /** The pictures the sample names by id, read, by the field's path. */\n  pictures?: ReadonlyMap<string, string>\n): readonly BindingFieldChoice[] {\n  return fields.map(field => {\n    const { fields: inside, ...own } = field;\n    const path = parent === undefined ? field.name : `${parent}.${field.name}`;\n    return {\n      ...own,\n      public: true,\n      ...sampled(sample?.[path], field, pictures?.get(path)),\n      // One step in, as the host lists a source's fields.\n      ...(inside === undefined || parent !== undefined\n        ? {}\n        : { fields: itemChoices(inside, sample, path, pictures) }),\n    };\n  });\n}\n","/**\n * The picker a bind button opens: the fields that fit the prop, grouped by\n * where they come from, each option's row and title, the list item's own\n * fields first inside a collection list, and the edit a pick makes.\n * `binding-controls.tsx` mounts it, for the bind button and for changing the\n * field a bound prop reads.\n *\n * @module binding-picker\n */\nimport {\n  bindablePropKind,\n  canBindFieldToProp,\n  fieldFitsProp,\n  findNode,\n  isPlainRecord,\n  type Binding,\n  type BindingFieldShape,\n  type BindingFormat,\n  type BlockDocument,\n  type BuilderOp,\n} from \"@nextlyhq/blocks-engine\";\nimport { EyeOff } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useClickedEntries } from \"../canvas/clicked-entry\";\nimport {\n  ChoiceList,\n  type ChoiceGroup,\n  type ListedChoice,\n} from \"../choice-list\";\nimport type { ContentServices } from \"../inspector/content/content-controls\";\nimport {\n  fieldLabel,\n  propLabel,\n  type EditableProp,\n} from \"../inspector/inspector\";\nimport { withArticle } from \"../with-article\";\n\nimport { defaultFormatFor, previewWithFormat } from \"./binding-format-field\";\nimport { bindOp } from \"./binding-ops\";\nimport {\n  useBindingSources,\n  useListSamples,\n  usePreviewFormatIn,\n  useSamplePictures,\n  type PreviewFormatIn,\n} from \"./binding-picker-reads\";\nimport type {\n  BindingFieldChoice,\n  BindingFieldSource,\n  ListSample,\n} from \"./binding-services\";\nimport {\n  settingSource,\n  SettingsReach,\n  type SettingSource,\n} from \"./binding-setting-source\";\nimport {\n  itemChoices,\n  useListItems,\n  type ItemSource,\n} from \"./item-binding-source\";\n\n/**\n * A source the picker lists: one the host lists, or the item of the list the\n * block sits in, which only the editor knows and the picker lists first, or,\n * in a component, its own settings, listed before both.\n */\ntype PickerSource =\n  | (Omit<BindingFieldSource, \"binding\"> & {\n      readonly binding:\n        | BindingFieldSource[\"binding\"]\n        | {\n            readonly source: \"item\";\n            /** An enclosing list further out than the nearest, by its id. */\n            readonly list?: string;\n          };\n    })\n  | SettingSource;\n\n/** One field the picker offers, with where it is read from. */\ninterface FieldOption extends ListedChoice {\n  readonly path: string;\n  readonly source: PickerSource;\n  readonly field: BindingFieldChoice;\n  /** The relation or group it sits in, named, for a field one step in. */\n  readonly parent?: string;\n  /**\n   * The format a pick writes, for a date or a number filling a text prop,\n   * which reaches it only through one; named in the option.\n   */\n  readonly format?: { readonly label: string; readonly format: BindingFormat };\n}\n\n/**\n * A link's props, where the prop being bound is a link's destination: its\n * address and the two halves of the entry reference it follows first.\n */\nexport interface EntryLink {\n  readonly link: string;\n  readonly collection: string;\n  readonly id: string;\n  /**\n   * Whether a related entry's pick may be written where the block sits: it\n   * writes both halves of the reference and removes the address's binding,\n   * so it is offered only where all three may change.\n   */\n  readonly writable: boolean;\n}\n\n/** The edit a pick makes, and the prop it binds, whose chip is drawn after. */\ninterface PickEdit {\n  readonly op: BuilderOp | null;\n  readonly bound: string;\n}\n\n/**\n * The edit a pick makes. A related entry's id fills the link's entry: its\n * collection is set to the relation's in the same edit, since a pick writes\n * both halves of the reference at once, and a stored entry id is emptied.\n * The address the link was bound to is unbound, since the entry replaces it,\n * as is a bound collection, which would otherwise overlay the one set,\n * and its fallback is not carried over, being an address rather than an id;\n * the address stored on the block is kept, so the link still goes there\n * where the entry is not read. Any other pick binds `prop`, emptying\n * `clearsOnBind`.\n */\nexport function pickOp(\n  at: {\n    readonly document: BlockDocument;\n    readonly nodeId: string;\n    readonly prop: string;\n    readonly clearsOnBind: readonly string[] | undefined;\n    readonly entryLink: EntryLink | undefined;\n  },\n  picked: FieldOption,\n  kept: Binding | undefined\n): PickEdit {\n  const entry = at.entryLink;\n  const collection = picked.field.linksTo;\n  if (entry === undefined || collection === undefined) {\n    const op = bindOp(\n      at.document,\n      at.nodeId,\n      at.prop,\n      pickedBinding(picked, kept),\n      at.clearsOnBind\n    );\n    return { op, bound: at.prop };\n  }\n  const op = bindOp(\n    at.document,\n    at.nodeId,\n    entry.id,\n    pickedBinding(picked, at.prop === entry.id ? kept : undefined),\n    [entry.id],\n    {\n      set: { [entry.collection]: collection },\n      // The collection is set, so a binding of it, which the page would fill\n      // over the value set, goes too.\n      unbind: [entry.link, entry.collection],\n    }\n  );\n  return { op, bound: entry.id };\n}\n\n/**\n * The binding a pick writes; for a component's setting, its id alone:\n * composing fills it from the setting and drops it, so a fallback or format\n * carried over from the field it replaces would never be read.\n */\nfunction pickedBinding(\n  option: FieldOption,\n  kept: Binding | undefined\n): Binding {\n  return option.source.binding.source === \"setting\"\n    ? { $bind: option.path, source: \"setting\" }\n    : bindingFor(option, kept);\n}\n\n/**\n * The binding a pick writes: the path, the source when not the entry, and\n * the format the option names, where it names one.\n */\nfunction bindingFor(option: FieldOption, kept: Binding | undefined): Binding {\n  const source = option.source.binding;\n  // The fallback is kept across a change of field, and the option's format\n  // is written with the pick, so a date or a number shows from the start.\n  const carried = {\n    ...(kept !== undefined && \"fallback\" in kept\n      ? { fallback: kept.fallback }\n      : {}),\n    ...(option.format === undefined ? {} : { format: option.format.format }),\n  };\n  if (source.source === \"single\") {\n    return {\n      $bind: option.path,\n      source: \"single\",\n      sourceKey: source.sourceKey,\n      ...carried,\n    };\n  }\n  return {\n    $bind: option.path,\n    ...(source.source === \"entry\" ? {} : { source: source.source }),\n    ...(\"list\" in source && source.list !== undefined\n      ? { list: source.list }\n      : {}),\n    ...carried,\n  };\n}\n\n/**\n * Whether a bind would empty a prop that may not be written: one of\n * `locked` the block holds. A held bind is not offered; one that would empty\n * nothing is, whatever the lock.\n */\nexport function clearHeld(\n  document: BlockDocument,\n  nodeId: string,\n  locked: readonly string[] | undefined\n): boolean {\n  if (locked === undefined || locked.length === 0) return false;\n  const props = findNode(document.nodes, nodeId)?.props;\n  return (\n    isPlainRecord(props) && locked.some(name => Object.hasOwn(props, name))\n  );\n}\n\n/** Whether `option` is the field and source `binding` reads. */\nfunction isBoundTo(option: FieldOption, binding: Binding): boolean {\n  if (option.path !== binding.$bind) return false;\n  const source = option.source.binding;\n  if (source.source !== (binding.source ?? \"entry\")) return false;\n  if (source.source === \"item\") {\n    return (\n      (source.list ?? undefined) ===\n      (\"list\" in binding ? binding.list : undefined)\n    );\n  }\n  return (\n    source.source !== \"single\" ||\n    (\"sourceKey\" in binding && binding.sourceKey === source.sourceKey)\n  );\n}\n\n/**\n * A binding as the picker matches it: one naming the nearest list (`list`)\n * reads what one naming no list reads, so it is matched as that.\n */\nfunction asListed(binding: Binding, nearest: string | undefined): Binding {\n  if (!(\"list\" in binding) || binding.list !== nearest) return binding;\n  const { list: _nearest, ...rest } = binding;\n  return rest;\n}\n\n/**\n * A source's name as the chip and the picker say it: \"This post\", \"Site\", and\n * for a list's item the name its group was given (\"Each post\").\n */\nexport function sourceName(source: PickerSource): string {\n  return source.binding.source === \"entry\"\n    ? `This ${source.label.toLowerCase()}`\n    : source.label;\n}\n\n/**\n * A source's group in the picker, by which source it is rather than where it\n * is listed: the list item's group, drawn once the list's fields are read,\n * then moves no other group's options, so a search or an option the author\n * is on keeps its place.\n */\nfunction groupOf(source: PickerSource): string {\n  const at = source.binding;\n  if (at.source === \"single\") return `single:${at.sourceKey}`;\n  return at.source === \"item\" && at.list !== undefined\n    ? `item:${at.list}`\n    : at.source;\n}\n\n/** The option `binding` reads, marked in the list. */\nfunction boundOption(\n  options: readonly FieldOption[],\n  binding: Binding\n): FieldOption | undefined {\n  return options.find(option => isBoundTo(option, binding));\n}\n\n/**\n * The picker's groups, in the sources' order: each that offers a field\n * (`offering`), a Single and the site folded while `folding`, except the\n * group kept `open`.\n */\nfunction pickerGroups(\n  sources: readonly PickerSource[],\n  offering: ReadonlySet<string | undefined>,\n  fold: { readonly folding: boolean; readonly open: string | undefined }\n): ChoiceGroup[] {\n  return sources.flatMap(source => {\n    const group = groupOf(source);\n    if (!offering.has(group)) return [];\n    return [pickerGroup(source, fold.folding && group !== fold.open)];\n  });\n}\n\n/** What choosing a folded Single or the site does, said to a screen reader. */\nconst FOLD_HINT = \"Shows its fields here.\";\n\n/**\n * A source's group in the picker: headed by its name, and, `folded`, a\n * Single or the site drawn as one row (\"Homepage\", \"Site settings\") under\n * \"Singles · Site\", which opens it in place.\n */\nfunction pickerGroup(source: PickerSource, folded: boolean): ChoiceGroup {\n  const group = { group: groupOf(source), heading: sourceName(source) };\n  const at = source.binding.source;\n  if (!folded || (at !== \"single\" && at !== \"site\")) return group;\n  return {\n    ...group,\n    fold:\n      at === \"single\"\n        ? { heading: \"Singles\", label: source.label, hint: FOLD_HINT }\n        : { heading: \"Site\", label: \"Site settings\", hint: FOLD_HINT },\n  };\n}\n\n/**\n * The fields of `sources` that fit `prop`, one step into a relation or a\n * group, in the order the picker lists them. A relation or group whose own\n * value does not fit is not offered itself, only what is inside it. A value\n * shown formatted is formatted in `formatIn`, as the page's render formats it.\n *\n * A related entry's id (`linksTo`) is offered only for a link, whose entry it\n * fills; the link's entry id, bound, is changed only to another such id.\n */\nfunction fittingOptions(\n  sources: readonly PickerSource[],\n  prop: EditableProp,\n  formatIn: PreviewFormatIn,\n  entryLink: EntryLink | undefined\n): readonly FieldOption[] {\n  // A related entry is offered only where visitors may read it: a link\n  // bound to one they can't read never goes there, so it is not a choice.\n  const offered = (field: BindingFieldChoice): boolean =>\n    field.linksTo !== undefined\n      ? entryLink?.writable === true && field.public\n      : prop.name !== entryLink?.id && fits(field, prop);\n  const options: FieldOption[] = [];\n  sources.forEach(source => {\n    const group = groupOf(source);\n    for (const field of source.fields) {\n      const label = choiceLabel(field);\n      if (offered(field)) {\n        options.push(\n          withFormatOnBind(\n            option(source, group, field, field.name, label),\n            prop,\n            formatIn\n          )\n        );\n      }\n      for (const inner of field.fields ?? []) {\n        if (!offered(inner)) continue;\n        options.push(\n          withFormatOnBind(\n            option(\n              source,\n              group,\n              inner,\n              `${field.name}.${inner.name}`,\n              choiceLabel(inner),\n              label\n            ),\n            prop,\n            formatIn\n          )\n        );\n      }\n    }\n  });\n  return options;\n}\n\n/**\n * The picker's options: a component's settings first, already judged for the\n * prop by the save's own rule (see {@link settingSource}), then the fields of\n * every other source that fit it.\n */\nfunction pickerOptions(\n  sources: readonly PickerSource[],\n  prop: EditableProp,\n  formatIn: PreviewFormatIn,\n  entryLink: EntryLink | undefined\n): readonly FieldOption[] {\n  const settings = sources.filter(\n    source => source.binding.source === \"setting\"\n  );\n  const others = sources.filter(source => source.binding.source !== \"setting\");\n  return [\n    ...settings.flatMap(source =>\n      source.fields.map(field =>\n        option(source, groupOf(source), field, field.name, choiceLabel(field))\n      )\n    ),\n    ...fittingOptions(others, prop, formatIn, entryLink),\n  ];\n}\n\n/**\n * Whether a field fills the prop: as it is, or, for a date or a number into\n * text, with the format a pick writes (see {@link formatOnBind}). One that\n * fills it neither way is not offered, since a binding to it shows its\n * fallback.\n */\nfunction fits(field: BindingFieldChoice, prop: EditableProp): boolean {\n  return (\n    canBindFieldToProp(field, prop.schema) &&\n    (fieldFitsProp(field, prop.schema) ||\n      formatOnBind(field, prop) !== undefined)\n  );\n}\n\n/**\n * The format a pick of `field` writes: the inspector's starting preset where\n * the field fills the prop only through a format, none where it fills it as\n * it is.\n */\nfunction formatOnBind(\n  field: BindingFieldChoice,\n  prop: EditableProp\n): FieldOption[\"format\"] {\n  if (fieldFitsProp(field, prop.schema)) return undefined;\n  return defaultFormatFor(bindablePropKind(prop.schema), field);\n}\n\n/**\n * An option with the format its pick writes, where it writes one, its value\n * previewed in that format in `formatIn`: the page's language and the site's\n * time zone.\n */\nfunction withFormatOnBind(\n  choice: FieldOption,\n  prop: EditableProp,\n  formatIn: PreviewFormatIn\n): FieldOption {\n  const format = formatOnBind(choice.field, prop);\n  if (format === undefined) return choice;\n  const { preview } = choice.field;\n  if (preview === undefined) return { ...choice, format };\n  // Its value as the pick will show it, in the format the option names.\n  const shown = previewWithFormat(\n    preview,\n    format.format,\n    bindablePropKind(prop.schema),\n    choice.field,\n    formatIn\n  );\n  return {\n    ...choice,\n    format,\n    field: { ...choice.field, preview: shown },\n    search: [choice.label, shown].join(\" \"),\n  };\n}\n\n/** One option, with its text as the list searches it and a reader hears it. */\nfunction option(\n  source: PickerSource,\n  group: string,\n  field: BindingFieldChoice,\n  path: string,\n  label: string,\n  parent?: string\n): FieldOption {\n  return {\n    key: `${group}:${path}`,\n    label: parent === undefined ? label : `${parent} › ${label}`,\n    group,\n    path,\n    source,\n    field,\n    ...(parent === undefined ? {} : { parent }),\n    // A related entry whose collection has no page yet is listed, said why,\n    // and can't be picked: the link would find no page to go to.\n    ...(field.noPageFor === undefined ? {} : { disabled: true }),\n    search: [parent, label, field.preview].filter(Boolean).join(\" \"),\n  };\n}\n\n/**\n * A row's tooltip: its name, then why it can't be picked yet, or the value\n * as the author reads it, whole where the row cuts it short.\n */\nfunction optionTitle(option: FieldOption): string {\n  const { field } = option;\n  if (field.noPageFor !== undefined) {\n    return `${option.label}: No page for ${field.noPageFor} yet`;\n  }\n  return field.preview === undefined\n    ? option.label\n    : `${option.label}: ${field.preview}`;\n}\n\n/**\n * A thumbnail's address, where it is one a picture may be drawn from: the\n * site's own path or a web address, never a script's.\n */\nfunction drawableThumbnail(address: string | undefined): string | undefined {\n  if (address === undefined) return undefined;\n  return /^(?:https?:\\/\\/|\\/(?!\\/))/i.test(address) ? address : undefined;\n}\n\n/**\n * A picture's value, small, before its name; the name says what it is, so\n * the picture itself is not read out.\n */\nfunction Thumbnail({\n  address,\n}: {\n  address: string | undefined;\n}): React.JSX.Element | null {\n  const drawn = drawableThumbnail(address);\n  return drawn === undefined ? null : (\n    <img\n      className=\"nx-binding-option__thumb\"\n      src={drawn}\n      alt=\"\"\n      width={20}\n      height={20}\n      loading=\"lazy\"\n      decoding=\"async\"\n    />\n  );\n}\n\n/**\n * A readable field's value as the author reads it: its text, or \"(empty)\"\n * for one holding nothing, with a draft's marked.\n */\nfunction ShownValue({\n  field,\n}: {\n  field: BindingFieldChoice;\n}): React.JSX.Element {\n  return (\n    <>\n      {field.preview !== undefined ? (\n        <span className=\"nx-binding-option__preview\">{field.preview}</span>\n      ) : field.empty === true ? (\n        <span className=\"nx-binding-option__preview nx-binding-option__empty\">\n          (empty)\n        </span>\n      ) : null}\n      {/* A draft's value is shown with the word beside it, so the author\n          sees the real value and knows it isn't live yet. */}\n      {field.draft === true ? (\n        <span className=\"nx-binding-option__tag\">Draft</span>\n      ) : null}\n    </>\n  );\n}\n\n/** The picker's row: the name, then the value as the author reads it, or why not. */\nfunction OptionRow({ option }: { option: FieldOption }): React.JSX.Element {\n  const { field } = option;\n  return (\n    <span className=\"nx-binding-option\">\n      <Thumbnail address={field.thumbnail} />\n      <span className=\"nx-binding-option__name\">\n        {option.parent === undefined ? null : (\n          <span className=\"nx-binding-option__parent\">{option.parent} › </span>\n        )}\n        {choiceLabel(field)}\n      </span>\n      {/* The format a pick writes, said quietly beside the name and read\n          with it, so the author knows the value will be formatted. */}\n      {option.format === undefined ? null : (\n        <span className=\"nx-binding-option__tag\">{option.format.label}</span>\n      )}\n      {/* Words, not a colour or an icon alone: each is part of the option's\n          own text, so a screen reader announces it with the field. */}\n      {field.noPageFor !== undefined ? (\n        // Why a related entry can't be picked yet, in words read with it.\n        <span className=\"nx-binding-option__tag\">\n          {`No page for ${field.noPageFor} yet`}\n        </span>\n      ) : !field.public ? (\n        <span className=\"nx-binding-option__tag\" data-tone=\"private\">\n          <EyeOff aria-hidden=\"true\" size={12} />\n          Not public\n        </span>\n      ) : (\n        <ShownValue field={field} />\n      )}\n    </span>\n  );\n}\n\n/**\n * A list's item as a source the picker lists, named for the list's entries\n * (\"Each post in the list\"): the nearest list's first, binding no list, then\n * each list further out, binding it by its id.\n */\nfunction itemPickerSource(\n  item: ItemSource,\n  nearest: boolean,\n  sample: ListSample | undefined,\n  pictures: ReadonlyMap<string, string>\n): PickerSource {\n  const list = item.list?.id;\n  return {\n    binding:\n      nearest || list === undefined\n        ? { source: \"item\" }\n        : { source: \"item\", list },\n    label: item.name,\n    fields: itemChoices(item.fields, sample, undefined, pictures),\n  };\n}\n\n/**\n * The item of every list the block sits in, nearest first, as picker\n * sources: each list's fields, with the values of the entry the author\n * clicked on the canvas to select the block, else the first entry's, and the\n * pictures they name by id. `loading` while a list's fields are being read.\n */\nfunction useItemPickerSources(\n  document: BlockDocument,\n  nodeId: string,\n  services: ContentServices | undefined\n): {\n  readonly sources: readonly PickerSource[];\n  readonly loading: boolean;\n  readonly nearest: string | undefined;\n} {\n  const items = useListItems(document, nodeId, services, true);\n  const clicked = useClickedEntries(nodeId);\n  const samples = useListSamples(\n    services?.readListSample,\n    items.flatMap(item => {\n      const list = item.list;\n      if (list === undefined) return [];\n      const entry = clicked?.get(list.id);\n      return [{ props: list.props, ...(entry === undefined ? {} : { entry }) }];\n    })\n  );\n  const pictures = useSamplePictures(\n    services?.readMedia,\n    items.map((item, index) => ({\n      fields: item.fields,\n      sample: samples[index],\n    }))\n  );\n  return {\n    sources: items.map((item, index) =>\n      itemPickerSource(\n        item,\n        index === 0,\n        samples[index],\n        pictures[index] ?? new Map()\n      )\n    ),\n    loading: items.some(item => item.loading),\n    nearest: items[0]?.list?.id,\n  };\n}\n\n/**\n * The picker: the fitting fields by source, nearest first (the list item a\n * block sits in, then the page, its Singles and the site, the last two\n * folded while an item is listed), each with its value, searched, moved\n * through by key.\n */\nexport function BindingPicker({\n  prop,\n  blockLabel,\n  document,\n  nodeId,\n  services,\n  current,\n  entryLink,\n  onPick,\n}: {\n  prop: EditableProp;\n  blockLabel: string;\n  /** The document the block is in, where its list is found. */\n  document: BlockDocument;\n  nodeId: string;\n  services: ContentServices | undefined;\n  /** The link's entry, where the prop is a link's destination. */\n  entryLink: EntryLink | undefined;\n  /** The prop's binding when it has one, marked in the list. */\n  current: Binding | undefined;\n  onPick: (option: FieldOption) => void;\n}): React.JSX.Element {\n  const listed = useBindingSources(services, true);\n  const items = useItemPickerSources(document, nodeId, services);\n  const settings = settingSource(document, nodeId, prop, entryLink?.id);\n  const formatIn = usePreviewFormatIn(services);\n  const name = propLabel(prop.name, prop.schema);\n  // The list's fields are waited for with the page's, so the groups are\n  // drawn once, in their order, rather than the item's arriving above.\n  if (listed === \"loading\" || items.loading) {\n    return <p className=\"nx-binding-picker__note\">Reading the fields…</p>;\n  }\n  if (listed === \"failed\") {\n    return (\n      <p className=\"nx-binding-picker__note\" role=\"alert\">\n        The fields could not be read. Close this and try again.\n      </p>\n    );\n  }\n  return (\n    <PickerBody\n      // A component's settings first, as nearest of all, then the lists'.\n      sources={[\n        ...(settings === undefined ? [] : [settings]),\n        ...items.sources,\n        ...listed,\n      ]}\n      nearest={settings !== undefined || items.sources.length > 0}\n      prop={prop}\n      name={name}\n      blockLabel={blockLabel}\n      formatIn={formatIn}\n      entryLink={entryLink}\n      current={\n        current === undefined ? undefined : asListed(current, items.nearest)\n      }\n      onPick={onPick}\n    />\n  );\n}\n\n/**\n * The picker's list once its sources are read: the fitting fields by\n * source, the field bound now marked, a Single and the site folded while a\n * list's item is listed (`nearest`), and the hint under it.\n */\nfunction PickerBody({\n  sources,\n  nearest,\n  prop,\n  name,\n  blockLabel,\n  formatIn,\n  entryLink,\n  current,\n  onPick,\n}: {\n  sources: readonly PickerSource[];\n  nearest: boolean;\n  prop: EditableProp;\n  name: string;\n  blockLabel: string;\n  formatIn: PreviewFormatIn;\n  entryLink: EntryLink | undefined;\n  current: Binding | undefined;\n  onPick: (option: FieldOption) => void;\n}): React.JSX.Element {\n  // Previewed in the page's language and the site's zone.\n  const options = pickerOptions(sources, prop, formatIn, entryLink);\n  // A source with nothing to offer this prop is not listed: an empty group\n  // only lengthens the list.\n  const offering = new Set(options.map(option => option.group));\n  // A source the host could not read is said, above the fields that did.\n  const failed = sources.filter(source => source.readFailed === true);\n  const marked =\n    current === undefined ? undefined : boundOption(options, current);\n  return (\n    <div className=\"nx-binding-picker\">\n      <ChoiceList\n        choices={options}\n        currentKey={marked?.key}\n        onPick={onPick}\n        label={`Fields for ${name}`}\n        searchLabel=\"Find a field\"\n        noMatch=\"No field matches.\"\n        groups={pickerGroups(sources, offering, {\n          // Folded while a list's item is nearer, except the source the\n          // prop is bound to now, which is shown marked.\n          folding: nearest,\n          open: marked?.group,\n        })}\n        renderChoice={choice => <OptionRow option={choice} />}\n        choiceTitle={optionTitle}\n        searchFrom={0}\n        leading={\n          <PickerLeading\n            failed={failed}\n            // A component's settings' group is keyed by its source.\n            settings={offering.has(\"setting\")}\n          />\n        }\n      />\n      <p className=\"nx-binding-picker__hint\">\n        {options.length === 0\n          ? `No field can fill ${withArticle(blockLabel.toLowerCase())}'s ${name.toLowerCase()}.`\n          : `Only fields ${withArticle(blockLabel.toLowerCase())}'s ${name.toLowerCase()} can show are listed.`}\n      </p>\n    </div>\n  );\n}\n\n/**\n * What the picker says between its search and its rows: how many pages use\n * the component, over its settings where they are listed, and a source the\n * host could not read.\n */\nfunction PickerLeading({\n  failed,\n  settings,\n}: {\n  failed: readonly PickerSource[];\n  settings: boolean;\n}): React.JSX.Element {\n  return (\n    <>\n      {settings ? <SettingsReach /> : null}\n      {failed.length === 0 ? null : (\n        <p className=\"nx-binding-picker__failed\" role=\"status\">\n          {`Could not read ${failed.map(sourceName).join(\", \")}. Close this and try again.`}\n        </p>\n      )}\n    </>\n  );\n}\n\n/** A field as the chip names it and a format judges it, wherever it was read. */\nexport type NamedField = Omit<BindingFieldShape, \"fields\"> & {\n  readonly label?: string;\n  readonly fields?: readonly NamedField[];\n};\n\n/**\n * The name a field is listed by: the host's label where it gives one (\"Site\n * URL\"), else its stored name as a person reads it.\n */\nexport function choiceLabel(field: NamedField): string {\n  return field.label ?? fieldLabel(field.name);\n}\n","/**\n * The names a bound prop is said by: where its value comes from, the field's\n * own name and path, and the source a field outside the listed ones names.\n * `binding-controls.tsx` reads these for the chip and its menu, and\n * `useBoundFieldOf` answers the same for the image controls.\n *\n * @module binding-bound-names\n */\nimport type {\n  Binding,\n  BindingFieldShape,\n  BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { ContentServices } from \"../inspector/content/content-controls\";\nimport { fieldLabel } from \"../inspector/inspector\";\n\nimport {\n  choiceLabel,\n  type EntryLink,\n  type NamedField,\n  sourceName,\n} from \"./binding-picker\";\nimport { useBindingSources } from \"./binding-picker-reads\";\nimport type { BindingFieldSource } from \"./binding-services\";\nimport { settingBoundFrom } from \"./binding-setting-source\";\nimport { useItemSource, type ItemSource } from \"./item-binding-source\";\n\n/**\n * A bound path named segment by segment as the picker names it, through the\n * source's fields where they are read; a segment the source does not list is\n * named from its own key.\n */\nfunction pathName(\n  path: string,\n  fields: readonly NamedField[] | undefined\n): string {\n  const names: string[] = [];\n  let level = fields;\n  for (const segment of path.split(\".\")) {\n    const field = level?.find(candidate => candidate.name === segment);\n    names.push(field === undefined ? fieldLabel(segment) : choiceLabel(field));\n    level = field?.fields;\n  }\n  return names.join(\" › \");\n}\n\n/** The source a binding reads, once the sources are read and it is among them. */\nexport function boundSource(\n  binding: Binding,\n  sources: readonly BindingFieldSource[] | \"loading\" | \"failed\"\n): BindingFieldSource | undefined {\n  if (typeof sources === \"string\") return undefined;\n  const wanted = binding.source ?? \"entry\";\n  return sources.find(\n    candidate =>\n      candidate.binding.source === wanted &&\n      (candidate.binding.source !== \"single\" ||\n        (\"sourceKey\" in binding &&\n          candidate.binding.sourceKey === binding.sourceKey))\n  );\n}\n\n/**\n * A source named from the binding alone, for one the host did not list: a\n * Single with nothing saved yet, or an entry it could not read. Named from\n * its key, so the chip still says where the field comes from.\n */\nfunction unlistedSourceName(binding: Binding): string {\n  if (binding.source === \"single\") return fieldLabel(binding.sourceKey);\n  return binding.source === \"site\" ? \"Site\" : \"This entry\";\n}\n\n/** Where a binding reads, named, and that source's fields where they are read. */\ninterface BoundFrom {\n  /** `undefined` only while the sources are being read. */\n  readonly name: string | undefined;\n  readonly fields: readonly NamedField[] | undefined;\n  /**\n   * Set where `$bind` names one field by its whole key, dots and all, as a\n   * component's setting id does, rather than a path through its fields.\n   */\n  readonly whole?: true;\n}\n\n/**\n * Where a binding reads: a list's item from its list's collection, any other\n * source from the host's sources, and one the host did not list from the\n * binding itself once the sources are read.\n */\nfunction boundFrom(\n  binding: Binding,\n  sources: readonly BindingFieldSource[] | \"loading\" | \"failed\",\n  item: ItemSource | undefined\n): BoundFrom {\n  if (item !== undefined) return { name: item.name, fields: item.fields };\n  const found = boundSource(binding, sources);\n  if (found !== undefined) {\n    return { name: sourceName(found), fields: found.fields };\n  }\n  return {\n    name: sources === \"loading\" ? undefined : unlistedSourceName(binding),\n    fields: undefined,\n  };\n}\n\n/** The field a binding reads, named, and its source. */\nexport function boundNames(\n  binding: Binding,\n  from: BoundFrom,\n  /** The bound prop, and the link it is the entry of, where it is one. */\n  at: { readonly prop: string; readonly entryLink?: EntryLink | undefined }\n): { readonly field: string; readonly source: string | undefined } {\n  if (from.whole === true) {\n    const field = boundField(binding, from);\n    return {\n      field: field === undefined ? binding.$bind : choiceLabel(field),\n      source: from.name,\n    };\n  }\n  // A link's entry is named by the relation it goes through (\"Author\"): the\n  // entry the link goes to, not the id the binding reads of it.\n  const segments = binding.$bind.split(\".\");\n  const path =\n    at.prop === at.entryLink?.id && segments.length > 1\n      ? segments.slice(0, -1).join(\".\")\n      : binding.$bind;\n  return { field: pathName(path, from.fields), source: from.name };\n}\n\n/**\n * The field a binding reads, as its source lists it: one step into a\n * relation or a group at most, as a path may go. `undefined` until the\n * source's fields are read, and for a field they don't list.\n */\nexport function boundField(\n  binding: Binding,\n  from: BoundFrom\n): NamedField | undefined {\n  if (from.whole === true) {\n    return from.fields?.find(field => field.name === binding.$bind);\n  }\n  const [first, inner, ...rest] = binding.$bind.split(\".\");\n  if (rest.length > 0) return undefined;\n  const top = from.fields?.find(field => field.name === first);\n  if (inner === undefined) return top;\n  return top?.fields?.find(field => field.name === inner);\n}\n\n/**\n * Where a bound prop reads, as the chip names it: the host's sources read\n * once, or the list's collection for an item, then `boundFrom`. The one way\n * the editor finds a binding's source, for the chip and for any control that\n * asks what the bound field is.\n */\nexport function useBoundFrom(\n  binding: Binding,\n  document: BlockDocument,\n  nodeId: string,\n  services: ContentServices | undefined\n): {\n  /** Where the binding reads, named, with its fields once they are read. */\n  readonly from: BoundFrom;\n  /** The host's sources as read, for what else is worded from them. */\n  readonly sources: ReturnType<typeof useBindingSources>;\n  /** The list's item source, for an item binding. */\n  readonly item: ItemSource | undefined;\n} {\n  const sources = useBindingSources(services, true);\n  const item = useItemSource(binding, document, nodeId, services);\n  // A component's setting is named from the component itself.\n  const from =\n    settingBoundFrom(binding, document) ?? boundFrom(binding, sources, item);\n  return { from, sources, item };\n}\n\n/**\n * The field a bound prop reads, as its source lists it: `undefined` while the\n * sources are read, and for a field they don't list. Derived from the same\n * source the chip names, so a control reading the field's type and the chip\n * naming it cannot disagree.\n */\nexport function useBoundFieldOf(\n  binding: Binding,\n  document: BlockDocument,\n  nodeId: string,\n  services: ContentServices | undefined\n): Omit<BindingFieldShape, \"fields\"> | undefined {\n  const { from } = useBoundFrom(binding, document, nodeId, services);\n  return boundField(binding, from);\n}\n","/**\n * The note an unbind leaves under its field: what it kept, or why it was\n * refused.\n *\n * @module binding-notes\n */\nimport { Check, EyeOff } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { UnbindAnswer } from \"../composition-actions\";\nimport { fieldLabel } from \"../inspector/inspector\";\n\n/**\n * What an unbind said, and how: kept as visitors saw it, kept in place of a\n * field visitors can't read, or refused.\n */\nexport interface UnbindNote {\n  readonly text: string;\n  readonly tone: \"kept\" | \"private\" | \"refused\";\n}\n\n/** The note an unbind leaves under its field. */\nexport function UnboundNote({ note }: { note: UnbindNote }): React.JSX.Element {\n  return (\n    <p className=\"nx-binding-note\" data-tone={note.tone} role=\"status\">\n      {note.tone === \"kept\" ? <Check aria-hidden=\"true\" size={14} /> : null}\n      {note.tone === \"private\" ? <EyeOff aria-hidden=\"true\" size={14} /> : null}\n      <span>\n        {note.tone === \"refused\" ? note.text : `Unbound. ${note.text}`}\n      </span>\n    </p>\n  );\n}\n\n/**\n * What an unbind kept, said as the author reads it: the block keeps what\n * visitors saw, the fallback, or its own value. The answer's own reason\n * says more, for an API client; the note says what changed on the page.\n */\nexport function noteFor(\n  answer: UnbindAnswer,\n  blockLabel: string,\n  propName: string,\n  /** The bound field, named as the chip names it. */\n  fieldName: string,\n  /** The block's label for the prop an image's address went into. */\n  intoLabel?: string\n): string {\n  const block = `The ${blockLabel.toLowerCase()}`;\n  const value =\n    typeof answer.value === \"string\" && answer.value !== \"\"\n      ? `: “${answer.value}”`\n      : \"\";\n  // A field visitors can't read: its value was never copied in, and the note\n  // says so before what was kept in its place. Said first, since what was\n  // kept matters less than that the field is private.\n  if (answer.unreadable === true) {\n    const unread = `Visitors can't read “${fieldName}”, so its value wasn't copied in.`;\n    return answer.kept === \"fallback\"\n      ? `${unread} ${block} keeps the fallback${value}.`\n      : `${unread} ${block} keeps its own ${propName.toLowerCase()}.`;\n  }\n  // A link's entry kept by reference: the link goes on to the page visitors\n  // were sent to, named by its title where a visitor may read it, never by\n  // the id the prop now holds.\n  if (answer.entry !== undefined) {\n    const title = answer.entry.title;\n    const page =\n      title === undefined ? \"the page visitors saw\" : `${title}'s page`;\n    return `The link keeps going to ${page}.`;\n  }\n  // An image kept by its address goes to another prop than the one unbound,\n  // which is left empty, so the note names where the address went.\n  if (answer.into !== undefined) {\n    const into = intoLabel ?? fieldLabel(answer.into);\n    switch (answer.kept) {\n      case \"visitor\":\n        return `Visitors saw an image address, not a library image, so it's kept in ${into}.`;\n      // The fallback is said where it is what visitors saw: the binding's\n      // own address, not one the field gave.\n      case \"fallback\":\n        return `Visitors saw the fallback's image address, so it's kept in ${into}.`;\n      default:\n        return `The image address given is kept in ${into}.`;\n    }\n  }\n  switch (answer.kept) {\n    case \"visitor\":\n      return `${block} keeps what visitors saw${value}.`;\n    case \"fallback\":\n      return `Visitors saw the fallback, so ${block.toLowerCase()} keeps it${value}.`;\n    case \"own\":\n      return `${block} keeps its own ${propName.toLowerCase()}.`;\n    default:\n      return `${block} keeps the value given${value}.`;\n  }\n}\n","\"use client\";\n\n/**\n * A bound image's Fallback: what visitors see when the bound field has no\n * picture to give.\n *\n * An image's fallback is either an image address (`https://…`, `http://…` or\n * a path on the site) or a media id, a file chosen from the media library:\n * the two values the engine draws an image fallback from. Read by the\n * engine's own reading of an image value (`imageValueOf`), so the row and a\n * visitor's page agree on which one is stored.\n *\n * - An address is typed into the row's field, and anything that is not one is\n *   held back with the reason, rather than saving a fallback the page would\n *   ignore. A stored address is shown with a small picture of it and the\n *   address itself, cut where the inspector is narrow; the whole of it is on\n *   the field's tooltip and in its accessible name.\n * - A media id is shown by its file's picture and name, read through the\n *   host's `readMedia`, never as the raw id, with a button that removes it.\n *\n * The library button in the row's actions opens a popover anchored on the\n * row: the newest images, a search by name, and \"Browse all…\" for the host's\n * full media dialog. An image address typed or pasted into its search is\n * offered as \"Use this address\", which is how an address replaces a file.\n * Every way of filling the row writes through `onFallback` alone: a media id\n * from the grid or the dialog, an address from the field or the search.\n *\n * @module image-binding-fallback\n */\nimport { imageValueOf, type Binding } from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@nextlyhq/ui\";\nimport { Images, Search, X } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport {\n  useMediaSummary,\n  type ContentServices,\n  type FoundMedia,\n  type MediaPickerProps,\n} from \"../inspector/content/content-controls\";\n\n/** What an image's Fallback row is given. */\nexport interface ImageBindingFallbackProps {\n  /** The image prop's binding, whose `fallback` the row shows and edits. */\n  readonly binding: Binding;\n  /** Store a fallback: an image address, a media id, or `\"\"` for none. */\n  readonly onFallback: (value: string) => void;\n  /**\n   * The host's services: the library search and dialog the row's library\n   * button opens, and the read that names a chosen file.\n   */\n  readonly services: ContentServices | undefined;\n  readonly disabled?: boolean;\n  /** The id of the prop's name, which the row is about. */\n  readonly describedBy?: string;\n  /**\n   * When the fallback is shown, as the library picker's hint says it:\n   * \"Shown when a post has no cover image.\" Plain words that fit every\n   * binding when absent.\n   */\n  readonly shownWhen?: string;\n}\n\n/** What the row says of a typed value that is not an image address. */\nconst NOT_AN_ADDRESS =\n  \"Enter an image address: one starting https:// or http://, or a path on this site such as /media/spring.jpg.\";\n\n/** The picker's hint where the binding's own words are not given. */\nconst SHOWN_WHEN = \"Shown when the bound field has no image.\";\n\n/** What the library button, its tooltip and the search are called. */\nconst CHOOSE_FROM_LIBRARY = \"Choose from library\";\n// The search takes an image address as well, so it says so where the author\n// types: the picker has no other place to paste one.\nconst FIND_IN_LIBRARY = \"Find an image, or paste an address\";\n\n/** How long the search waits after a keystroke before it asks the library. */\nconst SEARCH_DELAY_MS = 200;\n\n/** The picker's grid columns, which the up and down arrows move by. */\nconst COLUMNS = 3;\n\n/** How many empty tiles stand in for the images while they are read. */\nconst LOADING_TILES = 6;\n\n/**\n * Whether a value is an image address, by the engine's own reading of an\n * image value: the same one a visitor's page draws a fallback by.\n */\nfunction isImageAddress(value: string): boolean {\n  return imageValueOf(value)?.holds === \"address\";\n}\n\n/** The binding's fallback as text, or `\"\"` for none. */\nfunction storedFallback(binding: Binding): string {\n  return \"fallback\" in binding && typeof binding.fallback === \"string\"\n    ? binding.fallback\n    : \"\";\n}\n\n/** A stored fallback's media id, when it holds one rather than an address. */\nfunction storedMediaId(stored: string): string | undefined {\n  const read = imageValueOf(stored);\n  return read?.holds === \"media\" ? read.value : undefined;\n}\n\n/** A found image as the picker names it: its file, else its alt text. */\nfunction mediaLabel(media: FoundMedia): string {\n  return media.name ?? media.alt ?? \"Untitled image\";\n}\n\n/** A bound image's Fallback row. */\nexport function ImageBindingFallback({\n  binding,\n  onFallback,\n  services,\n  disabled = false,\n  describedBy,\n  shownWhen = SHOWN_WHEN,\n}: ImageBindingFallbackProps): React.JSX.Element {\n  const id = React.useId();\n  const errorId = React.useId();\n  const stored = storedFallback(binding);\n  const mediaId = storedMediaId(stored);\n  const [refusal, setRefusal] = React.useState(false);\n  // The library popover, and the host's full dialog, each while open.\n  const [picking, setPicking] = React.useState(false);\n  const [browsing, setBrowsing] = React.useState(false);\n  const focusAddress = useFocusAfterRemove(id, mediaId);\n  const searchMedia = services?.searchMedia;\n  const Picker = services?.MediaPicker;\n  // A pick of the value already stored writes nothing, so it adds no edit\n  // to the history.\n  // A refusal said of a typed address goes with any pick: the row now holds\n  // the chosen file or address, which the refusal was not about.\n  const choose = (value: string): void => {\n    setRefusal(false);\n    if (value !== stored) onFallback(value);\n  };\n  const openDialog = (): void => {\n    setPicking(false);\n    setBrowsing(true);\n  };\n  const libraryButton = (\n    <LibraryButton\n      searchable={searchMedia !== undefined}\n      dialog={Picker !== undefined}\n      open={picking}\n      disabled={disabled}\n      onDialog={openDialog}\n    />\n  );\n\n  return (\n    <div className=\"nx-binding__fallback nx-image-fallback\">\n      <FallbackLabel id={id} fromLibrary={mediaId !== undefined} />\n      <Popover open={picking} onOpenChange={setPicking}>\n        {/* The popover opens under the whole row, not the small button. */}\n        <PopoverAnchor asChild>\n          <div className=\"nx-image-fallback__value\">\n            {mediaId === undefined ? (\n              <AddressField\n                id={id}\n                errorId={errorId}\n                stored={stored}\n                disabled={disabled}\n                describedBy={describedBy}\n                refusal={refusal}\n                onRefusal={setRefusal}\n                onFallback={onFallback}\n              />\n            ) : (\n              <LibraryFallback\n                mediaId={mediaId}\n                read={services?.readMedia}\n                disabled={disabled}\n                describedBy={describedBy}\n                onRemove={() => {\n                  focusAddress.current = true;\n                  onFallback(\"\");\n                }}\n                // Inside the file's box, beside Remove: the name gets the\n                // width the button would take beside it.\n                libraryButton={libraryButton}\n              />\n            )}\n            {/* The row's other way to fill it: the media library. Not drawn\n                while empty, nor beside a chosen file, whose box holds it. */}\n            <div\n              className=\"nx-image-fallback__actions\"\n              data-fallback-actions=\"\"\n            >\n              {mediaId === undefined ? libraryButton : null}\n            </div>\n          </div>\n        </PopoverAnchor>\n        {searchMedia === undefined ? null : (\n          <PopoverContent\n            align=\"end\"\n            className=\"nx-binding-popover nx-library-pick\"\n          >\n            <LibraryPicker\n              search={searchMedia}\n              current={stored.trim()}\n              shownWhen={shownWhen}\n              onPick={value => {\n                setPicking(false);\n                choose(value);\n              }}\n              onBrowse={Picker === undefined ? undefined : openDialog}\n            />\n          </PopoverContent>\n        )}\n      </Popover>\n      <BrowseDialog\n        Picker={browsing ? Picker : undefined}\n        mediaId={mediaId}\n        onOpenChange={setBrowsing}\n        onChoose={choose}\n      />\n      {refusal ? (\n        <p className=\"nx-inspector__error\" id={errorId} role=\"alert\">\n          {NOT_AN_ADDRESS}\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * A flag Remove sets, so the address field drawn in the file's place takes\n * focus rather than leaving it on a button that is gone.\n */\nfunction useFocusAfterRemove(\n  id: string,\n  mediaId: string | undefined\n): React.MutableRefObject<boolean> {\n  const focusAddress = React.useRef(false);\n  React.useEffect(() => {\n    if (mediaId !== undefined || !focusAddress.current) return;\n    focusAddress.current = false;\n    document.getElementById(id)?.focus();\n  }, [mediaId, id]);\n  return focusAddress;\n}\n\n/**\n * The row's name: the address field's label, or, beside a library file whose\n * group carries \"Fallback\" in its own name, a word not read twice.\n */\nfunction FallbackLabel({\n  id,\n  fromLibrary,\n}: {\n  id: string;\n  fromLibrary: boolean;\n}): React.JSX.Element {\n  return fromLibrary ? (\n    <span className=\"nx-binding__fallback-label\" aria-hidden=\"true\">\n      Fallback\n    </span>\n  ) : (\n    <label className=\"nx-binding__fallback-label\" htmlFor={id}>\n      Fallback\n    </label>\n  );\n}\n\n/**\n * The address field, with a small picture of a stored address inside its\n * start. A typed value is committed on Enter or on leaving the field, and one\n * that is not an image address is held back, `refusal` said under the row.\n */\nfunction AddressField({\n  id,\n  errorId,\n  stored,\n  disabled,\n  describedBy,\n  refusal,\n  onRefusal,\n  onFallback,\n}: {\n  id: string;\n  errorId: string;\n  stored: string;\n  disabled: boolean;\n  describedBy: string | undefined;\n  refusal: boolean;\n  onRefusal: (refused: boolean) => void;\n  onFallback: (value: string) => void;\n}): React.JSX.Element {\n  // The address whose picture would not load, so a broken one draws no\n  // empty frame; another address is tried afresh.\n  const [broken, setBroken] = React.useState<string>();\n  const pictured = isImageAddress(stored) && broken !== stored;\n  const commit = (typed: string): void => {\n    const next = typed.trim();\n    // Held back rather than saved: the field takes an image address only,\n    // and a media id is chosen from the library, never typed.\n    const refused = next !== stored && next !== \"\" && !isImageAddress(next);\n    onRefusal(refused);\n    if (!refused && next !== stored) onFallback(next);\n  };\n  const described = [describedBy, refusal ? errorId : undefined]\n    .filter(Boolean)\n    .join(\" \");\n  const whole = stored === \"\" ? undefined : `Fallback: ${stored}`;\n  return (\n    <div\n      className=\"nx-image-fallback__address\"\n      data-pictured={pictured ? \"\" : undefined}\n    >\n      {pictured ? (\n        // Decorative: the address beside it says which picture it is.\n        <img\n          className=\"nx-image-fallback__thumb\"\n          src={stored}\n          alt=\"\"\n          loading=\"lazy\"\n          decoding=\"async\"\n          referrerPolicy=\"no-referrer\"\n          onError={() => setBroken(stored)}\n        />\n      ) : null}\n      <Input\n        id={id}\n        // Remounted for a fallback changed elsewhere (an undo, the library),\n        // so the field never shows a stale address.\n        key={stored}\n        defaultValue={stored}\n        placeholder=\"https://… or /media/…\"\n        spellCheck={false}\n        disabled={disabled}\n        // The whole address, which the field cuts where it is narrow.\n        title={whole}\n        aria-label={whole}\n        aria-invalid={refusal ? true : undefined}\n        aria-describedby={described === \"\" ? undefined : described}\n        onChange={() => {\n          if (refusal) onRefusal(false);\n        }}\n        onBlur={event => commit(event.currentTarget.value)}\n        onKeyDown={event => {\n          if (event.key !== \"Enter\") return;\n          event.preventDefault();\n          commit(event.currentTarget.value);\n        }}\n      />\n    </div>\n  );\n}\n\n/**\n * The library button: the popover's trigger where the host can search the\n * library, else straight to its dialog, else none, so nothing is offered\n * that does nothing.\n */\nfunction LibraryButton({\n  searchable,\n  dialog,\n  open,\n  disabled,\n  onDialog,\n}: {\n  searchable: boolean;\n  dialog: boolean;\n  open: boolean;\n  disabled: boolean;\n  onDialog: () => void;\n}): React.JSX.Element | null {\n  if (!searchable && !dialog) return null;\n  const button = (\n    <button\n      type=\"button\"\n      className=\"nx-image-fallback__library\"\n      aria-label={CHOOSE_FROM_LIBRARY}\n      title={CHOOSE_FROM_LIBRARY}\n      disabled={disabled}\n      data-open={open ? \"\" : undefined}\n      onClick={searchable ? undefined : onDialog}\n    >\n      <Images aria-hidden=\"true\" size={14} />\n    </button>\n  );\n  return searchable ? (\n    <PopoverTrigger asChild>{button}</PopoverTrigger>\n  ) : (\n    button\n  );\n}\n\n/**\n * The host's full media dialog, images only. Given a `Picker` only while\n * open, so each opening starts from what the row stores now rather than from\n * the dialog's last choice.\n */\nfunction BrowseDialog({\n  Picker,\n  mediaId,\n  onOpenChange,\n  onChoose,\n}: {\n  Picker: React.ComponentType<MediaPickerProps> | undefined;\n  mediaId: string | undefined;\n  onOpenChange: (open: boolean) => void;\n  onChoose: (mediaId: string) => void;\n}): React.JSX.Element | null {\n  if (Picker === undefined) return null;\n  return (\n    <Picker\n      open\n      onOpenChange={onOpenChange}\n      title=\"Choose a fallback image\"\n      accept=\"image/*\"\n      initialSelectedIds={new Set(mediaId === undefined ? [] : [mediaId])}\n      onSelect={media => {\n        const first = media[0];\n        // Closed here: the dialog leaves closing to whoever opened it.\n        onOpenChange(false);\n        if (first !== undefined) onChoose(first.id);\n      }}\n    />\n  );\n}\n\n/**\n * A fallback chosen from the library, in the address field's place: the\n * file's picture and name as the host reads them by its id, never the id. A\n * neutral picture and \"Library image\" while it is read (or where the host\n * reads none), and a plain sentence for a file the library no longer has.\n */\nfunction LibraryFallback({\n  mediaId,\n  read,\n  disabled,\n  describedBy,\n  onRemove,\n  libraryButton,\n}: {\n  mediaId: string;\n  read: ContentServices[\"readMedia\"];\n  disabled: boolean;\n  describedBy: string | undefined;\n  onRemove: () => void;\n  /** The way to choose another file, drawn at the box's end. */\n  libraryButton: React.ReactNode;\n}): React.JSX.Element {\n  const summary = useMediaSummary(read, mediaId);\n  const name =\n    summary === null\n      ? // A read that answers nothing may be a file removed or a read that\n        // failed for now: the row says neither, only that it can't be shown.\n        \"A library image that can't be shown\"\n      : (summary?.name ?? summary?.alt ?? \"Library image\");\n  const label = `Fallback: ${name}`;\n  return (\n    <div\n      className=\"nx-image-fallback__media\"\n      role=\"group\"\n      aria-label={label}\n      aria-describedby={describedBy}\n      title={label}\n      data-missing={summary === null ? \"\" : undefined}\n    >\n      {summary?.thumbnail === undefined ? (\n        <span\n          className=\"nx-image-fallback__media-thumb\"\n          data-neutral=\"\"\n          aria-hidden=\"true\"\n        />\n      ) : (\n        // Decorative: the name beside it says which file it is.\n        <img\n          className=\"nx-image-fallback__media-thumb\"\n          src={summary.thumbnail}\n          alt=\"\"\n          loading=\"lazy\"\n          decoding=\"async\"\n        />\n      )}\n      <MiddleCut text={name} className=\"nx-image-fallback__media-name\" />\n      <button\n        type=\"button\"\n        className=\"nx-image-fallback__clear\"\n        aria-label=\"Remove fallback\"\n        title=\"Remove fallback\"\n        disabled={disabled}\n        onClick={onRemove}\n      >\n        <X aria-hidden=\"true\" size={12} />\n      </button>\n      {libraryButton}\n    </div>\n  );\n}\n\n/** How many letters before a file's extension stay whole with it. */\nconst KEPT_BEFORE_EXTENSION = 3;\n/** The longest ending read as an extension (\".webp\" and its dot is 5). */\nconst LONGEST_EXTENSION = 6;\n\n/**\n * A text's graphemes, as the platform segments them; by code point where it\n * has no segmenter, which at least never splits a character in two.\n */\nfunction graphemesOf(text: string): string[] {\n  if (typeof Intl.Segmenter !== \"function\") return Array.from(text);\n  const segments = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n  return Array.from(segments.segment(text), part => part.segment);\n}\n\n/**\n * A file name split into the start that may be cut and the end kept whole:\n * its extension and the few characters before it, or its last few where it\n * has no extension; `undefined` for a name too short to cut, whose start\n * would be all but gone. Counted in graphemes, the characters a reader sees,\n * so neither an emoji nor a sequence joined into one (a family emoji, a\n * letter with its accent) is split across the ellipsis.\n */\nfunction splitForCut(\n  name: string\n): { readonly head: string; readonly tail: string } | undefined {\n  const chars = graphemesOf(name);\n  const dot = chars.lastIndexOf(\".\");\n  const at =\n    dot > 0 && chars.length - dot <= LONGEST_EXTENSION\n      ? Math.max(0, dot - KEPT_BEFORE_EXTENSION)\n      : chars.length - LONGEST_EXTENSION;\n  if (at <= KEPT_BEFORE_EXTENSION) return undefined;\n  return { head: chars.slice(0, at).join(\"\"), tail: chars.slice(at).join(\"\") };\n}\n\n/**\n * A file name cut in its middle where it is drawn narrow, its start and its\n * end kept (\"spring-ba…ner.jpg\"): the one chosen file is told by its start,\n * and the end carries the extension. The start shrinks with an ellipsis; the end\n * is never cut. The whole name is on the tooltip and in the accessible name\n * of what holds it, so this is hidden from assistive technology.\n */\nfunction MiddleCut({\n  text,\n  className,\n}: {\n  text: string;\n  className: string;\n}): React.JSX.Element {\n  const split = splitForCut(text);\n  return (\n    <span className={`${className} nx-middle-cut`} aria-hidden=\"true\">\n      <span className=\"nx-middle-cut__head\">{split?.head ?? text}</span>\n      {split === undefined ? null : (\n        <span className=\"nx-middle-cut__tail\">{split.tail}</span>\n      )}\n    </span>\n  );\n}\n\n/** One choice in the picker: an address typed into the search, or a file. */\ntype PickOption =\n  | { readonly kind: \"address\"; readonly value: string; readonly label: string }\n  | {\n      readonly kind: \"media\";\n      readonly value: string;\n      readonly label: string;\n      readonly media: FoundMedia;\n    };\n\n/** Where the library's answer to the current search stands. */\ntype Found =\n  | { readonly state: \"loading\" }\n  | { readonly state: \"ready\"; readonly items: readonly FoundMedia[] }\n  | { readonly state: \"failed\" };\n\n/**\n * The option an arrow key moves to in a grid of `COLUMNS`, from `at`, with\n * `last` the last option's index; `undefined` for a key that is not a move.\n * Down from the last row's start goes to the last option, so a short last\n * row is still reached.\n */\nfunction movedTo(key: string, at: number, last: number): number | undefined {\n  switch (key) {\n    case \"ArrowRight\":\n      return Math.min(at + 1, last);\n    case \"ArrowLeft\":\n      return Math.max(at - 1, 0);\n    case \"ArrowDown\":\n      return Math.min(at + COLUMNS, last);\n    case \"ArrowUp\":\n      return at - COLUMNS < 0 ? at : at - COLUMNS;\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Where an arrow key moves the active option, or `undefined` where the key\n * is left to the search: an address being edited keeps its arrows for the\n * caret, and so does a modified arrow, which selects text.\n */\nfunction gridMove(\n  event: React.KeyboardEvent,\n  at: number,\n  count: number,\n  editingAddress: boolean\n): number | undefined {\n  const modified =\n    event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;\n  if (editingAddress || modified || count === 0) return undefined;\n  return movedTo(event.key, at, count - 1);\n}\n\n/** The image address the search holds, when it holds one. */\nfunction addressIn(query: string): string | undefined {\n  const read = imageValueOf(query);\n  return read?.holds === \"address\" ? read.value : undefined;\n}\n\n/**\n * What the picker offers: an address in the search as itself, else the\n * images the library found for it.\n */\nfunction pickOptions(\n  address: string | undefined,\n  found: Found\n): readonly PickOption[] {\n  if (address !== undefined) {\n    return [{ kind: \"address\", value: address, label: \"Use this address\" }];\n  }\n  if (found.state !== \"ready\") return [];\n  return found.items.map(media => ({\n    kind: \"media\",\n    value: media.id,\n    label: mediaLabel(media),\n    media,\n  }));\n}\n\n/**\n * What the picker says in place of images: that the library could not be\n * read, or that the search found none, with what was searched.\n */\nfunction pickerMessage(\n  address: string | undefined,\n  found: Found,\n  wanted: string\n): { readonly role: \"alert\" | \"status\"; readonly text: string } | null {\n  if (address !== undefined) return null;\n  if (found.state === \"failed\") {\n    return { role: \"alert\", text: \"Couldn't read the media library.\" };\n  }\n  if (found.state !== \"ready\" || found.items.length > 0) return null;\n  return {\n    role: \"status\",\n    text:\n      wanted === \"\"\n        ? \"The media library has no images yet.\"\n        : `No images match “${wanted}”.`,\n  };\n}\n\n/**\n * The library's answer to `query`: the first, the newest images, asked at\n * once, and a later one after a pause in typing, each aborting the one\n * before it so an older answer never lands over a newer one. Nothing is\n * asked while the search holds an image address.\n */\nfunction useLibrarySearch(\n  search: NonNullable<ContentServices[\"searchMedia\"]>,\n  query: string,\n  address: string | undefined\n): Found {\n  const [found, setFound] = React.useState<Found>({ state: \"loading\" });\n  const asked = React.useRef(false);\n  React.useEffect(() => {\n    if (address !== undefined) return;\n    const controller = new AbortController();\n    const settle = (next: Found): void => {\n      if (!controller.signal.aborted) setFound(next);\n    };\n    const timer = window.setTimeout(\n      () => {\n        setFound({ state: \"loading\" });\n        void search(query.trim(), controller.signal).then(\n          items => settle({ state: \"ready\", items }),\n          () => settle({ state: \"failed\" })\n        );\n      },\n      asked.current ? SEARCH_DELAY_MS : 0\n    );\n    asked.current = true;\n    return () => {\n      window.clearTimeout(timer);\n      controller.abort();\n    };\n  }, [search, query, address]);\n  return found;\n}\n\n/**\n * The library picker inside the popover: a search, a grid of the images it\n * finds, and a hint with the way to the host's full dialog.\n *\n * Focus stays in the search, and the active option is named by\n * `aria-activedescendant`, so typing keeps working while the arrows move\n * through the grid, as the inspector's other pickers do. The file the row\n * stores is marked selected.\n */\nfunction LibraryPicker({\n  search,\n  current,\n  shownWhen,\n  onPick,\n  onBrowse,\n}: {\n  search: NonNullable<ContentServices[\"searchMedia\"]>;\n  /** The stored fallback, marked where the grid shows it. */\n  current: string;\n  shownWhen: string;\n  /** A media id or an image address chosen. */\n  onPick: (value: string) => void;\n  /** Close the popover and open the host's dialog; absent without one. */\n  onBrowse: (() => void) | undefined;\n}): React.JSX.Element {\n  const listId = React.useId();\n  const input = React.useRef<HTMLInputElement>(null);\n  const [query, setQuery] = React.useState(\"\");\n  const [active, setActive] = React.useState(0);\n  // Whether the arrows have moved the active option since the search last\n  // changed: its ring is drawn only then, so the first tile does not read as\n  // the chosen one before the author has moved to it.\n  const [keyed, setKeyed] = React.useState(false);\n  // An image address in the search is offered as itself; the library is not\n  // searched for one, since no file is named like an address.\n  const address = addressIn(query);\n  const found = useLibrarySearch(search, query, address);\n  const options = pickOptions(address, found);\n  const at = Math.min(active, options.length - 1);\n  const activeOption = options[at];\n  const optionId = (index: number): string => `${listId}-option-${index}`;\n  const message = pickerMessage(address, found, query.trim());\n  const loading = address === undefined && found.state === \"loading\";\n\n  React.useEffect(() => {\n    input.current?.focus();\n  }, []);\n\n  // Focus stays in the search, so the browser scrolls nothing as the arrows\n  // move: the grid is scrolled to the option they moved to, or a row below\n  // the fold could be picked unseen.\n  React.useEffect(() => {\n    if (!keyed) return;\n    document\n      .getElementById(`${listId}-option-${at}`)\n      ?.scrollIntoView?.({ block: \"nearest\" });\n  }, [keyed, at, listId]);\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>): void => {\n    if (event.key === \"Enter\" && activeOption !== undefined) {\n      event.preventDefault();\n      onPick(activeOption.value);\n      return;\n    }\n    const next = gridMove(event, at, options.length, address !== undefined);\n    if (next === undefined) return;\n    event.preventDefault();\n    setActive(next);\n    setKeyed(true);\n  };\n\n  return (\n    <div className=\"nx-library-pick__body\">\n      <div className=\"nx-library-pick__search\">\n        <Search aria-hidden=\"true\" size={14} />\n        <Input\n          ref={input}\n          type=\"search\"\n          role=\"combobox\"\n          aria-label={FIND_IN_LIBRARY}\n          aria-controls={listId}\n          aria-expanded=\"true\"\n          aria-autocomplete=\"list\"\n          aria-activedescendant={\n            activeOption === undefined ? undefined : optionId(at)\n          }\n          placeholder={FIND_IN_LIBRARY}\n          spellCheck={false}\n          autoComplete=\"off\"\n          value={query}\n          onChange={event => {\n            setQuery(event.target.value);\n            setActive(0);\n            setKeyed(false);\n          }}\n          onKeyDown={onKeyDown}\n        />\n      </div>\n      <div\n        id={listId}\n        role=\"listbox\"\n        aria-label=\"Images in the media library\"\n        aria-busy={loading}\n        className=\"nx-library-pick__grid\"\n      >\n        {loading ? (\n          <LoadingTiles />\n        ) : (\n          options.map((option, index) => (\n            <PickerOption\n              key={`${option.kind}:${option.value}`}\n              id={optionId(index)}\n              option={option}\n              selected={option.value === current}\n              // An address offered is the one option, which Enter takes\n              // whatever the arrows did; a tile is ringed once they move.\n              active={index === at && (keyed || option.kind === \"address\")}\n              onActive={() => setActive(index)}\n              onPick={() => onPick(option.value)}\n            />\n          ))\n        )}\n      </div>\n      {message === null ? null : (\n        <p className=\"nx-library-pick__note\" role={message.role}>\n          {message.text}\n        </p>\n      )}\n      <div className=\"nx-library-pick__foot\">\n        <p className=\"nx-library-pick__hint\">{shownWhen}</p>\n        {onBrowse === undefined ? null : (\n          <button\n            type=\"button\"\n            className=\"nx-library-pick__browse\"\n            onClick={onBrowse}\n          >\n            Browse all…\n          </button>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/** Empty tiles standing in for the images while they are read. */\nfunction LoadingTiles(): React.JSX.Element {\n  return (\n    <>\n      {Array.from({ length: LOADING_TILES }, (_, index) => (\n        <span\n          key={index}\n          className=\"nx-library-pick__tile\"\n          data-loading=\"\"\n          aria-hidden=\"true\"\n        />\n      ))}\n    </>\n  );\n}\n\n/**\n * One option of the grid: a file's tile, or the search's address across the\n * grid. Pressed, it is picked; hovered, it is the active one.\n */\nfunction PickerOption({\n  id,\n  option,\n  selected,\n  active,\n  onActive,\n  onPick,\n}: {\n  id: string;\n  option: PickOption;\n  selected: boolean;\n  active: boolean;\n  onActive: () => void;\n  onPick: () => void;\n}): React.JSX.Element {\n  const isAddress = option.kind === \"address\";\n  return (\n    <div\n      id={id}\n      role=\"option\"\n      aria-selected={selected}\n      // A tile's caption is drawn cut and hidden from assistive technology,\n      // so the tile carries its whole name itself.\n      aria-label={isAddress ? undefined : option.label}\n      data-active={active ? \"\" : undefined}\n      className={\n        isAddress ? \"nx-library-pick__address\" : \"nx-library-pick__tile\"\n      }\n      title={isAddress ? `Use this address: ${option.value}` : option.label}\n      // Focus stays in the search, where typing goes.\n      onMouseDown={event => event.preventDefault()}\n      onMouseMove={onActive}\n      onClick={onPick}\n    >\n      {option.kind === \"address\" ? (\n        <AddressOption address={option.value} />\n      ) : (\n        <TileContent media={option.media} label={option.label} />\n      )}\n    </div>\n  );\n}\n\n/** A file's tile: its picture, with its name captioned over the foot. */\nfunction TileContent({\n  media,\n  label,\n}: {\n  media: FoundMedia;\n  label: string;\n}): React.JSX.Element {\n  return (\n    <>\n      {media.thumbnail === undefined ? (\n        <span\n          className=\"nx-library-pick__image\"\n          data-neutral=\"\"\n          aria-hidden=\"true\"\n        />\n      ) : (\n        // Decorative: the caption names it, and is the option's name.\n        <img\n          className=\"nx-library-pick__image\"\n          src={media.thumbnail}\n          alt=\"\"\n          loading=\"lazy\"\n          decoding=\"async\"\n        />\n      )}\n      {/* Cut at its end, its start kept: tiles side by side are told apart by\n          how their names begin, and many end alike (\"-final.png\"). The whole\n          name is the tile's own label and tooltip. */}\n      <span className=\"nx-library-pick__caption\" aria-hidden=\"true\">\n        {label}\n      </span>\n    </>\n  );\n}\n\n/**\n * The search's address offered as the fallback: a small picture of it, where\n * it loads, beside \"Use this address\" and the address itself.\n */\nfunction AddressOption({ address }: { address: string }): React.JSX.Element {\n  // The address whose picture would not load, so it draws no broken frame.\n  const [broken, setBroken] = React.useState<string>();\n  return (\n    <>\n      {broken === address ? (\n        <span\n          className=\"nx-library-pick__address-thumb\"\n          data-neutral=\"\"\n          aria-hidden=\"true\"\n        />\n      ) : (\n        // Decorative: the words beside it say what it is.\n        <img\n          className=\"nx-library-pick__address-thumb\"\n          src={address}\n          alt=\"\"\n          decoding=\"async\"\n          referrerPolicy=\"no-referrer\"\n          onError={() => setBroken(address)}\n        />\n      )}\n      <span className=\"nx-library-pick__address-text\">\n        <span>Use this address</span>\n        <small>{address}</small>\n      </span>\n    </>\n  );\n}\n","/**\n * The inspector's binding controls for one prop: a bind button beside a\n * bindable field, the picker it opens, and, once the prop is bound, a chip\n * naming the field, its fallback, and a menu to change the field or unbind.\n *\n * The picker lists only the fields that fit the prop, by the engine's own\n * rule (`canBindFieldToProp`), from what the host reads for the person\n * editing (`ContentServices.listBindingFields`), and, for a block inside a\n * collection list, the list item's own fields first, with their values from\n * the list's first entry (`readListSample`): fields visitors may not read say\n * so, and a draft's value is shown with \"Draft\" beside it, in each option's\n * own text, so a screen reader announces both. An unbind is planned by the\n * host, by the decision the page actions API takes, and applied here as any\n * edit; the reason it gives is said under the field.\n *\n * This module holds the bind button and the bound field with its chip, menu,\n * fallback and values, and is the entry for the rest: the picker is in\n * `binding-picker.tsx`, the names a bound prop is said by in\n * `binding-bound-names.ts`, and the note an unbind leaves in\n * `binding-notes.tsx`.\n *\n * @module binding-controls\n */\nimport {\n  bindablePropKind,\n  findNode,\n  followsSetting,\n  getBlock,\n  sameJsonValue,\n  type Binding,\n  type BindingFormat,\n  type BlockDocument,\n  type BuilderOp,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n  Input,\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n  PopoverTrigger,\n  Textarea,\n} from \"@nextlyhq/ui\";\nimport { ChevronDown, Database, ExternalLink, Unlink } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { UnbindAnswer } from \"../composition-actions\";\nimport type { ContentServices } from \"../inspector/content/content-controls\";\nimport { propLabel, type EditableProp } from \"../inspector/inspector\";\n\nimport {\n  boundField,\n  boundNames,\n  boundSource,\n  useBoundFrom,\n} from \"./binding-bound-names\";\nimport { BindingFormatField, offersFormat } from \"./binding-format-field\";\nimport { noteFor, type UnbindNote, UnboundNote } from \"./binding-notes\";\nimport { bindOp, unbindOp } from \"./binding-ops\";\nimport {\n  BindingPicker,\n  clearHeld,\n  type EntryLink,\n  type NamedField,\n  pickOp,\n} from \"./binding-picker\";\nimport type {\n  BindingFieldSource,\n  UnbindAsk,\n  UnbindPlanAnswer,\n} from \"./binding-services\";\nimport { ImageBindingFallback } from \"./image-binding-fallback\";\nimport type { ItemSource } from \"./item-binding-source\";\n\n// The picker, the names a bound prop is said by and the notes under a field\n// live in modules of their own beside the controls; every name this module\n// exported still is.\nexport { useBoundFieldOf } from \"./binding-bound-names\";\n\n/** The binding with `fallback` as its fallback; none when it is empty. */\nfunction withFallback(binding: Binding, fallback: string): Binding {\n  const rest = Object.fromEntries(\n    Object.entries(binding).filter(([key]) => key !== \"fallback\")\n  );\n  return (fallback === \"\" ? rest : { ...rest, fallback }) as Binding;\n}\n\n/** The binding with `format` as its format, through the same write as a fallback. */\nfunction withFormat(binding: Binding, format: BindingFormat): Binding {\n  return { ...binding, format };\n}\n\n/** What the bound and bindable rows are handed. */\nexport interface BindingControlProps {\n  readonly nodeId: string;\n  readonly prop: EditableProp;\n  /** The block's name as the panel shows it: \"Heading\". */\n  readonly blockLabel: string;\n  /** The prop's binding, when it has one. */\n  readonly binding: Binding | undefined;\n  /** The document the block is in, which an op is planned against. */\n  readonly document: BlockDocument;\n  readonly services: ContentServices | undefined;\n  readonly disabled: boolean;\n  /** Apply one op as an edit; `false` where the editor refused it. */\n  readonly onApply: (op: BuilderOp) => boolean;\n  /**\n   * Props emptied in the same edit as a bind: what would win over the bound\n   * prop, such as a button's entry reference over its address.\n   */\n  readonly clearsOnBind?: readonly string[] | undefined;\n  /**\n   * Those of `clearsOnBind` that may not be written where the block sits: a\n   * bind or a change of field that would empty one is held.\n   */\n  readonly clearsLocked?: readonly string[] | undefined;\n  /**\n   * Where the prop is a link's destination, or its bound entry id: the\n   * link's props. The picker then offers the entries a relation names, and a\n   * pick of one binds the link's entry (see `pickOp`).\n   */\n  readonly entryLink?: EntryLink | undefined;\n  /** The prop's own control, drawn while it is not bound. */\n  readonly children: React.ReactNode;\n}\n\n/**\n * A prop's row with its binding controls: the field and a bind button while\n * unbound, a chip with its fallback once bound. A prop no field can fill, or\n * a host that reads no fields, draws the field alone.\n */\nexport function BindableField(props: BindingControlProps): React.JSX.Element {\n  const { prop, binding, services, children } = props;\n  // The note an unbind leaves under the field: kept until the next one.\n  const [note, setNote] = React.useState<UnbindNote | null>(null);\n  const bindable =\n    bindablePropKind(prop.schema) !== undefined &&\n    services?.listBindingFields !== undefined;\n  if (binding !== undefined) {\n    return <BoundField {...props} binding={binding} onUnbound={setNote} />;\n  }\n  // No bind button where no field can fill it or none are listed; an\n  // unbind's note is still said.\n  if (!bindable) {\n    return (\n      <>\n        {children}\n        {note === null ? null : <UnboundNote note={note} />}\n      </>\n    );\n  }\n  return (\n    <div className=\"nx-binding-row\">\n      <div className=\"nx-binding-row__field\">{children}</div>\n      <BindButton\n        {...props}\n        onBound={() => setNote(null)}\n        onRefused={text => setNote({ text, tone: \"refused\" })}\n      />\n      {note === null ? null : <UnboundNote note={note} />}\n    </div>\n  );\n}\n\n/** The bind button and its picker. */\nfunction BindButton({\n  nodeId,\n  prop,\n  blockLabel,\n  document,\n  services,\n  disabled,\n  onApply,\n  clearsOnBind,\n  clearsLocked,\n  entryLink,\n  onBound,\n  onRefused,\n}: BindingControlProps & {\n  onBound: () => void;\n  onRefused: (reason: string) => void;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const name = propLabel(prop.name, prop.schema);\n  const trigger = React.useRef<HTMLButtonElement>(null);\n  // The inspector's fields, taken from the button before a pick replaces it\n  // with the chip: the picker is drawn in a portal, outside them. And the\n  // prop the pick bound, whose chip that is: a related entry binds the\n  // link's entry, not this prop.\n  const pickedIn = React.useRef<Element | null>(null);\n  const boundProp = React.useRef(prop.name);\n  return (\n    <Popover open={open} onOpenChange={setOpen}>\n      <PopoverTrigger asChild>\n        <button\n          ref={trigger}\n          type=\"button\"\n          className=\"nx-binding-row__bind\"\n          aria-label={`Bind ${name} to a field`}\n          title={`Bind ${name} to a field`}\n          disabled={disabled || clearHeld(document, nodeId, clearsLocked)}\n          data-open={open ? \"\" : undefined}\n        >\n          <Database aria-hidden=\"true\" size={14} />\n        </button>\n      </PopoverTrigger>\n      <PopoverContent\n        align=\"end\"\n        className=\"nx-binding-popover\"\n        // The bound chip replaces this button, so focus is handed to it once\n        // the pick has drawn it.\n        onCloseAutoFocus={event => {\n          const fields = pickedIn.current;\n          pickedIn.current = null;\n          if (fields === null) return;\n          event.preventDefault();\n          requestAnimationFrame(() => {\n            fields\n              .querySelector<HTMLElement>(\n                `[data-binding-chip=\"${CSS.escape(`${nodeId}:${boundProp.current}`)}\"]`\n              )\n              ?.focus();\n          });\n        }}\n      >\n        <BindingPicker\n          prop={prop}\n          blockLabel={blockLabel}\n          document={document}\n          nodeId={nodeId}\n          services={services}\n          current={undefined}\n          entryLink={entryLink}\n          onPick={picked => {\n            pickedIn.current =\n              trigger.current?.closest(\".nx-inspector__fields\") ?? null;\n            const { op, bound } = pickOp(\n              { document, nodeId, prop: prop.name, clearsOnBind, entryLink },\n              picked,\n              undefined\n            );\n            boundProp.current = bound;\n            setOpen(false);\n            if (op === null || !onApply(op)) {\n              pickedIn.current = null;\n              onRefused(EDIT_REFUSED);\n              return;\n            }\n            onBound();\n          }}\n        />\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/** The prop types whose value, and so whose fallback, is plain text. */\nconst TEXT_PROP_TYPES: ReadonlySet<string> = new Set([\n  \"text\",\n  \"textarea\",\n  \"url\",\n]);\n\n/**\n * The bindable kinds whose value is plain text: text, and a link or an\n * address (`url` and `link` props both bind as \"link\").\n */\nconst TEXT_KINDS: ReadonlySet<string> = new Set([\"text\", \"link\"]);\n\n/** Whether a prop's fallback is written as text: by its type or its kind. */\nfunction takesTextFallback(prop: EditableProp): boolean {\n  return (\n    TEXT_PROP_TYPES.has(prop.schema.type) ||\n    TEXT_KINDS.has(bindablePropKind(prop.schema) ?? \"\")\n  );\n}\n\n/** Said under a field where the editor refused the binding's edit. */\nconst EDIT_REFUSED = \"The page refused this edit, so nothing changed.\";\n\n/** What the block names a prop, for a note naming another prop than the bound one. */\nfunction blockPropLabel(\n  document: BlockDocument,\n  nodeId: string,\n  name: string | undefined\n): string | undefined {\n  if (name === undefined) return undefined;\n  const node = findNode(document.nodes, nodeId);\n  const schema =\n    node === undefined ? undefined : getBlock(node.type)?.props?.[name];\n  return schema === undefined ? undefined : propLabel(name, schema);\n}\n\n/**\n * The chip menu's way to the field's source: a link, so it opens as one, in a\n * new tab with the editor kept and no hold on this window. Named with the\n * field, so the item says whose source it opens.\n */\nfunction OpenSourceItem({\n  href,\n  field,\n}: {\n  href: string;\n  field: string;\n}): React.JSX.Element {\n  return (\n    <DropdownMenuItem asChild>\n      <a href={href} target=\"_blank\" rel=\"noopener noreferrer\">\n        <ExternalLink aria-hidden=\"true\" size={14} />\n        {`Open ${field}'s source`}\n      </a>\n    </DropdownMenuItem>\n  );\n}\n\n/**\n * When a bound image's fallback is shown, in the words of its source and\n * field: \"Shown when a post has no cover image.\" Said so only for one entry\n * of a collection (the page's own, or a list's item) and a field named in one\n * step; anywhere else, in the plain words that fit every binding.\n */\nfunction fallbackShownWhen(\n  binding: Binding,\n  sources: readonly BindingFieldSource[] | \"loading\" | \"failed\",\n  item: ItemSource | undefined,\n  field: string\n): string {\n  const found =\n    binding.source === undefined || binding.source === \"entry\"\n      ? boundSource(binding, sources)?.label.toLowerCase()\n      : undefined;\n  const one = item?.one ?? found;\n  // A path's names joined with \"›\" read badly inside a sentence.\n  if (one === undefined || field.includes(\"›\")) {\n    return \"Shown when the bound field has no image.\";\n  }\n  const article = /^[aeiou]/i.test(one) ? \"an\" : \"a\";\n  return `Shown when ${article} ${one} has no ${field.toLowerCase()}.`;\n}\n\n/**\n * A bound prop's rows under its chip, none for a binding following a\n * component's setting: composing fills it from the setting and drops it, so\n * neither a fallback nor a format it carried would ever show.\n */\nfunction BoundRows(\n  props: React.ComponentProps<typeof BoundValueRows>\n): React.JSX.Element | null {\n  return followsSetting(props.binding) ? null : <BoundValueRows {...props} />;\n}\n\n/** A bound prop's own rows under its chip: its Fallback, and its Format. */\nfunction BoundValueRows({\n  prop,\n  binding,\n  field,\n  shownWhen,\n  services,\n  disabled,\n  labelId,\n  textFallback,\n  onRebind,\n}: {\n  prop: EditableProp;\n  binding: Binding;\n  /** Whether a text fallback is offered where the prop's value is text. */\n  textFallback: boolean;\n  /** When an image's fallback is shown, said under its library picker. */\n  shownWhen: string;\n  /** The field the binding reads, once its source's fields are read. */\n  field: NamedField | undefined;\n  services: ContentServices | undefined;\n  disabled: boolean;\n  /** The id of the prop's name, which each row is about. */\n  labelId: string;\n  /** Write the binding with a new fallback or format. */\n  onRebind: (next: Binding) => void;\n}): React.JSX.Element {\n  const kind = bindablePropKind(prop.schema);\n  const fallback =\n    \"fallback\" in binding && typeof binding.fallback === \"string\"\n      ? binding.fallback\n      : \"\";\n  return (\n    <>\n      {kind === \"image\" ? (\n        // An image's fallback: an address with its picture shown, or a file\n        // chosen from the media library, shown by its name.\n        <ImageBindingFallback\n          binding={binding}\n          shownWhen={shownWhen}\n          services={services}\n          disabled={disabled}\n          describedBy={labelId}\n          onFallback={next => onRebind(withFallback(binding, next))}\n        />\n      ) : textFallback && takesTextFallback(prop) ? (\n        // A text input writes text: offered for a prop whose value is text\n        // alone, so a number's, a choice's or a passage's fallback is never\n        // rewritten.\n        <FallbackInput\n          describedBy={labelId}\n          fallback={fallback}\n          disabled={disabled}\n          // A long-text prop keeps its fallback's line breaks.\n          multiline={prop.schema.type === \"textarea\"}\n          onCommit={next => onRebind(withFallback(binding, next))}\n        />\n      ) : null}\n      {offersFormat(kind, field) ? (\n        <BindingFormatField\n          // Keyed by what the binding reads, so a rebind to another field\n          // starts the row afresh: a currency picked but not yet given a code\n          // belongs to the field it was picked for, not to the next one.\n          key={`${binding.source ?? \"\"}:${binding.sourceKey ?? \"\"}:${binding.$bind}`}\n          stored={binding.format}\n          kind={kind}\n          field={field}\n          disabled={disabled}\n          describedBy={labelId}\n          onFormat={format => onRebind(withFormat(binding, format))}\n        />\n      ) : null}\n    </>\n  );\n}\n\n/**\n * The unbind of a bound prop: planned by the host against the document the\n * editor holds, then applied to the document as it is when the plan comes\n * back, so an edit made meanwhile stays; refused where the binding changed\n * meanwhile, and said where the plan could not be read.\n */\nfunction useUnbind(args: {\n  readonly nodeId: string;\n  readonly prop: EditableProp;\n  readonly binding: Binding;\n  readonly document: BlockDocument;\n  readonly services: ContentServices | undefined;\n  /** Apply one op as an edit; `false` where the editor refused it. */\n  readonly onApply: (op: BuilderOp) => boolean;\n  readonly onUnbound: (note: UnbindNote) => void;\n  readonly onRefused: (reason: string) => void;\n  readonly note: (answer: UnbindAnswer) => string;\n}): () => Promise<void> {\n  // The document as the editor holds it now, read when a plan comes back.\n  const latest = React.useRef(args.document);\n  latest.current = args.document;\n  // Whether the field is still drawn, and an unbind still being planned: a\n  // plan answered after the field is gone (its prop already unbound) or a\n  // second one asked meanwhile is dropped, since neither can see the\n  // document as it is by then.\n  const mounted = React.useRef(true);\n  const pending = React.useRef(false);\n  React.useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n    };\n  }, []);\n  const { nodeId, prop, binding, services } = args;\n  // A plan's answer, applied to the document as it is now: refused where it\n  // is one, where the binding changed meanwhile, or where the editor refuses\n  // the edit.\n  const settle = (plan: UnbindPlanAnswer): void => {\n    if (\"refusal\" in plan) {\n      args.onRefused(plan.refusal);\n      return;\n    }\n    const now = latest.current;\n    const still = findNode(now.nodes, nodeId)?.bindings?.[prop.name];\n    if (!sameJsonValue(still, binding)) {\n      args.onRefused(\n        \"The binding changed while the unbind was planned. Unbind it again.\"\n      );\n      return;\n    }\n    const op = unbindOp(now, nodeId, prop.name, plan.kept);\n    if (op === null || !args.onApply(op)) {\n      args.onRefused(EDIT_REFUSED);\n      return;\n    }\n    args.onUnbound({\n      text: args.note(plan.answer),\n      tone: plan.answer.unreadable === true ? \"private\" : \"kept\",\n    });\n  };\n  return async () => {\n    if (pending.current) return;\n    pending.current = true;\n    const plan = await planOf(services, {\n      document: latest.current,\n      nodeId,\n      prop: prop.name,\n    }).finally(() => {\n      pending.current = false;\n    });\n    if (plan !== undefined && mounted.current) settle(plan);\n  };\n}\n\n/**\n * The host's plan for an unbind; a refusal saying so where the plan could\n * not be read, and nothing where the host plans no unbinds.\n */\nasync function planOf(\n  services: ContentServices | undefined,\n  ask: UnbindAsk\n): Promise<UnbindPlanAnswer | undefined> {\n  try {\n    return await services?.planUnbind?.(ask);\n  } catch {\n    return { refusal: \"The unbind could not be planned. Try again.\" };\n  }\n}\n\n/** A bound text prop's fallback, written when the field is left. */\nfunction FallbackInput({\n  describedBy,\n  fallback,\n  disabled,\n  multiline,\n  onCommit,\n}: {\n  describedBy: string;\n  fallback: string;\n  disabled: boolean;\n  /** A textarea prop's: a one-line input would drop its line breaks. */\n  multiline: boolean;\n  onCommit: (next: string) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  const field = {\n    id,\n    defaultValue: fallback,\n    disabled,\n    title: fallback === \"\" ? undefined : `Fallback: ${fallback}`,\n    \"aria-describedby\": describedBy,\n    onBlur: (\n      event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>\n    ) => {\n      const next = event.currentTarget.value;\n      if (next !== fallback) onCommit(next);\n    },\n  };\n  return (\n    <div className=\"nx-binding__fallback\">\n      <label className=\"nx-binding__fallback-label\" htmlFor={id}>\n        Fallback\n      </label>\n      {/* Keyed by the stored value, so a value written elsewhere is shown. */}\n      {multiline ? (\n        <Textarea key={fallback} {...field} rows={3} />\n      ) : (\n        <Input key={fallback} {...field} />\n      )}\n    </div>\n  );\n}\n\n/**\n * The bound chip: the field, then its source, cut source first where the\n * panel is narrow; the whole of both on its tooltip and in its name.\n */\nconst BoundChip = React.forwardRef<\n  HTMLButtonElement,\n  {\n    id: string;\n    label: string;\n    whole: string;\n    field: string;\n    source: string | undefined;\n    disabled: boolean;\n    /** Whether it opens a menu; without one it is a label, with no chevron. */\n    menu: boolean;\n  } & React.ButtonHTMLAttributes<HTMLButtonElement>\n>(function BoundChip(\n  { id, label, whole, field, source, disabled, menu, ...trigger },\n  ref\n) {\n  if (!menu) {\n    return (\n      <p\n        className=\"nx-binding-chip\"\n        data-binding-chip={id}\n        role=\"group\"\n        aria-label={label}\n        title={whole}\n      >\n        <Database aria-hidden=\"true\" size={14} />\n        <ChipText field={field} source={source} />\n      </p>\n    );\n  }\n  return (\n    <button\n      {...trigger}\n      ref={ref}\n      type=\"button\"\n      className=\"nx-binding-chip\"\n      data-binding-chip={id}\n      aria-label={label}\n      title={whole}\n      disabled={disabled}\n    >\n      <Database aria-hidden=\"true\" size={14} />\n      <ChipText field={field} source={source} />\n      <ChevronDown aria-hidden=\"true\" size={14} />\n    </button>\n  );\n});\n\n/** The chip's words: the field, then its source, cut source first. */\nfunction ChipText({\n  field,\n  source,\n}: {\n  field: string;\n  source: string | undefined;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-binding-chip__text\">\n      <span className=\"nx-binding-chip__field\">{field}</span>\n      {source === undefined ? null : (\n        <span className=\"nx-binding-chip__source\">\n          {/* A no-break space: a flex item drops a leading plain one. */}\n          {\"\\u00a0· \"}\n          {source}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/** The chip's menu: change the field, where fields can be listed; unbind, where it can be planned. */\nfunction ChipMenuItems({\n  canChange,\n  canUnbind,\n  propName,\n  source,\n  onChange,\n  onUnbind,\n}: {\n  canChange: boolean;\n  canUnbind: boolean;\n  propName: string;\n  /** Where the field's source is edited, where the host has a screen for it. */\n  source: { readonly href: string; readonly field: string } | undefined;\n  onChange: () => void;\n  onUnbind: () => void;\n}): React.JSX.Element {\n  return (\n    <>\n      {canChange ? (\n        <DropdownMenuItem onSelect={onChange}>\n          <Database aria-hidden=\"true\" size={14} />\n          Change field…\n        </DropdownMenuItem>\n      ) : null}\n      {source === undefined ? null : (\n        <OpenSourceItem href={source.href} field={source.field} />\n      )}\n      {canUnbind ? (\n        <>\n          <DropdownMenuSeparator />\n          <DropdownMenuItem onSelect={onUnbind}>\n            <Unlink aria-hidden=\"true\" size={14} />\n            Unbind, keep the {propName.toLowerCase()}\n          </DropdownMenuItem>\n        </>\n      ) : null}\n    </>\n  );\n}\n\n/**\n * The bound chip and what it offers: a menu to change the field or unbind,\n * the change picker anchored to it, and focus given back to it when the\n * picker closes. With nothing to offer, the chip is a label with no menu.\n */\nfunction ChipWithMenu({\n  chip,\n  canChange,\n  canUnbind,\n  propName,\n  source,\n  onUnbind,\n  picker,\n}: {\n  chip: {\n    id: string;\n    label: string;\n    whole: string;\n    field: string;\n    source: string | undefined;\n    disabled: boolean;\n  };\n  canChange: boolean;\n  canUnbind: boolean;\n  propName: string;\n  /** Where the field's source is edited, where the host has a screen for it. */\n  source: { readonly href: string; readonly field: string } | undefined;\n  onUnbind: () => void;\n  /** The change picker, handed how to close itself. */\n  picker: (close: () => void) => React.ReactNode;\n}): React.JSX.Element {\n  const chipRef = React.useRef<HTMLButtonElement>(null);\n  const [changing, setChanging] = React.useState(false);\n  if (!canChange && !canUnbind && source === undefined) {\n    return <BoundChip {...chip} menu={false} />;\n  }\n  return (\n    // The menu opens from the chip; \"Change field\" opens the picker at the\n    // same place, anchored to it rather than triggered by it, so one press\n    // never opens both.\n    <Popover open={changing} onOpenChange={setChanging}>\n      <DropdownMenu modal={false}>\n        <PopoverAnchor asChild>\n          <DropdownMenuTrigger asChild>\n            <BoundChip ref={chipRef} {...chip} menu />\n          </DropdownMenuTrigger>\n        </PopoverAnchor>\n        <DropdownMenuContent align=\"end\" className=\"nx-binding-menu\">\n          <ChipMenuItems\n            canChange={canChange}\n            canUnbind={canUnbind}\n            propName={propName}\n            source={source}\n            onChange={() => setChanging(true)}\n            onUnbind={onUnbind}\n          />\n        </DropdownMenuContent>\n      </DropdownMenu>\n      <PopoverContent\n        align=\"end\"\n        className=\"nx-binding-popover\"\n        // Anchored, not triggered, so Radix has no trigger to give focus back\n        // to: it goes to the chip, which stays.\n        onCloseAutoFocus={event => {\n          const target = chipRef.current;\n          if (target === null) return;\n          event.preventDefault();\n          target.focus();\n        }}\n      >\n        {picker(() => setChanging(false))}\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/** A bound prop: the chip, its menu, and the fallback a visitor sees without a value. */\nfunction BoundField({\n  nodeId,\n  prop,\n  blockLabel,\n  binding,\n  document,\n  services,\n  disabled,\n  onApply,\n  clearsOnBind,\n  clearsLocked,\n  entryLink,\n  onUnbound,\n}: Omit<BindingControlProps, \"binding\" | \"children\"> & {\n  binding: Binding;\n  onUnbound: (note: UnbindNote) => void;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  const [refusal, setRefusal] = React.useState<string | null>(null);\n  const { from, sources, item } = useBoundFrom(\n    binding,\n    document,\n    nodeId,\n    services\n  );\n  const name = propLabel(prop.name, prop.schema);\n  const names = boundNames(binding, from, { prop: prop.name, entryLink });\n  // Where \"Open source\" leads: the host's answer, absent where it has none.\n  const sourceHref = services?.sourceHref?.(binding);\n  // The whole of it, on the tooltip and in the accessible name: the chip\n  // cuts the source first, then the field, where the panel is narrow.\n  const whole =\n    names.source === undefined\n      ? names.field\n      : `${names.field} of ${names.source.replace(/^(This|Each) /, word => word.toLowerCase())}`;\n  const unbind = useUnbind({\n    nodeId,\n    prop,\n    binding,\n    document,\n    services,\n    onApply,\n    onUnbound,\n    onRefused: setRefusal,\n    // An image kept by its address names the prop the address went into,\n    // as the block labels it.\n    note: answer =>\n      noteFor(\n        answer,\n        blockLabel,\n        name,\n        names.field,\n        blockPropLabel(document, nodeId, answer.into)\n      ),\n  });\n  return (\n    <div className=\"nx-inspector__field nx-binding\" data-bound=\"\">\n      <p className=\"nx-inspector__field-name\" id={labelId}>\n        {name}\n      </p>\n      <div className=\"nx-binding__value\">\n        {/* The menu opens from the chip; \"Change field\" opens the picker at\n            the same place, anchored to it rather than triggered by it, so\n            one press never opens both. */}\n        <ChipWithMenu\n          chip={{\n            id: `${nodeId}:${prop.name}`,\n            label: `${name}: bound to ${whole}`,\n            whole,\n            field: names.field,\n            source: names.source,\n            disabled,\n          }}\n          canChange={\n            services?.listBindingFields !== undefined &&\n            !clearHeld(document, nodeId, clearsLocked)\n          }\n          canUnbind={services?.planUnbind !== undefined}\n          propName={name}\n          source={\n            sourceHref === undefined\n              ? undefined\n              : { href: sourceHref, field: names.field }\n          }\n          onUnbind={() => void unbind()}\n          picker={close => (\n            <BindingPicker\n              prop={prop}\n              blockLabel={blockLabel}\n              document={document}\n              nodeId={nodeId}\n              services={services}\n              current={binding}\n              entryLink={entryLink}\n              onPick={picked => {\n                const { op } = pickOp(\n                  {\n                    document,\n                    nodeId,\n                    prop: prop.name,\n                    clearsOnBind,\n                    entryLink,\n                  },\n                  picked,\n                  binding\n                );\n                close();\n                // A refusal said of the earlier field is no longer true; one\n                // of this edit is said in its place.\n                setRefusal(op !== null && onApply(op) ? null : EDIT_REFUSED);\n              }}\n            />\n          )}\n        />\n        <BoundRows\n          prop={prop}\n          binding={binding}\n          field={boundField(binding, from)}\n          shownWhen={fallbackShownWhen(binding, sources, item, names.field)}\n          services={services}\n          disabled={disabled}\n          labelId={labelId}\n          // A link's entry id has no fallback a person could type: with no\n          // entry read, the link keeps its own address.\n          textFallback={prop.name !== entryLink?.id}\n          // One write for the fallback and the format alike: the binding\n          // replaced, as a pick replaces it.\n          onRebind={next => {\n            const op = bindOp(document, nodeId, prop.name, next);\n            setRefusal(op !== null && onApply(op) ? null : EDIT_REFUSED);\n          }}\n        />\n        {refusal === null ? null : (\n          <UnboundNote note={{ text: refusal, tone: \"refused\" }} />\n        )}\n      </div>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The badge on a block whose bound value a visitor will not see.\n *\n * The canvas draws a page's bound props from sources read as the person\n * editing, who may read fields a visitor may not. A binding to such a field\n * falls back on the published page, so the author is told on the block itself:\n * the block is outlined in a faint amber dash, and a small \"Visitors won't see\n * this\" badge sits on that outline's top-right edge, a tab of it, with the\n * field and what a visitor sees instead in a tooltip: a fallback chosen from\n * the media library named by its file, with a small picture of it, as the\n * host's `readMedia` reads it, never by its raw id. The outline is what makes\n * the badge plainly this block's: on blocks stacked tight, a badge alone above\n * a block reads as the mark of the one above it.\n *\n * Which bindings those are is the host's question, answered by the engine's\n * `visitorUnreadableBindings` (the published page's own binding check, with the\n * field shapes a visitor may read); this only draws the answer.\n *\n * A layer of its own rather than a mark in `canvas-marks.tsx`: the marks are\n * boxes hidden from assistive technology, and this badge is a control a\n * keyboard reaches. Its tooltip shows on focus as well as on hover, and Escape\n * hides it without moving either.\n *\n * Placed as `empty-container-appender.tsx` places its controls: the block's\n * element found by its id, measured through `canvasContentRect` and placed in\n * the chrome's coordinates, so it lands right at any zoom. The outline runs\n * just outside the block's box, as the selection ring does, and the badge\n * above it, so neither covers the block's own content; the badge goes inside\n * the outline's top corner only when the block starts at the top of what is\n * on screen, where nothing above it is drawn, as the canvas's other tags do.\n *\n * Where another tab is in the way, the badge takes the next place it may use:\n * another block's badge or at-rest tab (\"Conditional\"), this block's own\n * at-rest tab, or the block toolbar over a selected block. Every layer drawing\n * tabs over the canvas posts them to one board and places them by one pass\n * (`canvas-tab-places.ts`), so the badge then sits on its outline's bottom\n * edge, or inside its top corner, or steps left along the edge, as the\n * at-rest tabs do.\n *\n * @module visitor-unreadable-badges\n */\n\nimport {\n  imageValueOf,\n  type VisitorUnreadableBinding,\n} from \"@nextlyhq/blocks-engine\";\nimport { EyeOff } from \"lucide-react\";\nimport {\n  Fragment,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type ReactElement,\n} from \"react\";\n\nimport {\n  CANVAS_ROOT_CLASS,\n  CHROME_ATTRIBUTE,\n  nodeElement,\n} from \"../canvas/canvas\";\nimport { useCanvasFrame } from \"../canvas/canvas-frame-context\";\nimport {\n  watchCanvasFor,\n  watchScreenBand,\n} from \"../canvas/canvas-geometry-watch\";\nimport {\n  overlaps,\n  tabBoardOf,\n  useTabPost,\n  type TabAt,\n  type TabDraft,\n} from \"../canvas/canvas-tab-places\";\nimport { isHTMLElement } from \"../canvas/dom-kind\";\nimport {\n  canvasContentRect,\n  clippedByAncestorRect,\n  onScreenOf,\n  overlaySpaceOf,\n  type OverlaySpace,\n} from \"../canvas/geometry-dom\";\nimport type { Rect } from \"../geometry\";\nimport {\n  useMediaSummary,\n  type MediaSummary,\n} from \"../inspector/content/content-controls\";\n\n/** The badge's words: what the author needs to know, at a glance. */\nconst VISITOR_UNREADABLE_WORDS = \"Visitors won't see this\";\n\n/**\n * How far outside the block's box its dashed outline runs: as far as the\n * selection ring, so the outline never covers the block's own content.\n */\nconst OUTLINE_OUTSET_PX = 2;\n/** The badge's height, as the stylesheet draws it. */\nconst BADGE_HEIGHT_PX = 22;\n/**\n * About how wide the badge is drawn, for its first placement: its 11px words,\n * icon and padding, erring wide. Once drawn, its own width is used.\n */\nconst BADGE_WIDTH_ESTIMATE_PX = 170;\n/**\n * The tooltip's widest, as the stylesheet caps it (18rem). Right-aligned with\n * the badge it runs this far left at most; a badge nearer the screen's left\n * edge than this has its tooltip start at its own left edge instead, so the\n * tooltip is never cut by the canvas's edge.\n */\nconst TIP_MAX_WIDTH_PX = 288;\n\n/**\n * Whether a badge whose right edge is at `right` has its tooltip run right\n * from its left edge: the screen, starting at `screenLeft`, has too little\n * room left of `right` for the widest tooltip to run left from there.\n */\nexport function tipRunsFromStart(right: number, screenLeft: number): boolean {\n  return right - screenLeft < TIP_MAX_WIDTH_PX;\n}\n\n/**\n * About the tallest a tooltip is drawn, its sentence wrapped at its widest\n * over a few lines, erring tall: drawn hidden until asked for, it has no\n * height to measure before it shows.\n */\nconst TIP_HEIGHT_ESTIMATE_PX = 120;\n\n/** The gap the stylesheet leaves between a badge and its tooltip (0.375rem). */\nconst TIP_GAP_PX = 6;\n\n/** No canvas on screen: nothing measured yet, or the layer is gone. */\nconst NO_SCREEN: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n/**\n * Whether a badge whose top is at `top` has its tooltip open upwards: the\n * screen, `screen` in the chrome's coordinates, has too little room under the\n * badge for the tooltip and more above it. A badge on its block's bottom\n * edge near the foot of the screen would otherwise show its tooltip where the\n * canvas clips it.\n */\nexport function tipRunsUp(top: number, screen: Rect): boolean {\n  const roomBelow =\n    screen.y + screen.height - (top + BADGE_HEIGHT_PX + TIP_GAP_PX);\n  const roomAbove = top - TIP_GAP_PX - screen.y;\n  return roomBelow < TIP_HEIGHT_ESTIMATE_PX && roomAbove > roomBelow;\n}\n\n/** The badge's drawn width for `id`, or the estimate before it is drawn. */\nfunction badgeWidthOf(\n  layer: HTMLElement | null,\n  space: OverlaySpace,\n  id: string\n): number {\n  const drawn = layer?.querySelector(`[data-badge-node=\"${CSS.escape(id)}\"]`);\n  // In the chrome's coordinates, as the outline and the band are: measured\n  // through the overlay's own normalization, which a scaled canvas needs.\n  const width = isHTMLElement(drawn) ? space.sizeOf(drawn).width : 0;\n  return width > 0 ? width : BADGE_WIDTH_ESTIMATE_PX;\n}\n\n/** Where one block's mark is drawn, in the chrome's coordinates. */\ninterface BadgePlace {\n  /** The dashed outline around the block, just outside its box. */\n  readonly outline: Rect;\n  /** The badge's right edge: the outline's, or the screen's when nearer. */\n  readonly right: number;\n  /** The badge's top; its right edge is the outline's right edge. */\n  readonly top: number;\n  /**\n   * Where the badge sits: on the outline's top edge, a tab of it; on its\n   * bottom edge where something else takes the top; or inside its top corner\n   * where there is no room above it on screen.\n   */\n  readonly at: TabAt;\n  /**\n   * The tooltip runs right from the badge's left edge: too little room on\n   * screen to the badge's left for it to run left from the badge's right.\n   */\n  readonly tipFromStart: boolean;\n  /** The tooltip opens upwards: too little room on screen under the badge. */\n  readonly tipUp: boolean;\n}\n\n/** One marked block as measured: its outline, and its badge to place. */\ninterface MeasuredBadge {\n  readonly id: string;\n  readonly outline: Rect;\n  readonly tab: TabDraft;\n}\n\n/** The badge's top for a place on `outline`, its border shared with the dash. */\nfunction badgeTopOf(outline: Rect, at: TabAt): number {\n  if (at === \"inside\") return outline.y;\n  return at === \"below\"\n    ? outline.y + outline.height - 1\n    : outline.y - BADGE_HEIGHT_PX + 1;\n}\n\n/** Where a badge may go on `outline`, in order of preference. */\nfunction badgePlacesOf(outline: Rect, onScreen: Rect): TabAt[] {\n  // On the outline's top edge where there is room above it on screen, else\n  // inside its top corner, as alone; on its bottom edge, where there is room\n  // below, when another tab takes the first.\n  const above = outline.y - onScreen.y >= BADGE_HEIGHT_PX;\n  const below =\n    outline.y + outline.height + BADGE_HEIGHT_PX <=\n    onScreen.y + onScreen.height;\n  const bottom = below ? ([\"below\"] as const) : [];\n  return above ? [\"above\", ...bottom, \"inside\"] : [\"inside\", ...bottom];\n}\n\n/**\n * The block `id`'s outline and badge to place, measured in the chrome's\n * coordinates, or nothing where there is no block on screen to point at.\n */\nfunction measuredBadgeOf(\n  layer: HTMLElement | null,\n  space: OverlaySpace,\n  onScreen: Rect,\n  id: string\n): MeasuredBadge | undefined {\n  const target = nodeElement(space.root, id);\n  // A block the page draws nothing for, or one an ancestor clips, has no\n  // place on screen a badge could point at.\n  if (target === null || clippedByAncestorRect(target, space.root)) {\n    return undefined;\n  }\n  const box = space.place(canvasContentRect(target, space.root));\n  if (box.width === 0 && box.height === 0) return undefined;\n  // A block wholly off screen gets no badge: one the layer clips away would\n  // still be a stop for the keyboard, with nothing to see.\n  if (!overlaps(box, onScreen)) return undefined;\n  const outline: Rect = {\n    x: box.x - OUTLINE_OUTSET_PX,\n    y: box.y - OUTLINE_OUTSET_PX,\n    width: box.width + OUTLINE_OUTSET_PX * 2,\n    height: box.height + OUTLINE_OUTSET_PX * 2,\n  };\n  const width = badgeWidthOf(layer, space, id);\n  // In from the screen's right edge as far as the block runs past it, and\n  // never so far left that the badge, drawn leftwards from here, runs past\n  // the screen's left edge: a block scrolled partly off either side keeps\n  // its whole badge in view.\n  const right = Math.max(\n    Math.min(outline.x + outline.width, onScreen.x + onScreen.width),\n    onScreen.x + width\n  );\n  return {\n    id,\n    outline,\n    tab: {\n      block: box,\n      edge: outline,\n      places: badgePlacesOf(outline, onScreen),\n      side: outline.x + outline.width - right,\n      width,\n      height: BADGE_HEIGHT_PX,\n      // Sitting on the outline's edge, its border shared with the outline's,\n      // so the two read as one mark of this block.\n      foot: 1,\n      leftmost: onScreen.x,\n    },\n  };\n}\n\nexport interface VisitorUnreadableBadgesProps {\n  /** The bindings a visitor will not see filled, by the id of the node holding them. */\n  readonly marked: ReadonlyMap<string, readonly VisitorUnreadableBinding[]>;\n  /** Pressed: the host selects the block, whose inspector says it in full. */\n  readonly onSelect?: (nodeId: string) => void;\n  /** Hidden while the canvas is mid-drag, as the other controls over it are. */\n  readonly hidden?: boolean;\n  /**\n   * A media item by its id, as the inspector reads one, so a fallback chosen\n   * from the library is named by its file. Absent, such a fallback is said\n   * to be a library image, without its name.\n   */\n  readonly readMedia?: (mediaId: string) => Promise<MediaSummary | null>;\n}\n\n/**\n * The media id an image binding's fallback names, when it is a file from the\n * library rather than an address. Asked only of an image prop, by the\n * engine's reading of an image value: the same text on a heading is text.\n */\nfunction fallbackMediaId(\n  binding: VisitorUnreadableBinding\n): string | undefined {\n  if (binding.kind !== \"image\" || binding.fallback === undefined) {\n    return undefined;\n  }\n  const read = imageValueOf(binding.fallback.value);\n  return read?.holds === \"media\" ? read.value : undefined;\n}\n\n/**\n * A fallback as a reader sees it: text quoted, a library file named by its\n * file name (`fileName`, once read), anything else named.\n */\nfunction fallbackWords(\n  binding: VisitorUnreadableBinding,\n  fileName: string | undefined\n): string {\n  if (binding.fallback === undefined) {\n    return \"They see the block's own value instead.\";\n  }\n  // A media id is no word a reader knows: the file it names, or that it is\n  // a file, while that is read or where it can't be.\n  if (fallbackMediaId(binding) !== undefined) {\n    return fileName === undefined\n      ? \"They see a fallback image from the library.\"\n      : `They see the fallback image “${fileName}”.`;\n  }\n  const value = binding.fallback.value;\n  return typeof value === \"string\" && value.trim() !== \"\"\n    ? `They see the fallback: “${value}”.`\n    : \"They see the fallback instead.\";\n}\n\n/**\n * One sentence per binding: the field, and what a visitor sees instead.\n * Synchronous, so a library file's name is handed in once read\n * (`fileName`); without it the file is said to be a library image.\n */\nexport function visitorUnreadableSentence(\n  binding: VisitorUnreadableBinding,\n  fileName?: string\n): string {\n  return `Visitors can't read “${binding.path}”. ${fallbackWords(binding, fileName)}`;\n}\n\n/**\n * One binding's sentence, its library fallback read by its id through\n * `readMedia` and named by its file; with `pictured`, a small picture of\n * that file before it, where the badge's tooltip has room for one.\n */\nexport function VisitorUnreadableLine({\n  binding,\n  readMedia,\n  pictured = false,\n}: {\n  readonly binding: VisitorUnreadableBinding;\n  readonly readMedia:\n    | ((mediaId: string) => Promise<MediaSummary | null>)\n    | undefined;\n  readonly pictured?: boolean;\n}): ReactElement {\n  const summary = useMediaSummary(readMedia, fallbackMediaId(binding) ?? null);\n  const sentence = visitorUnreadableSentence(binding, summary?.name);\n  const thumbnail = pictured ? summary?.thumbnail : undefined;\n  if (thumbnail === undefined) return <>{sentence}</>;\n  return (\n    <span className=\"nx-visitor-unreadable__pictured\">\n      {/* Decorative: the sentence names the file. */}\n      <img\n        className=\"nx-visitor-unreadable__thumb\"\n        src={thumbnail}\n        alt=\"\"\n        decoding=\"async\"\n      />\n      <span>{sentence}</span>\n    </span>\n  );\n}\n\n/**\n * The badges over the canvas's blocks whose bound values a visitor will not\n * see.\n *\n * @experimental\n */\nexport function VisitorUnreadableBadges({\n  marked,\n  onSelect,\n  hidden = false,\n  readMedia,\n}: VisitorUnreadableBadgesProps): ReactElement | null {\n  const layer = useRef<HTMLDivElement | null>(null);\n  const [places, setPlaces] = useState<ReadonlyMap<string, BadgePlace>>(\n    () => new Map()\n  );\n  // The badge whose tooltip Escape put away, until it is left.\n  const [dismissed, setDismissed] = useState<string | null>(null);\n  const idPrefix = useId();\n  const canvasFrame = useCanvasFrame();\n\n  // The last measure, which placing the badges again reads: another layer's\n  // post moves where the badges go, not which blocks have one.\n  const measured = useRef<{\n    readonly root: HTMLElement | null;\n    readonly badges: readonly MeasuredBadge[];\n    /** What of the canvas is on screen, as last measured. */\n    readonly screen: Rect;\n  }>({ root: null, badges: [], screen: NO_SCREEN });\n\n  // The badges as last measured, placed where the board puts them now, with\n  // the canvas's other tabs and the block toolbar.\n  const placeBadges = useCallback(() => {\n    const { root, badges, screen } = measured.current;\n    const placements =\n      root === null ? [] : tabBoardOf(root).placesOf(\"visitor\");\n    const next = new Map<string, BadgePlace>();\n    badges.forEach(({ id, outline, tab }, index) => {\n      const { at, side } = placements[index] ?? {\n        at: tab.places[0] ?? \"inside\",\n        side: tab.side,\n      };\n      const right = outline.x + outline.width - side;\n      const top = badgeTopOf(outline, at);\n      next.set(id, {\n        outline,\n        right,\n        top,\n        at,\n        // Read from where the badge is placed, which a step left or a move to\n        // the bottom edge to keep clear of another tab changes, so its\n        // tooltip still fits on screen.\n        tipFromStart: tipRunsFromStart(right, screen.x),\n        tipUp: tipRunsUp(top, screen),\n      });\n    });\n    setPlaces(next);\n  }, []);\n  const postTabs = useTabPost(\"visitor\", placeBadges);\n\n  const measure = useCallback(() => {\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) {\n      measured.current = { root: null, badges: [], screen: NO_SCREEN };\n      postTabs(null);\n      setPlaces(current => (current.size === 0 ? current : new Map()));\n      return;\n    }\n    const onScreen = onScreenOf(space);\n    const badges = [...marked.keys()].flatMap(id => {\n      const badge = measuredBadgeOf(element, space, onScreen, id);\n      return badge === undefined ? [] : [badge];\n    });\n    measured.current = { root: space.root, badges, screen: onScreen };\n    postTabs(space.root, { tabs: badges.map(({ tab }) => tab), taken: [] });\n    placeBadges();\n  }, [marked, postTabs, placeBadges]);\n\n  useLayoutEffect(() => {\n    // Hidden, the layer draws no badge, so no other tab keeps clear of one.\n    if (hidden) {\n      postTabs(null);\n      return;\n    }\n    measure();\n  }, [measure, hidden, canvasFrame, postTabs]);\n\n  useEffect(() => {\n    if (hidden || marked.size === 0) return;\n    return watchCanvasFor(() => layer.current, measure);\n  }, [measure, hidden, marked, canvasFrame]);\n\n  // The scrolls that move what of the canvas is on screen, which decide\n  // whether a badge has room above its block.\n  useEffect(() => {\n    if (hidden || marked.size === 0) return;\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) return;\n    return watchScreenBand(space.root, space.frame, measure);\n  }, [measure, hidden, marked, canvasFrame]);\n\n  if (hidden || marked.size === 0) return null;\n\n  return (\n    <div\n      ref={layer}\n      className=\"nx-visitor-unreadable\"\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n    >\n      {[...marked].map(([id, bindings], index) => {\n        const place = places.get(id);\n        if (place === undefined) return null;\n        const tipId = `${idPrefix}-tip-${String(index)}`;\n        const { outline } = place;\n        return (\n          <Fragment key={id}>\n            {/* The block itself, outlined in the badge's amber, so at rest\n                the badge plainly belongs to this block and not the one\n                above it. Drawn only: the badge says it in words. */}\n            <div\n              className=\"nx-visitor-unreadable__outline\"\n              aria-hidden=\"true\"\n              style={{\n                left: outline.x,\n                top: outline.y,\n                width: outline.width,\n                height: outline.height,\n              }}\n            />\n            <div\n              className=\"nx-visitor-unreadable__badge\"\n              data-badge-node={id}\n              // One attribute per place, so the stylesheet shapes each\n              // badge's corners from its own place alone.\n              data-above={place.at === \"above\" ? \"\" : undefined}\n              data-inside={place.at === \"inside\" ? \"\" : undefined}\n              data-below={place.at === \"below\" ? \"\" : undefined}\n              data-tip-start={place.tipFromStart ? \"\" : undefined}\n              data-tip-up={place.tipUp ? \"\" : undefined}\n              data-dismissed={dismissed === id ? \"\" : undefined}\n              style={{ left: place.right, top: place.top }}\n              onMouseLeave={() => {\n                if (dismissed === id) setDismissed(null);\n              }}\n            >\n              <button\n                type=\"button\"\n                className=\"nx-visitor-unreadable__button\"\n                aria-describedby={tipId}\n                onClick={() => onSelect?.(id)}\n                onBlur={() => {\n                  if (dismissed === id) setDismissed(null);\n                }}\n                onKeyDown={event => {\n                  // Put the tooltip away without moving focus or the pointer.\n                  if (event.key === \"Escape\" && dismissed !== id) {\n                    event.stopPropagation();\n                    setDismissed(id);\n                  }\n                }}\n              >\n                <EyeOff size={12} aria-hidden=\"true\" />\n                <span>{VISITOR_UNREADABLE_WORDS}</span>\n              </button>\n              <span\n                id={tipId}\n                role=\"tooltip\"\n                className=\"nx-visitor-unreadable__tip\"\n              >\n                {bindings.map(binding => (\n                  <span\n                    key={binding.prop}\n                    className=\"nx-visitor-unreadable__line\"\n                  >\n                    <VisitorUnreadableLine\n                      binding={binding}\n                      readMedia={readMedia}\n                      pictured\n                    />\n                  </span>\n                ))}\n              </span>\n            </div>\n          </Fragment>\n        );\n      })}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The bound props a visitor will not see, handed by the host to the parts of\n * the shell that say so: the inspector's note under each such prop.\n *\n * A context rather than a member of `ContentServices`: the services are one\n * object per language and person, kept so a control's reads are not redone,\n * while this answer changes with every edit to a binding.\n *\n * @module visitor-unreadable-context\n */\n\nimport type { VisitorUnreadableBinding } from \"@nextlyhq/blocks-engine\";\nimport { EyeOff } from \"lucide-react\";\nimport { createContext, useContext, type ReactNode } from \"react\";\n\nimport type { ContentServices } from \"../inspector/content/content-controls\";\n\nimport { VisitorUnreadableLine } from \"./visitor-unreadable-badges\";\n\n/** The answer before a host gives one: nothing marked. */\nconst NONE: ReadonlyMap<string, readonly VisitorUnreadableBinding[]> =\n  new Map();\n\nconst VisitorUnreadable =\n  createContext<ReadonlyMap<string, readonly VisitorUnreadableBinding[]>>(NONE);\n\n/**\n * Hands the shell the bindings a visitor will not see, by the id of the node\n * holding them.\n *\n * @experimental\n */\nexport function VisitorUnreadableProvider({\n  value,\n  children,\n}: {\n  readonly value: ReadonlyMap<string, readonly VisitorUnreadableBinding[]>;\n  readonly children?: ReactNode;\n}): React.JSX.Element {\n  return (\n    <VisitorUnreadable.Provider value={value}>\n      {children}\n    </VisitorUnreadable.Provider>\n  );\n}\n\n/** The bindings on `nodeId` a visitor will not see filled. */\nexport function useVisitorUnreadable(\n  nodeId: string\n): readonly VisitorUnreadableBinding[] {\n  return useContext(VisitorUnreadable).get(nodeId) ?? [];\n}\n\n/**\n * The note under a prop whose bound value a visitor will not see: the field,\n * and what the published page shows instead, a fallback from the library\n * named by its file as the badge names it. Nothing for a prop with none.\n */\nexport function VisitorUnreadableNote({\n  bindings,\n  props,\n  services,\n}: {\n  readonly bindings: readonly VisitorUnreadableBinding[];\n  /** The props the field above it draws. */\n  readonly props: ReadonlySet<string>;\n  /** The host's services, whose media read names a library fallback's file. */\n  readonly services?: ContentServices | undefined;\n}): React.JSX.Element | null {\n  const shown = bindings.filter(binding => props.has(binding.prop));\n  if (shown.length === 0) return null;\n  return (\n    <div className=\"nx-inspector__visitor-unreadable\" role=\"note\">\n      <EyeOff size={14} aria-hidden=\"true\" />\n      <div className=\"nx-inspector__visitor-unreadable-lines\">\n        {shown.map(binding => (\n          <p key={binding.prop}>\n            <VisitorUnreadableLine\n              binding={binding}\n              readMedia={services?.readMedia}\n            />\n          </p>\n        ))}\n      </div>\n    </div>\n  );\n}\n","/**\n * A List's own marker, said under \"List as\": a list that stores a\n * `list-style-type` of its own draws that marker, not the bullets or numbers\n * its kind names, so the kind's choice would read as a promise the page does\n * not keep. The note says the marker is custom, and Clear removes it, at\n * every state and device it is stored at, so the kind decides again.\n *\n * The marker itself is a CSS detail, added and changed from \"Add CSS\n * property\" in Style; this is only where Content says it is there.\n *\n * @module list-marker-note\n */\nimport type {\n  BlockNode,\n  BreakpointId,\n  StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { chainedStyleOp } from \"../../canvas/columns-layout\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { readStyleValue } from \"../../styles/style-values\";\n\n/** The block a marker note belongs to. */\nconst LIST_BLOCK = \"core/list\";\n\n/** The style property a List's own marker is stored under. */\nconst MARKER = \"listStyleType\";\n\n/** Each state and device a List stores a marker of its own at. */\nexport function customMarkerAt(node: BlockNode): readonly {\n  readonly state: StyleState;\n  readonly breakpoint: BreakpointId;\n}[] {\n  const styles = node.styles;\n  if (styles === undefined || styles === null) return [];\n  return Object.entries(styles).flatMap(([state, devices]) =>\n    typeof devices === \"object\" && devices !== null\n      ? Object.keys(devices).flatMap(breakpoint => {\n          const at = {\n            state: state as StyleState,\n            breakpoint,\n          };\n          return readStyleValue(styles, {\n            ...at,\n            property: MARKER,\n            path: [],\n          }) === undefined\n            ? []\n            : [at];\n        })\n      : []\n  );\n}\n\n/** One op clearing the List's own marker wherever it is stored, or none. */\nexport function planClearMarker(node: BlockNode): BuilderOp | null {\n  return chainedStyleOp(\n    node,\n    customMarkerAt(node).map(at => ({\n      address: { ...at, property: MARKER, path: [] },\n      value: null,\n    }))\n  );\n}\n\n/** \"Custom marker · Clear\", under a List's \"List as\", while it has one. */\nexport function ListMarkerNote({\n  node,\n  disabled,\n  onApply,\n}: {\n  node: BlockNode | undefined;\n  /** Whether the block's styles may not be changed here, as under a lock. */\n  disabled: boolean;\n  onApply: (op: BuilderOp) => boolean;\n}): React.JSX.Element | null {\n  if (node?.type !== LIST_BLOCK || customMarkerAt(node).length === 0) {\n    return null;\n  }\n  return (\n    <p className=\"nx-settings-note\">\n      Custom marker ·{\" \"}\n      <button\n        type=\"button\"\n        className=\"nx-settings-note__link\"\n        disabled={disabled}\n        aria-label=\"Clear the custom marker\"\n        onClick={() => {\n          const op = planClearMarker(node);\n          if (op !== null) onApply(op);\n        }}\n      >\n        Clear\n      </button>\n    </p>\n  );\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","\"use client\";\n\n/**\n * An image's source and alt text, each drawn as one control over the two\n * props it is made of (see `image-group`).\n *\n * - Source: \"Library | URL\". Only the chosen side's field shows: the media\n *   chip, or the address. Switching sides writes nothing; what the author\n *   then picks or types does.\n * - Alt text: one field that grows with its words, holding the words in use:\n *   the page's own, else the library's, marked \"From the media library\";\n *   and \"Decorative, no alt text\", which keeps the words for when it is\n *   cleared.\n *\n * Each offers binding through the inspector's `bindable` wrapper: the Source\n * row binds the image (`mediaId`, which takes a media field or an image\n * address), the address field binds the address, and the alt row binds the\n * alt text. A bound image draws only what its binding gives, so while it is\n * bound the Source row is its chip and neither side is shown.\n *\n * Every write goes through the group's one edit, so a choice that changes two\n * props is one step to undo. A stored state no option names exactly (an\n * address kept beside a library file, alt text kept on a decorative image,\n * an empty alt) is shown as it is and left as it is until the author acts.\n *\n * @module image-controls\n */\n\nimport {\n  bindingKindOf,\n  findNode,\n  isAuthoredText,\n  type Binding,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button, Checkbox, Label, Textarea } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useBoundFieldOf } from \"../../bindings/binding-controls\";\nimport { useVisitorUnreadable } from \"../../shell/visitor-unreadable-context\";\nimport { HeldByLock } from \"../held-by-lock\";\nimport { propLabel, type EditableProp } from \"../inspector\";\n\nimport {\n  contentControlFor,\n  MediaField,\n  SegmentedChoice,\n  useMediaSummary,\n  type ContentServices,\n} from \"./content-controls\";\nimport {\n  addressChanges,\n  altModeOf,\n  altTextChanges,\n  decorativeChanges,\n  mediaPickChanges,\n  sourceModeOf,\n  storedAlt,\n  type AltMode,\n  type ImageAltGroup,\n  type ImageChanges,\n  type ImageSourceGroup,\n  type SourceMode,\n} from \"./image-group\";\nimport type { BindableWrapper } from \"./prop-groups\";\n\n/** What both image controls are given. */\ninterface ImageGroupFieldProps {\n  /** The block's props, as the inspector reads them. */\n  readonly props: readonly EditableProp[];\n  /** Whether one prop may be set where the block sits. */\n  readonly writable: (name: string) => boolean;\n  /** The id of the lock reason a held control points to. */\n  readonly reasonId: string;\n  readonly services: ContentServices | undefined;\n  /** Every set of props the block can be placed with. */\n  readonly placedWith: ReadonlyArray<Readonly<Record<string, unknown>>>;\n  /** Write several props as one edit. */\n  readonly onCommitMany: (changes: ImageChanges) => unknown;\n  /** One prop's binding controls, from the inspector; absent, none are drawn. */\n  readonly bindable?: BindableWrapper | undefined;\n  /** The document the block is in, whose bindings say which props are bound. */\n  readonly document?: BlockDocument | undefined;\n  /** The block's id. */\n  readonly nodeId?: string | undefined;\n}\n\n/** A field drawn as it is, where the inspector offers no binding controls. */\nconst unwrapped: BindableWrapper = (_name, field) => field;\n\n/**\n * Where the image's picture comes from, as the block reads it: a binding on\n * its media prop first, then a stored library file, else none here (an\n * address, or nothing). The one reading the source and alt controls share.\n */\ntype PictureSource =\n  | { readonly kind: \"bound\" }\n  | { readonly kind: \"library\"; readonly id: string }\n  | { readonly kind: \"none\" };\n\nfunction pictureSourceOf(\n  media: string | undefined,\n  values: Readonly<Record<string, unknown>>,\n  bound: ReadonlySet<string>\n): PictureSource {\n  if (media === undefined) return { kind: \"none\" };\n  if (bound.has(media)) return { kind: \"bound\" };\n  const id = storedString(values[media]);\n  return id === undefined ? { kind: \"none\" } : { kind: \"library\", id };\n}\n\n/** The names of the block's props that hold a binding. */\nfunction boundPropsOf(\n  document: BlockDocument | undefined,\n  nodeId: string | undefined\n): ReadonlySet<string> {\n  if (document === undefined || nodeId === undefined) return new Set();\n  return new Set(Object.keys(findNode(document.nodes, nodeId)?.bindings ?? {}));\n}\n\n/** The props as STORED, by name: a default is not a value the page holds. */\nfunction storedValues(\n  props: readonly EditableProp[]\n): Readonly<Record<string, unknown>> {\n  return Object.fromEntries(props.map(prop => [prop.name, prop.value]));\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/** Whether every prop a change names may be written. */\nfunction allWritable(\n  changes: ImageChanges,\n  writable: (name: string) => boolean\n): boolean {\n  return Object.keys(changes).every(writable);\n}\n\nconst SOURCE_MODES: readonly SourceMode[] = [\"library\", \"url\"];\nconst SOURCE_LABELS: readonly string[] = [\"Library\", \"URL\"];\n\n/** The address field, as the registry's own URL control draws it. */\nfunction AddressField({\n  prop,\n  disabled,\n  onCommit,\n}: {\n  prop: EditableProp;\n  disabled: boolean;\n  onCommit: (typed: string) => void;\n}): React.JSX.Element | null {\n  const id = React.useId();\n  const Control = contentControlFor(prop.schema.type);\n  if (Control === undefined) return null;\n  return (\n    <Control\n      id={id}\n      prop={prop}\n      disabled={disabled}\n      // The URL control commits the typed text; anything else, or a removal,\n      // reads as an emptied field.\n      onCommit={(_, value) => onCommit(typeof value === \"string\" ? value : \"\")}\n    />\n  );\n}\n\n/** A source side's field, with what it is given to write. */\ninterface SourceSideProps {\n  /** A prop's binding controls around its field. */\n  readonly wrap: BindableWrapper;\n  readonly group: ImageSourceGroup;\n  readonly props: readonly EditableProp[];\n  readonly values: Readonly<Record<string, unknown>>;\n  readonly writable: (name: string) => boolean;\n  readonly reasonId: string;\n  /** Write several props as one edit, where every one may be written. */\n  readonly write: (changes: ImageChanges) => void;\n}\n\n/** The library side: the media chip, and an address stored beside it. */\nfunction LibrarySide({\n  group,\n  props,\n  values,\n  writable,\n  reasonId,\n  write,\n  services,\n  showLibraryAlt,\n  placedWith,\n}: SourceSideProps & {\n  services: ContentServices | undefined;\n  showLibraryAlt: boolean;\n  placedWith: ImageGroupFieldProps[\"placedWith\"];\n}): React.JSX.Element {\n  const id = React.useId();\n  const media = props.find(prop => prop.name === group.media);\n  const storedMedia = storedString(values[group.media]);\n  const storedAddress = storedString(values[group.address]);\n  const accept = media?.schema.accept;\n  return (\n    <HeldByLock reasonId={writable(group.media) ? undefined : reasonId}>\n      <MediaField\n        id={id}\n        label={\n          media === undefined ? \"Image\" : propLabel(media.name, media.schema)\n        }\n        stored={storedMedia ?? null}\n        accept={typeof accept === \"string\" ? accept : undefined}\n        disabled={!writable(group.media)}\n        services={services}\n        showAlt={showLibraryAlt}\n        onChange={next =>\n          write(\n            next === undefined\n              ? { [group.media]: undefined }\n              : mediaPickChanges(group, next, values, placedWith)\n          )\n        }\n      />\n      {storedMedia === undefined || storedAddress === undefined ? null : (\n        <p className=\"nx-inspector__note\">\n          An address is also stored, and is drawn if the library file is\n          missing: {storedAddress}\n        </p>\n      )}\n    </HeldByLock>\n  );\n}\n\n/** The address side: the address field, and a library file still chosen. */\nfunction AddressSide({\n  group,\n  props,\n  values,\n  writable,\n  reasonId,\n  write,\n  wrap,\n}: SourceSideProps): React.JSX.Element {\n  const address = props.find(prop => prop.name === group.address);\n  const storedMedia = storedString(values[group.media]);\n  return (\n    <HeldByLock reasonId={writable(group.address) ? undefined : reasonId}>\n      {address === undefined\n        ? null\n        : wrap(\n            group.address,\n            <AddressField\n              prop={address}\n              disabled={!writable(group.address)}\n              onCommit={typed => write(addressChanges(group, typed, values))}\n            />,\n            // The block draws a library file before an address, so binding\n            // the address empties a stored file in the same edit, as typing\n            // one does (`addressChanges`).\n            { clearsOnBind: [group.media] }\n          )}\n      {storedMedia === undefined ? null : (\n        <div className=\"nx-inspector__note-row\">\n          <p className=\"nx-inspector__note\">\n            A library file is chosen, and is drawn instead. An address entered\n            here replaces it.\n          </p>\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"ghost\"\n            disabled={!writable(group.media)}\n            onClick={() => write({ [group.media]: undefined })}\n          >\n            Remove the library file\n          </Button>\n        </div>\n      )}\n    </HeldByLock>\n  );\n}\n\n/**\n * The side the stored props read as: `sourceModeOf`, except that an address\n * bound with no library file stored is on the URL side, where its chip is\n * drawn.\n */\nfunction storedSide(\n  group: ImageSourceGroup,\n  values: Readonly<Record<string, unknown>>,\n  bound: ReadonlySet<string>\n): SourceMode {\n  const addressBound = !bound.has(group.media) && bound.has(group.address);\n  return addressBound && storedString(values[group.media]) === undefined\n    ? \"url\"\n    : sourceModeOf(group, values);\n}\n\n/** The chosen side's field: the library chip, or the address. */\nfunction SourceSideShown({\n  mode,\n  side,\n  services,\n  showLibraryAlt,\n  placedWith,\n}: {\n  mode: SourceMode;\n  side: SourceSideProps;\n  services: ContentServices | undefined;\n  showLibraryAlt: boolean;\n  placedWith: ImageGroupFieldProps[\"placedWith\"];\n}): React.JSX.Element {\n  return mode === \"library\" ? (\n    <LibrarySide\n      {...side}\n      services={services}\n      showLibraryAlt={showLibraryAlt}\n      placedWith={placedWith}\n    />\n  ) : (\n    <AddressSide {...side} />\n  );\n}\n\n/**\n * Where an image's picture comes from: a library file or an address, one\n * shown at a time.\n */\nexport function ImageSourceField({\n  group,\n  props,\n  writable,\n  reasonId,\n  services,\n  placedWith,\n  onCommitMany,\n  showLibraryAlt,\n  bindable,\n  document,\n  nodeId,\n}: ImageGroupFieldProps & {\n  group: ImageSourceGroup;\n  /** Whether the chip shows the library's alt text: not when a row says it. */\n  showLibraryAlt: boolean;\n}): React.JSX.Element {\n  const id = React.useId();\n  const values = storedValues(props);\n  const wrap = bindable ?? unwrapped;\n  const bound = boundPropsOf(document, nodeId);\n  const imageBound =\n    pictureSourceOf(group.media, values, bound).kind === \"bound\";\n  // The side shown, starting from what is stored. Choosing a side changes\n  // only what is shown; the props change when a file is picked or an\n  // address typed, so looking at the other side never loses a value.\n  const stored = storedSide(group, values, bound);\n  const [view, setView] = React.useState<{\n    readonly mode: SourceMode;\n    readonly from: SourceMode;\n  }>({ mode: stored, from: stored });\n  // Followed again whenever the stored props come to read as another side:\n  // an undo, a redo or a document replaced from outside changes them under\n  // a field that stays mounted. A side chosen while they stay as they are\n  // is kept. Set during render, as React sets state derived from props, so\n  // the wrong side is never drawn first.\n  if (view.from !== stored) setView({ mode: stored, from: stored });\n  const mode = view.from === stored ? view.mode : stored;\n  const setMode = (next: SourceMode) => setView({ mode: next, from: stored });\n  const side: SourceSideProps = {\n    wrap,\n    group,\n    props,\n    values,\n    writable,\n    reasonId,\n    write: changes => {\n      if (allWritable(changes, writable)) onCommitMany(changes);\n    },\n  };\n  return (\n    <div className=\"nx-image-group\" data-image-group=\"source\">\n      {/* The image's bind button sits on the Source row, which says where\n          the picture comes from; bound, the row is the chip, and an unbind's\n          note stays under it whichever side the kept value is on. */}\n      {wrap(\n        group.media,\n        <div className=\"nx-inspector__field\" data-content-control=\"source\">\n          <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n            Source\n          </p>\n          <SegmentedChoice\n            id={id}\n            labelledBy={`${id}-label`}\n            options={SOURCE_MODES}\n            labels={SOURCE_LABELS}\n            value={mode}\n            disabled={!writable(group.media) && !writable(group.address)}\n            onChoose={next => setMode(next === \"url\" ? \"url\" : \"library\")}\n          />\n        </div>\n      )}\n      {imageBound ? null : (\n        <SourceSideShown\n          mode={mode}\n          side={side}\n          services={services}\n          showLibraryAlt={showLibraryAlt}\n          placedWith={placedWith}\n        />\n      )}\n    </div>\n  );\n}\n\n/**\n * A text field one line tall that grows with its words, committed on blur\n * so an edit is one step to undo.\n *\n * Its words follow `value`, with one exception: while the author is typing,\n * a new `value` that only changes what is shown (the library's words\n * arriving for a field that held none yet) leaves their words alone. A move\n * of what the document stores (`stored`: an undo, an edit elsewhere) is\n * followed whatever is being typed, as every inspector field gives way to\n * the document.\n */\nfunction GrowingText({\n  id,\n  value,\n  stored,\n  placeholder,\n  disabled,\n  describedBy,\n  onCommit,\n}: {\n  /** The field's id, which its label names it by. */\n  id: string;\n  /** The words shown while nothing is being typed. */\n  value: string;\n  /** What the document stores for the field, which a draft gives way to. */\n  stored: string;\n  placeholder: string;\n  disabled: boolean;\n  describedBy: string | undefined;\n  /** Write the words; answers whether anything was written. */\n  onCommit: (text: string) => boolean;\n}): React.JSX.Element {\n  const [draft, setDraft] = React.useState(value);\n  // Whether the author has typed since the words last followed `value`.\n  const typing = React.useRef(false);\n  const lastStored = React.useRef(stored);\n  React.useEffect(() => {\n    const documentMoved = lastStored.current !== stored;\n    lastStored.current = stored;\n    if (!documentMoved && typing.current) return;\n    typing.current = false;\n    setDraft(value);\n  }, [value, stored]);\n  // A commit that writes nothing (the words already in use, an emptied field\n  // with no words of the page's own to remove, or one a lock refuses) leaves\n  // the document where it was, so nothing else brings the shown words back:\n  // the field shows them again itself.\n  const commit = (): void => {\n    typing.current = false;\n    if (draft !== value && !onCommit(draft)) setDraft(value);\n  };\n  const field = React.useRef<HTMLTextAreaElement>(null);\n  // Fitted to its words after each change, up to the six lines the style\n  // caps it at, past which it scrolls.\n  React.useLayoutEffect(() => {\n    const element = field.current;\n    if (element === null) return;\n    element.style.height = \"auto\";\n    element.style.height = `${element.scrollHeight}px`;\n  }, [draft]);\n  return (\n    <Textarea\n      ref={field}\n      id={id}\n      rows={1}\n      className=\"nx-inspector__growing\"\n      placeholder={placeholder}\n      {...(describedBy === undefined\n        ? {}\n        : { \"aria-describedby\": describedBy })}\n      disabled={disabled}\n      value={draft}\n      onChange={event => {\n        typing.current = true;\n        setDraft(event.target.value);\n      }}\n      onBlur={commit}\n      // Enter commits rather than breaking the line: alt text is read out as\n      // one run, so a line break in it means nothing, and Enter is what an\n      // author presses to say they are done.\n      onKeyDown={event => {\n        if (event.key !== \"Enter\") return;\n        event.preventDefault();\n        commit();\n      }}\n    />\n  );\n}\n\n/** A picture bound to a field, as the alt note reads which field it is. */\ninterface BoundPicture {\n  /** The media prop the binding fills. */\n  readonly prop: string;\n  readonly binding: Binding;\n  readonly document: BlockDocument;\n  readonly nodeId: string;\n  readonly services: ContentServices | undefined;\n}\n\n/**\n * A bound picture's binding and where it sits, for the alt note to read the\n * field's kind: `undefined` for a picture not bound, or where the block's\n * document or node is not in hand.\n */\nfunction boundPictureOf(\n  picture: PictureSource,\n  at: {\n    readonly document: BlockDocument | undefined;\n    readonly nodeId: string | undefined;\n    readonly services: ContentServices | undefined;\n  },\n  media: string | undefined\n): BoundPicture | undefined {\n  const { document, nodeId, services } = at;\n  if (picture.kind !== \"bound\" || media === undefined) return undefined;\n  if (document === undefined || nodeId === undefined) return undefined;\n  const binding = findNode(document.nodes, nodeId)?.bindings?.[media];\n  return binding === undefined\n    ? undefined\n    : { prop: media, binding, document, nodeId, services };\n}\n\n/**\n * What the alt field says under its words, while the page stores none of its\n * own: whose words they are, or why there are none.\n */\nfunction LibraryAltNote({\n  id,\n  bound,\n  mediaId,\n  libraryAlt,\n  read,\n}: {\n  /** The note's id, which the field is described by. */\n  id: string;\n  /** The picture's binding, whose field is read on the page; none if unbound. */\n  bound: BoundPicture | undefined;\n  mediaId: string | undefined;\n  libraryAlt: string | undefined;\n  read: boolean;\n}): React.JSX.Element | null {\n  // A bound picture is read when the page is drawn, so no file is \"not\n  // chosen\": what applies is the bound field's, said by its kind.\n  if (bound !== undefined) return <BoundPictureAltNote id={id} {...bound} />;\n  if (mediaId === undefined) {\n    return (\n      <p className=\"nx-inspector__note\" id={id}>\n        No library file is chosen, so screen readers get no alt text. Type some\n        to describe the picture.\n      </p>\n    );\n  }\n  if (!read) return null;\n  if (libraryAlt === undefined) {\n    return (\n      <p className=\"nx-inspector__note\" id={id}>\n        The media library has no alt text for this picture.\n      </p>\n    );\n  }\n  // Marked as the library's: the words in the field are in use, and are the\n  // library's until the author types their own.\n  return (\n    <p className=\"nx-inspector__note nx-image-alt__source\" id={id}>\n      From the media library\n    </p>\n  );\n}\n\n/**\n * The note for a bound picture, by the kind of field it reads, as the engine\n * types it (`bindingKindOf`): a library file is described by its own alt\n * text, which the page reads with it; an image address has none, so screen\n * readers get none. Until the field is known (the sources still read, or a\n * field they don't list), the note says both, promising neither.\n */\nfunction BoundPictureAltNote({\n  id,\n  prop,\n  binding,\n  document,\n  nodeId,\n  services,\n}: BoundPicture & { id: string }): React.JSX.Element {\n  const field = useBoundFieldOf(binding, document, nodeId, services);\n  // A field visitors can't read never fills the published picture: they see\n  // the binding's fallback where it keeps one, else the block's own image, as\n  // the note under the group says. Whatever the field's kind, its alt text\n  // is not theirs.\n  const unreadable = useVisitorUnreadable(nodeId).find(\n    each => each.prop === prop\n  );\n  if (unreadable !== undefined) {\n    return (\n      <p className=\"nx-inspector__note\" id={id} data-bound-picture=\"unreadable\">\n        Visitors can&apos;t read the bound field, so they see{\" \"}\n        {instead(unreadable.fallback !== undefined)}. Type alt text to describe\n        the image they see.\n      </p>\n    );\n  }\n  const kind = field === undefined ? undefined : bindingKindOf(field);\n  if (kind === \"media\") {\n    // The field's type says it holds a file, not that every entry fills it:\n    // an empty one shows what the binding falls back to, so the note says so.\n    return (\n      <p className=\"nx-inspector__note\" id={id} data-bound-picture=\"media\">\n        The image comes from a bound library file, so its own alt text is used.\n        Where the field is empty, visitors see{\" \"}\n        {instead(\"fallback\" in binding && binding.fallback !== undefined)}. Type\n        alt text to describe it here instead.\n      </p>\n    );\n  }\n  if (kind === \"url\" || kind === \"text\") {\n    // An empty field, or an address the page refuses, shows what the binding\n    // falls back to instead, which may well be a described library file.\n    return (\n      <p className=\"nx-inspector__note\" id={id} data-bound-picture=\"address\">\n        This image comes from an address, which carries no alt text. Where the\n        field holds no usable address, visitors see{\" \"}\n        {instead(\"fallback\" in binding && binding.fallback !== undefined)}. Type\n        alt text to describe it for screen readers.\n      </p>\n    );\n  }\n  return (\n    <p className=\"nx-inspector__note\" id={id}>\n      The image comes from a bound field. A library file it holds is described\n      by its own alt text; an image address has none, so type alt text to\n      describe it.\n    </p>\n  );\n}\n\n/**\n * What visitors see in place of a bound picture the field doesn't fill: the\n * binding's fallback where it keeps one, else the block's own image, as the\n * page resolves it.\n */\nfunction instead(hasFallback: boolean): string {\n  return hasFallback ? \"its fallback\" : \"the block's own image\";\n}\n\n/** What the field says while the image is decorative. */\nfunction DecorativeNote({ id }: { id: string }): React.JSX.Element {\n  return (\n    <p className=\"nx-inspector__note\" id={id}>\n      Screen readers skip this image. Its alt text is kept for if you clear\n      this.\n    </p>\n  );\n}\n\n/** The label the block gives one of its props, or `fallback`. */\nfunction labelOf(\n  name: string,\n  props: readonly EditableProp[],\n  fallback: string\n): string {\n  const prop = props.find(each => each.name === name);\n  return prop === undefined ? fallback : propLabel(prop.name, prop.schema);\n}\n\n/**\n * The library file the picture is picked from, read for its alt text: none\n * for a bound picture, whose file the page reads, or for no file at all.\n */\nfunction useLibraryAlt(\n  services: ContentServices | undefined,\n  picture: PictureSource\n): {\n  readonly mediaId: string | undefined;\n  readonly summary: ReturnType<typeof useMediaSummary>;\n  readonly libraryAlt: string | undefined;\n} {\n  const mediaId = picture.kind === \"library\" ? picture.id : undefined;\n  const summary = useMediaSummary(services?.readMedia, mediaId ?? null);\n  return { mediaId, summary, libraryAlt: storedString(summary?.alt) };\n}\n\n/**\n * What a screen reader is given for an image: one \"Alt text\" field holding\n * the words in use, and \"Decorative, no alt text\".\n *\n * While the page stores no words of its own, the field holds the library\n * file's, marked \"From the media library\", so the author sees what screen\n * readers hear and can change it; what they type is stored as the page's\n * own, and \"Use the media library's alt text\" puts the library's back.\n * Decorative keeps the words, held, for when it is cleared.\n */\nexport function ImageAltField({\n  group,\n  props,\n  writable,\n  reasonId,\n  services,\n  onCommitMany,\n  bindable,\n  document,\n  nodeId,\n}: ImageGroupFieldProps & { group: ImageAltGroup }): React.JSX.Element {\n  const id = React.useId();\n  const noteId = React.useId();\n  const values = storedValues(props);\n  const picture = pictureSourceOf(\n    group.media,\n    values,\n    boundPropsOf(document, nodeId)\n  );\n  const { mediaId, summary, libraryAlt } = useLibraryAlt(services, picture);\n  const mode = altModeOf(group, values);\n  const own = storedAlt(group, values);\n  const ownStored = isAuthoredText(values[group.alt]);\n  // Whether anything was written: no change, or one a lock refuses, writes\n  // nothing.\n  const write = (changes: ImageChanges): boolean => {\n    if (Object.keys(changes).length === 0) return false;\n    if (!allWritable(changes, writable)) return false;\n    onCommitMany(changes);\n    return true;\n  };\n  const altHeld = !writable(group.alt);\n  const bound = boundPictureOf(\n    picture,\n    { document, nodeId, services },\n    group.media\n  );\n  // Back to the file's own words drops the page's: one edit, either source.\n  const useFileAlt = (): boolean => write({ [group.alt]: undefined });\n  const wrap = bindable ?? unwrapped;\n  // The alt text's bind button sits on its row; bound, the chip stands for\n  // the words and the decorative mark alike.\n  return (\n    <>\n      {wrap(\n        group.alt,\n        <div className=\"nx-image-group\" data-image-group=\"alt\">\n          <HeldByLock reasonId={altHeld ? reasonId : undefined}>\n            <div className=\"nx-inspector__field\" data-content-control=\"alt\">\n              <Label htmlFor={id}>\n                {labelOf(group.alt, props, \"Alt text\")}\n              </Label>\n              <GrowingText\n                id={id}\n                // The words in use: the page's own where it stores some (an\n                // empty alt included, which the block draws as none), else\n                // the library's.\n                value={ownStored ? own : (libraryAlt ?? \"\")}\n                // The page's own words, or none: the library's arriving is\n                // not the document moving.\n                stored={ownStored ? `own:${own}` : \"library\"}\n                placeholder=\"Describe the picture\"\n                disabled={altHeld || mode === \"decorative\"}\n                describedBy={noteId}\n                onCommit={typed =>\n                  write(altTextChanges(group, typed, values, libraryAlt))\n                }\n              />\n              <AltNote\n                id={noteId}\n                mode={mode}\n                own={ownStored ? own : undefined}\n                bound={bound}\n                mediaId={mediaId}\n                libraryAlt={libraryAlt}\n                read={summary !== undefined}\n              />\n              <AltReset\n                bound={bound}\n                libraryAlt={libraryAlt}\n                offered={ownStored && mode !== \"decorative\"}\n                held={altHeld}\n                onUse={useFileAlt}\n              />\n            </div>\n          </HeldByLock>\n          <DecorativeBox\n            label={labelOf(group.decorative, props, \"Decorative, no alt text\")}\n            checked={mode === \"decorative\"}\n            heldBy={writable(group.decorative) ? undefined : reasonId}\n            onChange={on => write(decorativeChanges(group, on, values))}\n          />\n        </div>,\n        // The block reads a decorative image before its alt text, so binding\n        // the words lifts the mark in the same edit, or the bound alt would\n        // never reach a screen reader.\n        { clearsOnBind: [group.decorative] }\n      )}\n    </>\n  );\n}\n\n/**\n * What the alt field says under its words: that screen readers skip a\n * decorative image or an empty alt, and otherwise, while the page stores no\n * words of its own, whose words are shown (see {@link LibraryAltNote}).\n */\nfunction AltNote({\n  id,\n  mode,\n  own,\n  ...library\n}: {\n  id: string;\n  mode: AltMode;\n  /** The page's own words, where it stores some, an empty alt included. */\n  own: string | undefined;\n} & Omit<\n  React.ComponentProps<typeof LibraryAltNote>,\n  \"id\"\n>): React.JSX.Element | null {\n  if (mode === \"decorative\") return <DecorativeNote id={id} />;\n  if (own === undefined) return <LibraryAltNote id={id} {...library} />;\n  if (own.trim() !== \"\") return null;\n  return (\n    <p className=\"nx-inspector__note\" id={id}>\n      Empty: screen readers skip this image.\n    </p>\n  );\n}\n\n/**\n * \"Use the media library's alt text\": where the page stores words of its own\n * and the library has some, the way back to the library's, which removes the\n * page's own.\n */\nfunction UseLibraryAlt({\n  offered,\n  held,\n  onUse,\n}: {\n  offered: boolean;\n  held: boolean;\n  onUse: () => void;\n}): React.JSX.Element | null {\n  if (!offered) return null;\n  return (\n    <Button\n      type=\"button\"\n      size=\"sm\"\n      variant=\"ghost\"\n      className=\"nx-image-alt__reset\"\n      disabled={held}\n      onClick={onUse}\n    >\n      Use the media library&apos;s alt text\n    </Button>\n  );\n}\n\n/**\n * The way back from the page's own alt text to the file's: for a picked file\n * once the library's words are read, and for a bound one by its field.\n */\nfunction AltReset({\n  bound,\n  libraryAlt,\n  offered,\n  held,\n  onUse,\n}: {\n  bound: BoundPicture | undefined;\n  libraryAlt: string | undefined;\n  /** Whether the page stores words of its own, on an image not decorative. */\n  offered: boolean;\n  held: boolean;\n  onUse: () => void;\n}): React.JSX.Element | null {\n  if (bound !== undefined) {\n    return (\n      <UseBoundFileAlt {...bound} offered={offered} held={held} onUse={onUse} />\n    );\n  }\n  return (\n    <UseLibraryAlt\n      offered={offered && libraryAlt !== undefined}\n      held={held}\n      onUse={onUse}\n    />\n  );\n}\n\n/**\n * The way back to a bound picture's file's own alt text, over words the page\n * stores. The editor can't show the file's words, since the page reads the\n * field when it is drawn, so this is offered without them; a stored empty\n * alt leaves the field blank already, and emptying it again writes nothing,\n * so without this there would be no way back. A field known to hold an\n * address has no library words to go back to, so none is offered there.\n */\nfunction UseBoundFileAlt({\n  binding,\n  document,\n  nodeId,\n  services,\n  offered,\n  held,\n  onUse,\n}: BoundPicture & {\n  offered: boolean;\n  held: boolean;\n  onUse: () => void;\n}): React.JSX.Element | null {\n  const field = useBoundFieldOf(binding, document, nodeId, services);\n  const kind = field === undefined ? undefined : bindingKindOf(field);\n  const address = kind === \"url\" || kind === \"text\";\n  return (\n    <UseLibraryAlt offered={offered && !address} held={held} onUse={onUse} />\n  );\n}\n\n/** \"Decorative, no alt text\": a box beside its words. */\nfunction DecorativeBox({\n  label,\n  checked,\n  heldBy,\n  onChange,\n}: {\n  label: string;\n  checked: boolean;\n  /** The lock reason's id where a lock holds the mark. */\n  heldBy: string | undefined;\n  onChange: (on: boolean) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <HeldByLock reasonId={heldBy}>\n      <div className=\"nx-image-alt__decorative\">\n        <Checkbox\n          id={id}\n          checked={checked}\n          disabled={heldBy !== undefined}\n          onCheckedChange={next => onChange(next === true)}\n        />\n        <Label htmlFor={id}>{label}</Label>\n      </div>\n    </HeldByLock>\n  );\n}\n","\"use client\";\n\n/**\n * What a click on a picture does, drawn as one control over the choice and\n * the link it follows: \"When clicked: Nothing / Link / Enlarge\", with the\n * shared link settings (where it goes, a new tab, its relationship) under it\n * only while Link is the choice.\n *\n * The choice shown is the block's own reading of its props\n * (`whenClickedOf`), the one its render follows, so the panel never says a\n * picture links while the page draws it unlinked. A link the author set\n * stays stored while another choice is made, so switching back to Link\n * brings it back as it was.\n *\n * A picture inside a gallery follows the gallery while it says nothing\n * itself and holds no link, so it is offered one more choice, first: \"Same\n * as the gallery (Enlarge)\", naming what the gallery says. Shown while the\n * picture follows it, and choosing it clears the picture's own choice. A\n * picture holding a link is not offered it: cleared, its choice would read\n * as Link, the link coming before the gallery, so its choices are Nothing,\n * Link and Enlarge, as any picture's are.\n *\n * @module when-clicked-control\n */\n\nimport { findNode, optionLabel } from \"@nextlyhq/blocks-engine\";\nimport { whenClickedOf } from \"@nextlyhq/blocks-react\";\nimport * as React from \"react\";\n\nimport { HeldByLock } from \"../held-by-lock\";\nimport { propLabel, type EditableProp } from \"../inspector\";\n\nimport { SegmentedChoice } from \"./content-controls\";\nimport { galleryPictureOf, type GalleryChoice } from \"./gallery-pictures\";\nimport { isLinkBound, LinkGroupField } from \"./link-control\";\nimport type { LinkGroup } from \"./link-group\";\nimport type { PropGroupContext } from \"./prop-groups\";\n\n/** The choices this control can stand for, as the block reads them. */\nconst CLICK_CHOICES: ReadonlySet<string> = new Set([\n  \"nothing\",\n  \"link\",\n  \"enlarge\",\n]);\n\n/** A block's click choice and the link it follows. */\nexport interface WhenClickedGroup {\n  /** The choice's prop. */\n  readonly choice: string;\n  /** The link the Link choice follows. */\n  readonly link: LinkGroup;\n  /** Every prop the control draws: the choice and the link's. */\n  readonly drawn: ReadonlySet<string>;\n}\n\n/**\n * The click group of a block's props, or `undefined` where it has none: a\n * `whenClicked` select offering Link among choices this control reads, and\n * a link group for Link to show. A `whenClicked` with no link to follow (a\n * gallery's Nothing or Enlarge) keeps its own row.\n */\nexport function whenClickedGroupOf(\n  props: ReadonlyArray<Pick<EditableProp, \"name\" | \"schema\">>,\n  link: LinkGroup | undefined\n): WhenClickedGroup | undefined {\n  if (link === undefined) return undefined;\n  const choice = props.find(prop => prop.name === \"whenClicked\");\n  const options = choice?.schema.options;\n  if (choice?.schema.type !== \"select\" || !Array.isArray(options)) {\n    return undefined;\n  }\n  if (\n    !options.includes(\"link\") ||\n    !options.every(option => CLICK_CHOICES.has(String(option)))\n  ) {\n    return undefined;\n  }\n  return {\n    choice: choice.name,\n    link,\n    drawn: new Set([choice.name, ...link.drawn]),\n  };\n}\n\n/** The props as stored, by name: a default is not a value the page holds. */\nfunction storedValues(\n  props: readonly EditableProp[]\n): Readonly<Record<string, unknown>> {\n  return Object.fromEntries(props.map(prop => [prop.name, prop.value]));\n}\n\n/**\n * Whether the picture, its own choice cleared, would follow what it sits\n * in: asked of the block's own reading (`whenClickedOf`), which reads a link\n * the page would follow (an address, or an entry) before any gallery, and\n * of a bound link, which the page fills before the block reads it.\n */\nfunction followsWhenCleared(\n  group: WhenClickedGroup,\n  values: Readonly<Record<string, unknown>>,\n  bindings: Readonly<Record<string, unknown>> | undefined\n): boolean {\n  const cleared = { ...values, [group.choice]: undefined };\n  return (\n    whenClickedOf(cleared) !== \"link\" && !isLinkBound(group.link, bindings)\n  );\n}\n\n/** The choice a picture in a gallery shows while it follows the gallery. */\nconst FOLLOW_GALLERY = \"same-as-gallery\";\n\n/**\n * The choice the picture reads as now: the block's reading of what is\n * stored, and Link where nothing is chosen and the link is bound, since the\n * page fills a bound link before the block reads it. Inside a gallery, one\n * that says nothing and holds no link follows the gallery.\n */\nfunction choiceShown(\n  group: WhenClickedGroup,\n  values: Readonly<Record<string, unknown>>,\n  bindings: Readonly<Record<string, unknown>> | undefined,\n  followed: GalleryChoice | undefined\n): string {\n  const unchosen = !CLICK_CHOICES.has(String(values[group.choice]));\n  // Read on its own, a picture that says nothing and holds no link reads as\n  // Nothing: what it would follow, where it follows anything.\n  const unlinked = unchosen && whenClickedOf(values) === \"nothing\";\n  if (unlinked && isLinkBound(group.link, bindings)) return \"link\";\n  if (unlinked && followed !== undefined) return FOLLOW_GALLERY;\n  return whenClickedOf(values, followed);\n}\n\n/** \"When clicked\", and under Link the link's own settings. */\nexport function WhenClickedField({\n  group,\n  ...context\n}: PropGroupContext & { group: WhenClickedGroup }): React.JSX.Element {\n  const id = React.useId();\n  const { props, writable, reasonId, onCommitMany, document, nodeId } = context;\n  const prop = props.find(each => each.name === group.choice);\n  const own = Array.isArray(prop?.schema.options)\n    ? prop.schema.options.map(String)\n    : [];\n  const values = storedValues(props);\n  const bindings = findNode(document.nodes, nodeId)?.bindings;\n  // What the gallery the picture sits in says, if it sits in one and the\n  // picture would follow it with its own choice cleared.\n  const followed = followsWhenCleared(group, values, bindings)\n    ? galleryPictureOf(document, nodeId)?.galleryChoice\n    : undefined;\n  const options = followed === undefined ? own : [FOLLOW_GALLERY, ...own];\n  const labelOf = (option: string): string =>\n    option === FOLLOW_GALLERY\n      ? `Same as the gallery (${labelOf(followed ?? \"nothing\")})`\n      : prop === undefined\n        ? option\n        : optionLabel(prop.schema, option);\n  const shown = choiceShown(group, values, bindings, followed);\n  const held = !writable(group.choice);\n  return (\n    <div className=\"nx-when-clicked\" data-content-control=\"when-clicked\">\n      <HeldByLock reasonId={held ? reasonId : undefined}>\n        {/* In the column the other rows' fields take beside their bind\n            buttons, so its edges line up with theirs. */}\n        <div className=\"nx-binding-row\">\n          <div className=\"nx-inspector__field\" data-content-control=\"select\">\n            {/* Named by the section it heads, which already says the words,\n              so the row draws the choices alone. */}\n            <SegmentedChoice\n              id={id}\n              labelledBy={`${id}-label`}\n              options={options}\n              labels={options.map(labelOf)}\n              value={shown}\n              disabled={held}\n              // Only the choice is written, so a stored link stays for the\n              // next time Link is chosen. Following the gallery is the\n              // picture's own choice cleared.\n              onChoose={next => {\n                if (next === shown) return;\n                onCommitMany({\n                  [group.choice]: next === FOLLOW_GALLERY ? undefined : next,\n                });\n              }}\n            />\n            <span id={`${id}-label`} hidden>\n              {prop === undefined\n                ? \"When clicked\"\n                : propLabel(prop.name, prop.schema)}\n            </span>\n          </div>\n        </div>\n      </HeldByLock>\n      {shown === \"link\" ? (\n        <LinkGroupField group={group.link} {...context} />\n      ) : null}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The Content tab's prop groups: several props a block declares that an\n * author reads as one thing, drawn as one control where the first of them\n * (the group's lead) would sit, with no row of their own for the rest.\n *\n * One list of finders, each asked of the block's props, so a link and an\n * image's source and alt text are entries in it rather than cases in the\n * panel. A finder names its group's props by name and type; the block\n * schemas stay as they are.\n *\n * A group draws the bind button for the props an author binds on their own\n * (an image's source, its alt text, a link's address) through the\n * inspector's `bindable` wrapper, so the chip, its menu and its notes are the\n * one implementation every row uses. The rest of a group's props qualify\n * those (how a link opens, whether an image is decorative, which entry a\n * button points at, a list's query) and are set through the group's own\n * control, so the group names exactly which it offers as `bindable`.\n *\n * @module prop-groups\n */\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport type * as React from \"react\";\n\nimport type { EditableProp } from \"../inspector\";\n\nimport type { ContentServices } from \"./content-controls\";\nimport { ImageAltField, ImageSourceField } from \"./image-controls\";\nimport { imageGroupOf } from \"./image-group\";\nimport { LinkGroupField } from \"./link-control\";\nimport { linkGroupOf } from \"./link-group\";\nimport { LIST_QUERY_PROPS, ListQueryField } from \"./list-query-controls\";\nimport { WhenClickedField, whenClickedGroupOf } from \"./when-clicked-control\";\n\n/** What a group may say about one prop's binding beyond its name. */\nexport interface BindableOptions {\n  /**\n   * The group's other props a bind empties in the same edit: those the block\n   * would follow before the bound prop, such as a button's entry reference\n   * before its address.\n   */\n  readonly clearsOnBind?: readonly string[];\n  /**\n   * A link's address and the two halves of the entry reference it follows\n   * first, where the bound prop is a link's destination: the picker also\n   * offers the entries a relation names, whose pick binds the entry's id,\n   * and a bound entry id is drawn in the address's place.\n   */\n  readonly entryLink?: {\n    readonly link: string;\n    readonly collection: string;\n    readonly id: string;\n    /** Whether both halves of the reference may be written where it sits. */\n    readonly writable: boolean;\n  };\n}\n\n/**\n * Wrap one prop's field with its binding controls: the field and a bind\n * button while unbound, the bound chip, Fallback and menu in its place once\n * bound. Hands the field back as it is for a prop no field can fill.\n */\nexport type BindableWrapper = (\n  propName: string,\n  field: React.ReactNode,\n  options?: BindableOptions\n) => React.ReactNode;\n\n/** What a group is drawn with. */\nexport interface PropGroupContext {\n  /** The block's props, as the inspector reads them. */\n  readonly props: readonly EditableProp[];\n  /** Whether one prop may be set where the block sits. */\n  readonly writable: (name: string) => boolean;\n  /** The id of the lock reason a held control points to. */\n  readonly reasonId: string;\n  readonly services: ContentServices | undefined;\n  /** Every set of props the block can be placed with: see `BlockInspection`. */\n  readonly placedWith: ReadonlyArray<Readonly<Record<string, unknown>>>;\n  /** Write several props as one edit. */\n  readonly onCommitMany: (\n    changes: Readonly<Record<string, unknown>>\n  ) => BlockDocument | null | void;\n  /** The document the block is in, for a group that reads around it. */\n  readonly document: BlockDocument;\n  /** The block's id. */\n  readonly nodeId: string;\n  /** Whether the canvas draws this block's empty state, for a list. */\n  readonly showsEmpty: boolean;\n  /** Draw a list's empty state on the canvas, or its entries again. */\n  readonly onShowEmpty?: ((empty: boolean) => void) | undefined;\n  /**\n   * The count of the latest ask, from a list's canvas note, to fix this\n   * list's sort: each new count takes the author to its first sort row.\n   */\n  readonly sortFieldAsked?: number | undefined;\n  /** Tag a list on the canvas while a new source waits for an input. */\n  readonly onStillShowing?: ((words: string | undefined) => void) | undefined;\n  /**\n   * The inspector's binding controls for one of the group's props, for the\n   * props the group names as `bindable`. Absent, as in a component's\n   * placement panel, the group draws its fields alone.\n   */\n  readonly bindable?: BindableWrapper | undefined;\n}\n\n/** One group of a block's props. */\nexport interface PropGroup {\n  /** The prop the group is drawn in place of. */\n  readonly lead: string;\n  /** Every prop the group draws, its lead included. */\n  readonly drawn: ReadonlySet<string>;\n  /**\n   * The props the group offers a bind button for, each through\n   * `PropGroupContext.bindable`; the others it draws are set through its own\n   * control only.\n   */\n  readonly bindable: ReadonlySet<string>;\n  /** The group's control. */\n  readonly render: (context: PropGroupContext) => React.JSX.Element;\n}\n\ntype PropGroupFinder = (props: readonly EditableProp[]) => readonly PropGroup[];\n\n/** A link and what qualifies it: see `link-group`. */\nconst linkGroups: PropGroupFinder = props => {\n  const group = linkGroupOf(props);\n  if (group === undefined) return [];\n  return [\n    {\n      lead: group.link,\n      drawn: group.drawn,\n      // Where it goes. Its target and rel qualify that address. The entry\n      // reference is bound only from the address's own picker, to a related\n      // entry's id, which writes both halves at once (its id bound and its\n      // collection set), so it has no bind button of its own.\n      bindable: new Set([group.link]),\n      render: context => <LinkGroupField group={group} {...context} />,\n    },\n  ];\n};\n\n/**\n * What a click on a picture does, and the link Link follows: see\n * `when-clicked-control`. Asked before the link alone, so the link it holds\n * is drawn under the choice, and only while Link is chosen.\n */\nconst whenClickedGroups: PropGroupFinder = props => {\n  const group = whenClickedGroupOf(props, linkGroupOf(props));\n  if (group === undefined) return [];\n  return [\n    {\n      lead: group.choice,\n      drawn: group.drawn,\n      // Where the link goes, as the link's own group offers it.\n      bindable: new Set([group.link.link]),\n      render: context => <WhenClickedField group={group} {...context} />,\n    },\n  ];\n};\n\n/** An image's source, and its alt text: see `image-group`. */\nconst imageGroups: PropGroupFinder = props => {\n  const group = imageGroupOf(props);\n  if (group === undefined) return [];\n  const { source, alt } = group;\n  return [\n    ...(source === undefined\n      ? []\n      : [\n          {\n            lead: source.media,\n            drawn: source.drawn,\n            // The picture, by its library id or, in URL mode, its address.\n            bindable: new Set([source.media, source.address]),\n            render: (context: PropGroupContext) => (\n              <ImageSourceField\n                group={source}\n                // The chip says the library's alt text only where no alt\n                // row of its own says it.\n                showLibraryAlt={alt === undefined}\n                {...context}\n              />\n            ),\n          },\n        ]),\n    ...(alt === undefined\n      ? []\n      : [\n          {\n            lead: alt.alt,\n            drawn: alt.drawn,\n            // The words; whether the image is decorative is a mode of the\n            // same menu, not a value of its own to fill.\n            bindable: new Set([alt.alt]),\n            render: (context: PropGroupContext) => (\n              <ImageAltField group={alt} {...context} />\n            ),\n          },\n        ]),\n  ];\n};\n\n/**\n * A collection list's query: its source, filters, sort and window, drawn as\n * one group where its collection sits. Asked for by the block declaring its\n * filters with `display: \"listFilters\"`, beside the props the engine's\n * `readListQuery` reads, so no prop of another block is drawn by it.\n */\nconst listQueryGroups: PropGroupFinder = props => {\n  const asks = props.some(\n    prop => prop.name === \"filters\" && prop.schema.display === \"listFilters\"\n  );\n  if (!asks || !props.some(prop => prop.name === \"collection\")) return [];\n  const drawn = new Set<string>(\n    LIST_QUERY_PROPS.filter(name => props.some(prop => prop.name === name))\n  );\n  return [\n    {\n      lead: \"collection\",\n      drawn,\n      // A list's query is chosen, not filled from a field.\n      bindable: new Set<string>(),\n      render: context => <ListQueryField {...context} />,\n    },\n  ];\n};\n\n/** Every finder, in the order its groups claim props. */\nconst FINDERS: readonly PropGroupFinder[] = [\n  whenClickedGroups,\n  linkGroups,\n  imageGroups,\n  listQueryGroups,\n];\n\n/**\n * The groups among a block's props, in finder order. A group naming a prop\n * an earlier group already draws is left out, so no prop is drawn twice and\n * no write reaches a prop through two controls.\n */\nexport function propGroupsOf(props: readonly EditableProp[]): PropGroup[] {\n  const claimed = new Set<string>();\n  const groups: PropGroup[] = [];\n  for (const group of FINDERS.flatMap(find => find(props))) {\n    if ([...group.drawn].some(name => claimed.has(name))) continue;\n    for (const name of group.drawn) claimed.add(name);\n    groups.push(group);\n  }\n  return groups;\n}\n","/**\n * What a Table of contents says under \"Headings\": it lists the page's\n * headings, and any one of them can be left out, from the Heading's own\n * Advanced settings. Said here because the setting lives on each Heading,\n * not on the contents block an author has selected when they look for it.\n *\n * @module toc-left-out-note\n */\nimport type { BlockNode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\n/** The block the note belongs to. */\nconst TABLE_OF_CONTENTS_BLOCK = \"core/table-of-contents\";\n\n/** The setting the note sits under: which heading levels are listed. */\nexport const TOC_NOTE_PROP = \"depth\";\n\n/** The note's words, naming the path to the setting. */\nexport const TOC_LEFT_OUT_HINT =\n  \"Any heading can be left out: Heading → Advanced → Leave out of table of contents\";\n\n/** The note, under a Table of contents' \"Headings\"; nothing on any other block. */\nexport function TocLeftOutNote({\n  node,\n}: {\n  node: Pick<BlockNode, \"type\"> | undefined;\n}): React.JSX.Element | null {\n  if (node?.type !== TABLE_OF_CONTENTS_BLOCK) return null;\n  return <p className=\"nx-settings-note\">{TOC_LEFT_OUT_HINT}</p>;\n}\n","\"use client\";\n\n/**\n * A tab's generated fields: one field per setting the tab draws, grouped,\n * with a list's view and the binding a link group is drawn with. Content and\n * Advanced each draw the block's settings placed in them.\n *\n * @module inspector-content-fields\n */\n\nimport {\n  authoredText,\n  findNode,\n  type BlockDocument,\n  type BuilderOp,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { BindableField } from \"../bindings/binding-controls\";\nimport type { EditorState } from \"../editor-state\";\nimport {\n  useVisitorUnreadable,\n  VisitorUnreadableNote,\n} from \"../shell/visitor-unreadable-context\";\n\nimport {\n  PropExposeControl,\n  type ComponentFieldsBinding,\n} from \"./component-fields-panel\";\nimport {\n  contentControlFor,\n  UnsupportedField,\n  type ContentServices,\n} from \"./content/content-controls\";\nimport { ListMarkerNote } from \"./content/list-marker-note\";\nimport {\n  propGroupsOf,\n  type BindableOptions,\n  type BindableWrapper,\n} from \"./content/prop-groups\";\nimport { TOC_NOTE_PROP, TocLeftOutNote } from \"./content/toc-left-out-note\";\nimport { HeldByLock } from \"./held-by-lock\";\nimport {\n  propLabel,\n  type BlockInspection,\n  type EditableProp,\n} from \"./inspector\";\nimport { SettingSlot } from \"./settings-filter\";\n\n/**\n * The prop whose binding a link group's lead is drawn with: the entry's,\n * where the link follows its bound entry, else the address's.\n *\n * The same precedence the renderer reads a link by (`linkFor` in\n * blocks-react's `blocks/props.ts`): an entry reference, both its halves\n * given, before the address. So a block whose entry is bound and whose\n * collection is set is drawn, and changed, as its entry, whether or not its\n * address is bound too; with no collection the renderer follows the address,\n * and so does the panel. A half counts as given stored or bound, as the\n * render fills a bound one before reading the link.\n */\nfunction drawnBinding(\n  lead: string,\n  entry: BindableOptions[\"entryLink\"],\n  bindings: Readonly<Record<string, unknown>> | undefined,\n  props: readonly EditableProp[]\n): string {\n  if (entry === undefined || bindings?.[entry.id] === undefined) return lead;\n  const collection = props.find(prop => prop.name === entry.collection);\n  // Read as the renderer reads it (`text`, which is `authoredText`).\n  const given =\n    bindings[entry.collection] !== undefined ||\n    authoredText(collection?.value) !== \"\";\n  return given ? entry.id : lead;\n}\n\n/** Whether the canvas draws a list's empty state, and the way to switch it. */\ninterface ListView {\n  readonly showsEmpty: boolean;\n  readonly onShowEmpty: (empty: boolean) => void;\n  /** The count of the latest ask to fix this list's sort, when it has one. */\n  readonly sortFieldAsked: number | undefined;\n  /** Tag the list on the canvas while a new source waits for an input. */\n  readonly onStillShowing: ((words: string | undefined) => void) | undefined;\n}\n\n/** A block's list view, where the editor keeps one. */\nexport function listViewOf(\n  editor: EditorState,\n  nodeId: string\n): ListView | undefined {\n  const show = editor.showListEmpty;\n  if (show === undefined) return undefined;\n  return {\n    showsEmpty: editor.listsShowingEmpty?.has(nodeId) === true,\n    onShowEmpty: empty => show(nodeId, empty),\n    sortFieldAsked:\n      editor.sortFieldAsked?.id === nodeId\n        ? editor.sortFieldAsked.seq\n        : undefined,\n    onStillShowing:\n      editor.tagListStillShowing === undefined\n        ? undefined\n        : words => editor.tagListStillShowing?.(nodeId, words),\n  };\n}\n\n/** What a group is told of the list view: none drawn empty when none is kept. */\nfunction listGroupView(listView: ListView | undefined): {\n  showsEmpty: boolean;\n  onShowEmpty: ListView[\"onShowEmpty\"] | undefined;\n  sortFieldAsked: number | undefined;\n  onStillShowing: ListView[\"onStillShowing\"];\n} {\n  return {\n    showsEmpty: listView?.showsEmpty === true,\n    onShowEmpty: listView?.onShowEmpty,\n    sortFieldAsked: listView?.sortFieldAsked,\n    onStillShowing: listView?.onStillShowing,\n  };\n}\n\n/** One field per setting in `rows`, or the note that there are none. */\nexport function ContentFields({\n  inspection,\n  rows,\n  onCommit,\n  services,\n  reasonId,\n  fields,\n  writable,\n  onCommitMany,\n  document,\n  listView,\n  onApply,\n}: {\n  inspection: BlockInspection;\n  /**\n   * The settings this list draws, in order: those its tab holds. The rest of\n   * the block's props are still read beside them, for a group or a control\n   * whose choices depend on another prop.\n   */\n  rows: readonly EditableProp[];\n  /** Apply one op as an edit: a binding's, which writes props and bindings at once. */\n  onApply: (op: BuilderOp) => boolean;\n  /** The document the block is in, for a group that reads around it. */\n  document: BlockDocument;\n  /** Whether the canvas draws this block's empty state, and the switch. */\n  listView?: ListView | undefined;\n  onCommit: (name: string, value: unknown) => BlockDocument | null | void;\n  /** Several props written as one edit, for a block's prop groups. */\n  onCommitMany: (\n    changes: Readonly<Record<string, unknown>>\n  ) => BlockDocument | null | void;\n  services: ContentServices | undefined;\n  /** The id of the lock reason a held field points to. */\n  reasonId: string;\n  /**\n   * Whether one prop may be set: not on a locked block, and inside a\n   * `contentOnly` area only for content props. The same rule the commit and\n   * the save apply, asked so the field is drawn read-only rather than met with\n   * a refusal.\n   */\n  writable: (name: string) => boolean;\n  /** The component's own view, when the document is a component. */\n  fields?: ComponentFieldsBinding | undefined;\n}): React.JSX.Element {\n  // The bindings on this block a visitor will not see filled, each said under\n  // the field that draws its prop.\n  const unreadable = useVisitorUnreadable(inspection.nodeId);\n  // The block's bindings as the document holds them, so a bound prop draws\n  // its chip in place of its own control.\n  const bindings = findNode(document.nodes, inspection.nodeId)?.bindings;\n  // A prop the inspector leaves out draws no control, but in a component's\n  // view keeps its expose icon: a page may clear what hides it.\n  const drawn = rows.filter(prop => prop.offered || fields !== undefined);\n  if (drawn.length === 0) {\n    return (\n      <p className=\"nx-inspector__note\">\n        This block has no editable properties.\n      </p>\n    );\n  }\n  // What the block holds, for a control whose choices depend on another of\n  // its props: a loop's sort offers its collection's fields.\n  const values = Object.fromEntries(\n    inspection.props.map(prop => [prop.name, prop.value])\n  );\n  // Props an author reads as one thing (a link and what qualifies it, an\n  // image's source, its alt text) are drawn as one group, where the group's\n  // lead prop sits; the others it draws get no row of their own. Built from\n  // the props the block offers, so a sibling its own `onlyWithout` hides is\n  // neither drawn nor written by a group.\n  const groups = propGroupsOf(inspection.props.filter(prop => prop.offered));\n  const leads = new Map(groups.map(group => [group.lead, group]));\n  const grouped = new Set(groups.flatMap(group => [...group.drawn]));\n  // A group's prop wrapped in the same binding controls a prop on its own\n  // row gets, for the props the group offers: one chip, one menu and one\n  // note for every bindable prop, wherever it is drawn.\n  const bindableIn = (offered: ReadonlySet<string>): BindableWrapper =>\n    function wrapBindable(lead, field, options) {\n      const entry = options?.entryLink;\n      const name = drawnBinding(lead, entry, bindings, inspection.props);\n      const prop = inspection.props.find(each => each.name === name);\n      // Offered by the group's lead: a bound entry id is drawn in its place.\n      if (prop === undefined || !prop.offered || !offered.has(lead)) {\n        return field;\n      }\n      const clears = options?.clearsOnBind ?? [];\n      return (\n        <BindableField\n          nodeId={inspection.nodeId}\n          prop={prop}\n          blockLabel={inspection.label}\n          binding={bindings?.[name]}\n          entryLink={entry}\n          document={document}\n          services={services}\n          disabled={!writable(name)}\n          onApply={onApply}\n          clearsOnBind={clears}\n          // The props a bind would empty that may not be written here: a\n          // bind or a change that would empty one is held, while the\n          // fallback and the unbind, which empty nothing, stay offered.\n          clearsLocked={clears.filter(each => !writable(each))}\n        >\n          {field}\n        </BindableField>\n      );\n    };\n  return (\n    <div className=\"nx-inspector__fields\">\n      {drawn.map(prop => (\n        // Hidden while the panel's filter keeps none of what it draws; a\n        // group is kept by any of its props.\n        <SettingSlot\n          key={`${inspection.nodeId}:${prop.name}`}\n          ids={[...(leads.get(prop.name)?.drawn ?? [prop.name])]}\n        >\n          {rowOf(prop)}\n        </SettingSlot>\n      ))}\n    </div>\n  );\n\n  /**\n   * A prop drawn inside its group: in a component's view still a prop of\n   * its own to expose, named, with its icon, as a prop the inspector leaves\n   * out is, so a placement may still set it; elsewhere nothing.\n   */\n  function exposedOnly(prop: EditableProp): React.ReactNode {\n    if (fields === undefined) return null;\n    return (\n      <div\n        key={`${inspection.nodeId}:${prop.name}`}\n        className=\"nx-inspector__prop\"\n      >\n        <p className=\"nx-inspector__note\">\n          {propLabel(prop.name, prop.schema)}\n        </p>\n        <PropExposeControl\n          binding={fields}\n          nodeId={inspection.nodeId}\n          prop={prop}\n        />\n      </div>\n    );\n  }\n\n  function rowOf(prop: EditableProp): React.ReactNode {\n    const group = leads.get(prop.name);\n    if (group === undefined && grouped.has(prop.name)) return exposedOnly(prop);\n    const groupField =\n      group === undefined ? undefined : (\n        <React.Fragment key={`${inspection.nodeId}:${prop.name}`}>\n          {group.render({\n            props: inspection.props,\n            writable,\n            reasonId,\n            services,\n            placedWith: inspection.placedWith,\n            onCommitMany,\n            document,\n            nodeId: inspection.nodeId,\n            ...listGroupView(listView),\n            bindable: bindableIn(group.bindable),\n          })}\n        </React.Fragment>\n      );\n    // Under the field: the props it draws whose bound value a visitor\n    // will not see, a group's included.\n    const note = (\n      <VisitorUnreadableNote\n        bindings={unreadable}\n        props={group === undefined ? new Set([prop.name]) : group.drawn}\n        // A library fallback named by its file, as the image row names it.\n        services={services}\n      />\n    );\n    // Named as the block names it, so its icon is not drawn bare.\n    const field = !prop.offered ? (\n      <p className=\"nx-inspector__note\">{propLabel(prop.name, prop.schema)}</p>\n    ) : (\n      (groupField ?? (\n        <HeldByLock\n          // Keyed by node AND prop: a bare prop name would let React reuse\n          // one block's field for the next block's same-named prop, so the\n          // input would keep the previous block's uncommitted text.\n          key={`${inspection.nodeId}:${prop.name}`}\n          // A held field points at the reason in the card.\n          reasonId={writable(prop.name) ? undefined : reasonId}\n        >\n          <BindableField\n            nodeId={inspection.nodeId}\n            prop={prop}\n            blockLabel={inspection.label}\n            binding={bindings?.[prop.name]}\n            document={document}\n            services={services}\n            disabled={!writable(prop.name)}\n            onApply={onApply}\n          >\n            <PropField\n              prop={prop}\n              disabled={!writable(prop.name)}\n              onCommit={onCommit}\n              services={services}\n              values={values}\n            />\n          </BindableField>\n        </HeldByLock>\n      ))\n    );\n    // Under a List's \"List as\": whether a marker of its own overrides it.\n    // Held as \"List as\" is: a design prop may be set exactly where the\n    // block's styles may change, so the same lock check (Layers, a block it\n    // sits inside, a content-only area) holds the Clear that writes them.\n    // Under a Table of contents' \"Headings\": where a heading is left out.\n    const marker =\n      prop.name === \"kind\" ? (\n        <ListMarkerNote\n          node={findNode(document.nodes, inspection.nodeId)}\n          disabled={!writable(prop.name)}\n          onApply={onApply}\n        />\n      ) : prop.name === TOC_NOTE_PROP ? (\n        <TocLeftOutNote node={findNode(document.nodes, inspection.nodeId)} />\n      ) : null;\n    if (fields === undefined) {\n      // Always a fragment under one key, so a note appearing or going\n      // never remounts the field above it and its uncommitted text.\n      return (\n        <React.Fragment key={`${inspection.nodeId}:${prop.name}`}>\n          {field}\n          {note}\n          {marker}\n        </React.Fragment>\n      );\n    }\n    // The switch sits OUTSIDE the lock's fieldset: a prop a lock holds is\n    // still one a designer may try to expose, and the refusal that says\n    // why is the answer they need, which a disabled switch would withhold.\n    return (\n      <div\n        key={`${inspection.nodeId}:${prop.name}`}\n        className=\"nx-inspector__prop\"\n      >\n        {field}\n        {note}\n        {marker}\n        <PropExposeControl\n          binding={fields}\n          nodeId={inspection.nodeId}\n          prop={prop}\n        />\n      </div>\n    );\n  }\n}\n\nfunction PropField({\n  prop,\n  disabled,\n  onCommit,\n  services,\n  values,\n}: {\n  prop: EditableProp;\n  disabled: boolean;\n  onCommit: (name: string, value: unknown) => BlockDocument | null | void;\n  services: ContentServices | undefined;\n  /** The block's props as stored, for a control that reads another of them. */\n  values: Readonly<Record<string, unknown>>;\n}): React.JSX.Element {\n  // Unique per mount, so two editors on one page never share a field id and a\n  // label never points at the other editor's control.\n  const id = React.useId();\n  const Control = contentControlFor(prop.schema.type);\n\n  if (Control === undefined) {\n    return <UnsupportedField prop={prop} />;\n  }\n\n  return (\n    <Control\n      id={id}\n      prop={prop}\n      disabled={disabled}\n      onCommit={onCommit}\n      services={services}\n      values={values}\n    />\n  );\n}\n","/**\n * A panel kept mounted while it is hidden, so what is typed in it survives,\n * but not rendered again until it shows: a hidden panel draws nothing an\n * author sees, so a selection made while another tab shows costs none of it.\n *\n * @module kept-while-hidden\n */\nimport { findNode, type BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { BlockInspection } from \"./inspector\";\n\n/** What every panel handed here is told: whether it is the one showing. */\ninterface ShownOrNot {\n  readonly onScreen: boolean;\n}\n\n/**\n * `panel`, rendered again whenever it shows or is shown, and while it stays\n * hidden only for a change `heard` says it must follow.\n *\n * It renders once as it hides, which tells it it left the screen, and again\n * as it shows, with what it is handed then. While hidden it keeps what it\n * last drew, so a handler drawn then still acts for what it was drawn for.\n */\nexport function keptWhileHidden<P extends ShownOrNot>(\n  panel: React.FunctionComponent<P>,\n  heard: (before: P, after: P) => boolean = () => false\n): React.NamedExoticComponent<P> {\n  return React.memo(\n    panel,\n    (before, after) =>\n      !before.onScreen && !after.onScreen && !heard(before, after)\n  );\n}\n\n/** What a Content or Advanced tab is drawn from: the block, and the page. */\ninterface DrawnFor {\n  readonly block: Pick<BlockInspection, \"nodeId\">;\n  readonly editor: { readonly document: BlockDocument };\n}\n\n/**\n * Whether the block a hidden Content or Advanced tab was drawn for has\n * changed: its props, its CSS id or attributes, anything the page holds for\n * it.\n *\n * Heard so what the tab holds stays the block as it is: a block's own\n * inspector can hold its commit across an await, and a commit copies the\n * block's props whole, so one built on the block as it hid would put back an\n * undo made on Style since, and Advanced follows its CSS id and attributes\n * the same way. Another block selected is not heard: the tab is drawn for that\n * one when it shows.\n */\nexport function ownBlockChanged(before: DrawnFor, after: DrawnFor): boolean {\n  const id = before.block.nodeId;\n  if (after.block.nodeId !== id) return false;\n  if (before.editor.document === after.editor.document) return false;\n  return (\n    findNode(before.editor.document.nodes, id) !==\n    findNode(after.editor.document.nodes, id)\n  );\n}\n","\"use client\";\n\n/**\n * \"Keep out of search previews\" in the Advanced tab: one switch that marks a\n * container so its root element carries `data-nosnippet`, which keeps its\n * text out of search snippets, Google's AI Overviews and AI Mode among them,\n * while visitors still see it. A Page Builder setting about the block's own\n * HTML, so it works with or without an SEO plugin.\n *\n * Offered on every container: a block that holds other blocks and renders a\n * root element of the tag its author picks. Google reads the mark on `span`,\n * `div` and `section` elements only\n * (https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag),\n * so a container whose tag is another one says so rather than being wrapped\n * in an element the page did not ask for.\n *\n * @module never-quote\n */\n\nimport { findNode, type BlockNode } from \"@nextlyhq/blocks-engine\";\nimport { containerRootTag } from \"@nextlyhq/blocks-react\";\nimport { Switch } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport { BUILT_IN_WRITES } from \"./code-hints\";\nimport { CssHint } from \"./css-hint\";\n\n/**\n * The containers the mark is offered on, and whether each may render a link\n * (an `<a>` root while linked).\n */\nconst MARKABLE: Readonly<Record<string, { linkable: boolean }>> = {\n  \"core/section\": { linkable: false },\n  \"core/box\": { linkable: true },\n  \"core/card\": { linkable: true },\n  \"core/columns\": { linkable: false },\n  \"core/column\": { linkable: false },\n  \"core/accordion\": { linkable: false },\n  \"core/gallery\": { linkable: false },\n};\n\n/** The tags Google reads `data-nosnippet` on that a container may render. */\nconst READ_ON: ReadonlySet<string> = new Set([\"section\", \"div\"]);\n\n/** Whether the mark is offered on `node`: a container. */\nexport function offersNeverQuote(node: Pick<BlockNode, \"type\">): boolean {\n  return Object.hasOwn(MARKABLE, node.type);\n}\n\n/** Whether Google reads the mark on the element `node` renders as its root. */\nfunction readByGoogle(node: BlockNode): boolean {\n  const linkable = MARKABLE[node.type]?.linkable ?? false;\n  return READ_ON.has(containerRootTag(node.props, linkable));\n}\n\n/**\n * The op that marks the node or clears its mark: stored only while on, so a\n * block never marked keeps the document it had.\n */\nfunction neverQuoteOp(nodeId: string, on: boolean): BuilderOp {\n  return on\n    ? { kind: \"update\", id: nodeId, patch: { nosnippet: true } }\n    : { kind: \"update\", id: nodeId, patch: {}, unset: [\"nosnippet\"] };\n}\n\nexport interface NeverQuoteProps {\n  readonly editor: EditorState;\n  readonly nodeId: string;\n  /**\n   * Why a lock holds the block's design, or `undefined` while nothing does:\n   * what its root element carries is part of it, as its id and attributes are.\n   */\n  readonly heldBy?: string | undefined;\n  /** The id of the element saying why, which a held switch points to. */\n  readonly reasonId?: string;\n}\n\nexport function NeverQuote({\n  editor,\n  nodeId,\n  heldBy,\n  reasonId,\n}: NeverQuoteProps): React.JSX.Element | null {\n  const id = React.useId();\n  const node = findNode(editor.document.nodes, nodeId);\n  if (node === undefined || !offersNeverQuote(node)) return null;\n  const on = node.nosnippet === true;\n  const titleId = `${id}-title`;\n  const describedBy = [\n    `${id}-help`,\n    ...(heldBy !== undefined && reasonId !== undefined ? [reasonId] : []),\n  ].join(\" \");\n  return (\n    <section\n      className=\"nx-list-query__group nx-never-quote\"\n      aria-labelledby={titleId}\n      data-never-quote=\"\"\n    >\n      <div className=\"nx-never-quote__head\">\n        <h3 id={titleId} className=\"nx-list-query__title\">\n          Keep out of search previews\n        </h3>\n        {/* What it writes: `data-nosnippet` on the block's root. */}\n        <CssHint writes={BUILT_IN_WRITES.searchPreviews}>\n          <Switch\n            aria-labelledby={titleId}\n            aria-describedby={describedBy}\n            checked={on}\n            disabled={heldBy !== undefined}\n            onCheckedChange={next => editor.apply(neverQuoteOp(nodeId, next))}\n          />\n        </CssHint>\n      </div>\n      <p className=\"nx-inspector__note\" id={`${id}-help`}>\n        Google won&apos;t show this block&apos;s text under the page&apos;s\n        link, or use it as a direct source in AI Overviews and AI Mode. Visitors\n        still see it.\n      </p>\n      {on ? (\n        <p className=\"nx-inspector__note nx-never-quote__on\">\n          On: marked <code>data-nosnippet</code>.\n        </p>\n      ) : null}\n      {on && !readByGoogle(node) ? (\n        <p className=\"nx-inspector__note nx-never-quote__caution\">\n          Google reads this only when the HTML tag is section or div.\n        </p>\n      ) : null}\n    </section>\n  );\n}\n","\"use client\";\n\n/**\n * A section of the block panel, as every tab draws it: a fold header with the\n * section's name in bold, a dot beside it while it holds a value, and the\n * chevron, over the section's controls; sections divided by a line and each\n * folding on its own (`panel-folds`).\n *\n * @module panel-section\n */\nimport {\n  Accordion,\n  AccordionContent,\n  AccordionItem,\n  AccordionTrigger,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditableProp } from \"./inspector\";\nimport { useTabFolds } from \"./panel-folds-context\";\nimport {\n  SettingTabContext,\n  sectionShown,\n  useSettingsMatch,\n} from \"./settings-filter\";\nimport type { SettingTab } from \"./settings-index\";\n\n/**\n * A section's header: its name, the dot when it holds a value, the chevron.\n *\n * The dot carries \"has changes\" for a screen reader, so it is never colour\n * alone, and it sits beside the name it qualifies, so it moves no control.\n */\nexport function SectionHeading({\n  label,\n  holdsValues,\n}: {\n  label: string;\n  holdsValues: boolean;\n}): React.JSX.Element {\n  return (\n    // The panel's own class sets the heading's height and turns the shared\n    // chevron to point right while closed and down while open.\n    <AccordionTrigger className=\"nx-style-inspector__section-trigger\">\n      <span className=\"nx-style-inspector__section-label\">\n        {label}\n        {holdsValues ? (\n          <span className=\"nx-style-inspector__section-dot\" data-has-values=\"\">\n            <span aria-hidden=\"true\" className=\"nx-style-inspector__dot\" />\n            <span className=\"nx-sr-only\">has changes</span>\n          </span>\n        ) : null}\n      </span>\n    </AccordionTrigger>\n  );\n}\n\n/** One section a tab draws: what it is called, and what it holds. */\nexport interface PanelSection {\n  /** What the section is known by in the page: unique in its tab. */\n  readonly key: string;\n  readonly label: string;\n  /** Whether it holds a value for what is being edited. */\n  readonly holdsValue: boolean;\n  /** `false` keeps it folded while it holds a value (`FoldedSection`). */\n  readonly opensWithValue?: false;\n  readonly body: React.ReactNode;\n}\n\n/**\n * A tab's sections, each folding on its own and remembered by the tab and\n * the section's name.\n *\n * A closed section's controls stay mounted, only hidden: a field commits on\n * blur and some hold a draft, so taking them away with the fold would throw\n * away what an author typed.\n */\nexport function PanelSections({\n  tab,\n  sections,\n}: {\n  tab: string;\n  sections: readonly PanelSection[];\n}): React.JSX.Element {\n  const { open, onOpenChange } = useTabFolds(tab, sections);\n  const match = useSettingsMatch();\n  return (\n    <SettingTabContext.Provider value={tab as SettingTab}>\n      <Accordion\n        type=\"multiple\"\n        value={open}\n        onValueChange={onOpenChange}\n        className=\"nx-panel-sections\"\n      >\n        {sections.map(section => (\n          <AccordionItem\n            key={section.key}\n            value={section.key}\n            data-section={section.key}\n            className=\"nx-panel-section\"\n            // A section the filter keeps nothing in is not drawn while it is on.\n            hidden={!sectionShown(match, tab, section.key)}\n          >\n            <SectionHeading\n              label={section.label}\n              holdsValues={section.holdsValue}\n            />\n            {/* Kept mounted but hidden while closed: forced present, the\n              accordion would otherwise leave a closed section's controls\n              on screen and in the Tab order. */}\n            <AccordionContent\n              forceMount\n              hidden={!open.includes(section.key)}\n              className=\"nx-panel-section__body\"\n            >\n              {section.body}\n            </AccordionContent>\n          </AccordionItem>\n        ))}\n      </Accordion>\n    </SettingTabContext.Provider>\n  );\n}\n\n/** Whether any of a section's settings is stored on the block. */\nexport function rowsHoldValue(rows: readonly EditableProp[]): boolean {\n  return rows.some(row => row.value !== undefined);\n}\n","\"use client\";\n\n/**\n * The inspector's Advanced tab: where the block shows and how it is built\n * into the page. Visibility first (which devices, which entries, search\n * previews), then HTML (the block's own HTML settings such as its tag, its\n * anchor, its CSS classes and its attributes), then any other Advanced\n * section the block declares, and last Custom CSS, for a person who may\n * change the site's code.\n *\n * The builder draws the shared settings here for every block, whatever the\n * block declares, so no block can leave them out or draw them elsewhere; a\n * block's own inspector replaces only its Content controls.\n *\n * @module inspector-advanced-tab\n */\n\nimport {\n  BASE_BREAKPOINT,\n  findNode,\n  type BlockDocument,\n  type BlockNode,\n  type BreakpointId,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\nimport type { BlockResolver } from \"@nextlyhq/blocks-react\";\nimport * as React from \"react\";\n\nimport { ShowWhen } from \"../conditions/condition-controls\";\nimport type { EditorState } from \"../editor-state\";\n\nimport { AdvancedPanel } from \"./advanced-panel\";\nimport {\n  VisibilityExposeControl,\n  type ComponentFieldsBinding,\n} from \"./component-fields-panel\";\nimport type { ContentServices } from \"./content/content-controls\";\nimport { commitLinkChanges } from \"./content/link-control\";\nimport type { BlockCustomCssAccess } from \"./custom-css\";\nimport { customCssSections } from \"./custom-css-section\";\nimport { HeldByLock } from \"./held-by-lock\";\nimport { HideOn, type BreakpointsStatus } from \"./hide-on\";\nimport {\n  designReadOnlyReason,\n  lockViewOf,\n  writablePropsOf,\n  type BlockInspection,\n  type EditableProp,\n} from \"./inspector\";\nimport { ContentFields, listViewOf } from \"./inspector-content-fields\";\nimport { keptWhileHidden, ownBlockChanged } from \"./kept-while-hidden\";\nimport { NeverQuote } from \"./never-quote\";\nimport { PanelSections, rowsHoldValue } from \"./panel-section\";\nimport { SettingSlot } from \"./settings-filter\";\n\n/** The Advanced section the builder's own HTML settings join. */\nexport const VISIBILITY_SECTION = \"Visibility\";\nexport const HTML_SECTION = \"HTML\";\n\n/**\n * The Advanced tab. Kept mounted while hidden, so a half-typed attribute\n * survives a look at another tab; drawn again then only when its own block\n * changes.\n */\nexport const AdvancedTab: React.NamedExoticComponent<\n  React.ComponentProps<typeof DrawnAdvancedTab>\n> = keptWhileHidden(DrawnAdvancedTab, ownBlockChanged);\n\nfunction DrawnAdvancedTab({\n  block,\n  editor,\n  onCommit,\n  services,\n  blocks,\n  onScreen,\n  reasonId,\n  fields,\n  breakpoints,\n  breakpoint,\n  breakpointsStatus,\n  customCss,\n}: {\n  block: BlockInspection;\n  editor: EditorState;\n  onCommit: (name: string, value: unknown) => BlockDocument | null | void;\n  services: ContentServices | undefined;\n  blocks: BlockResolver | undefined;\n  /** Whether the Advanced tab is the one showing. */\n  onScreen: boolean;\n  /** The id of the lock reason held controls point to, in the card. */\n  reasonId: string;\n  /** The component's own view, when the document is a component. */\n  fields: ComponentFieldsBinding | undefined;\n  /** The site's breakpoints, for \"Hide on\". */\n  breakpoints: BreakpointSet | undefined;\n  /** The device being edited; the base one where the host names none. */\n  breakpoint: BreakpointId | undefined;\n  /** Whether `breakpoints` is the site's own set yet. */\n  breakpointsStatus: BreakpointsStatus;\n  /** The block's own CSS, given only to a person who may change site code. */\n  customCss: BlockCustomCssAccess | undefined;\n}): React.JSX.Element {\n  const designLocked = designReadOnlyReason(\n    editor.document,\n    block.nodeId,\n    lockViewOf(editor)\n  );\n  // Which props the block's locks leave writable, read once per document and\n  // block rather than once per field the tab draws.\n  const writable = React.useMemo(\n    () => writablePropsOf(editor.document, block.nodeId, lockViewOf(editor)),\n    [editor, block.nodeId]\n  );\n  // The block's own Advanced settings, by section: those in HTML are drawn\n  // above the anchor, the others in sections of their own after it.\n  const { htmlRows, visibilityRows, others } = advancedRowsBySection(\n    block.sections.advanced\n  );\n  const fieldsFor = (rows: readonly EditableProp[]): React.JSX.Element => (\n    <ContentFields\n      inspection={block}\n      rows={rows}\n      onCommit={onCommit}\n      services={services}\n      reasonId={reasonId}\n      fields={fields}\n      writable={writable}\n      onCommitMany={changes => commitLinkChanges(editor, block.nodeId, changes)}\n      onApply={op => editor.apply(op) !== null}\n      document={editor.document}\n      listView={listViewOf(editor, block.nodeId)}\n    />\n  );\n\n  const visibility = (\n    <>\n      {/* In a component's own view: whether each page may hide the block. */}\n      {fields === undefined ? null : (\n        <VisibilityExposeControl\n          binding={fields}\n          nodeId={block.nodeId}\n          blockName={block.label}\n        />\n      )}\n      {/* Which devices the block is hidden on. */}\n      <SettingSlot ids={[\"hideOn\"]}>\n        <HideOn\n          editor={editor}\n          nodeId={block.nodeId}\n          breakpoints={breakpoints}\n          editing={breakpoint ?? BASE_BREAKPOINT}\n          status={breakpointsStatus}\n          heldBy={designLocked}\n          reasonId={reasonId}\n        />\n      </SettingSlot>\n      {/* Whether the block shows at all, by the entry or list item it is\n          drawn with. Keyed by the block, so a row added and not yet\n          finished stays with the block it was added to rather than moving\n          to the next one. */}\n      <SettingSlot ids={[\"showWhen\"]}>\n        <ShowWhen\n          key={block.nodeId}\n          editor={editor}\n          nodeId={block.nodeId}\n          services={services}\n          heldBy={designLocked}\n          reasonId={reasonId}\n        />\n      </SettingSlot>\n      {/* Whether search engines may quote the block's text. Drawn only on a\n          container. */}\n      <SettingSlot ids={[\"neverQuote\"]}>\n        <NeverQuote\n          editor={editor}\n          nodeId={block.nodeId}\n          heldBy={designLocked}\n          reasonId={reasonId}\n        />\n      </SettingSlot>\n      {/* The block's own settings it places in Visibility. */}\n      {visibilityRows.length === 0 ? null : fieldsFor(visibilityRows)}\n    </>\n  );\n  const html = (\n    <>\n      {htmlRows.length === 0 ? null : fieldsFor(htmlRows)}\n      {/*\n        Held while the design is locked: every native control inside is\n        read-only at once and points at the reason in the card, and the\n        panel's own write path refuses what the save would.\n      */}\n      <HeldByLock reasonId={designLocked === undefined ? undefined : reasonId}>\n        <AdvancedPanel\n          // Keyed by node, so a half-typed attribute does not travel to the\n          // next block the way an uncommitted name would. The panel holds\n          // rows locally; without this an author would select another block\n          // and find this one's unsaved row waiting there.\n          key={`${block.nodeId}:advanced`}\n          nodeId={block.nodeId}\n          cssId={block.html.cssId}\n          attributes={block.html.attributes}\n          editor={editor}\n          active={onScreen}\n          blocks={blocks}\n        />\n      </HeldByLock>\n    </>\n  );\n  const node = findNode(editor.document.nodes, block.nodeId);\n  // Custom CSS, for a person who may change site code: the builder's own\n  // row, never one a block declares.\n  const customCssSection = customCssSections({\n    access: customCss,\n    block,\n    stored: node?.customCss,\n    editor,\n    active: onScreen,\n    heldBy: designLocked === undefined ? undefined : reasonId,\n  });\n  // Visibility first, then HTML, then any section the block declares, then\n  // Custom CSS last, for every block.\n  return (\n    <PanelSections\n      tab=\"advanced\"\n      sections={[\n        {\n          key: \"visibility\",\n          label: VISIBILITY_SECTION,\n          holdsValue:\n            visibilityHoldsValue(node) || rowsHoldValue(visibilityRows),\n          body: visibility,\n        },\n        {\n          key: \"html\",\n          label: HTML_SECTION,\n          holdsValue: htmlHoldsValue(block, htmlRows),\n          body: html,\n        },\n        ...others.map(section => ({\n          key: `own:${section.label}`,\n          label: section.label,\n          holdsValue: rowsHoldValue(section.rows),\n          body: fieldsFor(section.rows),\n        })),\n        ...customCssSection,\n      ]}\n    />\n  );\n}\n\n/**\n * A block's own Advanced settings by where they are drawn: its Visibility and\n * HTML settings join the builder's sections of those names, so each is one\n * section, folded as one; any other section it declares is its own.\n */\nexport function advancedRowsBySection(\n  own: BlockInspection[\"sections\"][\"advanced\"]\n): {\n  htmlRows: readonly EditableProp[];\n  visibilityRows: readonly EditableProp[];\n  others: BlockInspection[\"sections\"][\"advanced\"];\n} {\n  const rowsOf = (label: string) =>\n    own.find(section => section.label === label)?.rows ?? [];\n  return {\n    htmlRows: rowsOf(HTML_SECTION),\n    visibilityRows: rowsOf(VISIBILITY_SECTION),\n    others: own.filter(\n      section =>\n        section.label !== HTML_SECTION && section.label !== VISIBILITY_SECTION\n    ),\n  };\n}\n\n/** Whether the block's HTML holds a value: a CSS id, attributes, a setting. */\nfunction htmlHoldsValue(\n  block: BlockInspection,\n  rows: readonly EditableProp[]\n): boolean {\n  return (\n    block.html.cssId !== undefined ||\n    block.html.attributes !== undefined ||\n    rowsHoldValue(rows)\n  );\n}\n\n/**\n * Whether the block's Visibility holds a value: a device it is hidden on, a\n * condition it shows by, or the mark that keeps it out of search previews.\n */\nfunction visibilityHoldsValue(node: BlockNode | undefined): boolean {\n  if (node === undefined) return false;\n  const { visibility } = node;\n  const devices = visibility?.devices;\n  const hidden =\n    devices !== undefined && Object.values(devices).some(shown => !shown);\n  const conditions = visibility?.conditions;\n  return (\n    hidden ||\n    (Array.isArray(conditions) && conditions.length > 0) ||\n    node.nosnippet === true\n  );\n}\n","/**\n * What an Embed's empty state, and its Link setting, decide without drawing\n * anything: which canvas boxes are Embeds waiting for a link, what the editor\n * says about a link, and what storing one writes to the block.\n *\n * Kept apart from the overlay (`embed-states.tsx`) and the inspector's Embed\n * section (`embed-sections.tsx`), which both store a link through\n * {@link embedLinkOp} and say the same words about it, so a link pasted on the\n * canvas and one typed in the panel do the same thing.\n *\n * @module canvas/embed-states-model\n */\n\nimport {\n  BASE_BREAKPOINT,\n  findNode,\n  type BlockDocument,\n  type BlockNode,\n  type NodeStyles,\n  type StyleValues,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  detectEmbed,\n  EMBED_EMPTY_ATTRIBUTE,\n  INSTANCE_ATTRIBUTE,\n  NODE_ID_ATTRIBUTE,\n  type EmbedMatch,\n  type EmbedProviderId,\n  type EmbedShape,\n} from \"@nextlyhq/blocks-react\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\n\n/** The block whose empty state this is. */\nexport const EMBED_BLOCK_TYPE = \"core/embed\";\n\n/** The words the Embed's empty state and Link setting use, in one place. */\nexport const EMBED_STATE_WORDS = {\n  field: \"Paste a YouTube, Vimeo or other link\",\n  add: \"Embed\",\n  plain: \"Shown as a plain frame\",\n} as const;\n\n/**\n * What a provider's size was taken from, as the detection note says it: a\n * video's proportion, a player's height, a map's frame.\n */\nconst SIZED_FROM: Readonly<Record<EmbedProviderId, string>> = {\n  youtube: \"the video\",\n  vimeo: \"the video\",\n  spotify: \"the player\",\n  \"google-maps\": \"the map\",\n};\n\n/**\n * What the editor says about a link: the provider it found and that the\n * block was sized for it, or that it will be shown as a plain frame.\n * `undefined` for no link at all.\n */\nexport function linkNote(link: unknown): string | undefined {\n  if (typeof link !== \"string\" || link.trim() === \"\") return undefined;\n  const match = detectEmbed(link);\n  if (match === undefined) return EMBED_STATE_WORDS.plain;\n  return `${match.name} detected. Size set from ${SIZED_FROM[match.provider]}.`;\n}\n\n/** The Embed named `nodeId`, or `undefined` when there is no such Embed. */\nfunction embedNodeOf(\n  document: BlockDocument,\n  nodeId: string\n): BlockNode | undefined {\n  const node = findNode(document.nodes, nodeId);\n  return node?.type === EMBED_BLOCK_TYPE ? node : undefined;\n}\n\n/** A box an Embed with no link draws on the canvas, and whose it is. */\nexport interface EmptyEmbedBox {\n  readonly nodeId: string;\n  readonly element: Element;\n}\n\n/**\n * The boxes this page's Embeds draw while they have no link. One inside a\n * placed component is the component's, set where the component is edited,\n * so it is left out, as are boxes naming no Embed of this document.\n */\nexport function emptyEmbedBoxes(\n  root: ParentNode,\n  document: BlockDocument\n): EmptyEmbedBox[] {\n  const found: EmptyEmbedBox[] = [];\n  root.querySelectorAll(`[${EMBED_EMPTY_ATTRIBUTE}]`).forEach(element => {\n    if (element.hasAttribute(INSTANCE_ATTRIBUTE)) return;\n    const nodeId = element.getAttribute(NODE_ID_ATTRIBUTE);\n    if (nodeId === null || embedNodeOf(document, nodeId) === undefined) return;\n    found.push({ nodeId, element });\n  });\n  return found;\n}\n\n/**\n * The frames this page's Embeds draw once they have a link: each a document\n * of its own, which takes the pointer from the canvas, so the editor covers\n * it to keep a click selecting the block. One inside a placed component is\n * left out, as its box is.\n */\nexport function embedFrames(\n  root: ParentNode,\n  document: BlockDocument\n): EmptyEmbedBox[] {\n  const found: EmptyEmbedBox[] = [];\n  root.querySelectorAll(`iframe[${NODE_ID_ATTRIBUTE}]`).forEach(element => {\n    if (element.hasAttribute(INSTANCE_ATTRIBUTE)) return;\n    const nodeId = element.getAttribute(NODE_ID_ATTRIBUTE);\n    if (nodeId === null || embedNodeOf(document, nodeId) === undefined) return;\n    found.push({ nodeId, element });\n  });\n  return found;\n}\n\n/** The style values a provider's shape writes on the block, at its base. */\nfunction shapeValues(shape: EmbedShape): Record<string, string | undefined> {\n  // A proportion clears a height a player link set before, and a height\n  // clears the proportion, so the block takes the new link's shape whatever\n  // the last one was.\n  return \"aspectRatio\" in shape\n    ? { aspectRatio: shape.aspectRatio, height: undefined }\n    : { height: shape.height, aspectRatio: \"auto\" };\n}\n\n/** `styles` with the shape's values written at the base state and size. */\nfunction shapedStyles(\n  styles: NodeStyles | undefined,\n  shape: EmbedShape\n): NodeStyles {\n  const base: StyleValues = { ...(styles?.base?.[BASE_BREAKPOINT] ?? {}) };\n  for (const [name, value] of Object.entries(shapeValues(shape))) {\n    if (value === undefined) delete base[name];\n    else base[name] = value;\n  }\n  return { ...styles, base: { ...styles?.base, [BASE_BREAKPOINT]: base } };\n}\n\n/**\n * Storing a link on an Embed, as one step to undo: the link as the author\n * pasted it, and, for a provider the block knows, the provider's shape as the\n * block's own style values, which the author sees and may change.\n *\n * `null` when there is no such Embed, or nothing would change.\n */\nexport function embedLinkOp(\n  document: BlockDocument,\n  nodeId: string,\n  link: string,\n  /**\n   * Whether the block's design may change here. Where a lock holds it (a\n   * content-only area), only the link is written, so a link edit the lock\n   * allows is not refused for the size that would come with it.\n   */\n  options: { readonly shape: boolean } = { shape: true }\n): BuilderOp | null {\n  const node = embedNodeOf(document, nodeId);\n  if (node === undefined) return null;\n  const typed = link.trim();\n  if (typed === \"\" || node.props.src === typed) return null;\n  const match: EmbedMatch | undefined = detectEmbed(typed);\n  return {\n    kind: \"update\",\n    id: nodeId,\n    patch: {\n      props: { ...node.props, src: typed },\n      ...(match === undefined || !options.shape\n        ? {}\n        : { styles: shapedStyles(node.styles, match.shape) }),\n    },\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 * What the Style tab reads about the selection once, for every control:\n * which node, state and breakpoint it edits, the cascade a target is read\n * against, where each control's value came from, and what the cascade\n * applies at another tier.\n *\n * @module style-panel-reading\n */\nimport type {\n  BreakpointId,\n  BreakpointSet,\n  StyleState,\n  StyleSubject,\n} from \"@nextlyhq/blocks-engine\";\nimport type { PageStyleCascade } from \"@nextlyhq/blocks-react\";\n\nimport { breakpointsAtWidth } from \"../../canvas/canvas-width\";\nimport type { EditorState } from \"../../editor-state\";\nimport { editedTierLive } from \"../../styles/breakpoints\";\nimport {\n  breakpointBadge,\n  inheritedProvenance,\n  provenanceBeneath,\n} from \"../../styles/style-provenance\";\nimport { styleSubjectFor } from \"../../styles/style-subject\";\n\nimport type { CascadeAt, ProvenanceOf } from \"./style-field-surroundings\";\nimport type { StyleInspectionOptions } from \"./style-inspector\";\n\n/**\n * The same provenance reading the dots use, asked at a tier: what a canvas at\n * that tier's width applies, through the one ranking of the trace.\n */\nexport function appliedAtReader({\n  cascade,\n  subject,\n  state,\n  breakpoints,\n  nodeId,\n}: {\n  cascade: PageStyleCascade | undefined;\n  subject: StyleSubject | undefined;\n  state: StyleState;\n  breakpoints: BreakpointSet | undefined;\n  nodeId: string;\n}): CascadeAt | undefined {\n  if (cascade === undefined || subject === undefined) return undefined;\n  return (tier, cssProperty) => {\n    const width = breakpoints?.viewport.find(\n      each => each.id === tier\n    )?.maxWidth;\n    const read = provenanceReader({\n      cascade,\n      subject,\n      live: breakpointsAtWidth(breakpoints, width),\n      state,\n      breakpoint: tier,\n      breakpoints,\n      onJumpToBreakpoint: undefined,\n    });\n    const provenance = read({\n      kind: \"cssValue\",\n      cssProperty,\n      tokenKinds: [],\n    })?.provenance;\n    if (provenance === undefined || provenance.kind === \"unset\")\n      return undefined;\n    const { entry } = provenance;\n    return {\n      value: entry.value,\n      breakpoint: entry.breakpoint,\n      own: entry.origin.kind === \"node\" && entry.origin.id === nodeId,\n    };\n  };\n}\n\n/**\n * What the cascade applies to the block at a tier beneath its own\n * declarations: a shared style it wears, its block's defaults. What would stay\n * in force were the block's own values gone, which a control clearing one\n * must spell out to undo.\n */\nexport function beneathAtReader(args: {\n  cascade: PageStyleCascade | undefined;\n  subject: StyleSubject | undefined;\n  state: StyleState;\n  breakpoints: BreakpointSet | undefined;\n  nodeId: string;\n}): CascadeAt | undefined {\n  const { cascade, nodeId } = args;\n  if (cascade === undefined) return undefined;\n  return appliedAtReader({\n    ...args,\n    cascade: {\n      ...cascade,\n      entries: cascade.entries.filter(\n        entry => !(entry.origin.kind === \"node\" && entry.origin.id === nodeId)\n      ),\n    },\n  });\n}\n\n/**\n * The node the declarations describe, or `undefined` with nothing selected.\n *\n * Read from the CASCADE's own tree where there is one. Asking the raw document\n * instead would answer about a node the declarations may not describe — read\n * time repair can drop or replace one — and the fallback is only for a panel\n * with no cascade at all, where no indicator is drawn and the subject is read\n * for the block type alone.\n */\nexport function selectedSubject(\n  editor: EditorState,\n  cascade: PageStyleCascade | undefined,\n  tag: string | undefined\n): StyleSubject | undefined {\n  if (editor.selectedId === null) return undefined;\n  const subject = styleSubjectFor(\n    cascade?.nodes ?? editor.document.nodes,\n    editor.selectedId\n  );\n  // Spread only when there is one, so a host with no canvas leaves the field\n  // ABSENT rather than present-and-undefined. `styleOrigin` reads it as \"the\n  // caller cannot say\" either way, and an absent key says that more plainly to\n  // anyone reading a logged subject.\n  if (subject === undefined || tag === undefined) return subject;\n  return { ...subject, tag };\n}\n\n/**\n * The cascade as the inspection reads it, or `undefined` where there is no\n * cascade or no subject in it: both are needed to ask what applies here.\n */\nexport function cascadeFor(\n  cascade: PageStyleCascade | undefined,\n  subject: StyleSubject | undefined\n): StyleInspectionOptions[\"cascade\"] {\n  if (cascade === undefined || subject === undefined) return undefined;\n  return { trace: cascade.entries, subject };\n}\n\n/**\n * The reader that answers, per control, where its value came from.\n *\n * Built OUTSIDE the panel because nothing in it is React: it is a pure function\n * of inputs the panel has already resolved — one subject, one live set, one\n * trace — and closing over them inside the component put the whole derivation\n * into a body that also renders.\n */\nexport function provenanceReader({\n  cascade,\n  subject,\n  live,\n  state,\n  breakpoint,\n  breakpoints,\n  onJumpToBreakpoint,\n}: {\n  cascade: PageStyleCascade | undefined;\n  subject: StyleSubject | undefined;\n  live: readonly BreakpointId[] | undefined;\n  state: StyleState;\n  breakpoint: BreakpointId;\n  breakpoints: BreakpointSet | undefined;\n  onJumpToBreakpoint: ((breakpoint: BreakpointId) => void) | undefined;\n}): ProvenanceOf {\n  return leaf => {\n    // Absent means the question was never asked. A host that supplies no cascade\n    // gets no indicators, which is the honest answer for a surface that cannot\n    // compile — and not the same as \"nothing is inherited\".\n    if (cascade === undefined || subject === undefined) return undefined;\n    /*\n     * The same answer while the canvas is previewing and nobody has said which\n     * tier the preview BOX is showing.\n     *\n     * Under a preview compile the viewport tiers are container queries, and a\n     * `matchMedia` caller cannot evaluate them — so the window-derived set is\n     * the base context alone. Passed on, that is not silence: `[\"base\"]` is the\n     * CLAIM that base is what the browser is applying, and a narrow box showing\n     * the mobile tier would have every mobile declaration excluded and the base\n     * value reported as the visible winner.\n     *\n     * No dot says \"not asked\", which is true until a caller observes the box.\n     */\n    if (live === undefined) return undefined;\n    const query = {\n      trace: cascade.entries,\n      subject,\n      // The control's own leaf, never the catalog key: two keys can write one\n      // CSS property, and the trace records what was WRITTEN.\n      cssProperty: leaf.cssProperty,\n      descendant: leaf.descendant,\n      state: state,\n      breakpoint: breakpoint,\n      /*\n       * What the BROWSER is applying, and ONLY that. The edited breakpoint is a\n       * different fact and travels separately in `breakpoint`: it says where a\n       * write lands, not what is on screen.\n       *\n       * An earlier version forced the edited breakpoint into this set so a value\n       * authored there could be called \"authored here\". That inverted the\n       * premise — a host editing `mobile` while the canvas sits at desktop width\n       * would have the mobile declaration reported as the visible winner, which\n       * is a value the browser is not showing.\n       *\n       * The consequence is deliberate: editing a breakpoint whose query does not\n       * match reports its controls as unset. That is the honest answer, because\n       * the dot describes what is DISPLAYED rather than what is stored.\n       */\n      liveBreakpoints: live,\n    };\n    /*\n     * ONE query, ONE ranking, read twice. The badge is the breakpoint dimension\n     * of the same answer rather than a second opinion about it — two rankings\n     * of one trace would first disagree at exactly the boundaries the trace\n     * exists to settle.\n     */\n    const provenance = inheritedProvenance(query);\n    const badge = breakpointBadge(query, provenance, breakpoints);\n    /*\n     * Offered only for a tier a canvas can actually be taken to. A declaration\n     * stored under an id that lost its bound still names a real tier — worth\n     * saying — but a jump to it cannot be honoured, and the host would read the\n     * absent width as the unconditional tier and release the canvas instead.\n     */\n    const target =\n      badge.kind === \"inherited\" && badge.source.selectable\n        ? badge.source.breakpoint\n        : undefined;\n    /*\n     * At the tiers that match where the write lands rather than at the\n     * canvas's width: the line describes the position being edited.\n     */\n    const beneath = provenanceBeneath({\n      ...query,\n      liveBreakpoints: editedTierLive(breakpoints, breakpoint, live),\n    });\n    return {\n      provenance,\n      badge,\n      beneath,\n      ...(onJumpToBreakpoint === undefined || target === undefined\n        ? {}\n        : { jump: () => onJumpToBreakpoint(target) }),\n    };\n  };\n}\n","\"use client\";\n\n/**\n * An Accordion's Icon row in its Content tab: \"+ / −\", \"Chevron\" and \"None\"\n * as a row of radio buttons, each choice one step to undo\n * (`accordion-icon.ts`), held where a lock holds the accordion's design.\n *\n * @module accordion-icon-field\n */\nimport {\n  BASE_BREAKPOINT,\n  DISCLOSURE_ICON_PROPERTY,\n  findNode,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\nimport type { PageStyleCascade } from \"@nextlyhq/blocks-react\";\nimport { TooltipProvider } from \"@nextlyhq/ui\";\nimport { RotateCcw } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport type { EditorState } from \"../../editor-state\";\nimport { HeldByLock } from \"../held-by-lock\";\nimport type { PanelSection } from \"../panel-section\";\nimport { SettingSlot } from \"../settings-filter\";\nimport {\n  appliedAtReader,\n  selectedSubject,\n} from \"../style-inspector/style-panel-reading\";\n\nimport {\n  ACCORDION_BLOCK,\n  ACCORDION_ICON_WORDS,\n  ACCORDION_ICONS,\n  accordionIconHoldsValue,\n  accordionIconOf,\n  planAccordionIcon,\n  planAccordionIconReset,\n  type AccordionIcon,\n} from \"./accordion-icon\";\nimport { SegmentedChoice } from \"./content-controls\";\n\n/** The section's name, and the row's. */\nconst ICON_WORDS = \"Icon\";\n\n/** Whether a chosen option is one of the offered icons. */\nfunction isIcon(option: string): option is AccordionIcon {\n  return ACCORDION_ICONS.some(each => each === option);\n}\n\n/** The Icon row: the accordion's icon, chosen from three. */\nexport function AccordionIconField({\n  editor,\n  nodeId,\n  heldBy,\n  inherited,\n}: {\n  editor: Pick<EditorState, \"document\" | \"apply\">;\n  nodeId: string;\n  /** The id of the lock reason while a lock holds the design, else none. */\n  heldBy: string | undefined;\n  /**\n   * The icon reaching the accordion from elsewhere at its base values, a\n   * shared style it wears, which the canvas draws while it holds none.\n   */\n  inherited?: string | undefined;\n}): React.JSX.Element | null {\n  const id = React.useId();\n  const node = findNode(editor.document.nodes, nodeId);\n  if (node === undefined) return null;\n  const held = heldBy !== undefined;\n  return (\n    <SettingSlot ids={[\"disclosureIcon\"]}>\n      <HeldByLock reasonId={heldBy}>\n        <div\n          className=\"nx-inspector__field\"\n          data-content-control=\"accordion-icon\"\n        >\n          <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n            {ICON_WORDS}\n          </p>\n          <SegmentedChoice\n            id={id}\n            labelledBy={`${id}-label`}\n            options={ACCORDION_ICONS}\n            labels={ACCORDION_ICONS.map(each => ACCORDION_ICON_WORDS[each])}\n            value={accordionIconOf(node, inherited)}\n            disabled={held}\n            onChoose={option => {\n              if (held || !isIcon(option)) return;\n              const op = planAccordionIcon(node, option);\n              if (op !== null) editor.apply(op);\n            }}\n          />\n          {/* The way back to what a shared style or the block's default\n              sets, as the Style tab's rows offer: choosing + / − would\n              write the plus as the accordion's own. Drawn as Style draws\n              its reset, while the accordion holds an icon of its own. */}\n          {held || !accordionIconHoldsValue(node) ? null : (\n            <TooltipProvider delayDuration={300}>\n              <ChromeTooltip content=\"Reset\">\n                <button\n                  type=\"button\"\n                  className=\"nx-style-inspector__breakpoint-action\"\n                  data-action=\"reset\"\n                  aria-label={`Reset ${ICON_WORDS}`}\n                  onClick={() => {\n                    const op = planAccordionIconReset(node);\n                    if (op !== null) editor.apply(op);\n                  }}\n                >\n                  <RotateCcw size={14} aria-hidden=\"true\" />\n                </button>\n              </ChromeTooltip>\n            </TooltipProvider>\n          )}\n        </div>\n      </HeldByLock>\n    </SettingSlot>\n  );\n}\n\n/**\n * An Accordion's builder-drawn Content sections, by the names the inspector\n * gives them (`builderContentSectionsOf`), or none for any other block.\n */\nexport function accordionContentSections(\n  context: {\n    readonly editor: EditorState;\n    readonly nodeId: string;\n    readonly designHeldBy: string | undefined;\n    readonly breakpoints?: BreakpointSet | undefined;\n    /** The canvas's cascade, for an icon reaching it from a shared style. */\n    readonly cascade?: PageStyleCascade | undefined;\n    /** The tag the canvas draws the accordion as, the cascade's subject. */\n    readonly renderedTag?: string | undefined;\n  },\n  labels: readonly string[]\n): PanelSection[] {\n  const node = findNode(context.editor.document.nodes, context.nodeId);\n  if (node?.type !== ACCORDION_BLOCK || !labels.includes(ICON_WORDS)) {\n    return [];\n  }\n  // The icon in force at the base values, where the row writes, when it\n  // comes from something other than the accordion's own styles.\n  const reaching = appliedAtReader({\n    cascade: context.cascade,\n    subject: selectedSubject(\n      context.editor,\n      context.cascade,\n      context.renderedTag\n    ),\n    state: \"base\",\n    breakpoints: context.breakpoints,\n    nodeId: context.nodeId,\n  })?.(BASE_BREAKPOINT, DISCLOSURE_ICON_PROPERTY);\n  const inherited = reaching?.own === false ? reaching.value : undefined;\n  return [\n    {\n      key: ICON_WORDS,\n      label: ICON_WORDS,\n      holdsValue: accordionIconHoldsValue(node),\n      body: (\n        <AccordionIconField\n          editor={context.editor}\n          nodeId={context.nodeId}\n          heldBy={context.designHeldBy}\n          inherited={inherited}\n        />\n      ),\n    },\n  ];\n}\n","/**\n * A few choices side by side, one of them chosen: a radio group with one tab\n * stop whose arrow keys choose, as every radio group in the inspector steps.\n * With none chosen (a value no choice writes), the first takes the tab stop.\n *\n * @module segment-choices\n */\nimport * as React from \"react\";\n\nimport { radioGroupStep } from \"../roving-radios\";\n\nimport { CssHint } from \"./css-hint\";\n\n/**\n * The next choice an arrow key moves to, as every radio group here steps,\n * wrapping at either end and passing over the choices that are held.\n */\nfunction steppedTo(\n  key: string,\n  from: number,\n  allowed: readonly boolean[]\n): number | undefined {\n  const step = radioGroupStep(key);\n  if (step === null) return undefined;\n  for (let offset = 1; offset <= allowed.length; offset += 1) {\n    const index =\n      (from + step * offset + allowed.length * offset) % allowed.length;\n    if (allowed[index] === true) return index;\n  }\n  return undefined;\n}\n\n/** Move to the stepped choice: choose it, and take focus to it. */\nexport function arrowTo(\n  event: React.KeyboardEvent<HTMLElement>,\n  from: number,\n  allowed: readonly boolean[],\n  choose: (index: number) => void\n): void {\n  const next = steppedTo(event.key, from, allowed);\n  if (next === undefined) return;\n  event.preventDefault();\n  choose(next);\n  const options =\n    event.currentTarget.parentElement?.querySelectorAll<HTMLElement>(\n      '[role=\"radio\"]'\n    );\n  options?.[next]?.focus();\n}\n\nexport function SegmentChoices<T extends string>({\n  options,\n  on,\n  labels,\n  labelId,\n  onChoose,\n  writes,\n}: {\n  options: readonly T[];\n  /** The chosen one, or none while what is stored is no choice's value. */\n  on: T | undefined;\n  labels: Readonly<Record<T, React.ReactNode>>;\n  labelId: string;\n  onChoose: (on: T) => void;\n  /** What each choice writes, for its tooltip, where the caller knows. */\n  writes?: Readonly<Record<T, string>> | undefined;\n}): React.JSX.Element {\n  const allowed = options.map(() => true);\n  const stop = on === undefined ? options[0] : on;\n  return (\n    <div role=\"radiogroup\" aria-labelledby={labelId} className=\"nx-segment\">\n      {options.map((option, index) => (\n        <CssHint key={option} writes={writes?.[option]}>\n          <button\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={on === option}\n            tabIndex={stop === option ? 0 : -1}\n            className=\"nx-segment__option\"\n            onKeyDown={event =>\n              arrowTo(event, index, allowed, next => {\n                const target = options[next];\n                if (target !== undefined) onChoose(target);\n              })\n            }\n            onClick={() => onChoose(option)}\n          >\n            {labels[option]}\n          </button>\n        </CssHint>\n      ))}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * A Columns row's layout, in its Content tab: tiles that set how many\n * columns it holds and how wide, where it stacks, and whether it stacks\n * reversed.\n *\n * Every choice is one step of the history, its Style values and any empty\n * columns it adds or removes together. What each writes is in\n * `columns-layout.ts`.\n *\n * @module columns-layout-field\n */\nimport {\n  BASE_BREAKPOINT,\n  findNode,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\nimport type { PageStyleCascade } from \"@nextlyhq/blocks-react\";\nimport { Switch } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  COLUMNS_LAYOUTS,\n  COLUMNS_ROW,\n  defaultTemplate,\n  layoutHoldsValue,\n  layoutOf,\n  planLayout,\n  planStack,\n  reachedStacks,\n  stackOf,\n  type AppliedAt,\n  stackTiers,\n  type ColumnsLayout,\n  type StackOn,\n} from \"../../canvas/columns-layout\";\nimport type { EditorState } from \"../../editor-state\";\nimport { readStyleValue } from \"../../styles/style-values\";\nimport { HeldByLock } from \"../held-by-lock\";\nimport type { PanelSection } from \"../panel-section\";\nimport { arrowTo, SegmentChoices } from \"../segment-choices\";\nimport { SettingSlot } from \"../settings-filter\";\nimport {\n  appliedAtReader,\n  selectedSubject,\n} from \"../style-inspector/style-panel-reading\";\n\n/** Where a row stacks, each choice saying every device it applies on. */\nconst STACK_LABELS: Readonly<Record<StackOn, string>> = {\n  never: \"Never\",\n  tablet: \"Tablet and mobile\",\n  mobile: \"Mobile\",\n};\n\n/**\n * A tile's picture: its columns as bars, at their widths. Exported for the\n * first-add picker, which offers the same tiles.\n */\nexport function ColumnsLayoutGlyph({\n  layout,\n}: {\n  layout: ColumnsLayout;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-columns-layout__glyph\" aria-hidden=\"true\">\n      {layout.tracks.map((width, index) => (\n        <i key={index} style={{ flexGrow: width }} />\n      ))}\n    </span>\n  );\n}\n\n/** What the row's widths are, said under the tiles. */\nfunction hintFor(current: string, set: boolean): string {\n  if (current === \"custom\") return \"A layout of its own, set in Style.\";\n  if (current === \"none\") return \"Pick how many columns, and how wide.\";\n  return set\n    ? \"Columns at these widths.\"\n    : \"Equal columns that wrap when narrow.\";\n}\n\n/** How many columns the row holds now. */\nfunction countOf(row: Row): number {\n  return row.slots?.children?.length ?? 0;\n}\n\n/** Why the pointed tile is held, if one is. */\nfunction heldReason(\n  row: Parameters<typeof planLayout>[0],\n  pointed: string | undefined,\n  at: Parameters<typeof planLayout>[2]\n): string | undefined {\n  if (pointed === undefined) return undefined;\n  const plan = planLayout(row, pointed, at);\n  return plan.ok ? undefined : plan.reason;\n}\n\ntype Row = NonNullable<ReturnType<typeof findNode>>;\n\n/**\n * Where every choice here writes: the row's own base values, whatever device,\n * state or shared style the Style tab is editing, since how many columns a\n * row holds is its structure. Stacking still names the devices it applies on.\n * The first-add picker writes there too.\n */\nexport const ROW_OWN: {\n  readonly state: \"base\";\n  readonly breakpoint: typeof BASE_BREAKPOINT;\n} = { state: \"base\", breakpoint: BASE_BREAKPOINT };\n\n/** The width tiles: one tab stop, arrows choosing, a held tile saying why. */\nfunction WidthTiles({\n  row,\n  current,\n  labelId,\n  hintId,\n  onPoint,\n  editor,\n  held: locked,\n}: {\n  row: Row;\n  current: string;\n  labelId: string;\n  hintId: string;\n  onPoint: (key: string | undefined) => void;\n  editor: EditorState;\n  /** Whether the row's design is locked, so a choice writes nothing. */\n  held: boolean;\n}): React.JSX.Element {\n  const plans = COLUMNS_LAYOUTS.map(layout =>\n    planLayout(row, layout.key, ROW_OWN)\n  );\n  const allowed = plans.map(plan => plan.ok);\n  const stop = Math.max(\n    0,\n    COLUMNS_LAYOUTS.findIndex(layout => layout.key === current)\n  );\n  const choose = (index: number) => {\n    const plan = plans[index];\n    if (locked || plan?.ok !== true) return;\n    // The chosen tile again writes no template, only the columns it still\n    // needs: a row reading \"3 equal\" with a column deleted gets it back.\n    const ops =\n      COLUMNS_LAYOUTS[index]?.key === current ? plan.columnOps : plan.ops;\n    if (ops.length > 0) editor.applyAll([...ops]);\n  };\n  return (\n    <div\n      role=\"radiogroup\"\n      aria-labelledby={labelId}\n      className=\"nx-columns-layout__tiles\"\n    >\n      {COLUMNS_LAYOUTS.map((layout, index) => {\n        const plan = plans[index];\n        const held = plan !== undefined && !plan.ok;\n        return (\n          <button\n            key={layout.key}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={layout.key === current}\n            aria-label={layout.label}\n            tabIndex={index === stop ? 0 : -1}\n            // Held, not disabled: still reachable, so its reason can be read;\n            // the hint under the tiles says it, as its description.\n            {...(held\n              ? { \"aria-disabled\": true, \"aria-describedby\": hintId }\n              : {})}\n            className=\"nx-columns-layout__tile\"\n            onMouseEnter={() => onPoint(held ? layout.key : undefined)}\n            onMouseLeave={() => onPoint(undefined)}\n            onFocus={() => onPoint(held ? layout.key : undefined)}\n            onBlur={() => onPoint(undefined)}\n            onKeyDown={event => arrowTo(event, index, allowed, choose)}\n            onClick={() => choose(index)}\n          >\n            <ColumnsLayoutGlyph layout={layout} />\n            <span>{layout.label}</span>\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\nexport function ColumnsLayoutControl({\n  editor,\n  nodeId,\n  breakpoints,\n  applied,\n  heldBy,\n}: {\n  editor: EditorState;\n  nodeId: string;\n  breakpoints: BreakpointSet | undefined;\n  /**\n   * The id of the lock's reason while the row's design is locked: every\n   * control is then held, described by it, and writes nothing.\n   */\n  heldBy?: string | undefined;\n  /**\n   * What the cascade applies to the row at a tier, for a stack or a template\n   * reaching it from elsewhere.\n   */\n  applied?: AppliedAt | undefined;\n}): React.JSX.Element | null {\n  const labelId = React.useId();\n  const stackId = React.useId();\n  const hintId = React.useId();\n  // The held tile being hovered or focused, whose reason the hint then says.\n  const [pointed, setPointed] = React.useState<string | undefined>(undefined);\n  const row = findNode(editor.document.nodes, nodeId);\n  if (row === undefined) return null;\n  const stored = readStyleValue(row.styles, {\n    ...ROW_OWN,\n    property: \"gridTemplateColumns\",\n    path: [],\n  });\n  // While the row stores none, the template a shared style gives it is the\n  // one the canvas draws, so a tile chosen over it still writes its own.\n  const reaching =\n    stored === undefined\n      ? applied?.(BASE_BREAKPOINT, \"grid-template-columns\")\n      : undefined;\n  const inherited =\n    reaching?.own === false && reaching.value !== defaultTemplate(row)\n      ? reaching.value\n      : undefined;\n  const current = layoutOf(\n    stored ?? inherited,\n    defaultTemplate(row),\n    countOf(row)\n  );\n  const tiers = stackTiers(breakpoints);\n  const reached = reachedStacks(tiers, applied);\n  const stack = stackOf(row, tiers, ROW_OWN.state, reached);\n  const options = ([\"never\", \"tablet\", \"mobile\"] as const).filter(\n    on => on === \"never\" || tiers[on] !== undefined\n  );\n  const restack = (on: StackOn, reversed: boolean) => {\n    if (heldBy !== undefined) return;\n    const op = planStack(row, on, reversed, {\n      tiers,\n      state: ROW_OWN.state,\n      reached,\n    });\n    if (op !== null) editor.apply(op);\n  };\n  return (\n    <HeldByLock reasonId={heldBy}>\n      <div className=\"nx-columns-layout\" data-control=\"columns-layout\">\n        <SettingSlot ids={[\"columnsLayout\"]}>\n          <div className=\"nx-inspector__field nx-columns-layout__layout\">\n            <span className=\"nx-inspector__field-name\" id={labelId}>\n              Layout\n            </span>\n            <WidthTiles\n              row={row}\n              current={current}\n              labelId={labelId}\n              hintId={hintId}\n              onPoint={setPointed}\n              editor={editor}\n              held={heldBy !== undefined}\n            />\n          </div>\n          <p id={hintId} className=\"nx-inspector__note\" aria-live=\"polite\">\n            {heldReason(row, pointed, ROW_OWN) ??\n              hintFor(current, (stored ?? inherited) !== undefined)}\n          </p>\n        </SettingSlot>\n        {options.length > 1 ? (\n          <>\n            <SettingSlot ids={[\"stackOn\"]}>\n              <div className=\"nx-inspector__field\">\n                <span className=\"nx-inspector__field-name\" id={stackId}>\n                  Stack on\n                </span>\n                <SegmentChoices\n                  options={options}\n                  on={stack.on}\n                  labels={STACK_LABELS}\n                  labelId={stackId}\n                  onChoose={on => restack(on, stack.reversed)}\n                />\n              </div>\n            </SettingSlot>\n            <SettingSlot ids={[\"reverseStacked\"]}>\n              <div className=\"nx-inspector__field\">\n                <span className=\"nx-inspector__field-name\">\n                  Reverse when stacked\n                </span>\n                <Switch\n                  aria-label=\"Reverse when stacked\"\n                  checked={stack.reversed}\n                  disabled={stack.on === \"never\"}\n                  onCheckedChange={reversed => restack(stack.on, reversed)}\n                />\n              </div>\n            </SettingSlot>\n          </>\n        ) : null}\n      </div>\n    </HeldByLock>\n  );\n}\n\n/** What the Content tab knows of the page around a Columns row. */\nexport interface ColumnsSectionContext {\n  readonly editor: EditorState;\n  readonly nodeId: string;\n  /** The block's type, which decides whether it has the section at all. */\n  readonly blockName: string;\n  /** The section's name, as the inspection names it. */\n  readonly label: string;\n  readonly breakpoints: BreakpointSet | undefined;\n  /** The canvas's cascade, for a stack reaching the row from a shared style. */\n  readonly cascade: PageStyleCascade | undefined;\n  /** The tag the canvas draws the row as, which the cascade's subject names. */\n  readonly renderedTag: string | undefined;\n  /** The id of the lock's reason while the row's design is locked. */\n  readonly heldBy?: string | undefined;\n}\n\n/**\n * A Columns row's Content section, Layout and Stack on, or `undefined` for\n * any other block. Its dot shows while the row stores a template or a stack.\n * A stack reaching the row is read from the cascade's base state, the state\n * every choice here writes.\n */\nexport function columnsContentSection(\n  context: ColumnsSectionContext\n): PanelSection | undefined {\n  const { editor, nodeId, blockName, breakpoints } = context;\n  if (blockName !== COLUMNS_ROW) return undefined;\n  const row = findNode(editor.document.nodes, nodeId);\n  if (row === undefined) return undefined;\n  const applied = appliedAtReader({\n    cascade: context.cascade,\n    subject: selectedSubject(editor, context.cascade, context.renderedTag),\n    state: ROW_OWN.state,\n    breakpoints,\n    nodeId,\n  });\n  return {\n    key: context.label,\n    label: context.label,\n    holdsValue: layoutHoldsValue(row, stackTiers(breakpoints)),\n    body: (\n      <ColumnsLayoutControl\n        editor={editor}\n        nodeId={nodeId}\n        breakpoints={breakpoints}\n        applied={applied}\n        heldBy={context.heldBy}\n      />\n    ),\n  };\n}\n","\"use client\";\n\n/**\n * The Embed block's Content section, which the builder draws itself in place\n * of the generated rows: the block's declaration still says what is edited\n * there, and an editor without this draws the generated rows instead.\n *\n * - **Link** is the block's own field, bindable as any is; a link typed or\n *   pasted there takes the provider's shape in the same step (the Content\n *   tab's one write, `commitProp`, uses the canvas field's `embedLinkOp`).\n *   Under it, what was found: \"YouTube detected. Size set from the video.\"\n *   or \"Shown as a plain frame\".\n * - **Load** and **Poster** only for a link a provider owns, since any other\n *   link is a plain frame loaded with the page; **Poster** only while the\n *   player loads when played, as that is when a poster shows.\n * - **Privacy mode** only for a provider with a privacy-enhanced player.\n * - **Use the video's thumbnail** copies the provider's picture into the\n *   media library through the host, and makes it the poster.\n *\n * @module embed-sections\n */\nimport { detectEmbed } from \"@nextlyhq/blocks-react\";\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { linkNote } from \"../../canvas/embed-states-model\";\nimport type { BlockInspection, EditableProp } from \"../inspector\";\n\nimport type { ContentServices } from \"./content-services\";\n\n/** The block this section is drawn for. */\nconst EMBED_BLOCK = \"core/embed\";\n\n/** The section the block places its settings in: its own label. */\nconst EMBED_SECTION = \"Embed\";\n\n/** The words this section adds to the block's own labels. */\nconst EMBED_SECTION_WORDS = {\n  thumbnail: \"Use the video's thumbnail\",\n  copying: \"Copying the thumbnail…\",\n  copyFailed: \"The thumbnail couldn't be copied\",\n} as const;\n\n/** What drawing the section needs from the Content tab. */\nexport interface EmbedSectionsContext {\n  readonly inspection: BlockInspection;\n  /** The block's props as stored. */\n  readonly stored: Readonly<Record<string, unknown>>;\n  readonly services: ContentServices | undefined;\n  /** Whether a prop may be written here: a lock or a content-only area say. */\n  readonly writable: (name: string) => boolean;\n  readonly onCommit: (name: string, value: unknown) => void;\n  /** The generated rows for `rows`, as the tab draws any section's. */\n  readonly rowsOf: (rows: readonly EditableProp[]) => React.JSX.Element;\n  /** Whether the block's link is bound to a field. */\n  readonly linkBound?: boolean;\n}\n\n/**\n * The body of the Embed's section the builder draws, by its name, or none\n * for any other block.\n */\nexport function embedSectionBodies(\n  context: EmbedSectionsContext\n): ReadonlyMap<string, React.JSX.Element> | undefined {\n  const { inspection } = context;\n  if (inspection.blockName !== EMBED_BLOCK) return undefined;\n  return new Map([\n    [EMBED_SECTION, <EmbedSection key=\"embed\" context={context} />],\n  ]);\n}\n\n/** The props, by name, in the order they are drawn. */\nfunction rowsNamed(\n  inspection: BlockInspection,\n  names: readonly string[]\n): EditableProp[] {\n  return names.flatMap(name => {\n    const row = inspection.props.find(prop => prop.name === name);\n    return row === undefined ? [] : [row];\n  });\n}\n\nfunction EmbedSection({\n  context,\n}: {\n  readonly context: EmbedSectionsContext;\n}): React.JSX.Element {\n  const { inspection, stored, writable } = context;\n  // A link bound to a field is the field's, known only where the page is\n  // drawn: every setting a provider's link takes is offered, and nothing is\n  // judged from the stored literal it no longer shows.\n  const bound = context.linkBound === true;\n  const link = !bound && typeof stored.src === \"string\" ? stored.src : \"\";\n  const match = detectEmbed(link);\n  const provider = bound || match !== undefined;\n  // As the block reads them: a new Embed stores When played; one stored\n  // before the choice reads as Right away.\n  const played = provider && stored.load === \"click\";\n  const names = [\n    \"title\",\n    ...(provider ? [\"load\"] : []),\n    ...(bound || match?.privacyMode === true ? [\"privacy\"] : []),\n    ...(played ? [\"poster\"] : []),\n  ];\n  return (\n    <>\n      {context.rowsOf(rowsNamed(inspection, [\"src\"]))}\n      {/* What the link is, said again whenever it changes, so a screen\n          reader hears what was found without leaving the field. */}\n      <p className=\"nx-inspector__note nx-embed-note\" role=\"status\">\n        {linkNote(link) ?? \"\"}\n      </p>\n      {context.rowsOf(\n        rowsNamed(inspection, names).map(row =>\n          // An Embed stored before Load existed loads with the page, so its\n          // unset Load reads as Right away, as the block draws it, rather\n          // than as a new Embed's When played.\n          row.name === \"load\" && stored.load === undefined\n            ? { ...row, defaultValue: \"page\" }\n            : row\n        )\n      )}\n      {/* Only for a link the panel knows: a bound link's video is the\n          field's, and copying the stored literal's picture would be the\n          wrong one. */}\n      {played && match?.thumbnail !== undefined ? (\n        <ThumbnailCopy\n          // One copy per block and link: a reply for another block or link\n          // is never stored here, and a new link starts with no copy pending.\n          key={`${inspection.nodeId}\\n${link}`}\n          link={link}\n          copy={context.services?.copyEmbedThumbnail}\n          disabled={!writable(\"poster\")}\n          onCopied={id => context.onCommit(\"poster\", id)}\n        />\n      ) : null}\n    </>\n  );\n}\n\n/** \"Use the video's thumbnail\", and what became of the last press. */\nfunction ThumbnailCopy({\n  link,\n  copy,\n  disabled,\n  onCopied,\n}: {\n  readonly link: string;\n  readonly copy: ContentServices[\"copyEmbedThumbnail\"];\n  readonly disabled: boolean;\n  readonly onCopied: (mediaId: string) => void;\n}): React.JSX.Element | null {\n  const [state, setState] = React.useState<\"idle\" | \"copying\" | \"failed\">(\n    \"idle\"\n  );\n  // The latest way to store the poster, read when the reply arrives: a\n  // callback from the press would write over edits made while it was\n  // pending. And whether this copy is still shown, since it is one per\n  // block and link.\n  const store = React.useRef(onCopied);\n  store.current = onCopied;\n  const shown = React.useRef(true);\n  // Set on every setup as well as cleared on every cleanup: React may run\n  // the pair twice for one mount (Strict Mode), and a flag only cleared\n  // would stay down for the copy that is still shown.\n  React.useEffect(() => {\n    shown.current = true;\n    return () => {\n      shown.current = false;\n    };\n  }, []);\n  if (copy === undefined) return null;\n  return (\n    <div className=\"nx-inspector__field\">\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        disabled={disabled || state === \"copying\"}\n        onClick={() => {\n          setState(\"copying\");\n          copy(link).then(\n            media => {\n              if (!shown.current) return;\n              setState(\"idle\");\n              store.current(media.id);\n            },\n            () => {\n              if (shown.current) setState(\"failed\");\n            }\n          );\n        }}\n      >\n        {state === \"copying\"\n          ? EMBED_SECTION_WORDS.copying\n          : EMBED_SECTION_WORDS.thumbnail}\n      </Button>\n      <p className=\"nx-inspector__note\" role=\"status\">\n        {state === \"failed\" ? `${EMBED_SECTION_WORDS.copyFailed}.` : \"\"}\n      </p>\n    </div>\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","\"use client\";\n\n/**\n * A Form's \"After sending\": what a visitor sees once a send is accepted.\n *\n * \"Show a message\" or \"Go to a page\", with the message's words or the page\n * under the choice. A form picked from a provider starts on \"Use the form's\n * own setting (<what it is>)\", the provider's choice for that form, which\n * this block may override.\n *\n * The page is the shared link setting (a page of the site, or an address),\n * drawn by the caller with the block's link props.\n *\n * @module form-after-sending\n */\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { SegmentedChoice } from \"./content-controls\";\nimport type { ContentServices } from \"./content-services\";\nimport { pickedFormOf, type PickedForm } from \"./form-picked\";\n\n/** The words of each choice. */\nconst CHOICE_WORDS = {\n  message: \"Show a message\",\n  page: \"Go to a page\",\n} as const;\n\n/** What the block shows once sent, with the default for its mode applied. */\nfunction afterSendingOf(\n  stored: unknown,\n  picked: boolean\n): \"form\" | \"message\" | \"page\" {\n  if (stored === \"message\" || stored === \"page\") return stored;\n  if (stored === \"form\" && picked) return \"form\";\n  return picked ? \"form\" : \"message\";\n}\n\n/** What a picked form's own setting is, once the host says. */\nfunction useOwnSetting(\n  picked: PickedForm | undefined,\n  services: ContentServices | undefined\n): string | undefined {\n  const [own, setOwn] = React.useState<string | undefined>(undefined);\n  const describe = services?.describeForm;\n  const provider = picked?.provider;\n  const ref = picked?.ref;\n  React.useEffect(() => {\n    setOwn(undefined);\n    if (describe === undefined || provider === undefined || ref === undefined) {\n      return;\n    }\n    let current = true;\n    describe({ provider, ref })\n      .then(described => {\n        if (current && described !== undefined) {\n          setOwn(CHOICE_WORDS[described.afterSending.kind]);\n        }\n      })\n      .catch(() => undefined);\n    return () => {\n      current = false;\n    };\n  }, [describe, provider, ref]);\n  return own;\n}\n\n/** \"Use the form's own setting\", with what it is where that is known. */\nfunction ownSettingWords(own: string | undefined): string {\n  return own === undefined\n    ? \"Use the form's own setting\"\n    : `Use the form's own setting (${own})`;\n}\n\nexport function AfterSendingControl({\n  id,\n  props,\n  disabled,\n  services,\n  onCommit,\n  message,\n  page,\n}: {\n  id: string;\n  /** The block's stored props. */\n  props: Readonly<Record<string, unknown>>;\n  disabled: (name: string) => boolean;\n  services: ContentServices | undefined;\n  onCommit: (name: string, value: unknown) => void;\n  /** The message's own row, drawn for \"Show a message\". */\n  message: React.ReactNode;\n  /** The shared link setting, drawn for \"Go to a page\". */\n  page: React.ReactNode;\n}): React.JSX.Element {\n  const picked = pickedFormOf(props.form);\n  const chosen = afterSendingOf(props.afterSending, picked !== undefined);\n  const own = useOwnSetting(picked, services);\n  const options =\n    picked === undefined\n      ? ([\"message\", \"page\"] as const)\n      : ([\"form\", \"message\", \"page\"] as const);\n  const words = (option: (typeof options)[number]): string =>\n    option === \"form\" ? ownSettingWords(own) : CHOICE_WORDS[option];\n  return (\n    <div className=\"nx-form-after\" data-content-control=\"after-sending\">\n      <div className=\"nx-inspector__field nx-inspector__field--stacked\">\n        {/* Its own name, not the section's title again right above it. */}\n        <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n          Then\n        </p>\n        {picked === undefined ? (\n          <SegmentedChoice\n            id={id}\n            labelledBy={`${id}-label`}\n            options={options}\n            labels={options.map(words)}\n            value={chosen}\n            disabled={disabled(\"afterSending\")}\n            onChoose={next => onCommit(\"afterSending\", next)}\n          />\n        ) : (\n          // Three choices, one of them long: a menu.\n          <Select\n            value={chosen}\n            disabled={disabled(\"afterSending\")}\n            onValueChange={next => onCommit(\"afterSending\", next)}\n          >\n            <SelectTrigger id={id} aria-labelledby={`${id}-label`}>\n              <SelectValue />\n            </SelectTrigger>\n            <SelectContent>\n              {options.map(option => (\n                <SelectItem key={option} value={option}>\n                  {words(option)}\n                </SelectItem>\n              ))}\n            </SelectContent>\n          </Select>\n        )}\n      </div>\n      {chosen === \"message\" ? message : null}\n      {chosen === \"page\" ? page : null}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * A Form's Fields, as the author edits them: one row per field, named by its\n * label and type, dragged by its handle into a new order, opened to edit it,\n * and \"+ Add field\" below.\n *\n * Open, a field shows its label, its type, Required, a Dropdown's or a\n * Choice's options, and under Advanced the name its answer is sent under,\n * which is made from its label until the author writes one (the block's own\n * `sentNameOf`, so the name shown is the name sent).\n *\n * Every change writes the whole list once, as one step to undo. Text commits\n * on blur, as every inspector field does. The handle moves a field with the\n * arrow keys too, so the order is reachable without a pointer.\n *\n * @module form-fields-control\n */\nimport { FORM_MAX_FIELDS, formFields } from \"@nextlyhq/blocks-react\";\nimport {\n  Button,\n  Input,\n  Label,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n  Switch,\n} from \"@nextlyhq/ui\";\nimport { ChevronDown, GripVertical, Trash2, X } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useStoredDraft } from \"../../stored-draft\";\n\n/** One field as stored, as this control reads and writes it. */\nexport interface FormFieldSpec {\n  label?: string;\n  name?: string;\n  type?: string;\n  required?: boolean;\n  options?: string[];\n}\n\n/** A field type the block offers, and the words it is offered under. */\nexport interface FieldTypeChoice {\n  readonly value: string;\n  readonly words: string;\n}\n\n/** The types that take a list of options. */\nconst CHOICE_TYPES: ReadonlySet<string> = new Set([\"select\", \"radio\"]);\n\n/** Text, or `undefined` for anything else. */\nfunction textOr(value: unknown): string | undefined {\n  return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * A stored list member as a field, every setting this control reads checked:\n * a stored array can hold anything, and a label that is not text must not\n * stop the Fields from being drawn.\n */\nfunction asSpec(value: unknown): FormFieldSpec {\n  if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n    return {};\n  }\n  const field: Record<string, unknown> = {\n    ...(value as Record<string, unknown>),\n  };\n  // A setting of a shape this control cannot read is left out of the field\n  // it draws, and so out of what it writes back.\n  for (const key of [\"label\", \"name\", \"type\"]) {\n    if (field[key] !== undefined && textOr(field[key]) === undefined) {\n      delete field[key];\n    }\n  }\n  if (field.options !== undefined) {\n    if (Array.isArray(field.options)) {\n      field.options = field.options.filter(\n        (option): option is string => typeof option === \"string\"\n      );\n    } else {\n      delete field.options;\n    }\n  }\n  return field;\n}\n\n/**\n * Where the open field is once the field at `from` moves to `to`: with it,\n * where it is the one moved, and one place along where the move crosses it.\n */\nexport function openAfterMove(\n  open: number | null,\n  from: number,\n  to: number\n): number | null {\n  if (open === null) return null;\n  if (open === from) return to;\n  if (from < open && open <= to) return open - 1;\n  if (to <= open && open < from) return open + 1;\n  return open;\n}\n\n/** `list` with the member at `from` moved to `to`. */\nexport function moved<T>(list: readonly T[], from: number, to: number): T[] {\n  const next = [...list];\n  const [taken] = next.splice(from, 1);\n  if (taken === undefined) return [...list];\n  next.splice(Math.max(0, Math.min(to, next.length)), 0, taken);\n  return next;\n}\n\n/** A text box that commits its draft on blur and on Enter. */\nfunction DraftInput({\n  id,\n  value,\n  placeholder,\n  disabled,\n  label,\n  onCommit,\n}: {\n  id: string;\n  value: string;\n  placeholder?: string;\n  disabled: boolean;\n  /** Its accessible name, where no visible label names it. */\n  label?: string;\n  onCommit: (next: string) => void;\n}): React.JSX.Element {\n  const [draft, setDraft] = useStoredDraft(value);\n  const send = () => {\n    if (draft !== value) onCommit(draft);\n  };\n  return (\n    <Input\n      id={id}\n      value={draft}\n      disabled={disabled}\n      {...(placeholder === undefined ? {} : { placeholder })}\n      {...(label === undefined ? {} : { \"aria-label\": label })}\n      onChange={event => setDraft(event.target.value)}\n      onBlur={send}\n      onKeyDown={event => {\n        if (event.key === \"Enter\") {\n          event.preventDefault();\n          send();\n        }\n      }}\n    />\n  );\n}\n\n/** A Dropdown's or a Choice's options: one box each, removable, and \"+ Add option\". */\nfunction OptionsEditor({\n  id,\n  options,\n  disabled,\n  onChange,\n}: {\n  id: string;\n  options: readonly string[];\n  disabled: boolean;\n  onChange: (next: string[]) => void;\n}): React.JSX.Element {\n  return (\n    <div\n      className=\"nx-form-fields__options\"\n      role=\"group\"\n      aria-labelledby={`${id}-label`}\n    >\n      <p className=\"nx-inspector__field-name\" id={`${id}-label`}>\n        Options\n      </p>\n      {options.map((option, index) => (\n        <div key={index} className=\"nx-form-fields__option\">\n          <DraftInput\n            id={`${id}-${index}`}\n            value={option}\n            disabled={disabled}\n            label={`Option ${index + 1}`}\n            onCommit={next =>\n              onChange(options.map((each, at) => (at === index ? next : each)))\n            }\n          />\n          <Button\n            type=\"button\"\n            size=\"icon-sm\"\n            variant=\"ghost\"\n            disabled={disabled}\n            aria-label={`Remove option ${index + 1}`}\n            onClick={() => onChange(options.filter((_, at) => at !== index))}\n          >\n            <X aria-hidden=\"true\" />\n          </Button>\n        </div>\n      ))}\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"nx-form-fields__add\"\n        disabled={disabled}\n        onClick={() => onChange([...options, `Option ${options.length + 1}`])}\n      >\n        + Add option\n      </Button>\n    </div>\n  );\n}\n\n/** One field opened: its label, type, Required, options and sent name. */\nfunction FieldEditor({\n  id,\n  field,\n  sentName,\n  types,\n  disabled,\n  onChange,\n}: {\n  id: string;\n  field: FormFieldSpec;\n  types: readonly FieldTypeChoice[];\n  /** The name its answer is sent under now, made or written. */\n  sentName: string;\n  disabled: boolean;\n  onChange: (next: FormFieldSpec) => void;\n}): React.JSX.Element {\n  const type = field.type ?? \"text\";\n  const set = (patch: Partial<FormFieldSpec>) => {\n    const next: Record<string, unknown> = { ...field, ...patch };\n    for (const [key, value] of Object.entries(patch)) {\n      if (value === undefined || value === \"\") delete next[key];\n    }\n    onChange(next);\n  };\n  return (\n    <div className=\"nx-form-fields__editor\">\n      <div className=\"nx-inspector__field\">\n        <Label htmlFor={`${id}-label`}>Label</Label>\n        <DraftInput\n          id={`${id}-label`}\n          value={field.label ?? \"\"}\n          disabled={disabled}\n          onCommit={label => set({ label })}\n        />\n      </div>\n      <div className=\"nx-inspector__field\">\n        <Label htmlFor={`${id}-type`}>Field type</Label>\n        <Select\n          value={type}\n          disabled={disabled}\n          onValueChange={next =>\n            set({\n              type: next,\n              // A new Dropdown or Choice starts with options to edit.\n              ...(CHOICE_TYPES.has(next) && (field.options ?? []).length === 0\n                ? { options: [\"Option 1\", \"Option 2\"] }\n                : {}),\n            })\n          }\n        >\n          <SelectTrigger id={`${id}-type`}>\n            <SelectValue />\n          </SelectTrigger>\n          <SelectContent>\n            {types.map(option => (\n              <SelectItem key={option.value} value={option.value}>\n                {option.words}\n              </SelectItem>\n            ))}\n          </SelectContent>\n        </Select>\n      </div>\n      <div className=\"nx-inspector__field\">\n        <Label htmlFor={`${id}-required`}>Required</Label>\n        <Switch\n          id={`${id}-required`}\n          checked={field.required === true}\n          disabled={disabled}\n          onCheckedChange={required => set({ required: required || undefined })}\n        />\n      </div>\n      {CHOICE_TYPES.has(type) ? (\n        <OptionsEditor\n          id={`${id}-options`}\n          options={field.options ?? []}\n          disabled={disabled}\n          onChange={options => set({ options })}\n        />\n      ) : null}\n      <details className=\"nx-form-fields__advanced\">\n        <summary>\n          <ChevronDown aria-hidden=\"true\" />\n          Advanced\n        </summary>\n        <div className=\"nx-inspector__field nx-inspector__field--stacked\">\n          <Label htmlFor={`${id}-name`}>Name sent with the form</Label>\n          <DraftInput\n            id={`${id}-name`}\n            value={field.name ?? \"\"}\n            placeholder={sentName}\n            disabled={disabled}\n            onCommit={name => set({ name: name.trim() })}\n          />\n          <p className=\"nx-inspector__note\">\n            {field.name !== undefined &&\n            field.name !== \"\" &&\n            field.name !== sentName\n              ? `Sent as ${sentName}.`\n              : \"Made from the label. Each field's name is its own.\"}\n          </p>\n        </div>\n      </details>\n    </div>\n  );\n}\n\n/**\n * The Fields list. `value` is the block's stored `fields`; `onCommit` writes\n * the whole list.\n */\nexport function FormFieldsControl({\n  id,\n  value,\n  types,\n  disabled,\n  onCommit,\n}: {\n  id: string;\n  value: unknown;\n  /** The field types the block offers, read from its declaration. */\n  types: readonly FieldTypeChoice[];\n  disabled: boolean;\n  onCommit: (next: FormFieldSpec[]) => void;\n}): React.JSX.Element {\n  const list = React.useMemo(\n    () => (Array.isArray(value) ? value.map(asSpec) : []),\n    [value]\n  );\n  // The names each field's answer is sent under, as the block sends them.\n  const names = React.useMemo(\n    () => formFields({ fields: list }).map(field => field.name),\n    [list]\n  );\n  const [open, setOpen] = React.useState<number | null>(null);\n  const [dragged, setDragged] = React.useState<number | null>(null);\n  const [said, setSaid] = React.useState(\"\");\n  const grips = React.useRef<Array<HTMLButtonElement | null>>([]);\n\n  const titleOf = (field: FormFieldSpec, index: number): string =>\n    (field.label ?? \"\").trim() || names[index] || `Field ${index + 1}`;\n\n  const move = (from: number, to: number, focus: boolean) => {\n    if (to < 0 || to >= list.length || from === to) return;\n    const field = list[from];\n    onCommit(moved(list, from, to));\n    setOpen(current => openAfterMove(current, from, to));\n    setSaid(\n      `${titleOf(field ?? {}, from)} moved to position ${to + 1} of ${list.length}.`\n    );\n    if (focus) requestAnimationFrame(() => grips.current[to]?.focus());\n  };\n\n  return (\n    <div className=\"nx-form-fields\" data-content-control=\"form-fields\">\n      <ol className=\"nx-form-fields__rows\" aria-label=\"Fields\">\n        {list.map((field, index) => {\n          const title = titleOf(field, index);\n          const isOpen = open === index;\n          const type =\n            types.find(choice => choice.value === (field.type ?? \"text\"))\n              ?.words ?? \"Text\";\n          return (\n            <li\n              // Positions identify a field: a list holds no ids.\n              key={index}\n              className=\"nx-form-fields__row\"\n              data-open={isOpen ? \"\" : undefined}\n              data-dragged={dragged === index ? \"\" : undefined}\n              onDragOver={event => {\n                if (dragged === null) return;\n                event.preventDefault();\n                event.dataTransfer.dropEffect = \"move\";\n              }}\n              onDrop={event => {\n                event.preventDefault();\n                if (dragged !== null) move(dragged, index, false);\n                setDragged(null);\n              }}\n            >\n              <div className=\"nx-form-fields__head\">\n                <button\n                  ref={element => {\n                    grips.current[index] = element;\n                  }}\n                  type=\"button\"\n                  className=\"nx-form-fields__grip\"\n                  draggable={!disabled}\n                  disabled={disabled}\n                  aria-label={`Move ${title}`}\n                  aria-describedby={`${id}-grip-help`}\n                  onDragStart={event => {\n                    setDragged(index);\n                    event.dataTransfer.effectAllowed = \"move\";\n                    event.dataTransfer.setData(\"text/plain\", String(index));\n                  }}\n                  onDragEnd={() => setDragged(null)}\n                  onKeyDown={event => {\n                    if (event.key === \"ArrowUp\") {\n                      event.preventDefault();\n                      move(index, index - 1, true);\n                    } else if (event.key === \"ArrowDown\") {\n                      event.preventDefault();\n                      move(index, index + 1, true);\n                    }\n                  }}\n                >\n                  <GripVertical aria-hidden=\"true\" />\n                </button>\n                <button\n                  type=\"button\"\n                  className=\"nx-form-fields__title\"\n                  aria-expanded={isOpen}\n                  aria-controls={`${id}-${index}-editor`}\n                  onClick={() => setOpen(isOpen ? null : index)}\n                >\n                  <span className=\"nx-form-fields__label\">\n                    {title}\n                    {field.required === true ? (\n                      <>\n                        <span aria-hidden=\"true\"> *</span>\n                        <span className=\"nx-sr-only\">, required</span>\n                      </>\n                    ) : null}\n                  </span>\n                  <span className=\"nx-form-fields__type\">{type}</span>\n                </button>\n                <Button\n                  type=\"button\"\n                  size=\"icon-sm\"\n                  variant=\"ghost\"\n                  disabled={disabled}\n                  aria-label={`Remove ${title}`}\n                  onClick={() => {\n                    onCommit(list.filter((_, at) => at !== index));\n                    setOpen(null);\n                  }}\n                >\n                  <Trash2 aria-hidden=\"true\" />\n                </Button>\n              </div>\n              {isOpen ? (\n                <div id={`${id}-${index}-editor`}>\n                  <FieldEditor\n                    id={`${id}-${index}`}\n                    field={field}\n                    sentName={names[index] ?? \"\"}\n                    types={types}\n                    disabled={disabled}\n                    onChange={next =>\n                      onCommit(\n                        list.map((each, at) => (at === index ? next : each))\n                      )\n                    }\n                  />\n                </div>\n              ) : null}\n            </li>\n          );\n        })}\n      </ol>\n      <p className=\"nx-sr-only\" id={`${id}-grip-help`}>\n        Drag to reorder, or press the up and down arrow keys.\n      </p>\n      <p className=\"nx-sr-only\" role=\"status\" aria-live=\"polite\">\n        {said}\n      </p>\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"nx-form-fields__add\"\n        // No field past the most a form draws.\n        disabled={disabled || list.length >= FORM_MAX_FIELDS}\n        onClick={() => {\n          onCommit([...list, { label: \"New field\", type: \"text\" }]);\n          setOpen(list.length);\n        }}\n      >\n        + Add field\n      </Button>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * Where a Form block's form comes from: its first setting.\n *\n * - **With a form source installed** (the forms plugin), \"Form: <pick a\n *   form>\" lists the forms the author may pick, a draft or closed one\n *   marked. Once one is picked, the panel says that its fields, emails, spam\n *   protection and saved responses come from that source, links to the form\n *   in the admin (\"Edit this form ↗\"), and offers \"or use a simple form\",\n *   which clears the pick and keeps the block's own fields.\n * - **With none**, the block edits its own fields, and this says what\n *   installing the Forms plugin adds.\n *\n * Everything shown is what the host's `listForms` answers: the panel names\n * no plugin, collection or address of its own.\n *\n * @module form-source-control\n */\nimport { walkNodes, type BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Select,\n  SelectContent,\n  SelectGroup,\n  SelectItem,\n  SelectLabel,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { ContentServices, FormSource } from \"./content-services\";\nimport {\n  FORM_BLOCK,\n  FORM_WORDS,\n  pickedFormOf,\n  type PickedForm,\n} from \"./form-picked\";\n\n/** What reading the site's form sources has come to. */\nexport type FormSources =\n  | { readonly status: \"absent\" }\n  | { readonly status: \"loading\" }\n  | { readonly status: \"failed\" }\n  | { readonly status: \"ready\"; readonly sources: readonly FormSource[] };\n\n/**\n * A count that goes up each time the editor's tab is shown again: the author\n * coming back from another tab, such as a form's own page opened from \"Edit\n * this form ↗\", where the form may have been published, closed or deleted.\n * What was read about forms is read again on each. Counted as a transition,\n * so what is drawn again keeps showing what it drew until the new reads\n * come, rather than blinking out.\n */\nexport function useShownAgain(): number {\n  const [count, setCount] = React.useState(0);\n  React.useEffect(() => {\n    const shown = (): void => {\n      if (document.visibilityState !== \"visible\") return;\n      React.startTransition(() => setCount(n => n + 1));\n    };\n    document.addEventListener(\"visibilitychange\", shown);\n    return () => document.removeEventListener(\"visibilitychange\", shown);\n  }, []);\n  return count;\n}\n\n/** A tree of blocks as a host draws it. */\ntype DrawnTree = { readonly nodes: BlockDocument[\"nodes\"] };\n\n/** Whether any Form in `trees` picks a form from a provider. */\nfunction picksAForm(trees: readonly DrawnTree[]): boolean {\n  let picks = false;\n  for (const tree of trees) {\n    walkNodes(tree.nodes, node => {\n      if (\n        node.type === FORM_BLOCK &&\n        pickedFormOf(node.props.form) !== undefined\n      )\n        picks = true;\n    });\n  }\n  return picks;\n}\n\n/**\n * The round a page's picked forms are drawn in: a count that goes up each\n * time the author comes back to the editor (`useShownAgain`) while what is\n * drawn picks a form, and holds otherwise. A host draws its Forms afresh for\n * each round, so a form changed in its own tab is drawn as it now is, and a\n * page picking none is not drawn again for a return.\n *\n * `drawn` is every tree the host draws, as it draws them: the page with the\n * components it places composed in, and the header and footer of its\n * Layout, so a Form inside a placement or a region counts. The stored page\n * holds only the placement, never the Form it draws.\n *\n * @experimental Settles with the form provider contract.\n */\nexport function useFormsShownAgain(drawn: readonly DrawnTree[]): number {\n  const shown = useShownAgain();\n  const [seen, setSeen] = React.useState({ shown, round: 0 });\n  if (seen.shown === shown) return seen.round;\n  // Shown again since the last render: a new round only for a page drawing\n  // a picked form, kept so the next render agrees. Walked only on a return,\n  // never per edit, since the composed trees are the whole page.\n  const round = picksAForm(drawn) ? seen.round + 1 : seen.round;\n  setSeen({ shown, round });\n  return round;\n}\n\n/**\n * The site's form sources, read once per `listForms`, and again each time\n * the author comes back to the editor (`useShownAgain`). A read again keeps\n * the last list on screen until the new one comes, so nothing flickers.\n */\nexport function useFormSources(\n  listForms: ContentServices[\"listForms\"]\n): FormSources {\n  const [sources, setSources] = React.useState<FormSources>(\n    listForms === undefined ? { status: \"absent\" } : { status: \"loading\" }\n  );\n  const again = useShownAgain();\n  const listedBy = React.useRef<ContentServices[\"listForms\"]>(undefined);\n  React.useEffect(() => {\n    if (listForms === undefined) {\n      listedBy.current = undefined;\n      setSources({ status: \"absent\" });\n      return;\n    }\n    let current = true;\n    // Another host's list starts from nothing; the same one read again doesn't.\n    if (listedBy.current !== listForms) setSources({ status: \"loading\" });\n    listedBy.current = listForms;\n    listForms().then(\n      read => {\n        if (current) setSources({ status: \"ready\", sources: read });\n      },\n      () => {\n        if (current) setSources({ status: \"failed\" });\n      }\n    );\n    return () => {\n      current = false;\n    };\n  }, [listForms, again]);\n  return sources;\n}\n\n/** A picked form as a choice's value: both halves, never confused. */\nfunction formChoiceValue(form: PickedForm): string {\n  return JSON.stringify([form.provider, form.ref]);\n}\n\n/** The picked form a choice's value names. */\nexport function formOfChoice(value: string): PickedForm | undefined {\n  try {\n    const parsed: unknown = JSON.parse(value);\n    if (\n      Array.isArray(parsed) &&\n      typeof parsed[0] === \"string\" &&\n      typeof parsed[1] === \"string\"\n    ) {\n      return { provider: parsed[0], ref: parsed[1] };\n    }\n  } catch {\n    // Not a choice this control made.\n  }\n  return undefined;\n}\n\n/** A listed form's words: its title, and its state where it is not open. */\nfunction choiceWords(title: string, state: string): string {\n  const mark = FORM_WORDS.stateMark[state];\n  return mark === undefined ? title : `${title} (${mark})`;\n}\n\n/** The forms each source lists, as menu items, grouped where there are several. */\nexport function FormChoiceItems({\n  sources,\n}: {\n  readonly sources: readonly FormSource[];\n}): React.JSX.Element {\n  const items = (source: FormSource) =>\n    source.forms.map(form => (\n      <SelectItem\n        key={form.ref}\n        value={formChoiceValue({ provider: source.id, ref: form.ref })}\n      >\n        {choiceWords(form.title, form.state)}\n      </SelectItem>\n    ));\n  if (sources.length === 1 && sources[0] !== undefined) {\n    return <>{items(sources[0])}</>;\n  }\n  return (\n    <>\n      {sources.map(source => (\n        <SelectGroup key={source.id}>\n          <SelectLabel>{source.label}</SelectLabel>\n          {items(source)}\n        </SelectGroup>\n      ))}\n    </>\n  );\n}\n\n/** The listed form `picked` is, and its source. */\nfunction listedOf(\n  sources: readonly FormSource[],\n  picked: PickedForm | undefined\n):\n  | {\n      readonly source: FormSource;\n      readonly form: FormSource[\"forms\"][number] | undefined;\n    }\n  | undefined {\n  if (picked === undefined) return undefined;\n  const source = sources.find(each => each.id === picked.provider);\n  if (source === undefined) return undefined;\n  return { source, form: source.forms.find(form => form.ref === picked.ref) };\n}\n\n/** The id of the picker's trigger for a block, so another part can focus it. */\nfunction formPickerId(nodeId: string): string {\n  return `${nodeId}-form-pick`;\n}\n\nexport function FormSourceControl({\n  nodeId,\n  stored,\n  sources,\n  disabled,\n  onCommit,\n}: {\n  readonly nodeId: string;\n  /** The block's stored `form`. */\n  readonly stored: unknown;\n  readonly sources: FormSources;\n  /** Whether the pick may be changed here: a lock or a content-only area say. */\n  readonly disabled: boolean;\n  /** Write the block's `form`; `undefined` clears it. */\n  readonly onCommit: (form: PickedForm | undefined) => void;\n}): React.JSX.Element | null {\n  const picked = pickedFormOf(stored);\n  // A host that lists no sources says nothing either way.\n  if (sources.status === \"absent\" || sources.status === \"loading\") {\n    return null;\n  }\n  const useSimple =\n    picked === undefined ? null : (\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"sm\"\n        className=\"nx-form-source__simple\"\n        disabled={disabled}\n        onClick={() => onCommit(undefined)}\n      >\n        {FORM_WORDS.useSimple}\n      </Button>\n    );\n  if (sources.status === \"failed\") {\n    return (\n      <div className=\"nx-form-source\" data-content-control=\"form-source\">\n        <p className=\"nx-inspector__hint\" role=\"status\">\n          {FORM_WORDS.listFailed}\n        </p>\n        {useSimple}\n      </div>\n    );\n  }\n  if (sources.sources.length === 0) {\n    return (\n      <div className=\"nx-form-source\" data-content-control=\"form-source\">\n        <p className=\"nx-inspector__hint\">{FORM_WORDS.installHint}</p>\n        {useSimple}\n      </div>\n    );\n  }\n  const listed = listedOf(sources.sources, picked);\n  const id = formPickerId(nodeId);\n  const value =\n    picked !== undefined && listed?.form !== undefined\n      ? formChoiceValue(picked)\n      : \"\";\n  return (\n    <div className=\"nx-form-source\" data-content-control=\"form-source\">\n      <div className=\"nx-inspector__field nx-inspector__field--stacked\">\n        <label className=\"nx-inspector__field-name\" htmlFor={id}>\n          {FORM_WORDS.pickLabel}\n        </label>\n        <Select\n          value={value}\n          disabled={disabled}\n          onValueChange={next => {\n            const form = formOfChoice(next);\n            if (form !== undefined) onCommit(form);\n          }}\n        >\n          <SelectTrigger id={id}>\n            <SelectValue placeholder={FORM_WORDS.pickPlaceholder} />\n          </SelectTrigger>\n          <SelectContent>\n            <FormChoiceItems sources={sources.sources} />\n          </SelectContent>\n        </Select>\n      </div>\n      {listed === undefined ? null : (\n        <p className=\"nx-inspector__hint\">\n          {FORM_WORDS.comesFrom(listed.source.label)}\n        </p>\n      )}\n      {listed?.form?.editHref === undefined ? null : (\n        <a\n          className=\"nx-form-source__edit\"\n          href={listed.form.editHref}\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n        >\n          {FORM_WORDS.edit}\n        </a>\n      )}\n      {useSimple}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The Form block's Content sections the builder draws itself: Fields\n * (`form-fields-control`) and After sending (`form-after-sending`). Each\n * replaces the generated rows of the section the block places those props\n * in, so the block's declaration still says where they are edited, and an\n * editor without these draws the generated rows instead.\n *\n * And, first of all, where the form comes from (`form-source-control`):\n * the Form section's \"Form: <pick a form>\". While a form is picked, its\n * fields, its button and where its answers go are the provider's, so the\n * Fields section and the block's own Form rows are not drawn; \"or use a\n * simple form\" brings them back as they were.\n *\n * @module form-sections\n */\nimport * as React from \"react\";\n\nimport type { BlockInspection, EditableProp } from \"../inspector\";\nimport type { PanelSection } from \"../panel-section\";\n\nimport type { ContentServices } from \"./content-services\";\nimport { AfterSendingControl } from \"./form-after-sending\";\nimport { FormFieldsControl } from \"./form-fields-control\";\nimport { FORM_BLOCK, pickedFormOf } from \"./form-picked\";\nimport { FormSourceControl, type FormSources } from \"./form-source-control\";\n\n/** The sections the block places these props in, by their names. */\nconst FIELDS_SECTION = \"Fields\";\nconst AFTER_SENDING_SECTION = \"After sending\";\n/** Where the block's unsectioned props sit: the block's own name. */\nconst FORM_SECTION = \"Form\";\n\n/** The props \"Go to a page\" is: the block's shared link setting. */\nconst PAGE_PROPS: ReadonlySet<string> = new Set([\n  \"href\",\n  \"entryCollection\",\n  \"entryId\",\n]);\n\n/**\n * The field types the block's declaration offers, with their words: the\n * `type` of each item of its `fields`, so the panel offers exactly what the\n * block draws.\n */\nfunction fieldTypesOf(\n  prop: EditableProp | undefined\n): { readonly value: string; readonly words: string }[] {\n  const item = prop?.schema.item as\n    | { type?: { options?: unknown; optionLabels?: unknown } }\n    | undefined;\n  const options = Array.isArray(item?.type?.options) ? item.type.options : [];\n  const words = (item?.type?.optionLabels ?? {}) as Record<string, unknown>;\n  return options\n    .filter((option): option is string => typeof option === \"string\")\n    .map(option => ({\n      value: option,\n      words: wordsOf(words[option], option),\n    }));\n}\n\n/** A choice's declared words, or the choice itself. */\nfunction wordsOf(declared: unknown, option: string): string {\n  return typeof declared === \"string\" ? declared : option;\n}\n\n/** What drawing the sections needs from the Content tab. */\nexport interface FormSectionsContext {\n  readonly inspection: BlockInspection;\n  /**\n   * The block's props as stored, its picked form among them: a prop the\n   * block draws no row for is not in the inspection.\n   */\n  readonly stored: Readonly<Record<string, unknown>>;\n  readonly services: ContentServices | undefined;\n  /** Whether a prop may be written here: a lock or a content-only area say. */\n  readonly writable: (name: string) => boolean;\n  readonly onCommit: (name: string, value: unknown) => void;\n  /** The generated rows for `rows`, as the tab draws any section's. */\n  readonly rowsOf: (rows: readonly EditableProp[]) => React.JSX.Element;\n  /**\n   * In a component's own view, a setting's switch to expose it as a field\n   * of the component, as the generated rows draw one for each setting.\n   */\n  readonly exposeOf?: ((prop: EditableProp) => React.ReactNode) | undefined;\n}\n\n/**\n * The Form section's start, drawn before the block's own rows there: where\n * the form comes from. None for any other block.\n */\nexport function formSourceSections(\n  context: Pick<\n    FormSectionsContext,\n    \"inspection\" | \"stored\" | \"writable\" | \"onCommit\"\n  > & { readonly sources: FormSources }\n): PanelSection[] {\n  const { inspection } = context;\n  if (inspection.blockName !== FORM_BLOCK) return [];\n  return [\n    {\n      key: FORM_SECTION,\n      label: FORM_SECTION,\n      holdsValue: pickedFormOf(context.stored.form) !== undefined,\n      body: (\n        <FormSourceControl\n          nodeId={inspection.nodeId}\n          stored={context.stored.form}\n          sources={context.sources}\n          disabled={!context.writable(\"form\")}\n          onCommit={form => context.onCommit(\"form\", form)}\n        />\n      ),\n    },\n  ];\n}\n\n/**\n * The bodies of the Form's sections the builder draws, by section name, or\n * none for any other block. A section answered `null` is not drawn.\n */\nexport function formSectionBodies(\n  context: FormSectionsContext\n): ReadonlyMap<string, React.JSX.Element | null> | undefined {\n  const { inspection, writable, onCommit } = context;\n  if (inspection.blockName !== FORM_BLOCK) return undefined;\n  const values = context.stored;\n  // A picked form's fields, button and destination are its provider's.\n  const picked = pickedFormOf(values.form) !== undefined;\n  const pageRows = inspection.props.filter(prop => PAGE_PROPS.has(prop.name));\n  const messageRows = inspection.props.filter(prop => prop.name === \"message\");\n  const fieldsProp = inspection.props.find(prop => prop.name === \"fields\");\n  const afterSendingProp = inspection.props.find(\n    prop => prop.name === \"afterSending\"\n  );\n  return new Map<string, React.JSX.Element | null>([\n    ...(picked ? ([[FORM_SECTION, null]] as const) : []),\n    [\n      FIELDS_SECTION,\n      picked ? null : (\n        <FormFieldsControl\n          key=\"fields\"\n          id={`${inspection.nodeId}-form-fields`}\n          value={values.fields}\n          types={fieldTypesOf(fieldsProp)}\n          disabled={!writable(\"fields\")}\n          onCommit={next => onCommit(\"fields\", next)}\n        />\n      ),\n    ],\n    [\n      AFTER_SENDING_SECTION,\n      <React.Fragment key=\"after-sending\">\n        <AfterSendingControl\n          id={`${inspection.nodeId}-after-sending`}\n          props={values}\n          disabled={name => !writable(name)}\n          services={context.services}\n          onCommit={onCommit}\n          message={context.rowsOf(messageRows)}\n          page={context.rowsOf(pageRows)}\n        />\n        {afterSendingProp === undefined\n          ? null\n          : context.exposeOf?.(afterSendingProp)}\n      </React.Fragment>,\n    ],\n  ]);\n}\n","/**\n * A Gallery's \"Columns\" and \"On mobile\" tiles: what each choice writes, and\n * what the tiles read back.\n *\n * A Content control that writes the gallery's own style values, as a\n * Columns row's Layout tiles do (`columns-layout.ts`): Columns is its\n * `grid-template-columns` at the base values, On mobile the same property at\n * the site's mobile tier, the widest at a phone's width or narrower\n * (`stackTiers`). Each is a count of equal tracks that may shrink past their\n * content, so a wide picture never pushes the grid wider than the box.\n *\n * With nothing stored the block's own grid draws three across and one on a\n * phone, so the tiles read 3 and 1. Choosing Columns while the mobile tier\n * holds nothing also writes On mobile's 1 in the same edit: a stored count\n * reaches every narrower tier, and a phone must never inherit 3 or 4 across.\n *\n * @module gallery-columns\n */\nimport {\n  BASE_BREAKPOINT,\n  type BlockNode,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { chainedStyleOp, type StackTiers } from \"../../canvas/columns-layout\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { readStyleValue, type StyleAddress } from \"../../styles/style-values\";\n\n/** The counts the Columns tiles offer. */\nexport const GALLERY_COLUMNS: readonly number[] = [2, 3, 4];\n\n/** The counts the On mobile tiles offer. */\nexport const GALLERY_MOBILE: readonly number[] = [1, 2];\n\n/** What the block's default grid draws where nothing is stored. */\nconst DEFAULT_COLUMNS = 3;\nconst DEFAULT_MOBILE = 1;\n\n/** The property every choice here writes. */\nconst PROPERTY = \"gridTemplateColumns\";\n\n/** The template a count writes: equal tracks that may shrink to nothing. */\nfunction templateOf(count: number): string {\n  return `repeat(${String(count)}, minmax(0, 1fr))`;\n}\n\n/** The count a stored template is, where it is one a tile writes. */\nfunction countOf(value: StyleValue | undefined): number | undefined {\n  if (typeof value !== \"string\") return undefined;\n  const match =\n    /^repeat\\(\\s*(\\d+)\\s*,\\s*minmax\\(\\s*0\\s*,\\s*1fr\\s*\\)\\s*\\)$/.exec(\n      value.trim()\n    );\n  return match?.[1] === undefined ? undefined : Number(match[1]);\n}\n\n/** Where a choice writes: the gallery's own base state, at one tier. */\nfunction addressAt(breakpoint: string): StyleAddress {\n  return { state: \"base\", breakpoint, property: PROPERTY, path: [] };\n}\n\n/** The template the gallery stores at a tier. */\nfunction storedAt(\n  gallery: BlockNode,\n  breakpoint: string\n): StyleValue | undefined {\n  return readStyleValue(gallery.styles, addressAt(breakpoint));\n}\n\n/** What the two rows of tiles read: a count each, or none for no tile. */\nexport interface GalleryColumns {\n  readonly columns: number | undefined;\n  /** `undefined` also where the site has no mobile tier, so no row is drawn. */\n  readonly mobile: number | undefined;\n}\n\n/**\n * The template a wider tier hands down to a phone while the phone's own tier\n * says nothing: the nearest of the tiers between the base values and the\n * phone's that stores one, since a narrower tier's rule comes later in the\n * page's styles and wins where both apply.\n */\nfunction reachingPhone(\n  gallery: BlockNode,\n  tiers: StackTiers\n): StyleValue | undefined {\n  const managed = tiers.managed ?? [];\n  const at = managed.findIndex(tier => tier.id === tiers.mobile);\n  // Widest first, so the ones before the phone's are wider; nearest first.\n  const wider = at === -1 ? [] : managed.slice(0, at).reverse();\n  for (const tier of wider) {\n    const stored = storedAt(gallery, tier.id);\n    if (stored !== undefined) return stored;\n  }\n  return undefined;\n}\n\n/**\n * The counts the gallery lays its pictures out in: its own, else the\n * default grid's. On a phone, the mobile tier's own, else the count a wider\n * tier reaches it with (a tablet's, then the base values), else the\n * default's one.\n */\nexport function galleryColumnsOf(\n  gallery: BlockNode,\n  tiers: StackTiers\n): GalleryColumns {\n  const base = storedAt(gallery, BASE_BREAKPOINT);\n  const columns = base === undefined ? DEFAULT_COLUMNS : countOf(base);\n  if (tiers.mobile === undefined) return { columns, mobile: undefined };\n  const phone =\n    storedAt(gallery, tiers.mobile) ?? reachingPhone(gallery, tiers) ?? base;\n  const mobile = phone === undefined ? DEFAULT_MOBILE : countOf(phone);\n  return { columns, mobile };\n}\n\n/**\n * Choosing Columns, as ONE op: the count at the base values, and On mobile's\n * default at the mobile tier while nothing narrower than the base values\n * reaches a phone. `null` where it changes nothing.\n */\nexport function planGalleryColumns(\n  gallery: BlockNode,\n  count: number,\n  tiers: StackTiers\n): BuilderOp | null {\n  const steps: { address: StyleAddress; value: StyleValue }[] = [\n    { address: addressAt(BASE_BREAKPOINT), value: templateOf(count) },\n  ];\n  // Only where the base value is what reaches a phone: a tablet's count, or\n  // the phone's own, already decides it there.\n  if (\n    tiers.mobile !== undefined &&\n    storedAt(gallery, tiers.mobile) === undefined &&\n    reachingPhone(gallery, tiers) === undefined\n  ) {\n    steps.push({\n      address: addressAt(tiers.mobile),\n      value: templateOf(DEFAULT_MOBILE),\n    });\n  }\n  return chainedStyleOp(gallery, steps);\n}\n\n/**\n * Choosing On mobile, as ONE op at the mobile tier; `null` where the site\n * has none, or it changes nothing.\n */\nexport function planGalleryMobile(\n  gallery: BlockNode,\n  count: number,\n  tiers: StackTiers\n): BuilderOp | null {\n  if (tiers.mobile === undefined) return null;\n  return chainedStyleOp(gallery, [\n    { address: addressAt(tiers.mobile), value: templateOf(count) },\n  ]);\n}\n\n/** Whether the gallery stores a count of its own, for its section's dot. */\nexport function galleryColumnsHoldValue(\n  gallery: BlockNode,\n  tiers: StackTiers\n): boolean {\n  return (\n    storedAt(gallery, BASE_BREAKPOINT) !== undefined ||\n    (tiers.mobile !== undefined &&\n      storedAt(gallery, tiers.mobile) !== undefined)\n  );\n}\n","\"use client\";\n\n/**\n * A Gallery's Content sections the builder draws: Pictures, with\n * \"+ Add images\", and Layout, with \"Columns: 2 / 3 / 4\" and\n * \"On mobile: 1 / 2\" as tiles, the gallery's own \"When clicked\" following\n * them in the same section.\n *\n * \"+ Add images\" opens the host's media library to pick several files, and\n * adds one Image per file, in the order they were picked, after the pictures\n * the gallery holds, as ONE step of the history (`addPicturesOps`). The\n * tiles write the gallery's own style values, each choice one step\n * (`gallery-columns.ts`), and are held where a lock holds its design.\n *\n * @module gallery-fields\n */\nimport { findNode, type BreakpointSet } from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport { Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { stackTiers } from \"../../canvas/columns-layout\";\nimport type { EditorState } from \"../../editor-state\";\nimport { HeldByLock } from \"../held-by-lock\";\nimport type { PanelSection } from \"../panel-section\";\nimport { arrowTo } from \"../segment-choices\";\nimport { SettingSlot } from \"../settings-filter\";\n\nimport { ColumnsLayoutGlyph } from \"./columns-layout-field\";\nimport type { ContentServices } from \"./content-services\";\nimport {\n  galleryColumnsHoldValue,\n  galleryColumnsOf,\n  GALLERY_COLUMNS,\n  GALLERY_MOBILE,\n  planGalleryColumns,\n  planGalleryMobile,\n} from \"./gallery-columns\";\nimport { addPicturesTo, isGallery, picturesHeld } from \"./gallery-pictures\";\n\n/** The words these controls use, in one place. */\nconst GALLERY_FIELD_WORDS = {\n  pictures: \"Pictures\",\n  layout: \"Layout\",\n  addImages: \"Add images\",\n  pickerTitle: \"Choose images\",\n  noLibrary: \"The media library is not available here.\",\n  columns: \"Columns\",\n  onMobile: \"On mobile\",\n} as const;\n\n/** \"+ Add images\", and the library's picker it opens to pick several. */\nfunction AddImages({\n  editor,\n  nodeId,\n  services,\n  reasonId,\n}: {\n  editor: EditorState;\n  nodeId: string;\n  services: ContentServices | undefined;\n  reasonId: string;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const Picker = services?.MediaPicker;\n  if (Picker === undefined) {\n    return (\n      <p className=\"nx-inspector__note\">{GALLERY_FIELD_WORDS.noLibrary}</p>\n    );\n  }\n  const held = picturesHeld(editor, nodeId);\n  return (\n    <SettingSlot ids={[\"galleryAddImages\"]}>\n      <HeldByLock reasonId={held ? reasonId : undefined}>\n        <div className=\"nx-inspector__field\" data-content-control=\"gallery-add\">\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"outline\"\n            disabled={held}\n            onClick={() => setOpen(true)}\n          >\n            <Plus size={14} aria-hidden=\"true\" />\n            {GALLERY_FIELD_WORDS.addImages}\n          </Button>\n        </div>\n      </HeldByLock>\n      {/* Mounted only while open, so each opening starts with nothing\n          picked: every pick is a picture to add. */}\n      {open ? (\n        <Picker\n          open\n          mode=\"multi\"\n          onOpenChange={setOpen}\n          title={GALLERY_FIELD_WORDS.pickerTitle}\n          accept=\"image/*\"\n          initialSelectedIds={new Set()}\n          onSelect={media => {\n            // Closed here: the picker leaves closing to whoever opened it.\n            setOpen(false);\n            addPicturesTo(\n              editor,\n              nodeId,\n              media.map(each => each.id)\n            );\n          }}\n        />\n      ) : null}\n    </SettingSlot>\n  );\n}\n\n/** A row of count tiles: one tab stop, arrows choosing, as a radio group. */\nfunction CountTiles({\n  label,\n  counts,\n  chosen,\n  held,\n  onChoose,\n}: {\n  label: string;\n  counts: readonly number[];\n  chosen: number | undefined;\n  held: boolean;\n  onChoose: (count: number) => void;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  const stop = Math.max(0, counts.indexOf(chosen ?? -1));\n  const allowed = counts.map(() => !held);\n  const choose = (index: number) => {\n    const count = counts[index];\n    if (!held && count !== undefined) onChoose(count);\n  };\n  return (\n    <div className=\"nx-inspector__field nx-gallery-columns__row\">\n      <span className=\"nx-inspector__field-name\" id={labelId}>\n        {label}\n      </span>\n      <div\n        role=\"radiogroup\"\n        aria-labelledby={labelId}\n        className=\"nx-columns-layout__tiles nx-gallery-columns__tiles\"\n      >\n        {counts.map((count, index) => (\n          <button\n            key={count}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={count === chosen}\n            tabIndex={index === stop ? 0 : -1}\n            className=\"nx-columns-layout__tile\"\n            onKeyDown={event => arrowTo(event, index, allowed, choose)}\n            onClick={() => choose(index)}\n          >\n            {/* The count as equal bars, as the Columns row's tiles draw\n                theirs; the number is the tile's name. */}\n            <ColumnsLayoutGlyph\n              layout={{\n                key: String(count),\n                label: String(count),\n                template: undefined,\n                count,\n                tracks: Array.from({ length: count }, () => 1),\n              }}\n            />\n            <span>{count}</span>\n          </button>\n        ))}\n      </div>\n    </div>\n  );\n}\n\n/** Columns and On mobile, writing the gallery's own style values. */\nfunction GalleryColumnsControl({\n  editor,\n  nodeId,\n  breakpoints,\n  heldBy,\n}: {\n  editor: EditorState;\n  nodeId: string;\n  breakpoints: BreakpointSet | undefined;\n  heldBy: string | undefined;\n}): React.JSX.Element | null {\n  const gallery = findNode(editor.document.nodes, nodeId);\n  if (gallery === undefined) return null;\n  const tiers = stackTiers(breakpoints);\n  const shown = galleryColumnsOf(gallery, tiers);\n  const held = heldBy !== undefined;\n  const write = (op: ReturnType<typeof planGalleryColumns>) => {\n    if (!held && op !== null) editor.apply(op);\n  };\n  return (\n    <HeldByLock reasonId={heldBy}>\n      <div className=\"nx-gallery-columns\" data-control=\"gallery-columns\">\n        <SettingSlot ids={[\"galleryColumns\"]}>\n          <CountTiles\n            label={GALLERY_FIELD_WORDS.columns}\n            counts={GALLERY_COLUMNS}\n            chosen={shown.columns}\n            held={held}\n            onChoose={count => write(planGalleryColumns(gallery, count, tiers))}\n          />\n        </SettingSlot>\n        {/* Only where the site has a tier at a phone's width. */}\n        {tiers.mobile === undefined ? null : (\n          <SettingSlot ids={[\"galleryMobile\"]}>\n            <CountTiles\n              label={GALLERY_FIELD_WORDS.onMobile}\n              counts={GALLERY_MOBILE}\n              chosen={shown.mobile}\n              held={held}\n              onChoose={count =>\n                write(planGalleryMobile(gallery, count, tiers))\n              }\n            />\n          </SettingSlot>\n        )}\n      </div>\n    </HeldByLock>\n  );\n}\n\n/** What the Content tab knows of the page around a gallery. */\nexport interface GallerySectionContext {\n  readonly editor: EditorState;\n  readonly nodeId: string;\n  readonly breakpoints: BreakpointSet | undefined;\n  readonly services: ContentServices | undefined;\n  /** The id of the lock reason held controls point to. */\n  readonly reasonId: string;\n  /** That id while a lock holds the gallery's design, else `undefined`. */\n  readonly designHeldBy: string | undefined;\n}\n\n/**\n * A gallery's builder-drawn Content sections, by the names the inspector\n * gives them (`builderContentSectionsOf`), or none for any other block.\n */\nexport function galleryContentSections(\n  context: GallerySectionContext,\n  labels: readonly string[]\n): PanelSection[] {\n  const { editor, nodeId, breakpoints } = context;\n  const gallery = findNode(editor.document.nodes, nodeId);\n  if (gallery === undefined || !isGallery(gallery)) return [];\n  const sections: PanelSection[] = [];\n  for (const label of labels) {\n    if (label === GALLERY_FIELD_WORDS.pictures) {\n      sections.push({\n        key: label,\n        label,\n        holdsValue: false,\n        body: (\n          <AddImages\n            editor={editor}\n            nodeId={nodeId}\n            services={context.services}\n            reasonId={context.reasonId}\n          />\n        ),\n      });\n    } else if (label === GALLERY_FIELD_WORDS.layout) {\n      sections.push({\n        key: label,\n        label,\n        holdsValue: galleryColumnsHoldValue(gallery, stackTiers(breakpoints)),\n        body: (\n          <GalleryColumnsControl\n            editor={editor}\n            nodeId={nodeId}\n            breakpoints={breakpoints}\n            heldBy={context.designHeldBy}\n          />\n        ),\n      });\n    }\n  }\n  return sections;\n}\n","\"use client\";\n\n/**\n * The inspector's Content tab: the block's own inspector or the generated\n * fields of the settings it places in Content; and the one write path every\n * content control shares.\n *\n * @module inspector-content-tab\n */\n\nimport {\n  findNode,\n  type BlockDocument,\n  type BlockInspectorProps,\n  type BreakpointSet,\n} from \"@nextlyhq/blocks-engine\";\nimport type { PageStyleCascade } from \"@nextlyhq/blocks-react\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { EMBED_BLOCK_TYPE, embedLinkOp } from \"../canvas/embed-states-model\";\nimport type { EditorState } from \"../editor-state\";\nimport {\n  useVisitorUnreadable,\n  VisitorUnreadableNote,\n} from \"../shell/visitor-unreadable-context\";\n\nimport {\n  PropExposeControl,\n  type ComponentFieldsBinding,\n} from \"./component-fields-panel\";\nimport { ACCORDION_BLOCK } from \"./content/accordion-icon\";\nimport { accordionContentSections } from \"./content/accordion-icon-field\";\nimport { columnsContentSection } from \"./content/columns-layout-field\";\nimport type { ContentServices } from \"./content/content-controls\";\nimport { embedSectionBodies } from \"./content/embed-sections\";\nimport { FORM_BLOCK } from \"./content/form-picked\";\nimport { formSectionBodies, formSourceSections } from \"./content/form-sections\";\nimport { useFormSources } from \"./content/form-source-control\";\nimport { galleryContentSections } from \"./content/gallery-fields\";\nimport { commitLinkChanges } from \"./content/link-control\";\nimport {\n  blockIsReadOnly,\n  builderContentSectionsOf,\n  contentRowsOf,\n  designIsWritable,\n  designReadOnlyReason,\n  fieldLabel,\n  lockViewOf,\n  propIsWritable,\n  propPatch,\n  writablePropsOf,\n  type BlockInspection,\n  type EditableProp,\n} from \"./inspector\";\nimport { ContentFields, listViewOf } from \"./inspector-content-fields\";\nimport type { BlockInspectorResolver } from \"./inspector-panel-types\";\nimport { keptWhileHidden, ownBlockChanged } from \"./kept-while-hidden\";\nimport {\n  PanelSections,\n  rowsHoldValue,\n  type PanelSection,\n} from \"./panel-section\";\nimport { useSettingsMatch } from \"./settings-filter\";\n\n/**\n * The Content tab: what the block says, shows or links to. Kept mounted while\n * hidden, so a field's uncommitted text survives a look at another tab; drawn\n * again then only when its own block changes.\n */\nexport const ContentTab: React.NamedExoticComponent<\n  React.ComponentProps<typeof DrawnContentTab>\n> = keptWhileHidden(DrawnContentTab, ownBlockChanged);\n\nfunction DrawnContentTab({\n  block,\n  editor,\n  onCommit: commit,\n  inspectors,\n  services,\n  reasonId,\n  fields,\n  around,\n}: {\n  block: BlockInspection;\n  editor: EditorState;\n  onCommit: (name: string, value: unknown) => BlockDocument | null | void;\n  inspectors: BlockInspectorResolver | undefined;\n  services: ContentServices | undefined;\n  /** The id of the lock reason held controls point to, in the card. */\n  reasonId: string;\n  /** Whether the Content tab is the one showing. */\n  onScreen: boolean;\n  /** The component's own view, when the document is a component. */\n  fields: ComponentFieldsBinding | undefined;\n  /** The page around the block, for a section the builder draws itself. */\n  around?: ContentAround | undefined;\n}): React.JSX.Element {\n  return (\n    <ContentSurface\n      // Keyed by node, so a custom inspector holding local state does not\n      // carry one block's draft to the next, as the generated fields do not.\n      key={`${block.nodeId}:content`}\n      inspection={block}\n      editor={editor}\n      onCommit={commit}\n      inspectors={inspectors}\n      services={services}\n      reasonId={reasonId}\n      fields={fields}\n      around={around}\n    />\n  );\n}\n\n/**\n * What a section the builder draws in Content reads of the page around the\n * block: Columns' Stack on names the site's devices, and reads a stack\n * reaching the row through the canvas's cascade.\n */\ninterface ContentAround {\n  readonly breakpoints: BreakpointSet | undefined;\n  readonly cascade: PageStyleCascade | undefined;\n  readonly renderedTag: string | undefined;\n}\n\n/**\n * Set one prop of one node: the one write path every content control shares.\n *\n * The patch is built from the node in `document`, which the caller passes as\n * the document the edit applies to, and the result is returned so a caller\n * making several edits in a row can build the next one on it. The props are\n * copied whole (`propPatch`), so a patch built from an older copy would put\n * back every value an edit since then changed.\n *\n * @returns the document after the edit, or `null` when it was not applied\n */\nexport function commitProp(\n  editor: EditorState,\n  document: BlockDocument,\n  id: string,\n  name: string,\n  value: unknown\n): BlockDocument | null {\n  // Refused here, for every caller: a lock set after a field drew must still\n  // stop the write, and inside a `contentOnly` area only content may change.\n  if (!propIsWritable(document, id, name, lockViewOf(editor))) return null;\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return null;\n  // An Embed's link, typed or pasted into its Link field, takes the\n  // provider's shape with it, in the same step, as a link pasted on the\n  // canvas does.\n  if (\n    node.type === EMBED_BLOCK_TYPE &&\n    name === \"src\" &&\n    typeof value === \"string\"\n  ) {\n    const linked = embedLinkOp(document, id, value, {\n      shape: designIsWritable(document, id, lockViewOf(editor)),\n    });\n    if (linked !== null) return editor.apply(linked);\n  }\n  return editor.apply({\n    kind: \"update\",\n    id,\n    patch: propPatch(node, name, value),\n  });\n}\n\n/** The Content sections the builder draws itself for the block, if any. */\nfunction builderSectionsOf(\n  inspection: BlockInspection,\n  editor: EditorState,\n  around: ContentAround | undefined,\n  reasonId: string,\n  services: ContentServices | undefined\n): PanelSection[] {\n  const labels = builderContentSectionsOf(inspection.blockName);\n  if (labels.length === 0) return [];\n  // Layout, Stack on, Columns and On mobile write the block's design, so a\n  // design lock holds them.\n  const designHeldBy =\n    designReadOnlyReason(\n      editor.document,\n      inspection.nodeId,\n      lockViewOf(editor)\n    ) === undefined\n      ? undefined\n      : reasonId;\n  const gallery = galleryContentSections(\n    {\n      editor,\n      nodeId: inspection.nodeId,\n      breakpoints: around?.breakpoints,\n      services,\n      reasonId,\n      designHeldBy,\n    },\n    labels\n  );\n  if (gallery.length > 0) return gallery;\n  // An Accordion's Icon is drawn after the block's own Behaviour, below.\n  if (inspection.blockName === ACCORDION_BLOCK) return [];\n  const [label] = labels;\n  if (label === undefined) return [];\n  const section = columnsContentSection({\n    editor,\n    nodeId: inspection.nodeId,\n    blockName: inspection.blockName,\n    label,\n    breakpoints: around?.breakpoints,\n    cascade: around?.cascade,\n    renderedTag: around?.renderedTag,\n    heldBy: designHeldBy,\n  });\n  return section === undefined ? [] : [section];\n}\n\n/**\n * The builder's sections and the block's own, as one list: a block's\n * section named as one the builder draws is drawn inside it, after the\n * builder's controls, so the two never share a name in one tab.\n */\nfunction joinedSections(\n  builder: readonly PanelSection[],\n  own: readonly PanelSection[]\n): PanelSection[] {\n  const named = new Set(builder.map(section => section.key));\n  return [\n    ...builder.map(section => {\n      const same = own.find(each => each.key === section.key);\n      if (same === undefined) return section;\n      return {\n        ...section,\n        holdsValue: section.holdsValue || same.holdsValue,\n        body: (\n          <>\n            {section.body}\n            {same.body}\n          </>\n        ),\n      };\n    }),\n    ...own.filter(section => !named.has(section.key)),\n  ];\n}\n\n/**\n * The Content tab: the block's own inspector where it names one the host\n * loaded, and the generated fields otherwise.\n *\n * Only the content controls are replaced. The identity fields above the tabs,\n * the whole Style tab and the whole Advanced tab are drawn for every block,\n * so a plugin's inspector cannot lose them.\n */\nfunction ContentSurface({\n  inspection,\n  editor,\n  onCommit,\n  inspectors,\n  services,\n  reasonId,\n  fields,\n  around,\n}: {\n  inspection: BlockInspection;\n  editor: EditorState;\n  onCommit: (name: string, value: unknown) => BlockDocument | null | void;\n  inspectors: BlockInspectorResolver | undefined;\n  services: ContentServices | undefined;\n  reasonId: string;\n  /** The component's own view, when the document is a component. */\n  fields: ComponentFieldsBinding | undefined;\n  around: ContentAround | undefined;\n}): React.JSX.Element {\n  // A block's own inspector knows nothing of bindings visitors will not see,\n  // so beside one, every such binding on the block is said above it.\n  const unreadable = useVisitorUnreadable(inspection.nodeId);\n  const filterOn = useSettingsMatch().active;\n  // Which props the block's locks leave writable, read once per document and\n  // block rather than once per field the tab draws.\n  const writable = React.useMemo(\n    () =>\n      writablePropsOf(editor.document, inspection.nodeId, lockViewOf(editor)),\n    [editor, inspection.nodeId]\n  );\n  const fieldsFor = (rows: readonly EditableProp[]): React.JSX.Element => (\n    <ContentFields\n      inspection={inspection}\n      rows={rows}\n      onCommit={onCommit}\n      services={services}\n      reasonId={reasonId}\n      fields={fields}\n      writable={writable}\n      onCommitMany={changes =>\n        commitLinkChanges(editor, inspection.nodeId, changes)\n      }\n      // A binding's edits, applied as any other edit of the block.\n      // Whether the editor took it: a refused edit is said, not assumed.\n      onApply={op => editor.apply(op) !== null}\n      document={editor.document}\n      listView={listViewOf(editor, inspection.nodeId)}\n    />\n  );\n  // The Form's Fields and After sending, which the builder draws in place\n  // of their generated rows.\n  const stored =\n    findNode(editor.document.nodes, inspection.nodeId)?.props ?? {};\n  // Where a Form's form comes from, read only while a Form is inspected.\n  const formSources = useFormSources(\n    inspection.blockName === FORM_BLOCK ? services?.listForms : undefined\n  );\n  const formBodies = formSectionBodies({\n    inspection,\n    stored,\n    services,\n    writable,\n    onCommit: (name, value) => {\n      onCommit(name, value);\n    },\n    rowsOf: fieldsFor,\n    exposeOf:\n      fields === undefined\n        ? undefined\n        : prop => (\n            <PropExposeControl\n              binding={fields}\n              nodeId={inspection.nodeId}\n              prop={prop}\n            />\n          ),\n  });\n  // The Embed's section: its Link, which writes the provider's shape with\n  // the link, and the settings that apply to what the link is.\n  const embedNode = findNode(editor.document.nodes, inspection.nodeId);\n  const embedBodies = embedSectionBodies({\n    inspection,\n    stored: embedNode?.props ?? {},\n    linkBound: embedNode?.bindings?.src !== undefined,\n    services,\n    writable,\n    onCommit: (name, value) => {\n      onCommit(name, value);\n    },\n    rowsOf: fieldsFor,\n  });\n  // Each section the block places in Content, folding on its own, after\n  // the ones the builder draws for a core block (Columns' layout, a\n  // Gallery's Pictures and Layout); a block\n  // with none draws the fields' own note that there is nothing to set.\n  const sections = [\n    ...joinedSections(\n      [\n        ...formSourceSections({\n          inspection,\n          stored,\n          sources: formSources,\n          writable,\n          onCommit: (name, value) => {\n            onCommit(name, value);\n          },\n        }),\n        ...builderSectionsOf(inspection, editor, around, reasonId, services),\n      ],\n      // A section the builder draws as `null` is one the block has no use\n      // for as it stands: a picked form's own fields.\n      inspection.sections.content.flatMap(section => {\n        const body =\n          formBodies?.has(section.label) === true\n            ? formBodies.get(section.label)\n            : (embedBodies?.get(section.label) ?? fieldsFor(section.rows));\n        return body === null || body === undefined\n          ? []\n          : [\n              {\n                key: section.label,\n                label: section.label,\n                holdsValue: rowsHoldValue(section.rows),\n                body,\n              },\n            ];\n      })\n    ),\n    // An Accordion's Icon, after its Behaviour: what the questions show,\n    // read after how they open. Held by a design lock, as it writes styles.\n    ...accordionContentSections(\n      {\n        editor,\n        nodeId: inspection.nodeId,\n        designHeldBy:\n          designReadOnlyReason(\n            editor.document,\n            inspection.nodeId,\n            lockViewOf(editor)\n          ) === undefined\n            ? undefined\n            : reasonId,\n        breakpoints: around?.breakpoints,\n        cascade: around?.cascade,\n        renderedTag: around?.renderedTag,\n      },\n      builderContentSectionsOf(inspection.blockName)\n    ),\n  ];\n  const generated =\n    sections.length === 0 ? (\n      fieldsFor(contentRowsOf(inspection))\n    ) : (\n      <PanelSections tab=\"content\" sections={sections} />\n    );\n  const Custom =\n    inspection.inspector === undefined\n      ? undefined\n      : inspectors?.(inspection.inspector);\n  // While the panel is filtered, the generated fields are drawn, which the\n  // filter can hide row by row; the block's own inspector knows nothing of it.\n  if (Custom === undefined || filterOn) return generated;\n  return (\n    <>\n      <VisitorUnreadableNote\n        bindings={unreadable}\n        props={new Set(unreadable.map(binding => binding.prop))}\n        // A library fallback named by its file, as the image row names it.\n        services={services}\n      />\n      <CustomInspectorBoundary fallback={generated}>\n        <CustomInspector\n          Inspector={Custom}\n          nodeId={inspection.nodeId}\n          editor={editor}\n        />\n        {/*\n          A block's own inspector draws its own controls and knows nothing of\n          exposing them, so in a component's view its props are listed again\n          beneath it, each with its switch.\n        */}\n        {fields === undefined ? null : (\n          <ExposeRows inspection={inspection} fields={fields} />\n        )}\n      </CustomInspectorBoundary>\n    </>\n  );\n}\n\n/**\n * Each Content setting's expose switch, for a block whose own inspector draws\n * its controls. The Advanced tab draws its own settings' switches.\n */\nfunction ExposeRows({\n  inspection,\n  fields,\n}: {\n  inspection: BlockInspection;\n  fields: ComponentFieldsBinding;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-inspector__fields\" data-expose-rows=\"\">\n      {contentRowsOf(inspection).map(prop => (\n        <div\n          key={`${inspection.nodeId}:${prop.name}:expose`}\n          className=\"nx-inspector__prop\"\n        >\n          <p className=\"nx-inspector__note\">{fieldLabel(prop.name)}</p>\n          <PropExposeControl\n            binding={fields}\n            nodeId={inspection.nodeId}\n            prop={prop}\n          />\n        </div>\n      ))}\n    </div>\n  );\n}\n\n/**\n * A block's own inspector, given the contract every one is given.\n *\n * `commit` is the generated controls' own write path, addressed to THIS node\n * rather than to whatever is selected when it is called, with one guard in\n * front, asked of the document at the moment of the call: nothing is written\n * to a locked block, and inside a `\"contentOnly\"` area only its content props\n * are. `readOnly` tells the component to draw itself disabled, but the\n * component is plugin code, and a lock that held only while the plugin\n * honoured a flag would not be a lock. So the refusal is here, whatever the\n * component does with the flag.\n */\nfunction CustomInspector({\n  Inspector,\n  nodeId,\n  editor,\n}: {\n  Inspector: React.ComponentType<BlockInspectorProps>;\n  nodeId: string;\n  editor: EditorState;\n}): React.JSX.Element | null {\n  /*\n   * The editor and the document every commit reads, held where any copy of\n   * `commit` sees the latest.\n   *\n   * A component may commit twice in one handler, before the panel re-renders,\n   * or hold `commit` across an await while the document moves on. Either way\n   * the render's `editor.document` is out of date when the call runs, and a\n   * patch built from it would put back what changed in between (`propPatch`\n   * copies the props whole) and miss a lock set meanwhile. So each render\n   * publishes its editor here, each commit advances the document to what its\n   * own write produced, and the callback itself never changes.\n   */\n  const live = React.useRef({ editor, document: editor.document });\n  useIsomorphicLayoutEffect(() => {\n    live.current = { editor, document: editor.document };\n  }, [editor]);\n  const commit = React.useCallback(\n    (name: string, value: unknown): void => {\n      const { editor: current, document } = live.current;\n      if (!propIsWritable(document, nodeId, name, lockViewOf(current))) {\n        return;\n      }\n      const next = commitProp(current, document, nodeId, name, value);\n      if (next !== null) live.current = { editor: current, document: next };\n    },\n    [nodeId]\n  );\n  const node = findNode(editor.document.nodes, nodeId);\n  if (node === undefined) return null;\n  return (\n    <div className=\"nx-inspector__fields\" data-inspector=\"custom\">\n      <Inspector\n        node={node}\n        props={node.props}\n        commit={commit}\n        readOnly={blockIsReadOnly(editor.document, nodeId)}\n      />\n    </div>\n  );\n}\n\n/**\n * Keeps a plugin inspector that throws from taking the editor down with it.\n *\n * The generated controls are drawn instead, with a note, so the author can go\n * on editing the block: a broken plugin component is a reason to lose its\n * nicer controls, never the block's content.\n */\nclass CustomInspectorBoundary extends React.Component<\n  { fallback: React.ReactNode; children: React.ReactNode },\n  { failed: boolean }\n> {\n  override state = { failed: false };\n\n  static getDerivedStateFromError(): { failed: boolean } {\n    return { failed: true };\n  }\n\n  override render(): React.ReactNode {\n    if (!this.state.failed) return this.props.children;\n    return (\n      <>\n        <p className=\"nx-inspector__note\" role=\"status\">\n          This block&apos;s own controls could not be shown, so its standard\n          controls are shown instead.\n        </p>\n        {this.props.fallback}\n      </>\n    );\n  }\n}\n","/**\n * The style state the inspector edits, which is `base` unless a setter came\n * with it; the tab a mount opens on for it; and the tab the panel shows for\n * the selected block.\n *\n * @module inspector-style-state\n */\n\nimport type { StyleState } from \"@nextlyhq/blocks-engine\";\n\nimport type { StyleStateBinding } from \"./inspector-panel-types\";\n\n/**\n * The state the panel actually edits, which is `base` unless a setter came with\n * it.\n *\n * The binding permits a state without an `onChange`, and that shape has to mean\n * something rather than being merely allowed. Read literally it is a state\n * nobody can leave: the switcher is withheld because nothing could act on a\n * choice, the tab handler has no callback to return the canvas with, and every\n * control below would go on reading and writing a state with no visible control\n * saying which one — the exact arrangement this panel's contract exists to\n * prevent, reached through the type instead of through a miswiring.\n *\n * Normalised rather than refused, because a host part-way through adopting the\n * control should get a working base editor rather than a broken one.\n */\nexport function editedStyleState(\n  binding: StyleStateBinding | undefined\n): StyleState {\n  if (binding?.onChange === undefined) return \"base\";\n  return binding.state ?? \"base\";\n}\n\n/**\n * Which tab a mount opens on, given the state the host restored.\n *\n * `content` unless a state is in effect, which is the ordinary case and the\n * behaviour every existing caller already has: a host that names no state, or\n * names `base`, or supplies no setter — in which case {@link editedStyleState}\n * has already resolved the state to `base` and there is nothing to explain.\n */\nexport function openingTabFor(binding: StyleStateBinding | undefined): string {\n  return editedStyleState(binding) === \"base\" ? \"content\" : \"style\";\n}\n\n/**\n * The tab the panel shows: the one the author chose, where the selected\n * block has it, and the block's first tab otherwise.\n *\n * The author's choice is kept apart from what is shown, so a block without\n * their tab (a Spacer has no Content) shows its first and the next block\n * that has it shows theirs again: an author styling one block after another\n * stays on Style however many blocks without Content they pass through.\n *\n * @param chosen - the tab the author last chose, or the one a mount opened on\n * @param available - the selected block's tabs, in order\n */\nexport function shownTab(chosen: string, available: readonly string[]): string {\n  if (available.includes(chosen)) return chosen;\n  return available[0] ?? \"content\";\n}\n","/**\n * The viewer's colour-scheme preference, as the canvas sees it.\n *\n * One hook for every panel that shows token values the way the canvas does:\n * the style inspector's swatches and the Variables view's preview.\n *\n * @module prefers-dark\n */\nimport { DARK_MODE_ATTRIBUTE, type TokenMode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { nearestThemeMode } from \"./nearest-theme\";\n\n/**\n * Whether the viewer's system asks for a dark colour scheme.\n *\n * Read because the site sheet applies dark token values under\n * `@media (prefers-color-scheme:dark)`, so the canvas switches with the system\n * and nothing tells the panels. Resolving every token to its\n * light value regardless would paint swatches and report ratios for colours the\n * canvas is not showing.\n *\n * Starts `false` and subscribes after mount, so a server render and the first\n * client render agree — React discards a subtree whose two renders disagree,\n * which would take the whole Style tab with it. A viewer already in dark mode\n * sees one frame of light-mode swatches; the alternative is a hydration\n * mismatch, which is worse and harder to see.\n *\n * Asked of the CANVAS's window, which is a frame's when the canvas is in one:\n * the page's own media queries are evaluated there, so that is the window\n * whose answer the canvas is showing.\n */\nexport function usePrefersDark(): boolean {\n  const [prefersDark, setPrefersDark] = React.useState(false);\n  const view = useCanvasFrame().window;\n  React.useEffect(() => {\n    // Detected by CALLABILITY, not by presence. `\"matchMedia\" in window` is\n    // true under jsdom while the value is not a function, so the property test\n    // passes and the call throws — measured, and it took 85 tests down. A\n    // capability check has to ask the question the caller will ask.\n    if (view === null || typeof view.matchMedia !== \"function\") return;\n    const query = view.matchMedia(\"(prefers-color-scheme: dark)\");\n    setPrefersDark(query.matches);\n    const listen = (event: MediaQueryListEvent): void =>\n      setPrefersDark(event.matches);\n    query.addEventListener(\"change\", listen);\n    return () => query.removeEventListener(\"change\", listen);\n  }, [view]);\n  return prefersDark;\n}\n\n/**\n * The mode the canvas shows site variables in where the selected block is\n * drawn: the `data-nx-theme` marker nearest that block's element, which a\n * marker nested inside the page can set, else the one nearest the canvas\n * root, else the device's preference.\n *\n * THE one answer for every inspector control that shows a variable's value,\n * the colour picker's swatches, the variables list and its chip, and what a\n * typed variable name may match, so none of them shows or accepts a value of\n * the mode the selected block is not drawn in.\n *\n * Asked ONCE, by the Style panel, which hands the answer to its controls\n * through {@link CanvasTokenModeProvider}: a subscription per control would\n * repeat the same reading, on every change to the canvas, once per field.\n */\nexport function useCanvasTokenModeAt(selectedId: string | null): TokenMode {\n  const prefersDark = usePrefersDark();\n  const doc = useCanvasFrame().document;\n  const marker = React.useSyncExternalStore(\n    React.useCallback(\n      (changed: () => void) =>\n        doc === null ? () => undefined : watchMarkers(doc, changed),\n      [doc]\n    ),\n    () => (doc === null ? null : canvasMarker(doc, selectedId)),\n    // A server render has no canvas, and the device decides, as it does\n    // before the client's first answer.\n    () => null\n  );\n  return marker ?? (prefersDark ? \"dark\" : \"light\");\n}\n\n/** The mode the Style panel read, handed to its controls. */\nconst CanvasTokenModeContext = React.createContext<TokenMode | null>(null);\n\n/** Hands the panel's one reading of the mode to every control inside it. */\nexport const CanvasTokenModeProvider: React.Provider<TokenMode | null> =\n  CanvasTokenModeContext.Provider;\n\n/**\n * The mode a control shows variables in, as its panel read it. Light outside\n * a panel, which is what a document with no mode resolves.\n */\nexport function useCanvasTokenMode(): TokenMode {\n  return React.useContext(CanvasTokenModeContext) ?? \"light\";\n}\n\n/**\n * The mode the marker nearest the selected block's element names, else the\n * one nearest the canvas root, or `null` where no marker names one.\n */\nfunction canvasMarker(\n  doc: Document,\n  selectedId: string | null\n): TokenMode | null {\n  const drawn =\n    selectedId === null\n      ? undefined\n      : [...doc.querySelectorAll(\"[data-nx-node]\")].find(\n          element => element.getAttribute(\"data-nx-node\") === selectedId\n        );\n  const at = drawn ?? doc.querySelector(`.${CANVAS_ROOT_CLASS}`);\n  return at === null ? null : nearestThemeMode(at);\n}\n\n/**\n * The listeners waiting on one document's markers, and the one observer that\n * serves them, so a second panel reading the same canvas adds a listener and\n * not an observer.\n */\nconst MARKER_WATCHERS = new WeakMap<\n  Document,\n  { listeners: Set<() => void>; observer: MutationObserver | null }\n>();\n\n/**\n * Call `changed` whenever a marker is set, changed or removed in `doc`, or\n * the canvas root arrives already under one. Answers the way to stop.\n */\nfunction watchMarkers(doc: Document, changed: () => void): () => void {\n  let watch = MARKER_WATCHERS.get(doc);\n  if (watch === undefined) {\n    const listeners = new Set<() => void>();\n    const Observer = doc.defaultView?.MutationObserver;\n    // Built from the document's own window, the realm of what it observes.\n    const observer =\n      typeof Observer === \"function\"\n        ? new Observer(() => {\n            for (const listener of listeners) listener();\n          })\n        : null;\n    observer?.observe(doc.documentElement, {\n      attributes: true,\n      attributeFilter: [DARK_MODE_ATTRIBUTE],\n      childList: true,\n      subtree: true,\n    });\n    watch = { listeners, observer };\n    MARKER_WATCHERS.set(doc, watch);\n  }\n  const held = watch;\n  held.listeners.add(changed);\n  return () => {\n    held.listeners.delete(changed);\n    if (held.listeners.size > 0) return;\n    held.observer?.disconnect();\n    MARKER_WATCHERS.delete(doc);\n  };\n}\n","\"use client\";\n\n/**\n * The editing bar's target chip and its menu.\n *\n * The chip says what the next style edit changes: \"● This block\" in pink, or\n * \"◆ <style>\" in green while a shared style the block wears is the target. It\n * opens one menu that never changes shape: \"This block\", each shared style\n * the block wears with Detach and Remove under it, then \"Apply a shared\n * style…\" and \"Save as shared style…\". An edit only enables or holds an item;\n * a held item stays where it is with its reason under it, so nothing in the\n * menu, or in the panel below the bar, moves after the first edit.\n *\n * The colour is never the only sign: the mark, the words and the chip's name\n * all say which target it is.\n *\n * @module editing-chips\n */\n\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n} from \"@nextlyhq/ui\";\nimport { Check, ChevronDown, Lock } from \"lucide-react\";\nimport * as React from \"react\";\n\n/** One shared style the block wears, as the target menu lists it. */\nexport interface EditingBarChip {\n  readonly id: string;\n  readonly name: string;\n  /** Locked: its item carries a lock mark, named in words. */\n  readonly locked?: boolean;\n  /** The class the page carries for it, as developers read it: \".nx-c-card\". */\n  readonly className: string;\n  /**\n   * What choosing it does, in words, when that is worth saying: a block\n   * style's \"Edit Outline for every button that uses it\". The class name\n   * otherwise.\n   */\n  readonly hint?: string;\n}\n\n/** An action the menu always lists: runs, or is held with its reason. */\nexport type BarOffer =\n  | { readonly run: () => void; readonly held?: undefined }\n  | { readonly run?: undefined; readonly held: string };\n\n/** \"Apply a shared style…\": the picker it opens, or why it is held. */\nexport type ApplyOffer =\n  | {\n      /** The picker, drawn under the chip; `close` puts it away. */\n      readonly picker: (close: () => void) => React.ReactNode;\n      readonly held?: undefined;\n    }\n  | { readonly picker?: undefined; readonly held: string };\n\n/** What the chip shows for the target. */\nexport type ChipTarget =\n  | { readonly kind: \"block\" }\n  | {\n      readonly kind: \"shared\";\n      readonly id: string;\n      readonly name: string;\n      readonly className: string;\n      readonly locked: boolean;\n    };\n\nexport interface TargetChipProps {\n  readonly target: ChipTarget;\n  readonly chips: readonly EditingBarChip[];\n  /** Choose the target: a style's id, or `null` for this block. */\n  readonly onTargetChange?: ((id: string | null) => void) | undefined;\n  readonly onRemove?: ((id: string) => void) | undefined;\n  readonly onDetach?: ((id: string) => void) | undefined;\n  /** Why one style can't be detached: asked only while the menu is open. */\n  readonly detachHeld?: ((id: string) => string | undefined) | undefined;\n  /** Why Detach and Remove are held (the block's lock). */\n  readonly chipActionsHeld?: string | undefined;\n  /** Why a shared style can't be made the target (the block's design is held). */\n  readonly targetHeld?: string | undefined;\n  /** \"Apply a shared style…\": the picker it opens, or why it is held. */\n  readonly apply: ApplyOffer;\n  /** \"Save as shared style…\": runs, or why it is held. */\n  readonly save: BarOffer;\n}\n\n/** Why a shared style can't be chosen when nothing can carry the choice. */\nconst NO_SHARED_TARGET = \"Shared styles can't be edited from here.\";\n\n/** The chip's name for a reader: what is being edited, in words. */\nfunction targetChipName(target: ChipTarget): string {\n  if (target.kind === \"block\") return \"Editing: This block\";\n  const locked = target.locked ? \", locked\" : \"\";\n  return `Editing: shared style ${target.name}${locked}`;\n}\n\nexport function TargetChip({\n  target,\n  chips,\n  onTargetChange,\n  onRemove,\n  onDetach,\n  detachHeld,\n  chipActionsHeld,\n  targetHeld,\n  apply,\n  save,\n}: TargetChipProps): React.JSX.Element {\n  const chip = React.useRef<HTMLButtonElement>(null);\n  const [picking, setPicking] = React.useState(false);\n  // Set by \"Apply a shared style…\" and read as the menu hands focus back:\n  // the picker opens only then, so the menu's return of focus to the chip\n  // cannot take it from the picker's search field.\n  const pickNext = React.useRef(false);\n  const shared = target.kind === \"shared\";\n  const name = shared ? target.name : \"This block\";\n  return (\n    <Popover open={picking} onOpenChange={setPicking} modal>\n      <DropdownMenu modal={false}>\n        <PopoverAnchor asChild>\n          <DropdownMenuTrigger asChild>\n            <button\n              ref={chip}\n              type=\"button\"\n              className=\"nx-editing-bar__chip nx-editing-bar__target\"\n              data-tone={shared ? \"shared\" : \"block\"}\n              data-edit-target={target.kind}\n              aria-label={targetChipName(target)}\n              // The whole name, for a long one the chip ends in an ellipsis.\n              title={\n                shared\n                  ? `Shared style ${target.name}, ${target.className}`\n                  : \"This block only\"\n              }\n            >\n              <span className=\"nx-editing-bar__mark\" aria-hidden=\"true\">\n                {shared ? \"◆\" : \"●\"}\n              </span>\n              <span className=\"nx-editing-bar__name\">{name}</span>\n              {shared && target.locked ? (\n                <Lock aria-hidden=\"true\" size={11} />\n              ) : null}\n              <ChevronDown aria-hidden=\"true\" size={12} />\n            </button>\n          </DropdownMenuTrigger>\n        </PopoverAnchor>\n        {/* Kept clear of the window's edge. */}\n        <DropdownMenuContent\n          align=\"start\"\n          collisionPadding={8}\n          className=\"nx-editing-bar__menu\"\n          onCloseAutoFocus={event => {\n            if (!pickNext.current) return;\n            pickNext.current = false;\n            event.preventDefault();\n            setPicking(true);\n          }}\n        >\n          <TargetItem\n            mark=\"●\"\n            tone=\"block\"\n            label=\"This block\"\n            hint=\"Changes this block only\"\n            checked={!shared}\n            onSelect={() => onTargetChange?.(null)}\n          />\n          {chips.map(each => (\n            <SharedItems\n              key={each.id}\n              chip={each}\n              checked={shared && target.id === each.id}\n              held={\n                onTargetChange === undefined\n                  ? NO_SHARED_TARGET\n                  : shared && target.id === each.id\n                    ? undefined\n                    : targetHeld\n              }\n              onChoose={() => onTargetChange?.(each.id)}\n              onRemove={onRemove}\n              onDetach={onDetach}\n              detachHeld={detachHeld}\n              actionsHeld={chipActionsHeld}\n            />\n          ))}\n          <DropdownMenuSeparator />\n          <OfferItem\n            label=\"Apply a shared style…\"\n            offer={apply}\n            onSelect={() => {\n              pickNext.current = true;\n            }}\n          />\n          <OfferItem\n            label=\"Save as shared style…\"\n            offer={save}\n            onSelect={() => save.run?.()}\n          />\n        </DropdownMenuContent>\n      </DropdownMenu>\n      {apply.picker === undefined ? null : (\n        <PopoverContent\n          side=\"bottom\"\n          align=\"start\"\n          // Kept clear of the window's edge.\n          collisionPadding={8}\n          className=\"nx-vars-editor nx-shared-style-picker\"\n          aria-label=\"Apply a shared style\"\n          // Back to the chip that opened it: the picker has no trigger of\n          // its own for the popover to return focus to.\n          onCloseAutoFocus={event => {\n            event.preventDefault();\n            chip.current?.focus();\n          }}\n        >\n          {apply.picker(() => setPicking(false))}\n        </PopoverContent>\n      )}\n    </Popover>\n  );\n}\n\n/** An item's words: its label, and a line under it (a hint or a reason). */\nfunction ItemWords({\n  label,\n  line,\n  reason,\n}: {\n  label: React.ReactNode;\n  line: string | undefined;\n  /** Whether the line is why the item is held, read as one sentence. */\n  reason: boolean;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-editing-bar__item-words\">\n      <span>{label}</span>\n      {line === undefined || line === \"\" ? null : (\n        <span\n          className={\n            reason ? \"nx-editing-bar__item-reason\" : \"nx-editing-bar__item-hint\"\n          }\n        >\n          {/* Heard as one sentence; read as a line of its own. */}\n          <span className=\"nx-sr-only\"> — </span>\n          {line}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/** A target in the menu: one of a set, the chosen one ticked. */\nfunction TargetItem({\n  mark,\n  tone,\n  label,\n  hint,\n  checked,\n  held,\n  locked = false,\n  onSelect,\n}: {\n  mark: string;\n  tone: \"block\" | \"shared\";\n  label: string;\n  hint: string | undefined;\n  checked: boolean;\n  held?: string | undefined;\n  locked?: boolean;\n  onSelect: () => void;\n}): React.JSX.Element {\n  return (\n    <DropdownMenuItem\n      // One target of several, as the State menu's items are: a radio item,\n      // its choice ticked.\n      role=\"menuitemradio\"\n      aria-checked={checked}\n      disabled={held !== undefined}\n      data-target-item={tone}\n      onSelect={() => {\n        if (!checked) onSelect();\n      }}\n    >\n      <span className=\"nx-state-menu__tick\" aria-hidden=\"true\">\n        {checked ? <Check size={12} /> : null}\n      </span>\n      <ItemWords\n        label={\n          <span className=\"nx-editing-bar__item-target\" data-tone={tone}>\n            <span aria-hidden=\"true\">{mark}</span> {label}\n            {locked ? (\n              <>\n                <Lock aria-hidden=\"true\" size={11} />\n                <span className=\"nx-sr-only\">, locked</span>\n              </>\n            ) : null}\n          </span>\n        }\n        line={held ?? hint}\n        reason={held !== undefined}\n      />\n    </DropdownMenuItem>\n  );\n}\n\n/** A worn shared style: its target item, then its Detach and Remove. */\nfunction SharedItems({\n  chip,\n  checked,\n  held,\n  onChoose,\n  onRemove,\n  onDetach,\n  detachHeld,\n  actionsHeld,\n}: {\n  chip: EditingBarChip;\n  checked: boolean;\n  held: string | undefined;\n  onChoose: () => void;\n  onRemove: ((id: string) => void) | undefined;\n  onDetach: ((id: string) => void) | undefined;\n  detachHeld: ((id: string) => string | undefined) | undefined;\n  actionsHeld: string | undefined;\n}): React.JSX.Element {\n  // Asked while drawing the open menu only: answering plans the detach,\n  // which the bar's every render need not pay for.\n  const detachReason =\n    onDetach === undefined ? undefined : (actionsHeld ?? detachHeld?.(chip.id));\n  return (\n    <>\n      <TargetItem\n        mark=\"◆\"\n        tone=\"shared\"\n        label={chip.name}\n        hint={chip.hint ?? chip.className}\n        checked={checked}\n        held={held}\n        locked={chip.locked === true}\n        onSelect={onChoose}\n      />\n      {onDetach === undefined ? null : (\n        <DropdownMenuItem\n          className=\"nx-editing-bar__item-sub\"\n          disabled={detachReason !== undefined}\n          onSelect={() => onDetach(chip.id)}\n        >\n          <ItemWords\n            label={\n              <>\n                Detach<span className=\"nx-sr-only\"> {chip.name}</span>\n              </>\n            }\n            line={detachReason ?? \"Keep the look on this block only\"}\n            reason={detachReason !== undefined}\n          />\n        </DropdownMenuItem>\n      )}\n      {onRemove === undefined ? null : (\n        <DropdownMenuItem\n          className=\"nx-editing-bar__item-sub\"\n          disabled={actionsHeld !== undefined}\n          onSelect={() => onRemove(chip.id)}\n        >\n          <ItemWords\n            label={\n              <>\n                Remove<span className=\"nx-sr-only\"> {chip.name}</span>\n              </>\n            }\n            line={actionsHeld ?? `Take ${chip.name} off this block`}\n            reason={actionsHeld !== undefined}\n          />\n        </DropdownMenuItem>\n      )}\n    </>\n  );\n}\n\n/** \"Apply a shared style…\" or \"Save as shared style…\": always listed. */\nfunction OfferItem({\n  label,\n  offer,\n  onSelect,\n}: {\n  label: string;\n  offer: { readonly held?: string | undefined };\n  onSelect: () => void;\n}): React.JSX.Element {\n  return (\n    <DropdownMenuItem\n      disabled={offer.held !== undefined}\n      onSelect={onSelect}\n      data-bar-offer={label}\n    >\n      <span className=\"nx-state-menu__tick\" aria-hidden=\"true\" />\n      <ItemWords label={label} line={offer.held} reason />\n    </DropdownMenuItem>\n  );\n}\n","\"use client\";\n\n/**\n * The \"what you're editing\" bar at the top of the Style tab.\n *\n * One line of chips says, before any control does, what the next style edit\n * changes: the target (\"● This block\" in pink, or \"◆ <style>\" in green), the\n * device the canvas shows, and the state (amber when not Normal). Each chip\n * carries words as well as colour. The device and the state are the canvas's\n * own values, handed down and never a second copy kept here.\n *\n * The line keeps one height whatever the author does to the block: a value\n * changed, a block style or a shared style applied, a font picked. The one\n * thing that adds a line is choosing a shared style as the target, which says\n * how widely it is used and that an edit changes every block wearing it.\n *\n * Escape on a shared target returns to this block, and a switch of target is\n * announced.\n *\n * @module editing-bar\n */\n\nimport type { StyleState } from \"@nextlyhq/blocks-engine\";\nimport { TooltipProvider } from \"@nextlyhq/ui\";\nimport { Monitor } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\n\nimport {\n  type ApplyOffer,\n  type BarOffer,\n  type ChipTarget,\n  type EditingBarChip,\n  TargetChip,\n} from \"./editing-chips\";\nimport { stateLabel } from \"./state-switcher\";\n\nexport type { ApplyOffer, BarOffer, EditingBarChip } from \"./editing-chips\";\n\n/**\n * What a style edit writes to: this block, or one of the shared styles it\n * wears, with what the bar says about it.\n */\nexport type EditTarget =\n  | { readonly kind: \"block\" }\n  | {\n      readonly kind: \"shared\";\n      readonly id: string;\n      /** The style's name: \"Card\". */\n      readonly name: string;\n      /** The class name as developers read it: \".card\". */\n      readonly className: string;\n      /** How far it reaches, in words, or \"\" while that is not known. */\n      readonly reach: string;\n    };\n\nexport interface EditingBarProps {\n  readonly target: EditTarget;\n  /** The shared styles the block wears, in the order that decides which wins. */\n  readonly chips?: readonly EditingBarChip[];\n  /**\n   * Choose the target: a chip's id, or `null` for this block. Absent, the\n   * styles are listed but cannot become the target.\n   */\n  readonly onTargetChange?: (id: string | null) => void;\n  /** Take a style off the block. Absent withholds the item. */\n  readonly onRemove?: (id: string) => void;\n  /** Keep the style's look on this block only. Absent withholds the item. */\n  readonly onDetach?: (id: string) => void;\n  /**\n   * Why one style can't be detached, when its look can't be kept exactly:\n   * asked as its menu opens, so the item is held with the reason beside it.\n   */\n  readonly detachHeld?: (id: string) => string | undefined;\n  /** Why Detach and Remove are held (the block's lock), shown in the menu. */\n  readonly chipActionsHeld?: string;\n  /**\n   * Why a shared style can't be made the target (the block's design is held,\n   * which its shared styles' values are part of), said on each such item.\n   */\n  readonly targetHeld?: string;\n  /** \"Apply a shared style…\": the picker it opens, or why it is held. */\n  readonly apply: ApplyOffer;\n  /** \"Save as shared style…\": runs, or why it is held. */\n  readonly save: BarOffer;\n  /** Why a shared target's values can't be changed, when they can't. */\n  readonly sharedReadOnly?: string;\n  /** The device the canvas shows: \"Desktop\". */\n  readonly device: string;\n  /** The devices an edit reaches, in words: \"All devices\", \"Tablet and smaller\". */\n  readonly deviceReach?: string;\n  /** The device's glyph, as the top bar draws it. */\n  readonly deviceIcon?: React.ComponentType<{ className?: string }>;\n  /** The state being edited. */\n  readonly state: StyleState;\n  /**\n   * The control that changes the state, when the host can carry the choice to\n   * its canvas. Without it the bar names the state and offers no change.\n   */\n  readonly stateControl?: React.ReactNode;\n}\n\n/** The sentence a switch of target is announced with. */\nfunction targetAnnouncement(target: EditTarget): string {\n  return target.kind === \"block\"\n    ? \"Now editing this block\"\n    : `Now editing shared style ${target.name}`;\n}\n\n/** The line a shared target adds: how far it reaches, and what that means. */\nexport function sharedUsageLine(reach: string): string {\n  // The reach sentence starts a sentence of its own; here it follows a dot.\n  const said =\n    reach === \"\" ? \"\" : reach.charAt(0).toLowerCase() + reach.slice(1);\n  return said === \"\"\n    ? \"Shared style. Changes here change all of them.\"\n    : `Shared style · ${said}. Changes here change all of them.`;\n}\n\n/** The words over the sections while a state other than Normal is edited. */\nexport function stateLookLine(state: StyleState): string {\n  return `You are editing the ${stateLabel(state)} look. Normal stays as it is.`;\n}\n\nexport function EditingBar({\n  target,\n  chips = [],\n  sharedReadOnly,\n  device,\n  deviceReach,\n  deviceIcon,\n  state,\n  stateControl,\n  // What the target chip's menu offers, handed to it whole.\n  ...menu\n}: EditingBarProps): React.JSX.Element {\n  const announced = useSwitchAnnouncement(target);\n  const onTargetChange = menu.onTargetChange;\n  return (\n    // Its own provider, as each surface keeps one: the device chip says where\n    // the device is chosen in the editor's tooltip, wherever the bar is drawn.\n    <TooltipProvider delayDuration={300}>\n      <section\n        className=\"nx-editing-bar\"\n        aria-label=\"What you're editing\"\n        data-target={target.kind}\n        data-state={state}\n        onKeyDown={event => leaveOnEscape(event, target, onTargetChange)}\n      >\n        <div className=\"nx-editing-bar__line\">\n          <TargetChip\n            {...menu}\n            target={chipTarget(target, chips)}\n            chips={chips}\n          />\n          <DeviceChip device={device} reach={deviceReach} icon={deviceIcon} />\n          <StateChip state={state} stateControl={stateControl} />\n        </div>\n        {target.kind === \"shared\" ? (\n          <UsageLine reach={target.reach} readOnly={sharedReadOnly} />\n        ) : null}\n        <p className=\"nx-sr-only\" role=\"status\">\n          {announced}\n        </p>\n      </section>\n    </TooltipProvider>\n  );\n}\n\n/**\n * Escape on a shared target goes back to this block, so leaving a site-wide\n * edit is one key from anywhere in the bar. A key a menu inside the bar\n * already answered (its own Escape) is left alone, and the one answered here\n * is marked, so the editor's Escape, which skips an answered key, does not\n * also select the parent block.\n */\nfunction leaveOnEscape(\n  event: React.KeyboardEvent,\n  target: EditTarget,\n  onTargetChange: ((id: string | null) => void) | undefined\n): void {\n  if (event.key !== \"Escape\" || target.kind !== \"shared\") return;\n  if (onTargetChange === undefined || event.defaultPrevented) return;\n  event.preventDefault();\n  onTargetChange(null);\n}\n\n/** The target as its chip shows it, a worn style's lock included. */\nfunction chipTarget(\n  target: EditTarget,\n  chips: readonly EditingBarChip[]\n): ChipTarget {\n  if (target.kind === \"block\") return target;\n  const worn = chips.find(chip => chip.id === target.id);\n  return {\n    kind: \"shared\",\n    id: target.id,\n    name: target.name,\n    className: target.className,\n    locked: worn?.locked === true,\n  };\n}\n\n/** A shared target's line under the chips, and why it is read-only, if so. */\nfunction UsageLine({\n  reach,\n  readOnly,\n}: {\n  reach: string;\n  readOnly: string | undefined;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-editing-bar__usage\">\n      <p data-shared-reach=\"\">{sharedUsageLine(reach)}</p>\n      {readOnly === undefined ? null : (\n        <p className=\"nx-editing-bar__note\" data-shared-read-only=\"\">\n          {readOnly}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/**\n * The announcement for a switch of target: empty on mount and when a new\n * block is selected (nothing was switched), the sentence after a switch.\n */\nfunction useSwitchAnnouncement(target: EditTarget): string {\n  const key = target.kind === \"block\" ? \"\" : target.id;\n  const seen = React.useRef(key);\n  const [said, setSaid] = React.useState(\"\");\n  React.useEffect(() => {\n    if (seen.current === key) return;\n    seen.current = key;\n    setSaid(targetAnnouncement(target));\n  }, [key, target]);\n  return said;\n}\n\n/**\n * The device the canvas shows, with its glyph: a report, not a control. The\n * device is chosen in the top bar, which its tooltip says, with the devices\n * an edit here reaches; a reader hears both after its name.\n */\nfunction DeviceChip({\n  device,\n  reach,\n  icon: Icon = Monitor,\n}: {\n  device: string;\n  reach: string | undefined;\n  icon: React.ComponentType<{ className?: string }> | undefined;\n}): React.JSX.Element {\n  const about = [\n    reach === undefined ? undefined : `Changes here reach: ${reach}.`,\n    \"The device is chosen in the top bar.\",\n  ]\n    .filter(line => line !== undefined)\n    .join(\" \");\n  return (\n    <ChromeTooltip content={about}>\n      <span className=\"nx-editing-bar__chip nx-editing-bar__device\">\n        <Icon className=\"nx-editing-bar__device-icon\" aria-hidden=\"true\" />\n        <span data-edit-device=\"\">{device}</span>\n        <span className=\"nx-sr-only\">. {about}</span>\n      </span>\n    </ChromeTooltip>\n  );\n}\n\n/**\n * The state: the host's State menu drawn as a chip, amber when not Normal, or\n * the state's name when the host cannot carry a choice to its canvas.\n */\nfunction StateChip({\n  state,\n  stateControl,\n}: {\n  state: StyleState;\n  stateControl: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-editing-bar__state-chip\" data-state={state}>\n      {stateControl ?? (\n        // Said once, by the words below, for a reader.\n        <span\n          className=\"nx-editing-bar__chip nx-editing-bar__state\"\n          aria-hidden=\"true\"\n        >\n          {stateLabel(state)}\n        </span>\n      )}\n      {/* The state in words for a test or a reader, whichever draws it. */}\n      <span className=\"nx-sr-only\" data-edit-state={state}>\n        {stateLabel(state)}\n      </span>\n    </span>\n  );\n}\n","/**\n * The picture a style field aims over, and how the block fits it.\n *\n * @module focal-frame\n */\nimport * as React from \"react\";\n\n/**\n * The selected block's picture, as the canvas draws it, and the fit in force\n * for it here. Carried by context because only the focal point reads it, and\n * the field table it is drawn from passes every field the same props.\n */\nexport interface FocalFrameValue {\n  /** The picture's address, as the canvas shows it; none for no picture. */\n  readonly picture?: string | undefined;\n  /**\n   * Where the canvas places the picture, resolved there: what a contextual\n   * point (`inherit`, a variable) comes to, which the inspector cannot read.\n   */\n  readonly position?: string | undefined;\n  /** The `object-fit` keyword in force here, lowercased; none when unset. */\n  readonly fit?: string | undefined;\n}\n\nexport const FocalFrame: React.Context<FocalFrameValue> =\n  React.createContext<FocalFrameValue>({});\n","/**\n * The Style tab's \"Block style\" section, first in the tab and above the\n * editing bar: one tile per block style the selected block's type has, each\n * drawn as the block would be, its own style first and marked the default.\n * Choosing a tile swaps the block style the block wears; its shared style, if\n * any, stays. Under the tiles, one line says what a block style is and, where\n * the host can open Design, offers \"Edit block styles\" at the block's type.\n *\n * @module look-tiles-view\n */\n\nimport {\n  findNode,\n  getBlock,\n  type NamedClass,\n  type NodeStyles,\n  type SiteTokenSet,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport { ArrowUpRight, Check, Image as ImageIcon } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport { variationLabel } from \"../../panels/add/inserter\";\nimport { siteBaseOf } from \"../../panels/design/block-look-rows\";\nimport { radioGroupStep } from \"../../roving-radios\";\nimport { PanelSections } from \"../panel-section\";\nimport { sectionEntries, type SettingEntry } from \"../settings-index\";\n\nimport {\n  boundLooksOf,\n  lookChoice,\n  lookTiles,\n  lookStageStyle,\n  lookTileStyle,\n  looksOfType,\n  wornLook,\n  type LookTile,\n} from \"./look-tiles\";\n\nexport interface LookTilesProps {\n  readonly editor: EditorState;\n  readonly library: readonly NamedClass[] | undefined;\n  /** Why the block's design is held, when it is: the tiles are held too. */\n  readonly held: string | undefined;\n  readonly tokens: SiteTokenSet | undefined;\n  /** The mode the selected block is drawn in, which each tile draws in. */\n  readonly mode: TokenMode;\n  /** Says why a chosen look was not applied, through the shell's notices. */\n  readonly onRefused: (reason: string) => void;\n  /**\n   * Opens the Design panel's Block styles at a block type. Absent, the line\n   * under the tiles says what a block style is and offers no way there.\n   */\n  readonly onEditBlockStyles?: ((blockType: string) => void) | undefined;\n}\n\n/** The section's name, which its fold is remembered by. */\nconst BLOCK_STYLE_SECTION = \"Block style\";\n\n/**\n * What a specimen is drawn as, by the kind of block it stands for: a mark\n * (a Button's label, \"Aa\" for any other block), or a sample of the block\n * itself (an Image's picture, a Quote's words, a Section's band).\n */\ntype SpecimenKind = \"button\" | \"text\" | SampleKind;\ntype SampleKind = \"image\" | \"quote\" | \"band\";\n\nfunction specimenKind(blockType: string): SpecimenKind {\n  if (blockType === \"core/button\") return \"button\";\n  if (blockType === \"core/image\") return \"image\";\n  if (blockType === \"core/quote\") return \"quote\";\n  if (blockType === \"core/section\") return \"band\";\n  return \"text\";\n}\n\n/** Whether a kind is drawn as a sample of the block rather than a mark. */\nfunction isSample(kind: SpecimenKind): kind is SampleKind {\n  return kind === \"image\" || kind === \"quote\" || kind === \"band\";\n}\n\n/** The words a mark carries. */\nconst MARK_WORDS = { button: \"Button\", text: \"Aa\" };\n\n/**\n * What a sample draws of the block it stands for, where one is selected: the\n * picture the canvas shows for it, and its words. Absent (a Design row, or a\n * block with neither), the sample draws its type's own example.\n */\nexport interface BlockSample {\n  readonly picture?: string | undefined;\n  readonly words?: string | undefined;\n}\n\n/**\n * What the canvas draws of the selected block, as the Style tab hands it to\n * the tiles: the picture it shows and the quotation it shows, each read from\n * the canvas, so a library file, a typed address and a bound value are all\n * the one on the page. Empty where no canvas is read.\n */\nexport const RenderedSample: React.Context<BlockSample> =\n  React.createContext<BlockSample>({});\n\n/**\n * One look drawn as a small block of its type: the look's styles laid over the\n * type's base as the site draws it, so a tile and a Design row show what the\n * canvas shows.\n */\nexport function LookSpecimen({\n  blockType,\n  base,\n  styles,\n  tokens,\n  mode,\n  sample,\n}: {\n  readonly blockType: string;\n  readonly base: NodeStyles | undefined;\n  readonly styles: NodeStyles | undefined;\n  readonly tokens: SiteTokenSet | undefined;\n  readonly mode: TokenMode;\n  readonly sample?: BlockSample | undefined;\n}): React.JSX.Element {\n  const kind = specimenKind(blockType);\n  return (\n    <span\n      className=\"nx-look-tile__stage\"\n      aria-hidden=\"true\"\n      style={lookStageStyle(tokens, mode)}\n    >\n      {isSample(kind) ? (\n        <Sample\n          kind={kind}\n          blockType={blockType}\n          style={lookTileStyle(base, styles, tokens, mode, \"sample\")}\n          sample={sample}\n        />\n      ) : (\n        <span\n          className=\"nx-look-tile__specimen\"\n          data-kind={kind}\n          style={lookTileStyle(base, styles, tokens, mode)}\n        >\n          {MARK_WORDS[kind]}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/**\n * A sample of the block: drawn at the page's own sizes, in a frame standing\n * for the page's screen that scales it down whole (`styles/inspector.css`),\n * with the style laid on the block's box.\n */\nfunction Sample({\n  kind,\n  blockType,\n  style,\n  sample,\n}: {\n  readonly kind: SampleKind;\n  readonly blockType: string;\n  readonly style: Record<string, string>;\n  readonly sample: BlockSample | undefined;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-look-tile__frame\" data-kind={kind}>\n      <span className=\"nx-look-tile__specimen\" data-kind={kind} style={style}>\n        {kind === \"image\" ? (\n          // The fit is the picture's own property, as the page routes it to\n          // the picture: it is not inherited from the box that holds it.\n          <SamplePicture picture={sample?.picture} fit={style.objectFit} />\n        ) : kind === \"quote\" ? (\n          (sample?.words ?? exampleWords(blockType))\n        ) : (\n          <BandLines />\n        )}\n      </span>\n    </span>\n  );\n}\n\n/**\n * An Image's picture in its box, fitted as the style fits it and cropped to\n * the box where the style says nothing; with no picture, a picture's outline.\n */\nfunction SamplePicture({\n  picture,\n  fit,\n}: {\n  readonly picture: string | undefined;\n  readonly fit: string | undefined;\n}): React.JSX.Element {\n  if (picture === undefined) {\n    return (\n      <span className=\"nx-look-tile__placeholder\">\n        <ImageIcon size={28} strokeWidth={1.5} />\n      </span>\n    );\n  }\n  return (\n    <img\n      className=\"nx-look-tile__picture\"\n      src={picture}\n      alt=\"\"\n      draggable={false}\n      style={{\n        objectFit: (fit ?? \"cover\") as React.CSSProperties[\"objectFit\"],\n      }}\n    />\n  );\n}\n\n/**\n * What a Section's band holds: a heading and two lines of text as bars, which\n * stand in for its content and follow its alignment as words would.\n */\nfunction BandLines(): React.JSX.Element {\n  return (\n    <>\n      <span className=\"nx-look-tile__row\">\n        <span className=\"nx-look-tile__line\" data-line=\"heading\" />\n      </span>\n      <span className=\"nx-look-tile__row\">\n        <span className=\"nx-look-tile__line\" data-line=\"text\" />\n      </span>\n      <span className=\"nx-look-tile__row\">\n        <span className=\"nx-look-tile__line\" data-line=\"short\" />\n      </span>\n    </>\n  );\n}\n\n/** The words a block type's own example carries, for a sample of none. */\nfunction exampleWords(blockType: string): string {\n  const props = getBlock(blockType)?.example?.props;\n  const text = props !== undefined && \"text\" in props ? props.text : undefined;\n  return typeof text === \"string\" ? text : \"\";\n}\n\n/**\n * What the tiles draw of the selected block: the picture and the words the\n * canvas shows for it, and where the canvas shows no words (none read, as in\n * a panel with no canvas), its own stored words.\n */\nfunction sampleOfNode(\n  props: Readonly<Record<string, unknown>>,\n  rendered: BlockSample\n): BlockSample {\n  const stored = typeof props.text === \"string\" ? props.text : \"\";\n  const words = (rendered.words ?? stored).trim();\n  return {\n    picture: rendered.picture,\n    ...(words === \"\" ? {} : { words }),\n  };\n}\n\n/** The block's own look's name, as its definition names it. */\nfunction ownLookName(blockType: string): string | undefined {\n  const own = getBlock(blockType)?.editor?.variations?.find(\n    each => each.isDefault === true\n  );\n  return own === undefined ? undefined : variationLabel(own);\n}\n\n/** The node's classes after choosing a tile, as the op that stores them. */\nfunction lookOp(nodeId: string, next: readonly string[]) {\n  return next.length > 0\n    ? { kind: \"update\" as const, id: nodeId, patch: { classes: [...next] } }\n    : {\n        kind: \"update\" as const,\n        id: nodeId,\n        patch: {},\n        unset: [\"classes\" as const],\n      };\n}\n\n/**\n * The selected block, the block style it wears and the tiles its type offers,\n * or nothing where no Block style section is drawn: no block, no library yet,\n * or a type without block styles. One reading for the section and for the\n * Style tab, which tells the sections under the bar that one came first.\n */\nexport function blockStyleTilesOf(\n  editor: EditorState,\n  library: readonly NamedClass[] | undefined\n):\n  | {\n      readonly node: NonNullable<ReturnType<typeof findNode>>;\n      readonly worn: string | null;\n      readonly tiles: readonly LookTile[];\n    }\n  | undefined {\n  const nodeId = editor.selectedId;\n  const node =\n    nodeId === null ? undefined : findNode(editor.document.nodes, nodeId);\n  if (node === undefined || library === undefined) return undefined;\n  const worn = wornLook(node.classes, looksOfType(library, node.type));\n  const tiles = lookTiles(library, node.type, ownLookName(node.type), worn);\n  return tiles.length === 0 ? undefined : { node, worn, tiles };\n}\n\n/** The section's key in the Style tab, which the panel's filter keeps it by. */\nconst BLOCK_STYLE_KEY = \"block-style\";\n\n/**\n * The Block style section as \"Find a setting\" and \"Only changed\" read it:\n * one setting, found by its name and by each style's, and changed while the\n * block wears a style other than its own. None where the section isn't drawn.\n */\nexport function blockStyleEntries(\n  editor: EditorState,\n  library: readonly NamedClass[] | undefined\n): SettingEntry[] {\n  const offered = blockStyleTilesOf(editor, library);\n  if (offered === undefined) return [];\n  return sectionEntries(\n    \"style\",\n    { key: BLOCK_STYLE_KEY, label: BLOCK_STYLE_SECTION },\n    [\n      {\n        id: \"blockStyle\",\n        label: BLOCK_STYLE_SECTION,\n        options: offered.tiles.map(tile => tile.name),\n        set: offered.worn !== null,\n      },\n    ]\n  );\n}\n\nexport function LookTiles({\n  editor,\n  library,\n  held,\n  tokens,\n  mode,\n  onRefused,\n  onEditBlockStyles,\n}: LookTilesProps): React.JSX.Element | null {\n  // What the canvas draws of the selected block: an Image's tiles draw its\n  // picture in each shape, a Quote's its words in each style.\n  const rendered = React.useContext(RenderedSample);\n  const offered = blockStyleTilesOf(editor, library);\n  if (offered === undefined || library === undefined) return null;\n  const { node, worn, tiles } = offered;\n  // Every look of the type comes off when another is chosen, those the\n  // library no longer offers included, so none is left to return later.\n  const removable = boundLooksOf(library, node.type);\n  const choose = (tile: LookTile): void => {\n    if (held !== undefined) return;\n    const choice = lookChoice(node.classes, removable, tile.id);\n    if (choice.kind === \"unchanged\") return;\n    // A refused choice leaves the radio where it was: said, so the click does\n    // not read as ignored, in the panel's words for what a block wears.\n    if (choice.kind === \"full\") {\n      onRefused(\n        `${tile.name} could not be applied to this block: it already wears as many styles as a block can.`\n      );\n      return;\n    }\n    if (editor.applyAll([lookOp(node.id, choice.classes)]) === null) {\n      onRefused(\n        `${tile.name} could not be applied to this block: the page could not take the change.`\n      );\n    }\n  };\n  return (\n    // A panel section as every other in the tab, so it folds and is\n    // remembered as they are, and opens first as the tab's first section.\n    // Its own list of one: the editing bar sits between it and the rest.\n    <div className=\"nx-block-style\">\n      <PanelSections\n        tab=\"style\"\n        sections={[\n          {\n            key: BLOCK_STYLE_KEY,\n            label: BLOCK_STYLE_SECTION,\n            // A style other than the block's own is a choice the block holds.\n            holdsValue: worn !== null,\n            body: (\n              <div\n                className=\"nx-look-tiles\"\n                data-held={held === undefined ? undefined : \"\"}\n              >\n                <TileGrid\n                  tiles={tiles}\n                  worn={worn}\n                  held={held}\n                  blockType={node.type}\n                  base={siteBaseOf(library, node.type)}\n                  sample={sampleOfNode(node.props, rendered)}\n                  tokens={tokens}\n                  mode={mode}\n                  onChoose={choose}\n                />\n                {held === undefined ? null : (\n                  <p className=\"nx-look-tiles__held\">{held}</p>\n                )}\n                <BlockStyleLine\n                  blockType={node.type}\n                  onEditBlockStyles={onEditBlockStyles}\n                />\n              </div>\n            ),\n          },\n        ]}\n      />\n    </div>\n  );\n}\n\n/**\n * The tiles as one radio group, named by the section: one Tab stop, the\n * arrows moving the choice, and focus following it.\n */\nfunction TileGrid({\n  tiles,\n  worn,\n  held,\n  blockType,\n  base,\n  sample,\n  tokens,\n  mode,\n  onChoose,\n}: {\n  readonly tiles: readonly LookTile[];\n  readonly worn: string | null;\n  readonly held: string | undefined;\n  readonly blockType: string;\n  /** The base as the site draws it, its edits to the own look included. */\n  readonly base: NodeStyles | undefined;\n  /** What every tile draws of the selected block itself. */\n  readonly sample: BlockSample;\n  readonly tokens: SiteTokenSet | undefined;\n  readonly mode: TokenMode;\n  readonly onChoose: (tile: LookTile) => void;\n}): React.JSX.Element {\n  return (\n    <div\n      role=\"radiogroup\"\n      aria-label={BLOCK_STYLE_SECTION}\n      aria-disabled={held === undefined ? undefined : true}\n      className=\"nx-look-tiles__grid\"\n      data-count={tiles.length}\n      onKeyDown={event => {\n        const step = radioGroupStep(event.key);\n        if (step === null) return;\n        event.preventDefault();\n        const at = tiles.findIndex(tile => tile.id === worn);\n        const next = tiles[(at + step + tiles.length) % tiles.length];\n        if (next === undefined) return;\n        onChoose(next);\n        // Focus follows the choice, as a radio group's does.\n        const group = event.currentTarget;\n        requestAnimationFrame(() => {\n          group\n            .querySelector<HTMLElement>('[role=\"radio\"][aria-checked=\"true\"]')\n            ?.focus();\n        });\n      }}\n    >\n      {tiles.map(tile => {\n        const checked = tile.id === worn;\n        return (\n          <button\n            key={tile.id ?? \"own\"}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={checked}\n            tabIndex={checked ? 0 : -1}\n            className=\"nx-look-tile\"\n            title={held}\n            onClick={() => onChoose(tile)}\n          >\n            {/* The choice said without colour as well as with the ring:\n                aria-checked for a reader, a mark for the eye. */}\n            {checked ? (\n              <span className=\"nx-look-tile__check\" aria-hidden=\"true\">\n                <Check size={10} strokeWidth={3} />\n              </span>\n            ) : null}\n            <LookSpecimen\n              blockType={blockType}\n              base={base}\n              styles={tile.styles}\n              tokens={tokens}\n              mode={mode}\n              sample={sample}\n            />\n            <TileName tile={tile} />\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\n/** A tile's name, with \"Default\" on the block's own style and \"Hidden\" on one no longer offered. */\nfunction TileName({ tile }: { readonly tile: LookTile }): React.JSX.Element {\n  return (\n    <span className=\"nx-look-tile__name\">\n      {tile.name}\n      {tile.id === null && tile.name !== \"Default\" ? (\n        <span className=\"nx-look-tile__tag\">Default</span>\n      ) : null}\n      {/* Worn, and no longer offered to other blocks. */}\n      {tile.hidden ? <span className=\"nx-look-tile__tag\">Hidden</span> : null}\n    </span>\n  );\n}\n\n/**\n * The line under the tiles: what a block style is, by the block's own name\n * (\"A saved style for every Section.\"), and the way to the Design panel's\n * Block styles at this type, where its styles are added, renamed and removed.\n */\nfunction BlockStyleLine({\n  blockType,\n  onEditBlockStyles,\n}: {\n  readonly blockType: string;\n  readonly onEditBlockStyles: ((blockType: string) => void) | undefined;\n}): React.JSX.Element {\n  const label = getBlock(blockType)?.editor?.label ?? \"block\";\n  return (\n    <p className=\"nx-block-style__line\">\n      {`A saved style for every ${label}.`}\n      {onEditBlockStyles === undefined ? null : (\n        <>\n          {\" \"}\n          <button\n            type=\"button\"\n            className=\"nx-block-style__edit\"\n            onClick={() => onEditBlockStyles(blockType)}\n          >\n            Edit block styles\n            {/* It opens another panel: the arrow says so, and is not read. */}\n            <ArrowUpRight aria-hidden=\"true\" size={12} />\n          </button>\n        </>\n      )}\n    </p>\n  );\n}\n","/**\n * The value a style control shows while nothing is set here.\n *\n * @module inherited-value\n */\nimport * as React from \"react\";\n\n/**\n * The value reaching a style control from another tier, as it was written\n * there, or `undefined` when nothing does or a value is set here.\n *\n * Carried by context rather than as a prop because every control draws its\n * own empty state, the list, the icon group, the swatch and the font picker\n * among them, and a prop would thread through each for the one line that\n * draws the hint.\n */\nexport const InheritedValue: React.Context<string | undefined> =\n  React.createContext<string | undefined>(undefined);\n\n/**\n * What an unset control says: the inherited value where one reaches it, so\n * the field shows what the canvas draws, and otherwise the control's own hint.\n * Shown as a placeholder, greyed, so it never reads as set here.\n */\nexport function useUnsetHint(fallback: string): string {\n  return React.useContext(InheritedValue) ?? fallback;\n}\n","/**\n * What the site can actually render, and what it only claims to.\n *\n * The tokens studio already authors `fontFamily` tokens, and this module does\n * not author anything: a second editor for one question is the defect this\n * codebase names most often. What the studio cannot answer is whether a family\n * it just stored will RENDER, because it edits one token and knows nothing\n * about the faces the site loads.\n *\n * Nothing joins those two today. `compileSiteSheet` calls `emitFontFaces` and\n * `emitTokenBlocks` independently, so a token naming a family with no face is\n * emitted exactly like one that has it, and the page quietly draws in whatever\n * the browser reaches for next. That is the failure the sheet's own\n * `tokenPrefix` note describes for custom properties — \"nothing errors: the\n * reference resolves to nothing and the value silently does not apply\" — and it\n * is the same shape one property along.\n *\n * @module font-library\n */\nimport {\n  cssString,\n  emitTokenBlocks,\n  readFamilyList,\n  validateFontFace,\n  type FamilyListKind,\n  type FontFaceDef,\n  type ReadFamilyPart,\n  type SiteToken,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * Where a family's glyphs would come from.\n *\n * `not-provided` is deliberately not called \"missing\" or \"unavailable\". A named\n * family this site loads no face for may still be installed on the reader's\n * device — `Georgia` and `Helvetica` are the ordinary cases — so declaring it\n * absent would be a claim about a machine this code cannot see. What IS true is\n * that the site does not provide it, and that is what the word says.\n *\n * `dynamic` is a `var()` whose value only exists at render. Reporting it as\n * provided or not would be a guess either way, and the guess that reads worst\n * is the confident one: a host wiring a font through a custom property, which\n * is how `next/font` exposes one, would be told their token is broken.\n */\nexport type FamilySource = \"hosted\" | \"generic\" | \"dynamic\" | \"not-provided\";\n\n/** One family from a stack, and where it would come from. */\nexport interface FamilyReading {\n  /** The family name, with quotes removed and escapes resolved. */\n  readonly family: string;\n  readonly source: FamilySource;\n}\n\n/** A whole `font-family` value, read against the faces the site loads. */\nexport interface StackReading {\n  /**\n   * How CSS reads the value, from the engine's own classification.\n   *\n   * Four states rather than usable/unusable, because the browser has four\n   * answers and collapsing them misdescribes two: a `var()` stack is read\n   * perfectly and cannot be resolved here, and a lone `inherit` is valid while\n   * naming no family at all.\n   */\n  readonly kind: FamilyListKind;\n  /** Each family in the author's order. Empty unless `kind` names families. */\n  readonly families: readonly FamilyReading[];\n  /**\n   * The author's FIRST choice, which is the one they were expressing.\n   *\n   * Separated from the rest because a stack is a fallback chain and every entry\n   * after the first is a concession. An author who wrote `Brand, serif` chose\n   * `Brand`; reporting the stack as fine because `serif` resolves would answer\n   * a question they did not ask.\n   */\n  readonly firstChoice: FamilyReading | undefined;\n  /**\n   * Whether a family AFTER the first exists to fall back to.\n   *\n   * What separates \"readers see the next family in the list\" from \"readers see\n   * the browser's default\", which are different sentences and only one of them\n   * is true of a single-family stack.\n   */\n  readonly hasFallback: boolean;\n  /**\n   * Whether the site guarantees SOMETHING renders.\n   *\n   * True when any family is generic or hosted. A stack of named families alone\n   * can still render — every one may be installed — so this is a floor, not a\n   * prediction.\n   */\n  readonly guaranteed: boolean;\n}\n\n/**\n * The faces the compiler will actually EMIT.\n *\n * `emitFontFaces` drops a face whose `src` is empty, remote, or carries an\n * unusable descriptor, while the stored tier deliberately keeps those\n * shaped-but-invalid faces so their issues can be reported. Anything reading\n * \"what does this site load\" has to ask this rather than the raw list —\n * counting a refused face marks a token healthy against a `@font-face` the site\n * sheet does not contain, and listing one tells an author a file loads when it\n * does not.\n *\n * One filter for the family list and the token analysis, so the two cannot\n * disagree about which faces exist.\n */\nfunction emittableFaces(faces: readonly FontFaceDef[]): readonly FontFaceDef[] {\n  return faces.filter(face => validateFontFace(face, \"fonts\").length === 0);\n}\n\n/**\n * The families those faces provide, lowercased for comparison.\n *\n * NOT trimmed, because the emitter does not trim either: `emitFontFaces`\n * writes `font-family:\"${cssString(face.family)}\"`, so a face called\n * `\" Brand \"` declares a family whose name carries those spaces and only a\n * token quoting them verbatim selects it. Trimming one side and not the other\n * made the two representations disagree, and a face the browser matches was\n * reported as one the site never loads.\n */\nfunction hostedFamilies(faces: readonly FontFaceDef[]): ReadonlySet<string> {\n  return new Set(emittableFaces(faces).map(face => face.family.toLowerCase()));\n}\n\nfunction sourceOf(\n  entry: ReadFamilyPart,\n  hosted: ReadonlySet<string>\n): FamilySource {\n  if (entry.kind === \"dynamic\") return \"dynamic\";\n  // Generic BEFORE hosted, which is the opposite of what it seems it should be.\n  // The engine emits every face family quoted — `font-family:\"serif\"` — and an\n  // unquoted `serif` in a stack is the CSS keyword, which no `@font-face` can\n  // claim. So a site loading a face it called `serif` still gets the browser\n  // default from a bare `serif`, and only a quoted value reaches its file.\n  if (entry.kind === \"generic\") return \"generic\";\n  // NOT trimmed, and neither is the set this is looked up in — the two must\n  // normalise identically or they answer about different families. The reader\n  // already removed the separation around an unquoted name and kept a quoted\n  // one verbatim, so trimming here would undo that and match `\" Brand \"`\n  // against a face called `Brand`.\n  const key = entry.part.name.toLowerCase();\n  return hosted.has(key) ? \"hosted\" : \"not-provided\";\n}\n\n/**\n * Read one `font-family` value against the faces this site loads.\n *\n * The split and the classification are the engine's, asked through one call.\n * A family list is quoting, comma, escape and identifier rules together —\n * `\"ACME, Inc\", serif` is two families rather than three, and `Brand,` is a\n * parse error the browser drops the declaration for. A second reading of that\n * grammar here would agree on the easy values and diverge on the ones a site's\n * real font name produces.\n */\nexport function readStack(\n  value: string,\n  faces: readonly FontFaceDef[]\n): StackReading {\n  const reading = readFamilyList(value);\n  if (reading.kind !== \"families\" && reading.kind !== \"dynamic\") {\n    return {\n      kind: reading.kind,\n      families: [],\n      firstChoice: undefined,\n      hasFallback: false,\n      guaranteed: false,\n    };\n  }\n  const hosted = hostedFamilies(faces);\n  const families = reading.parts.map(entry => ({\n    family: entry.part.name,\n    source: sourceOf(entry, hosted),\n  }));\n  return {\n    kind: reading.kind,\n    families,\n    firstChoice: families[0],\n    hasFallback: families.length > 1,\n    guaranteed: families.some(f => f.source !== \"not-provided\"),\n  };\n}\n\n/** Which value of a token is being read. */\nexport type TokenMode = \"light\" | \"dark\";\n\n/** A `fontFamily` token, read against the faces the site loads. */\nexport interface FontTokenRow {\n  readonly token: SiteToken;\n  /** The light value's reading. Always present: `values.light` is required. */\n  readonly reading: StackReading;\n  /**\n   * The dark value's reading, when the token defines one.\n   *\n   * Read because the emitter applies it: a token whose light stack is hosted\n   * and whose dark stack is not would otherwise report an all-clear while every\n   * dark-mode reader gets a substitution. Absent when the token states no dark\n   * value, which is not the same as stating the same value twice.\n   */\n  readonly darkReading: StackReading | undefined;\n}\n\n/**\n * Every `fontFamily` token in the set, with what each would render as.\n *\n * Only `fontFamily` tokens: a `dimension` holding a font SIZE is typography and\n * is not a typeface, and including it would put rows in this panel that its\n * question does not apply to.\n */\nexport function fontTokenRows(\n  tokens: SiteTokenSet | undefined,\n  faces: readonly FontFaceDef[]\n): FontTokenRow[] {\n  /*\n   * The tokens the compiler WRITES, not every token in the set.\n   *\n   * `emitTokenBlocks` refuses a token on five separate grounds — a name that is\n   * not a token name, no light value, a value its guard rejects, a value that\n   * fetches, and two identities landing on one custom property — and a refused\n   * token reaches no page. Reporting on it would describe a typeface the site\n   * never emits, and say its hosted family renders when nothing references it.\n   *\n   * Asked of the emitter rather than re-derived here: five conditions restated\n   * in a second place agree today and drift the first time one changes. The\n   * selector is the one the sheet uses, so the answer is the sheet's own.\n   */\n  if (tokens === undefined) return [];\n  const emitted = emitTokenBlocks(tokens, \":root\").emitted;\n  return emitted\n    .filter(token => token.kind === \"fontFamily\")\n    .map(token => ({\n      token,\n      reading: readStack(token.values.light, faces),\n      darkReading:\n        token.values.dark === undefined\n          ? undefined\n          : readStack(token.values.dark, faces),\n    }));\n}\n\n/** One thing worth saying about one mode of one token. */\nexport interface TokenNote {\n  readonly mode: TokenMode;\n  readonly text: string;\n}\n\n/** Whether a single reading is one an author should look at. */\nfunction needsAttention(reading: StackReading): boolean {\n  if (reading.kind === \"invalid\") return true;\n  // A lone CSS-wide keyword is a deliberate, working value — `inherit` takes\n  // the parent's font — so it names no typeface and needs no comment.\n  if (reading.kind === \"keyword\") return false;\n  return reading.firstChoice?.source === \"not-provided\";\n}\n\n/** What to say about one reading, or nothing when it is working as written. */\nfunction noteFor(reading: StackReading, value: string): string | undefined {\n  if (reading.kind === \"invalid\") {\n    return `\"${value}\" is not a font-family value a browser will read, so this variable applies nothing.`;\n  }\n  if (reading.kind === \"keyword\") return undefined;\n  const first = reading.firstChoice;\n  if (first?.source !== \"not-provided\") return undefined;\n  // Branching on whether a later family EXISTS. Telling an author of a\n  // single-family stack that readers \"see the next family in the list\" names an\n  // entry that is not there, and points them at a fallback they never wrote.\n  const consequence = reading.hasFallback\n    ? \"Readers without it installed see the next font in the list instead.\"\n    : \"Readers without it installed see the browser\\u2019s default font instead.\";\n  return `${first.family} is the font this variable asks for first, and this site has no file for it. ${consequence}`;\n}\n\n/**\n * Everything worth saying about one token, one entry per affected mode.\n *\n * A list rather than a string because a token can be sound in light and not in\n * dark, and one sentence for both would have to name a mode it did not check.\n */\nexport function tokenNotes(row: FontTokenRow): readonly TokenNote[] {\n  const notes: TokenNote[] = [];\n  const light = noteFor(row.reading, row.token.values.light);\n  if (light !== undefined) notes.push({ mode: \"light\", text: light });\n  const dark = row.token.values.dark;\n  if (row.darkReading !== undefined && dark !== undefined) {\n    const darkNote = noteFor(row.darkReading, dark);\n    if (darkNote !== undefined) notes.push({ mode: \"dark\", text: darkNote });\n  }\n  return notes;\n}\n\n/**\n * The rows worth an author's attention, in EITHER mode.\n *\n * A row is drawn to attention when a mode's value cannot be read at all, or\n * when its FIRST family is one this site does not provide — that is the choice\n * the author expressed, and the one that silently does not happen.\n */\nexport function rowsNeedingAttention(\n  rows: readonly FontTokenRow[]\n): FontTokenRow[] {\n  return rows.filter(\n    row =>\n      needsAttention(row.reading) ||\n      (row.darkReading !== undefined && needsAttention(row.darkReading))\n  );\n}\n\n/** Where a family on the site came from, in the editor's terms. */\nexport type FamilyOrigin = \"google\" | \"upload\" | \"code\";\n\n/** One family the site loads, as the Fonts tab lists it. */\nexport interface SiteFamily {\n  /** The family lower-cased, as CSS matches it. */\n  readonly key: string;\n  /** The family as first written. */\n  readonly family: string;\n  readonly faces: readonly FontFaceDef[];\n  /**\n   * `code` when any face comes from the site's configuration, which the\n   * editor cannot change; otherwise where the stored faces say they came from.\n   */\n  readonly origin: FamilyOrigin;\n  /** Whether Remove is offered: when the site stored any of the faces. */\n  readonly removable: boolean;\n  /** The styles in a few characters: `3 styles`, or a variable `100–900`. */\n  readonly styles: string;\n  /** The licence in words, when the faces name one. */\n  readonly licence?: string;\n  /** The catalogue's category, when the faces name one. */\n  readonly category?: string;\n}\n\n/** The licences the catalogue uses, in the words their authors use. */\nconst LICENCE_NAMES: Readonly<Record<string, string>> = {\n  \"OFL-1.1\": \"SIL Open Font License\",\n  \"Apache-2.0\": \"Apache License 2.0\",\n  \"UFL-1.0\": \"Ubuntu Font Licence\",\n};\n\n/** A licence in words; an unknown one as the catalogue wrote it. */\nexport function licenceName(id: string | undefined): string | undefined {\n  if (id === undefined) return undefined;\n  return LICENCE_NAMES[id] ?? id;\n}\n\n/** What a face is for comparing two lists of faces: what it declares and loads. */\nfunction faceIdentity(face: FontFaceDef): string {\n  return [\n    face.family,\n    face.weight ?? \"\",\n    face.style ?? \"\",\n    face.unicodeRange ?? \"\",\n    face.src.map(source => source.url).join(\"|\"),\n  ].join(\"::\");\n}\n\n/** Whether a face's style slants: anything but `normal`. */\nfunction slanted(style: string | undefined): boolean {\n  const value = style?.trim().toLowerCase() ?? \"\";\n  return value !== \"\" && value !== \"normal\";\n}\n\n/** A weight descriptor's numbers: one, or the two ends of a range. */\nfunction weightNumbers(weight: string | undefined): number[] {\n  return (weight ?? \"400\")\n    .trim()\n    .split(/\\s+/)\n    .map(part =>\n      part === \"normal\" ? 400 : part === \"bold\" ? 700 : Number(part)\n    )\n    .filter(Number.isFinite);\n}\n\n/** A row's styles in a few characters: a variable range, else a count. */\nfunction styleSummary(faces: readonly FontFaceDef[]): string {\n  const range = faces\n    .map(face => weightNumbers(face.weight))\n    .find(numbers => numbers.length === 2);\n  if (range !== undefined) {\n    return `${String(range[0])}\\u2013${String(range[1])}`;\n  }\n  return styleCount(faces);\n}\n\n/** How many cuts the faces draw: `1 style`, `3 styles`. */\nfunction styleCount(faces: readonly FontFaceDef[]): string {\n  const cuts = new Set(faces.map(face => cutName(face.weight, face.style)));\n  return cuts.size === 1 ? \"1 style\" : `${String(cuts.size)} styles`;\n}\n\n/**\n * The families the site loads, grouped as CSS matches them (case-insensitive,\n * the first spelling kept), in the order the faces are listed.\n *\n * @param faces - Every face the page emits, from code and stored\n * @param fromCode - The faces the site's configuration supplies\n */\nexport function siteFamilies(\n  faces: readonly FontFaceDef[],\n  fromCode: readonly FontFaceDef[]\n): SiteFamily[] {\n  const coded = new Set(fromCode.map(faceIdentity));\n  const groups = new Map<string, FontFaceDef[]>();\n  const spelled = new Map<string, string>();\n  for (const face of emittableFaces(faces)) {\n    const key = face.family.toLowerCase();\n    if (!spelled.has(key)) spelled.set(key, face.family);\n    groups.set(key, [...(groups.get(key) ?? []), face]);\n  }\n  return [...groups].map(([key, members]) => {\n    const fromConfig = members.some(face => coded.has(faceIdentity(face)));\n    const source = members.find(face => face.source !== undefined)?.source;\n    const licence = licenceName(source?.licence);\n    return {\n      key,\n      family: spelled.get(key) ?? key,\n      faces: members,\n      origin: fromConfig ? \"code\" : (source?.kind ?? \"upload\"),\n      // Remove takes only the stored faces, so a family the site's code also\n      // supplies can still lose the cuts added beside it.\n      removable: members.some(face => !coded.has(faceIdentity(face))),\n      styles: styleSummary(members),\n      ...(licence === undefined ? {} : { licence }),\n      ...(source?.category === undefined ? {} : { category: source.category }),\n    };\n  });\n}\n\n/** The words a type foundry uses for each weight. */\nconst WEIGHT_NAMES: Readonly<Record<number, string>> = {\n  100: \"Thin\",\n  200: \"Extra light\",\n  300: \"Light\",\n  400: \"Regular\",\n  500: \"Medium\",\n  600: \"Semi bold\",\n  700: \"Bold\",\n  800: \"Extra bold\",\n  900: \"Black\",\n};\n\n/** The weights a font is named at, lightest first: 100 to 900. */\nexport const NAMED_WEIGHTS: readonly number[] = Object.keys(WEIGHT_NAMES)\n  .map(Number)\n  .sort((a, b) => a - b);\n\n/**\n * The named weights some face draws: each face's own weight, and every named\n * weight inside a variable face's range. Only the faces the stylesheet emits\n * count, the ones the Font picker lists, so a face kept only so its issue can\n * be said draws no weight.\n */\nexport function weightsDrawn(faces: readonly FontFaceDef[]): Set<number> {\n  const drawn = new Set<number>();\n  for (const face of emittableFaces(faces)) {\n    const [low, high = low] = weightNumbers(face.weight);\n    if (low === undefined) continue;\n    for (const weight of NAMED_WEIGHTS) {\n      if (weight >= low && weight <= high) drawn.add(weight);\n    }\n  }\n  return drawn;\n}\n\n/** A weight in words with its number: `Bold 700`. */\nexport function weightName(weight: number): string {\n  const name = WEIGHT_NAMES[weight];\n  return name === undefined ? String(weight) : `${name} ${String(weight)}`;\n}\n\n/**\n * Which cut of a family a face is: `Regular 400`, `Bold Italic 700`, or\n * `Variable 100–900` for a face covering a range.\n */\nexport function cutName(weight?: string, style?: string): string {\n  const numbers = weightNumbers(weight);\n  const italic = slanted(style);\n  if (numbers.length === 2) {\n    const range = `${String(numbers[0])}\\u2013${String(numbers[1])}`;\n    return italic ? `Variable Italic ${range}` : `Variable ${range}`;\n  }\n  const value = numbers[0];\n  if (weight === undefined || value === undefined) {\n    return italic ? \"Italic\" : \"Regular\";\n  }\n  if (!italic) return weightName(value);\n  const name = WEIGHT_NAMES[value];\n  // \"Italic 400\" rather than \"Regular Italic 400\", as foundries say it.\n  if (value === 400 || name === undefined) return `Italic ${String(value)}`;\n  return `${name} Italic ${String(value)}`;\n}\n\n/** Where a family came from, in words. */\nfunction originWords(origin: FamilyOrigin): string {\n  if (origin === \"google\") return \"from Google Fonts\";\n  if (origin === \"upload\") return \"uploaded\";\n  return \"set in your site\\u2019s code\";\n}\n\n/** A family in words, for its row's accessible name. */\nexport function familyDescription(family: SiteFamily): string {\n  const cuts = [\n    ...new Set(family.faces.map(face => cutName(face.weight, face.style))),\n  ];\n  return `${family.family}, ${styleCount(family.faces)}: ${cuts.join(\", \")}, ${originWords(family.origin)}`;\n}\n\n/** The stored faces without one family's, matched as CSS matches a family. */\nexport function withoutFamily(\n  faces: readonly FontFaceDef[],\n  key: string\n): FontFaceDef[] {\n  return faces.filter(face => face.family.toLowerCase() !== key);\n}\n\n/** The generic family each catalogue category falls back to. */\nconst GENERIC_FOR: Readonly<Record<string, string>> = {\n  \"sans-serif\": \"sans-serif\",\n  serif: \"serif\",\n  monospace: \"monospace\",\n  handwriting: \"cursive\",\n};\n\n/**\n * What picking a family stores: its name quoted, then the generic family its\n * category falls back to, so a reader still gets a sensible face while the\n * file loads or if it never does.\n */\nexport function familyStack(family: string, category?: string): string {\n  const generic =\n    category === undefined\n      ? \"system-ui\"\n      : (GENERIC_FOR[category] ?? \"system-ui\");\n  return `\"${cssString(family)}\", ${generic}`;\n}\n\n/**\n * The generic family a site-wide font falls back to: the one of its kind,\n * serif, monospace, or sans-serif for every other kind (display and\n * handwriting faces too), so body text never falls back to a script face.\n */\nfunction roleGeneric(category: string | undefined): string {\n  return category === \"serif\" || category === \"monospace\"\n    ? category\n    : \"sans-serif\";\n}\n\n/**\n * What picking a family for the site's Body or Headings font stores: its name\n * quoted, then the generic family of its kind ({@link roleGeneric}).\n */\nexport function roleStack(family: string, category?: string): string {\n  return `\"${cssString(family)}\", ${roleGeneric(category)}`;\n}\n\n/**\n * Whether the faces draw an upright bold: some upright face at weight 600 or\n * heavier, which a browser picks for a bold heading rather than thickening a\n * lighter one. An italic bold leaves upright headings thickened.\n */\nexport function drawsBold(faces: readonly FontFaceDef[]): boolean {\n  return emittableFaces(faces).some(face => {\n    if (slanted(face.style)) return false;\n    // A variable face's heavier end, which may fall between named weights.\n    const [low, high = low] = weightNumbers(face.weight);\n    return high !== undefined && high >= 600;\n  });\n}\n\n/** The specimen, one sentence with ascenders, descenders and round forms. */\nexport const SPECIMEN: string =\n  \"Almost before we knew it, we had left the ground\";\n\n/**\n * Specimen text for a face limited to one script.\n *\n * A face subset to a non-Latin `unicodeRange` covers none of the Latin sentence\n * above, so the browser draws that row from another subset of the family or\n * from a fallback — the row would claim to demonstrate a file whose glyphs are\n * nowhere on screen. A candidate is chosen by whether the declared range COVERS\n * it, not by which band the range opens in: a start codepoint says nothing\n * about how far the range reaches, so `U+0400-0401` would otherwise be handed a\n * whole Cyrillic sentence it can draw two characters of.\n *\n * Latin faces and faces declaring no range keep the sentence: it exercises\n * ascenders, descenders and round forms, which is what a specimen is for.\n */\nconst SCRIPT_SPECIMENS: readonly string[] = [\n  \"Αλμοστ πριν το καταλάβουμε\",\n  \"Почти прежде чем мы поняли\",\n  \"כמעט לפני שידענו זאת\",\n  \"تقريبا قبل أن ندرك ذلك\",\n  \"इससे पहले कि हमें पता चलता\",\n  \"เกือบก่อนที่เราจะรู้ตัว\",\n  \"気づく前に地面を離れていた\",\n  \"우리가 알기도 전에 땅을 떠났다\",\n];\n\n/**\n * The highest codepoint that exists.\n *\n * `validateFontFace` checks a `unicode-range` for characters that could break\n * out of the stylesheet; it does not check that the numbers name real\n * codepoints, and `U+110000-110010` passes it. `String.fromCodePoint` THROWS on\n * anything above this, which took down the whole panel rather than the one row.\n */\nconst MAX_CODEPOINT = 0x10ffff;\n\n/** One interval of a `unicode-range`, inclusive at both ends. */\ninterface CodepointRange {\n  readonly from: number;\n  readonly to: number;\n}\n\n/** `U+0400`, `U+0400-04FF` or the wildcard form `U+4??`, as one interval. */\nconst RANGE_ITEM = /^U\\+([0-9A-F]{1,6})(?:-([0-9A-F]{1,6}))?$/i;\nconst WILDCARD_ITEM = /^U\\+([0-9A-F]*\\?{1,6})$/i;\n\n/**\n * The intervals a `unicode-range` names, or none when it cannot be read.\n *\n * The wildcard form is a separate pattern because `?` is not a hex digit and\n * stands for every value that digit could take: `U+4??` is `U+0400-04FF`, so it\n * expands by filling the wildcards with `0` for the floor and `F` for the\n * ceiling. Reading it with the hex pattern captured the leading digits alone and\n * produced an interval three orders of magnitude below the one declared.\n *\n * An unreadable item abandons the whole descriptor rather than contributing a\n * partial answer: a range this cannot parse is one whose coverage is unknown,\n * and treating the items it did parse as the whole would under-state it.\n */\nfunction parseUnicodeRange(\n  range: string | undefined\n): readonly CodepointRange[] | undefined {\n  if (range === undefined) return undefined;\n  const parsed: CodepointRange[] = [];\n  for (const item of range.split(\",\")) {\n    const interval = parseRangeItem(item.trim());\n    if (interval === undefined) return undefined;\n    parsed.push(interval);\n  }\n  return parsed.length > 0 ? parsed : undefined;\n}\n\n/**\n * An interval, or nothing when it names no codepoints that exist.\n *\n * REFUSED rather than clamped. A descriptor reaching past the end of Unicode is\n * not a range with a typo in it — nothing can be concluded about what the face\n * covers — and clamping would invent a range the author never wrote and then\n * draw a specimen from it. Refusing sends the whole descriptor to the unreadable\n * path, where the Latin sentence is used and no claim is made.\n */\nfunction readableInterval(\n  from: number,\n  to: number\n): CodepointRange | undefined {\n  if (Number.isNaN(from) || Number.isNaN(to)) return undefined;\n  if (from > MAX_CODEPOINT || to > MAX_CODEPOINT) return undefined;\n  // An inverted interval names nothing, and iterating it yields nothing while\n  // reading as though a range had been declared.\n  if (from > to) return undefined;\n  return { from, to };\n}\n\n/** One comma-separated item of a `unicode-range`. */\nfunction parseRangeItem(item: string): CodepointRange | undefined {\n  const wildcard = WILDCARD_ITEM.exec(item);\n  if (wildcard?.[1] !== undefined) {\n    const digits = wildcard[1];\n    return readableInterval(\n      Number.parseInt(digits.replace(/\\?/g, \"0\"), 16),\n      Number.parseInt(digits.replace(/\\?/g, \"F\"), 16)\n    );\n  }\n  const match = RANGE_ITEM.exec(item);\n  if (match?.[1] === undefined) return undefined;\n  const from = Number.parseInt(match[1], 16);\n  const to = match[2] === undefined ? from : Number.parseInt(match[2], 16);\n  return readableInterval(from, to);\n}\n\n/**\n * Whether every glyph a candidate needs falls inside the declared intervals.\n *\n * Iterated by code point rather than by UTF-16 unit, so a character outside the\n * basic plane is tested as the one value a `unicode-range` names it by.\n * Whitespace is skipped: a space carries no glyph a specimen is demonstrating,\n * and no script subset includes `U+0020`, so requiring it would reject every\n * non-Latin candidate.\n */\nfunction rangesCover(ranges: readonly CodepointRange[], text: string): boolean {\n  for (const character of text) {\n    const point = character.codePointAt(0);\n    if (point === undefined || /\\s/.test(character)) continue;\n    if (!ranges.some(range => point >= range.from && point <= range.to)) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * Characters taken from the declared intervals themselves.\n *\n * The last resort, for a face whose range matches no sentence here — an icon\n * font, or a subset narrower than any phrase. Drawing a sentence it cannot\n * render would demonstrate a fallback, so this shows glyphs the face is\n * declared to carry instead. Control characters and the surrogate block are\n * skipped because neither renders as anything.\n */\nfunction sampleFromRanges(ranges: readonly CodepointRange[]): string {\n  const sampled: string[] = [];\n  for (const range of ranges) {\n    /*\n     * Stepped ACROSS the interval rather than taken from its start. A range\n     * opens on its least interesting characters — `U+0080-00FF` begins with\n     * thirty-two invisible controls and then a run of symbols — so a walk from\n     * the front spends the whole budget before reaching a letter the face can\n     * actually demonstrate. Striding shows what the interval holds.\n     */\n    const span = range.to - range.from + 1;\n    const stride = Math.max(1, Math.floor(span / SAMPLE_LENGTH));\n    for (let point = range.from; point <= range.to; point += stride) {\n      if (sampled.length >= SAMPLE_LENGTH) return sampled.join(\"\");\n      if (renderableCodepoint(point)) sampled.push(String.fromCodePoint(point));\n    }\n  }\n  return sampled.join(\"\");\n}\n\n/** How many glyphs a sampled specimen shows. Enough to read the shapes. */\nconst SAMPLE_LENGTH = 12;\n\n/**\n * Whether a codepoint draws anything: not a control, not half a pair.\n *\n * The C1 block is the one that bites. A face subset to `U+0080-00FF` covers no\n * canned sentence, so sampling starts at `U+0080` — and thirty-two invisible\n * controls fill the twelve-glyph budget before reaching a single accented\n * letter, leaving a specimen that renders as nothing at all.\n */\nfunction renderableCodepoint(point: number): boolean {\n  if (point < 0x20) return false;\n  // DEL, then the C1 controls.\n  if (point === 0x7f) return false;\n  if (point >= 0x80 && point <= 0x9f) return false;\n  return !(point >= 0xd800 && point <= 0xdfff);\n}\n\n/** What to draw for one face, so a specimen demonstrates the file it names. */\nexport function specimenText(face: FontFaceDef): string {\n  const ranges = parseUnicodeRange(face.unicodeRange);\n  // No descriptor, or one this cannot read, means the face is not declared to\n  // be a subset — the Latin sentence is the specimen with the most to show.\n  if (ranges === undefined) return SPECIMEN;\n  const covered = [SPECIMEN, ...SCRIPT_SPECIMENS].find(text =>\n    rangesCover(ranges, text)\n  );\n  return covered ?? sampleFromRanges(ranges);\n}\n\n/**\n * One weight the specimen element can actually carry.\n *\n * A variable face declares a RANGE — `100 900` — which is valid in\n * `@font-face` and invalid as a `font-weight` on an element: the browser drops\n * the whole declaration and draws at its normal weight, so a range excluding\n * 400 renders the specimen in a FALLBACK while the row claims to demonstrate\n * the file.\n *\n * 400 when the range covers it, because that is what a reader sees in ordinary\n * text; otherwise the lower bound, which the face definitely provides.\n */\nexport function specimenWeight(weight: string | undefined): string | undefined {\n  if (weight === undefined) return undefined;\n  const parts = weight.trim().split(/\\s+/);\n  if (parts.length < 2) return weight;\n  const low = Number(parts[0]);\n  const high = Number(parts[1]);\n  if (!Number.isFinite(low) || !Number.isFinite(high)) return undefined;\n  return low <= 400 && 400 <= high ? \"400\" : String(low);\n}\n","/**\n * What a style field offers from the site's variables, beyond what a colour\n * needs: matching a typed name, and the sample a list draws.\n *\n * Pure, for the reason `style-colour.ts` is. Which variable a typed word names\n * and how wide a sample is are derivation, and a test of the rendered field\n * cannot tell a right answer from a plausible wrong one.\n *\n * Every answer here reads the ONE projection of the site's variables,\n * {@link variablesFor}, so the list a field offers and the names it accepts\n * as typed cannot disagree.\n *\n * @module style-variables\n */\nimport type {\n  SiteTokenSet,\n  StyleLeaf,\n  TokenMode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { typeScaleProperty } from \"../panels/design/tokens-studio\";\n\nimport { lengthInPx } from \"./fluid-size\";\nimport { variableLabel, variablesFor, type SiteVariable } from \"./style-colour\";\n\n/**\n * The identity of the variable a typed word names at this leaf, or\n * `undefined` when it names none.\n *\n * An author who knows the site has a \"Display\" size types it, as they would\n * type `16px`. Asked BEFORE the text is read as a value, so the word reaches\n * the document as a reference rather than as a literal the catalog refuses\n * (\"Display is not a length\").\n *\n * Matched against what the list shows (the label, qualified where two share\n * it) and against the code name and identity, ignoring case and the spaces\n * around it, among the variables this leaf is offered and no others: a colour\n * variable's name typed into a length is still a literal, and is refused in\n * the catalog's own words.\n *\n * A word two different variables answer to names neither. Guessing would store\n * an identity the author could not have predicted, which is the failure the\n * qualified label exists to prevent in the list.\n *\n * The IDENTITY is returned, never the name typed, for the reason\n * {@link SiteVariable} records: a reference holding a name compiles to a custom\n * property nothing declares once the variable has been renamed.\n */\nexport function tokenForTypedName(\n  leaf: StyleLeaf,\n  tokens: SiteTokenSet | undefined,\n  text: string,\n  mode: TokenMode = \"light\"\n): string | undefined {\n  const wanted = text.trim().toLowerCase();\n  if (wanted === \"\") return undefined;\n  const offered = variablesFor(leaf, tokens, mode);\n  const named = new Set(\n    offered\n      .filter(variable =>\n        [\n          variable.label,\n          variableLabel(variable, offered),\n          variable.name,\n          variable.identity,\n        ].some(spelling => spelling.toLowerCase() === wanted)\n      )\n      .map(variable => variable.identity)\n  );\n  if (named.size !== 1) return undefined;\n  const [identity] = named;\n  return identity;\n}\n\n// One reading of a length for every place that measures one; kept beside\n// the fluid-size maths, which reads lengths too and imports nothing else.\nexport { lengthInPx };\n\n/**\n * Whether a variable is ONE length that changes with the page: `clamp()`,\n * `min()`, `max()` or `calc()` over the viewport, a container or a\n * percentage. A shadow, a fixed `calc(1rem + 2px)` and any value of several\n * parts are not, and read as themselves.\n */\nfunction isFluidLength(variable: ValueOfKind): boolean {\n  if (variable.kind !== \"dimension\") return false;\n  const value = variable.value.trim();\n  return (\n    /^(clamp|min|max|calc)\\(/i.test(value) &&\n    /\\d(?:[sld]?v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max)|%)/i.test(value)\n  );\n}\n\n/**\n * What reading a value's words needs: its kind and the value. Narrower than\n * {@link SiteVariable}, so the Variables tab, which lists the site's tokens\n * rather than picker records, words its rows through the same rule.\n */\nexport type ValueOfKind = Pick<SiteVariable, \"kind\" | \"value\">;\n\n/**\n * A variable's value in words short enough for a row: the value itself, or\n * \"Fluid\" for a length that changes with the page, whose whole text crowded\n * the name out of a list row. The whole value stays in the row's tooltip.\n */\nexport function variableValueText(variable: ValueOfKind): string {\n  return isFluidLength(variable) ? \"Fluid\" : variable.value;\n}\n\n/** What a list draws beside a variable's name to show its value. */\nexport type VariableSample =\n  /** The name itself, drawn at the type size, within {@link TYPE_SAMPLE_PX}. */\n  | { readonly kind: \"type\"; readonly px: number }\n  /** A bar as wide as the length, up to {@link BAR_SAMPLE_MAX_PX}. */\n  | { readonly kind: \"bar\"; readonly px: number }\n  /** A small box casting the shadow. */\n  | { readonly kind: \"shadow\"; readonly value: string }\n  /** A length through a function, such as `clamp()`, with no one size here. */\n  | { readonly kind: \"fluid\" }\n  /** Nothing drawn; the value beside the name says it in words. */\n  | { readonly kind: \"none\" };\n\n/**\n * The smallest and largest a type size's name is drawn at in a list.\n *\n * Bounded so a display size does not push the row past the popover and a tiny\n * caption size is still legible; the order between sizes survives inside the\n * bounds, which is what an author compares.\n */\nconst TYPE_SAMPLE_PX = { min: 10, max: 28 } as const;\n\n/**\n * The widest a length's bar is drawn, in CSS pixels: wide enough to tell the\n * steps of a spacing scale apart, narrow enough to leave the name its room.\n */\nconst BAR_SAMPLE_MAX_PX = 64;\n\n/**\n * The sample for one variable: a type size as its name at that size, any\n * other length as a bar scaled to it, a shadow as itself, and nothing for a\n * value that cannot be drawn faithfully here.\n */\nexport function variableSample(variable: SiteVariable): VariableSample {\n  if (variable.kind === \"shadow\") {\n    return { kind: \"shadow\", value: variable.value };\n  }\n  if (variable.kind !== \"dimension\") return { kind: \"none\" };\n  if (isFluidLength(variable)) return { kind: \"fluid\" };\n  // Through any other function (`calc(1rem + 2px)`) it has no length here\n  // to draw, though it is fixed: drawn as nothing rather than as fluid.\n  if (variable.value.includes(\"(\")) return { kind: \"none\" };\n  const px = lengthInPx(variable.value);\n  if (px === undefined) return { kind: \"none\" };\n  if (typeScaleProperty(variable) === \"font-size\") {\n    return {\n      kind: \"type\",\n      px: Math.min(TYPE_SAMPLE_PX.max, Math.max(TYPE_SAMPLE_PX.min, px)),\n    };\n  }\n  // The magnitude: a negative letter spacing is as long as its positive.\n  return { kind: \"bar\", px: Math.min(BAR_SAMPLE_MAX_PX, Math.abs(px)) };\n}\n","/**\n * What Design's Site text rows read and write.\n *\n * The rows are the engine's (`SITE_TEXT_ROLES`), their built-in values the\n * engine's (`resolveSiteText`), and the CSS a row writes the compiler's: this\n * module says each in the words the panel shows, and makes the token set an\n * edit produces. A row is held on the site's token set (`siteText`), beside\n * the type sizes it points at, so an edit saves and undoes as a variable\n * edit does.\n *\n * @module site-text-rows\n */\nimport {\n  compileStyleValues,\n  isTokenRef,\n  resolveSiteText,\n  resolveTokenPrefix,\n  SITE_TEXT_LABELS,\n  SITE_TEXT_ROLES,\n  siteTextStyles,\n  siteTextUses,\n  tokenCustomProperty,\n  tokenRef,\n  type SiteTextEntry,\n  type SiteTextMap,\n  type SiteTextRole,\n  type SiteTokenSet,\n  type StyleValue,\n  type TokenMode,\n  type NamedClass,\n  textStylesOf,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { declarationsText } from \"../../inspector/code-hints\";\nimport { fluidRange, lengthInPx } from \"../../styles/fluid-size\";\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\n\nimport { variableGroups } from \"./tokens-studio\";\n\n/** What a row says while it writes nothing. */\nexport const SITE_OWN_WORDS = \"Your site's own\";\n\n/** One type size a row can point at: a size and the line height it pairs with. */\nexport interface TypeSizeChoice {\n  /** The size variable's identity, to store as `{ $token }`. */\n  readonly size: string;\n  /** Its line height's identity, where it has one. */\n  readonly lineHeight: string | undefined;\n  /** Its name, as the Type tab lists it: \"H2\". */\n  readonly name: string;\n  /** Its size and line height, as {@link pairWords} says them. */\n  readonly pair: string;\n}\n\n/** One row as the panel draws it. */\nexport interface SiteTextRowView {\n  readonly role: SiteTextRole;\n  /** \"Body\", \"Heading 2\", \"Links\". */\n  readonly label: string;\n  /** The row's values, built-in where the site states none. */\n  readonly entry: SiteTextEntry | undefined;\n  /** \"28 / 1.2\", or \"Your site's own\" for a row that writes nothing. */\n  readonly pair: string;\n  /** The type size the row points at, where it points at one. */\n  readonly typeSize: TypeSizeChoice | undefined;\n  /** The size the row's text is drawn at, in px, where it reads as one. */\n  readonly px: number | undefined;\n  /** Whether the site states this row (it is not the built-in one). */\n  readonly stated: boolean;\n  /**\n   * The text style the row follows (\"Heading 1 uses Display\"), while it\n   * follows one the site has: its id and name.\n   */\n  readonly follows?: { readonly id: string; readonly name: string };\n}\n\n/** A number as a designer writes a size: no trailing zeros, two places at most. */\nfunction number(value: number): string {\n  return String(Math.round(value * 100) / 100);\n}\n\n/**\n * A size and a line height in the words a designer writes a type scale: the\n * size in px at a 16px root, then the line height (\"28 / 1.2\"). A size made\n * with Fluid… reads by its two ends (\"Fluid 16–24 / 1.3\"); one that reads as\n * neither is shown as written.\n */\nexport function pairWords(\n  size: string | undefined,\n  line: string | undefined\n): string {\n  const range = size === undefined ? undefined : fluidRange(size);\n  const px = size === undefined ? undefined : lengthInPx(size);\n  const sized =\n    range !== undefined\n      ? `Fluid ${number(range.minPx)}–${number(range.maxPx)}`\n      : px !== undefined\n        ? number(px)\n        : (size ?? \"\");\n  if (line === undefined || line === \"\") return sized;\n  return sized === \"\" ? line : `${sized} / ${line}`;\n}\n\n/**\n * The site's type sizes, each with its line height, by name and pair, in the\n * order the Type tab lists them. Read through the Type tab's own grouping,\n * which pairs a size and a line height by name.\n */\nexport function typeSizeChoices(\n  tokens: SiteTokenSet,\n  mode: TokenMode\n): TypeSizeChoice[] {\n  const type = variableGroups(tokens, mode).find(\n    group => group.group === \"type\"\n  );\n  return (type?.entries ?? [])\n    .filter(entry => entry.row.name.startsWith(\"font-size.\"))\n    .map(entry => ({\n      size: entry.row.identity,\n      lineHeight: entry.lineHeight?.identity,\n      name: entry.label,\n      pair: pairWords(entry.row.value, entry.lineHeight?.value),\n    }));\n}\n\n/**\n * A row's value as text: a variable's value in this mode, or the value.\n * Shared with the text styles, whose parts are read the same way.\n */\nexport function valueText(\n  value: StyleValue | undefined,\n  tokens: SiteTokenSet,\n  mode: TokenMode\n): string | undefined {\n  if (value === undefined) return undefined;\n  if (isTokenRef(value)) {\n    const token = tokens.tokens.find(\n      each => (each.id ?? each.name) === value.$token\n    );\n    return token === undefined\n      ? undefined\n      : (token.values[mode] ?? token.values.light);\n  }\n  return typeof value === \"string\" || typeof value === \"number\"\n    ? String(value)\n    : undefined;\n}\n\n/**\n * Every row, as the panel draws it. A row following one of the site's text\n * styles (`classes`) says so, and is drawn at the text style's size.\n */\nexport function siteTextRowViews(\n  tokens: SiteTokenSet,\n  mode: TokenMode,\n  classes?: readonly NamedClass[]\n): SiteTextRowView[] {\n  const rows = resolveSiteText(tokens.siteText);\n  const choices = typeSizeChoices(tokens, mode);\n  return SITE_TEXT_ROLES.map(role => {\n    const entry = rows[role];\n    const followed = followedTextStyle(role, entry, classes);\n    if (followed !== undefined) {\n      const values = followed.styles.base?.base;\n      const size = valueText(values?.fontSize, tokens, mode);\n      return {\n        role,\n        label: SITE_TEXT_LABELS[role],\n        entry,\n        pair: sharedStyleName(followed),\n        typeSize: undefined,\n        px: size === undefined ? undefined : lengthInPx(size),\n        stated: true,\n        follows: { id: followed.id, name: sharedStyleName(followed) },\n      };\n    }\n    const size = valueText(entry?.fontSize, tokens, mode);\n    const pointed = entry?.fontSize;\n    return {\n      role,\n      label: SITE_TEXT_LABELS[role],\n      entry,\n      pair: rowPair(\n        role,\n        entry,\n        size,\n        valueText(entry?.lineHeight, tokens, mode)\n      ),\n      typeSize: isTokenRef(pointed)\n        ? choices.find(choice => choice.size === pointed.$token)\n        : undefined,\n      px: size === undefined ? undefined : lengthInPx(size),\n      stated:\n        tokens.siteText !== undefined && Object.hasOwn(tokens.siteText, role),\n    };\n  });\n}\n\n/**\n * The text style a row follows, by the engine's own reading of the list the\n * class tier is written from, or `undefined`; never for Links.\n */\nfunction followedTextStyle(\n  role: SiteTextRole,\n  entry: SiteTextEntry | undefined,\n  classes: readonly NamedClass[] | undefined\n): NamedClass | undefined {\n  const id = entry?.textStyle;\n  if (role === \"link\" || id === undefined) return undefined;\n  return textStylesOf(classes).find(style => style.id === id);\n}\n\n/**\n * The set with a row following a text style (\"Heading 1 uses Display\"),\n * its own values kept, so they come back should it stop following one.\n * Never Links, which has no text style.\n */\nexport function withRowTextStyle(\n  tokens: SiteTokenSet,\n  role: SiteTextRole,\n  id: string\n): SiteTokenSet {\n  if (role === \"link\") return tokens;\n  const own = resolveSiteText(tokens.siteText)[role] ?? {};\n  return {\n    ...tokens,\n    siteText: { ...tokens.siteText, [role]: { ...own, textStyle: id } },\n  };\n}\n\n/**\n * What a row says of its values: \"Your site's own\" while it writes nothing,\n * \"Set\" for a link's look (the panel words it from the row), else its pair.\n */\nfunction rowPair(\n  role: SiteTextRole,\n  entry: SiteTextEntry | undefined,\n  size: string | undefined,\n  line: string | undefined\n): string {\n  if (siteTextStyles(role, entry) === undefined) return SITE_OWN_WORDS;\n  if (role === \"link\") return \"Set\";\n  // A row holding only the Body or Headings font says nothing of its size.\n  return size === undefined && line === undefined\n    ? SITE_OWN_WORDS\n    : pairWords(size, line);\n}\n\n/**\n * The set with one row as given, or, given `undefined`, with the site's own\n * row left out, so the built-in one stands again.\n *\n * The row keeps its font: the font is the Body and Headings fonts' to set\n * (`site-font-roles-model`), so a change of a row's size, or a Reset, leaves\n * it where it was.\n */\nexport function withSiteTextRow(\n  tokens: SiteTokenSet,\n  role: SiteTextRole,\n  entry: SiteTextEntry | undefined\n): SiteTokenSet {\n  const font = resolveSiteText(tokens.siteText)[role]?.fontFamily;\n  const rest: Partial<Record<SiteTextRole, SiteTextEntry>> = {\n    ...tokens.siteText,\n  };\n  delete rest[role];\n  // The row's size as given, with the font it holds now, never the given one.\n  const { fontFamily: _given, ...sized } =\n    entry ?? resolveSiteText(undefined)[role] ?? {};\n  const next =\n    font !== undefined\n      ? { ...sized, fontFamily: font }\n      : entry === undefined\n        ? undefined\n        : sized;\n  const siteText: SiteTextMap =\n    next === undefined ? rest : { ...rest, [role]: next };\n  return { ...tokens, siteText };\n}\n\n/**\n * The set with a row pointed at a type size: its size and, where the type\n * size has one, its line height, together, as one edit.\n */\nexport function withTypeSize(\n  tokens: SiteTokenSet,\n  role: SiteTextRole,\n  size: string\n): SiteTokenSet {\n  const choice = typeSizeChoices(tokens, \"light\").find(\n    each => each.size === size\n  );\n  return withSiteTextRow(tokens, role, {\n    fontSize: tokenRef(size),\n    ...(choice?.lineHeight === undefined\n      ? {}\n      : { lineHeight: tokenRef(choice.lineHeight) }),\n  });\n}\n\n/** The element a row's CSS is written on, as a developer names it. */\nconst ROW_SELECTOR: Readonly<Record<SiteTextRole, string>> = {\n  body: \".nx-pb-page\",\n  h1: \"h1\",\n  h2: \"h2\",\n  h3: \"h3\",\n  h4: \"h4\",\n  h5: \"h5\",\n  h6: \"h6\",\n  link: \"a\",\n  button: \".nx-bt-core--button\",\n  caption: \"figcaption\",\n};\n\n/**\n * The CSS a row writes, as the compiler writes it: the element and its\n * declarations, a link's hover rule after its own, or \"Nothing\" for a row\n * that writes none.\n */\nexport function siteTextWrites(\n  tokens: SiteTokenSet,\n  role: SiteTextRole,\n  entry: SiteTextEntry | undefined,\n  /** The site's classes: a row following a text style writes the style's. */\n  classes?: readonly NamedClass[]\n): string {\n  const styles = siteTextStyles(role, entry, classes);\n  if (styles === undefined) return \"Nothing\";\n  const { prefix } = resolveTokenPrefix(tokens.prefix);\n  const selector = ROW_SELECTOR[role];\n  const rules: string[] = [];\n  for (const [state, pseudo] of [\n    [\"base\", \"\"],\n    [\"hover\", \":hover\"],\n  ] as const) {\n    const values = styles[state]?.base;\n    if (values === undefined) continue;\n    const { declarations } = compileStyleValues(values, \"\", prefix);\n    rules.push(`${selector}${pseudo} { ${declarationsText(declarations)} }`);\n  }\n  return rules.join(\" \");\n}\n\n/**\n * The Site text rows using any of these variables, as a refusal names them\n * (\"Site text: Heading 1\"), or `undefined` when none does. The panel's own\n * reading of the rule the server refuses a removal by.\n */\nexport function siteTextUseWords(\n  tokens: SiteTokenSet,\n  identities: readonly string[]\n): string | undefined {\n  const uses = siteTextUses(tokens.siteText);\n  const { prefix } = resolveTokenPrefix(tokens.prefix);\n  // Pointed at by its identity, or read through `var()` of its property.\n  const usedBy = (identity: string, role: SiteTextRole): boolean =>\n    uses.get(identity)?.includes(role) === true ||\n    uses.get(tokenCustomProperty(identity, prefix))?.includes(role) === true;\n  const roles = SITE_TEXT_ROLES.filter(role =>\n    identities.some(identity => usedBy(identity, role))\n  );\n  if (roles.length === 0) return undefined;\n  return `Site text: ${roles.map(role => SITE_TEXT_LABELS[role]).join(\", \")}`;\n}\n\n/** The type size a value points at, where it points at one. */\nexport function pickedTypeSize(\n  tokens: SiteTokenSet | undefined,\n  value: StyleValue | undefined,\n  /** The mode its pair is read in: the one the canvas draws. */\n  mode: TokenMode = \"light\"\n): TypeSizeChoice | undefined {\n  if (tokens === undefined || !isTokenRef(value)) return undefined;\n  return typeSizeChoices(tokens, mode).find(\n    choice => choice.size === value.$token\n  );\n}\n","/**\n * Choosing a site variable for a style field that is not a colour: a font\n * size, a line height, a gap, a radius, a shadow; and showing one once it is\n * chosen.\n *\n * The site's variables are reached through the field's own value menu, never\n * through a button of their own beside it:\n *\n * - a field with a unit menu lists them first in that menu\n *   ({@link VariableSelectItems}: \"Your spacing\", \"Your sizes\", then units);\n * - a field with no menu of its own (a line height, a shadow, a width) draws\n *   one, a chevron at its end, that opens the list ({@link VariableChoice});\n * - a field holding a variable shows it as a green chip\n *   ({@link VariableChip}): its name opens the same list to choose another,\n *   its tooltip says what the variable is, and \"Unlink\" keeps its value as a\n *   plain one.\n *\n * The list is the colour picker's own `ChoiceList`, so every picker in the\n * inspector answers the keyboard the same way and searches past the same\n * length. What is offered is `variablesFor`, the one projection of the site's\n * variables the colour picker reads too, so a field can never offer a\n * variable the canvas does not declare.\n *\n * A pick hands back the variable's IDENTITY, which the field stores as\n * `{ $token }` exactly as a colour does. The page then follows the variable:\n * change its value in Design and every block holding the reference changes\n * with it, because the reference compiles to the variable's custom property\n * rather than to the value it had when it was picked.\n *\n * @module variable-choice\n */\nimport {\n  resolveTokenPrefix,\n  tokenCustomProperty,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type StyleValue,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n  SelectGroup,\n  SelectItem,\n  SelectLabel,\n  SelectSeparator,\n  TooltipProvider,\n} from \"@nextlyhq/ui\";\nimport { ChevronDown, Unlink2 } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport { ChoiceList } from \"../../choice-list\";\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport {\n  variableFor,\n  variableLabel,\n  variablesFor,\n  type SiteVariable,\n} from \"../../styles/style-colour\";\nimport { measurementOfText } from \"../../styles/style-numeric\";\nimport {\n  variableSample,\n  variableValueText,\n} from \"../../styles/style-variables\";\n\nimport { pickedTypeSize } from \"./site-text-rows\";\nimport {\n  lengthFamilyOf,\n  variableGroupHeadings,\n  variableGroupOf,\n  type VariableGroup,\n} from \"./tokens-studio\";\n\n/** What {@link VariableChoice} is given. */\nexport interface VariableChoiceProps {\n  /** The catalog leaf the field edits; its `tokenKinds` decide what is offered. */\n  readonly leaf: StyleLeaf;\n  /** The site's variables, or `undefined` when the host supplied none. */\n  readonly tokens: SiteTokenSet | undefined;\n  /** The identity the field holds, marked in the list, if it holds one. */\n  readonly current: string | undefined;\n  /** The field's name, for the button's and the list's names: \"Font size\". */\n  readonly label: string;\n  /** A variable was picked: its identity, to store as `{ $token }`. */\n  readonly onPick: (identity: string) => void;\n  /**\n   * The held variable's name, drawn as the trigger in place of the chevron\n   * alone, as a colour's trigger names its variable: a chip's name.\n   */\n  readonly named?: string;\n  /** What the named trigger's tooltip says: see {@link variableTip}. */\n  readonly tip?: string;\n}\n\n/** What {@link VariableChip} is given. */\nexport interface VariableChipProps {\n  /**\n   * The catalog leaf the field edits: the chip names its variable as the\n   * field's list does, qualified where another listed variable shares the name.\n   */\n  readonly leaf: StyleLeaf;\n  readonly tokens: SiteTokenSet | undefined;\n  /** The identity the field stores. */\n  readonly identity: string;\n  /** The field's name, for the chip's and its buttons' names: \"Font size\". */\n  readonly label: string;\n  /**\n   * The id of the field's visible label, to name the chip by. Without it the\n   * chip is named by {@link label}; with it, by the words an author sees.\n   */\n  readonly labelledBy?: string;\n  /** Another variable was picked from the chip's name. */\n  readonly onPick: (identity: string) => void;\n  /**\n   * \"Unlink\" was pressed: the variable's value, resolved in the mode the\n   * canvas shows and scaled as the reference is, to store as a plain value.\n   */\n  readonly onUnlink: (value: StyleValue) => void;\n  /** A factor the variable is scaled by (a Small button's padding), shown after its name. */\n  readonly times?: number | undefined;\n}\n\n/**\n * The variables offered at this leaf in the mode the canvas is showing, read\n * from the one source the colour picker reads too: the canvas's theme marker,\n * else the device's preference, so the list shows the values the canvas draws.\n */\nexport function useOfferedVariables(\n  leaf: StyleLeaf,\n  tokens: SiteTokenSet | undefined\n): readonly SiteVariable[] {\n  return variablesFor(leaf, tokens, useCanvasTokenMode());\n}\n\n/**\n * What kind of variable this is, in words, for its tooltip: \"Spacing\",\n * \"Type size\". Read from the groups the Design panel lists it under, so the\n * tooltip and Design call one variable the same thing.\n */\nfunction variableKindWord(variable: SiteVariable): string {\n  const group = variableGroupOf(variable);\n  if (group === \"type\") {\n    return lengthFamilyOf(variable) === \"line-height\"\n      ? \"Line height\"\n      : \"Type size\";\n  }\n  if (group === \"fonts\") {\n    return variable.kind === \"fontWeight\" ? \"Font weight\" : \"Font\";\n  }\n  return GROUP_KIND_WORDS[group];\n}\n\n/** Each group's variable in words; type and fonts are told apart above. */\nconst GROUP_KIND_WORDS: Readonly<Record<VariableGroup, string>> = {\n  colours: \"Colour\",\n  type: \"Type size\",\n  fonts: \"Font\",\n  spacing: \"Spacing\",\n  radius: \"Radius\",\n  shadows: \"Shadow\",\n  content: \"Size\",\n  other: \"Size\",\n};\n\n/**\n * A held variable's tooltip: what kind it is, its name, its value and the\n * CSS custom property the page reads it from, as\n * \"Spacing variable XL · 64px · --nx-space-xl\".\n *\n * The custom property is the engine's own spelling for the site's prefix,\n * so it is the name an author finds in the page's CSS.\n */\nexport function variableTip(\n  variable: SiteVariable,\n  name: string,\n  tokens: SiteTokenSet | undefined\n): string {\n  const { prefix } = resolveTokenPrefix(tokens?.prefix);\n  const css = tokenCustomProperty(variable.identity, prefix);\n  return `${variableKindWord(variable)} variable ${name} · ${variable.value} · ${css}`;\n}\n\n/**\n * Whether a variable's value is kept as a number when unlinked: a number\n * variable, and a weight written as one (\"700\"), which a weight is stored as;\n * a weight's keyword (\"bold\") stays a word.\n */\nfunction storedAsNumber(variable: SiteVariable): boolean {\n  const numeric =\n    variable.value.trim() !== \"\" && Number.isFinite(Number(variable.value));\n  return (\n    numeric && (variable.kind === \"number\" || variable.kind === \"fontWeight\")\n  );\n}\n\n/** The fewest decimals a scaled length is written with, so 0.1 × 3 reads 0.3. */\nconst SCALED_DECIMALS = 4;\n\n/**\n * The plain value a variable stands for, for \"Unlink\": its value in the mode\n * asked for, scaled as the reference is.\n *\n * A scaled measurement is multiplied out (\"16px\" × 0.75 is \"12px\"); any other\n * value, such as a fluid `clamp()`, is scaled by `calc()`, as the engine\n * scales the reference itself. A number variable, and a weight written as a\n * number, stay numbers, as a typed one is stored.\n */\nexport function unlinkedValue(\n  variable: SiteVariable,\n  times?: number\n): StyleValue {\n  const { value } = variable;\n  if (storedAsNumber(variable)) return Number(value) * (times ?? 1);\n  if (times === undefined) return value;\n  const measurement = measurementOfText(value);\n  if (measurement === undefined) return `calc(${value} * ${String(times)})`;\n  const scaled = Number((measurement.number * times).toFixed(SCALED_DECIMALS));\n  return `${String(scaled)}${measurement.unit}`;\n}\n\n/** An element's ancestors, nearest first. */\nfunction ancestorsOf(element: Element | null): readonly Element[] {\n  const chain: Element[] = [];\n  for (let at = element?.parentElement; at; at = at.parentElement) {\n    chain.push(at);\n  }\n  return chain;\n}\n\n/** What a field draws to choose a variable: its menu, or a chip's name. */\nconst CHOOSERS = \".nx-variable-menu, .nx-variable-chip__choose\";\n\n/**\n * Focus the variables trigger a field draws after a pick: the same one when\n * it survived the pick, otherwise the first one inside the nearest ancestor\n * still on the page.\n */\nfunction focusAfterPick(\n  trigger: HTMLElement | null,\n  chain: readonly Element[]\n): void {\n  if (trigger?.isConnected === true) {\n    trigger.focus();\n    return;\n  }\n  const kept = chain.find(ancestor => ancestor.isConnected);\n  kept?.querySelector<HTMLElement>(CHOOSERS)?.focus();\n}\n\n/**\n * After a variable is picked from a menu the pick replaces (a unit menu, whose\n * field becomes the chip), focus the chip's name once it is drawn, found from\n * the nearest of the menu's ancestors still on the page, rather than letting\n * focus fall to the page with the menu.\n */\nexport function focusVariableAfterPick(from: Element | null): void {\n  const chain = ancestorsOf(from);\n  requestAnimationFrame(() => focusAfterPick(null, chain));\n}\n\n/**\n * After Unlink, focus what the field draws in the chip's place once it is\n * drawn (its typed field, or the control that stayed), rather than letting\n * it fall to the page with the Unlink that held it.\n */\nexport function focusAfterUnlink(\n  find: () => HTMLElement | null | undefined\n): void {\n  requestAnimationFrame(() => find()?.focus());\n}\n\n/**\n * A field's own way to its variables where it has no menu to list them in:\n * a chevron at its end, or a held variable's name, opening the list.\n *\n * Renders NOTHING when the leaf takes no variable or the site has none of the\n * kinds it takes, so a field can mount it unconditionally and never shows an\n * empty list. Picking closes the list, and Escape closes it without a pick.\n */\nexport function VariableChoice({\n  leaf,\n  tokens,\n  current,\n  label,\n  onPick,\n  named,\n  tip,\n}: VariableChoiceProps): React.JSX.Element | null {\n  const offered = useOfferedVariables(leaf, tokens);\n  const [open, setOpen] = React.useState(false);\n  const trigger = React.useRef<HTMLButtonElement>(null);\n  // The trigger's ancestors at the moment of a pick, nearest first; `null`\n  // while no pick is waiting for the list to close.\n  const pickedFrom = React.useRef<readonly Element[] | null>(null);\n  if (offered.length === 0) return null;\n  const button =\n    named === undefined ? (\n      <button\n        ref={trigger}\n        type=\"button\"\n        className=\"nx-variable-menu\"\n        aria-label={`Variables for ${label}`}\n      >\n        <ChevronDown aria-hidden=\"true\" size={14} />\n      </button>\n    ) : (\n      <button\n        ref={trigger}\n        type=\"button\"\n        className=\"nx-variable-chip__choose\"\n        // Named as a colour's trigger is: the field, then what it holds.\n        aria-label={`Variables for ${label}: ${named}`}\n      >\n        <span className=\"nx-variable-chip__name\">{named}</span>\n        <ChevronDown aria-hidden=\"true\" size={12} />\n      </button>\n    );\n  return (\n    <Popover open={open} onOpenChange={setOpen}>\n      <VariableTipped tip={tip ?? \"Choose a variable\"}>\n        <PopoverTrigger asChild>{button}</PopoverTrigger>\n      </VariableTipped>\n      <PopoverContent\n        align=\"end\"\n        className=\"nx-style-inspector__picker\"\n        // The list puts focus on its search or its entries itself.\n        onOpenAutoFocus={event => event.preventDefault()}\n        /*\n         * Where focus goes once a pick closes the list.\n         *\n         * A pick usually REPLACES the field that drew this trigger — a typed\n         * value becomes a held variable — so the trigger focus would return\n         * to is gone and focus would fall to the page. It is handed instead\n         * to the trigger the field draws now, found from the nearest ancestor\n         * still on the page, after that field has drawn. A close without a\n         * pick returns to the trigger as usual.\n         */\n        onCloseAutoFocus={event => {\n          const chain = pickedFrom.current;\n          pickedFrom.current = null;\n          if (chain === null) return;\n          event.preventDefault();\n          requestAnimationFrame(() => focusAfterPick(trigger.current, chain));\n        }}\n      >\n        <VariableList\n          offered={offered}\n          current={current}\n          onPick={identity => {\n            pickedFrom.current = ancestorsOf(trigger.current);\n            onPick(identity);\n            setOpen(false);\n          }}\n        />\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/** What a variable's item in a select stores as its value: `var:<identity>`. */\nconst VARIABLE_ITEM = \"var:\";\n\n/**\n * The identity a select's choice picks, or `undefined` for a choice that is\n * not a variable (a unit, a keyword, an option).\n */\nexport function pickedVariable(choice: string): string | undefined {\n  return choice.startsWith(VARIABLE_ITEM)\n    ? choice.slice(VARIABLE_ITEM.length)\n    : undefined;\n}\n\n/** The heading a variable is listed under in a field's menu. */\ntype MenuHeading =\n  | \"Your spacing\"\n  | \"Your sizes\"\n  | \"Your weights\"\n  | \"Your values\";\n\n/** The headings in the order a menu lists them, spacing first. */\nconst MENU_HEADINGS: readonly MenuHeading[] = [\n  \"Your spacing\",\n  \"Your sizes\",\n  \"Your weights\",\n  \"Your values\",\n];\n\nfunction menuHeadingOf(variable: SiteVariable): MenuHeading {\n  if (variableGroupOf(variable) === \"spacing\") return \"Your spacing\";\n  if (variable.kind === \"dimension\") return \"Your sizes\";\n  return variable.kind === \"fontWeight\" ? \"Your weights\" : \"Your values\";\n}\n\n/**\n * The site's variables as the first items of a field's own select (a unit\n * menu, a weight list), under \"Your spacing\" and \"Your sizes\", with a line\n * after them where the field's own choices follow.\n *\n * Each item's value is `var:<identity>`, read back by {@link pickedVariable};\n * its name is the variable's and its value follows, as the list draws them.\n * Nothing where nothing is offered.\n */\nexport function VariableSelectItems({\n  offered,\n  before,\n}: {\n  offered: readonly SiteVariable[];\n  /** Whether the field's own choices follow, which a line then divides. */\n  before: boolean;\n}): React.JSX.Element | null {\n  if (offered.length === 0) return null;\n  return (\n    <>\n      {MENU_HEADINGS.map(heading => {\n        const listed = offered.filter(\n          variable => menuHeadingOf(variable) === heading\n        );\n        if (listed.length === 0) return null;\n        return (\n          <SelectGroup key={heading}>\n            <SelectLabel className=\"nx-variable-choice__heading\">\n              {heading}\n            </SelectLabel>\n            {listed.map(variable => (\n              <SelectItem\n                key={variable.identity}\n                value={`${VARIABLE_ITEM}${variable.identity}`}\n                className=\"nx-variable-choice__item\"\n              >\n                {variableLabel(variable, offered)}{\" \"}\n                <span className=\"nx-variable-choice__value\">\n                  {variableValueText(variable)}\n                </span>\n              </SelectItem>\n            ))}\n          </SelectGroup>\n        );\n      })}\n      {before ? <SelectSeparator /> : null}\n    </>\n  );\n}\n\n/** One variable as the list holds it. */\ninterface VariableEntry {\n  readonly key: string;\n  readonly label: string;\n  readonly group: VariableGroup;\n  readonly variable: SiteVariable;\n}\n\n/**\n * The variables by name, each with its value and a sample of it, grouped as\n * the Design panel groups them when more than one group is present.\n */\nfunction VariableList({\n  offered,\n  current,\n  onPick,\n}: {\n  offered: readonly SiteVariable[];\n  current: string | undefined;\n  onPick: (identity: string) => void;\n}): React.JSX.Element {\n  const entries: VariableEntry[] = offered.map(variable => ({\n    // The identity, which a rename leaves alone, so a renamed row keeps its\n    // place and its key never collides with a new variable's.\n    key: variable.identity,\n    // Qualified only where two listed variables share a name.\n    label: variableLabel(variable, offered),\n    group: variableGroupOf(variable),\n    variable,\n  }));\n  const present = new Set(entries.map(entry => entry.group));\n  // Headings only where they tell groups apart: one group under its own\n  // heading is a heading saying nothing.\n  const groups =\n    present.size > 1\n      ? variableGroupHeadings().filter(({ group }) => present.has(group))\n      : undefined;\n  return (\n    <div className=\"nx-style-inspector__variables\">\n      <ChoiceList\n        choices={entries}\n        currentKey={current}\n        onPick={entry => onPick(entry.variable.identity)}\n        label=\"Variables\"\n        searchLabel=\"Search variables\"\n        noMatch=\"No variables match this search.\"\n        {...(groups === undefined ? {} : { groups })}\n        choiceClassName=\"nx-variable-choice__option\"\n        renderChoice={entry => <VariableRow entry={entry} />}\n        // The whole name and value on the row, which never collapses, where\n        // the value itself may be cut short or given way entirely.\n        choiceTitle={entry => `${entry.label} ${entry.variable.value}`}\n      />\n    </div>\n  );\n}\n\n/**\n * One row: the sample, the name, then the value in words.\n *\n * The space between name and value is a text node on purpose. The row's\n * accessible name is read from its text, and without it a screen reader hears\n * \"Display48px\" as one word.\n */\nfunction VariableRow({ entry }: { entry: VariableEntry }): React.JSX.Element {\n  const sample = variableSample(entry.variable);\n  return (\n    <>\n      <span className=\"nx-variable-choice__sample\" aria-hidden=\"true\">\n        {sample.kind === \"bar\" ? (\n          <span\n            className=\"nx-variable-choice__bar\"\n            data-sample-px={sample.px}\n            style={{ inlineSize: `${String(sample.px)}px` }}\n          />\n        ) : null}\n        {sample.kind === \"fluid\" ? (\n          // No one size to scale to: a bar of its own, dashed.\n          <span className=\"nx-variable-choice__bar\" data-fluid=\"\" />\n        ) : null}\n        {sample.kind === \"shadow\" ? (\n          <span\n            className=\"nx-vars__shadow\"\n            style={{ boxShadow: sample.value }}\n          />\n        ) : null}\n      </span>\n      <span\n        className=\"nx-variable-choice__name\"\n        // A type size's name drawn at that size, so a scale reads as one.\n        style={\n          sample.kind === \"type\"\n            ? { fontSize: `${String(sample.px)}px` }\n            : undefined\n        }\n      >\n        {entry.label}\n      </span>{\" \"}\n      <span className=\"nx-variable-choice__value\">\n        {variableValueText(entry.variable)}\n      </span>\n    </>\n  );\n}\n\n/**\n * \"Unlink\", beside a value that comes from a variable: it keeps the value the\n * field shows now as a plain one, in one step, and the field stops following\n * the variable. Named by the field, since several fields can hold one\n * variable and a column of buttons named for it could not be told apart.\n *\n * An icon, its word in its tooltip and its name: a field's column is too\n * narrow for the variable's name, its value and a word beside them, and the\n * name is what the author reads first.\n */\nexport function UnlinkButton({\n  label,\n  onUnlink,\n  ...rest\n}: {\n  label: string;\n  onUnlink: () => void;\n} & Omit<\n  React.ButtonHTMLAttributes<HTMLButtonElement>,\n  \"onClick\" | \"type\"\n>): React.JSX.Element {\n  return (\n    <TooltipProvider delayDuration={300}>\n      <ChromeTooltip content=\"Unlink\">\n        <button\n          {...rest}\n          type=\"button\"\n          className=\"nx-variable-unlink\"\n          onClick={onUnlink}\n          aria-label={`Unlink ${label}`}\n        >\n          <Unlink2 aria-hidden=\"true\" size={14} />\n        </button>\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/**\n * What a chip says: its name, the value shown beside it, and its tooltip.\n */\nfunction chipWords({\n  leaf,\n  tokens,\n  identity,\n  times,\n  mode,\n  variable,\n  offered,\n}: {\n  leaf: StyleLeaf;\n  tokens: SiteTokenSet | undefined;\n  identity: string;\n  times: number | undefined;\n  mode: TokenMode;\n  variable: SiteVariable | undefined;\n  offered: readonly SiteVariable[];\n}): {\n  name: string;\n  shownValue: SiteVariable | undefined;\n  tip: string | undefined;\n} {\n  // Named through the list's own rule, so two variables sharing a name read\n  // here as they do there, and the chip says which one the document holds.\n  const named =\n    variable === undefined ? identity : variableLabel(variable, offered);\n  // A type size in a font size field reads by its name and pair, \"H2 ·\n  // 28 / 1.2\", which says its line height too; its value is in the pair.\n  const typeSize =\n    leaf.cssProperty === \"font-size\" && times === undefined\n      ? pickedTypeSize(tokens, { $token: identity }, mode)\n      : undefined;\n  const name = chipName(named, typeSize?.pair, times);\n  if (variable === undefined) {\n    return { name, shownValue: undefined, tip: undefined };\n  }\n  // The pair already holds the value, so it is not said twice; the tooltip\n  // says the value itself, so a type size is named plainly there.\n  return typeSize === undefined\n    ? { name, shownValue: variable, tip: variableTip(variable, name, tokens) }\n    : {\n        name,\n        shownValue: undefined,\n        tip: variableTip(variable, named, tokens),\n      };\n}\n\n/**\n * What a chip names its variable: a type size by its name and pair, a\n * scaled variable by its scale (\"padding-y × 0.75\"), any other by name.\n */\nfunction chipName(\n  named: string,\n  pair: string | undefined,\n  times: number | undefined\n): string {\n  if (pair !== undefined) return `${named} · ${pair}`;\n  return times === undefined ? named : `${named} × ${String(times)}`;\n}\n\n/**\n * The variable a field holds, shown in place of its typed value: a green chip\n * with the variable's name, which opens the list to choose another, its value,\n * and Unlink.\n *\n * A variable the site no longer defines shows the identity the document holds\n * rather than an empty space, and offers no Unlink: there is no value to keep.\n * The reference still compiles, so it is still on the page, and the row's\n * Reset removes it.\n */\nexport function VariableChip({\n  leaf,\n  tokens,\n  identity,\n  label,\n  labelledBy,\n  onPick,\n  onUnlink,\n  times,\n}: VariableChipProps): React.JSX.Element {\n  const mode = useCanvasTokenMode();\n  const variable = variableFor(identity, tokens, mode);\n  const offered = variablesFor(leaf, tokens, mode);\n  const { name, shownValue, tip } = chipWords({\n    leaf,\n    tokens,\n    identity,\n    times,\n    mode,\n    variable,\n    offered,\n  });\n  return (\n    // A group, so it can carry a name: a bare paragraph maps to a role that\n    // prohibits one. Focusable by script only, as the field's label targets it.\n    <p\n      className=\"nx-style-inspector__token nx-variable-chip\"\n      role=\"group\"\n      {...(labelledBy === undefined\n        ? { \"aria-label\": label }\n        : { \"aria-labelledby\": labelledBy })}\n      tabIndex={-1}\n    >\n      {/* One line: the name whole, and its value only while it fits; the\n          whole of both is in the name's tooltip. */}\n      <span className=\"nx-variable-chip__text\">\n        {offered.length === 0 ? (\n          <ChipName name={name} tip={tip} />\n        ) : (\n          <VariableChoice\n            leaf={leaf}\n            tokens={tokens}\n            current={identity}\n            label={label}\n            onPick={onPick}\n            named={name}\n            {...(tip === undefined ? {} : { tip })}\n          />\n        )}\n        {shownValue === undefined ? null : (\n          <>\n            {\" \"}\n            <span className=\"nx-variable-chip__value\">\n              {variableValueText(shownValue)}\n            </span>\n          </>\n        )}\n      </span>\n      {variable === undefined ? null : (\n        <UnlinkButton\n          label={label}\n          onUnlink={() => onUnlink(unlinkedValue(variable, times))}\n        />\n      )}\n    </p>\n  );\n}\n\n/**\n * A held variable's control with its tooltip saying what the variable is, or\n * none while nothing is held. Kept mounted without one, so the control stays\n * one element and keeps its focus as a variable comes and goes.\n *\n * Wrap the control alone, never a list it opens: focus inside the list would\n * reach the tooltip through React's tree and open it over the list.\n *\n * Opened by the pointer and by keyboard focus, not by focus a script moves\n * after a pick made with the mouse (the field turning into its chip): shown\n * then, the tooltip covered the field just changed, and took the Escape that\n * leaves the panel. Whether focus is the keyboard's is the browser's own\n * `:focus-visible`.\n */\nexport function VariableTipped({\n  tip,\n  children,\n}: {\n  tip: string | undefined;\n  children: React.ReactElement<React.HTMLAttributes<HTMLElement>>;\n}): React.JSX.Element {\n  const [quiet, setQuiet] = React.useState(false);\n  const own = children.props;\n  const trigger = React.cloneElement(children, {\n    onFocus: event => {\n      own.onFocus?.(event);\n      setQuiet(!event.currentTarget.matches(\":focus-visible\"));\n    },\n    onPointerEnter: event => {\n      own.onPointerEnter?.(event);\n      setQuiet(false);\n    },\n  });\n  return (\n    <TooltipProvider delayDuration={300}>\n      <ChromeTooltip content={tip} disabled={tip === undefined || quiet}>\n        {trigger}\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/** A held variable's name where no list offers another: text, with its tooltip. */\nfunction ChipName({\n  name,\n  tip,\n}: {\n  name: string;\n  tip: string | undefined;\n}): React.JSX.Element {\n  return (\n    <VariableTipped tip={tip}>\n      <span className=\"nx-variable-chip__name\">{name}</span>\n    </VariableTipped>\n  );\n}\n","/**\n * The inspector's Font control: choose from what the site can draw.\n *\n * Choose-only, with no box to type a family into. A typed name is a guess the\n * page may not be able to keep: a family the site has no file for renders in\n * whatever the reader's device has, and nothing says so. The list offers three\n * kinds of choice, each of which the published page can draw:\n *\n * - the site's font variables, stored as a reference so a change to the\n *   variable reaches every block using it;\n * - the families the site has files for, stored as the family followed by the\n *   generic family of its category, so a reader still gets a sensible face\n *   while the file loads;\n * - the system families, which every browser resolves.\n *\n * Every choice is drawn in itself. A value stored before, or written by the\n * API, that is none of these is shown as it is and can be cleared.\n *\n * A font variable chosen shows in green, as every value from a variable does,\n * with what it is in its tooltip and \"Unlink\" beside it, which keeps its\n * family as a plain one.\n *\n * @module font-family-field\n */\nimport {\n  GENERIC_FONT_FAMILIES,\n  isTokenRef,\n  readFamilyList,\n  resolveSiteTokens,\n  tokenDisplayLabel,\n  tokenIdentity,\n  type FontFaceDef,\n  type SiteTokenSet,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@nextlyhq/ui\";\nimport { ChevronDown } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport { ChoiceList } from \"../../choice-list\";\nimport { InheritedValue } from \"../../inspector/style-inspector/inherited-value\";\nimport { variableFor, type SiteVariable } from \"../../styles/style-colour\";\n\nimport { familyStack, siteFamilies } from \"./font-library\";\nimport {\n  focusAfterUnlink,\n  UnlinkButton,\n  VariableTipped,\n  variableTip,\n} from \"./variable-choice\";\n\nexport interface FontFamilyFieldProps {\n  /** The control's id, so its label can point at it. */\n  id?: string;\n  /** The id of the element naming the property. */\n  labelledBy?: string;\n  /** What the block stores now. */\n  stored: StyleValue | undefined;\n  /** The site's variables, whose font variables are offered first. */\n  tokens: SiteTokenSet | undefined;\n  /**\n   * The faces the page loads, or `undefined` while the site's style is being\n   * read. Families with files are offered from them.\n   */\n  faces: readonly FontFaceDef[] | undefined;\n  /** The faces the site's code supplies, which the editor cannot remove. */\n  fromCode: readonly FontFaceDef[];\n  /** Store a choice, or `null` to clear the property. */\n  onCommit: (value: StyleValue | null) => void;\n  /**\n   * Draws the family the keyboard or the pointer is on in the open list,\n   * before anything is stored; `null` once the list closes, said before a\n   * pick's commit. Absent, nothing is drawn until a family is picked.\n   */\n  onPreview?: (value: StyleValue | null) => void;\n  /** Open Design's fonts, where fonts are added. Absent, no link shows. */\n  onManageFonts?: () => void;\n}\n\n/**\n * What the inspector's host knows about the site's fonts: the faces the page\n * loads, the ones the site's code supplies, and a way to Design's fonts.\n */\nexport interface FontChoices {\n  /** The faces the page loads, or `undefined` while they are being read. */\n  readonly faces: readonly FontFaceDef[] | undefined;\n  /** The faces the site's code supplies. */\n  readonly fromCode: readonly FontFaceDef[];\n  /** Open Design's fonts. */\n  readonly onManageFonts?: () => void;\n}\n\n/**\n * The site's fonts, for the Font control wherever the inspector draws it.\n *\n * A context rather than a prop threaded through each section and field: only\n * one control reads it, and every layer between the panel and that control\n * would otherwise carry a value it never uses.\n */\nexport const FontChoicesContext: React.Context<FontChoices | undefined> =\n  React.createContext<FontChoices | undefined>(undefined);\n\n/** Whether a stored value is one this control can show: none, a stack, a reference. */\nexport function fontFamilyShowable(stored: StyleValue | undefined): boolean {\n  return (\n    stored === undefined || typeof stored === \"string\" || isTokenRef(stored)\n  );\n}\n\n/** One entry in the list. */\ninterface FontChoice {\n  readonly key: string;\n  readonly group: ChoiceGroup;\n  readonly label: string;\n  /** The stack the entry is drawn in, when one can be drawn. */\n  readonly drawn: string | undefined;\n  /** What picking it stores. */\n  readonly value: StyleValue;\n}\n\ntype ChoiceGroup = \"variables\" | \"site\" | \"system\";\n\nconst GROUPS: ReadonlyArray<{ group: ChoiceGroup; heading: string }> = [\n  { group: \"variables\", heading: \"Font variables\" },\n  { group: \"site\", heading: \"On this site\" },\n  { group: \"system\", heading: \"System\" },\n];\n\n/** The generic families in an author's words, the common ones first. */\nconst GENERIC_LABELS: Readonly<Record<string, string>> = {\n  \"system-ui\": \"System UI\",\n  \"sans-serif\": \"Sans serif\",\n  serif: \"Serif\",\n  monospace: \"Monospace\",\n  cursive: \"Cursive\",\n  fantasy: \"Fantasy\",\n  \"ui-sans-serif\": \"System sans serif\",\n  \"ui-serif\": \"System serif\",\n  \"ui-monospace\": \"System monospace\",\n  \"ui-rounded\": \"System rounded\",\n  math: \"Math\",\n  emoji: \"Emoji\",\n  fangsong: \"Fangsong\",\n};\n\n/**\n * The families every browser resolves: exactly the generic keywords the\n * engine accepts, so no value it stores reads as unknown here. One without\n * words of its own is shown as written.\n */\nconst SYSTEM: ReadonlyArray<{ label: string; value: string }> = [\n  ...Object.keys(GENERIC_LABELS).filter(value =>\n    GENERIC_FONT_FAMILIES.includes(value)\n  ),\n  ...GENERIC_FONT_FAMILIES.filter(value => !(value in GENERIC_LABELS)),\n].map(value => ({ label: GENERIC_LABELS[value] ?? value, value }));\n\n/** A stack that draws, or nothing for one that only resolves on the page. */\nfunction drawable(stack: string): string | undefined {\n  return /var\\s*\\(/i.test(stack) ? undefined : stack;\n}\n\n/** Every entry the control offers, in the order it lists them. */\nfunction choicesFor(\n  tokens: SiteTokenSet | undefined,\n  faces: readonly FontFaceDef[] | undefined,\n  fromCode: readonly FontFaceDef[]\n): FontChoice[] {\n  const variables: FontChoice[] =\n    tokens === undefined\n      ? []\n      : resolveSiteTokens(tokens)\n          .tokens.filter(token => token.kind === \"fontFamily\")\n          .map(token => {\n            const identity = tokenIdentity(token);\n            return {\n              key: `variable:${identity}`,\n              group: \"variables\",\n              label: tokenDisplayLabel(token),\n              drawn: drawable(token.values.light),\n              value: { $token: identity },\n            };\n          });\n  const site: FontChoice[] = siteFamilies(faces ?? [], fromCode).map(family => {\n    const stack = familyStack(family.family, family.category);\n    return {\n      key: `site:${family.key}`,\n      group: \"site\",\n      label: family.family,\n      drawn: stack,\n      value: stack,\n    };\n  });\n  const system: FontChoice[] = SYSTEM.map(entry => ({\n    key: `system:${entry.value}`,\n    group: \"system\",\n    label: entry.label,\n    drawn: entry.value,\n    value: entry.value,\n  }));\n  return [...variables, ...site, ...system];\n}\n\n/** A stack written the way two equal stacks compare: no spacing, no case. */\nfunction normalised(stack: string): string {\n  return stack\n    .replace(/\\s*,\\s*/g, \",\")\n    .trim()\n    .toLowerCase();\n}\n\n/**\n * The entry a stored value is, or nothing when it is none of them.\n *\n * A family stored without its generic, or with another one, is still that\n * family: the first name in a stack is the author's choice.\n */\n/**\n * The family reaching this block from another tier, shown greyed while none\n * is chosen here: named as the list names it where the site offers it, and\n * as written where it does not.\n */\nfunction useInheritedFamily(\n  choices: readonly FontChoice[]\n): string | undefined {\n  const inherited = React.useContext(InheritedValue);\n  if (inherited === undefined) return undefined;\n  return currentChoice(inherited, choices)?.label ?? inherited;\n}\n\nfunction currentChoice(\n  stored: StyleValue | undefined,\n  choices: readonly FontChoice[]\n): FontChoice | undefined {\n  if (stored === undefined) return undefined;\n  if (isTokenRef(stored)) {\n    return choices.find(\n      choice =>\n        isTokenRef(choice.value) && choice.value.$token === stored.$token\n    );\n  }\n  if (typeof stored !== \"string\") return undefined;\n  const exact = choices.find(\n    choice =>\n      typeof choice.value === \"string\" &&\n      normalised(choice.value) === normalised(stored)\n  );\n  if (exact !== undefined) return exact;\n  const reading = readFamilyList(stored);\n  if (reading.kind !== \"families\") return undefined;\n  const first = reading.parts[0]?.part.name.toLowerCase();\n  return choices.find(\n    choice => choice.group === \"site\" && choice.key === `site:${first ?? \"\"}`\n  );\n}\n\n/** The stored value in words, for one the list does not hold. */\nfunction storedText(stored: StyleValue): string {\n  if (isTokenRef(stored)) return stored.$token;\n  return typeof stored === \"string\" ? stored : JSON.stringify(stored);\n}\n\nexport function FontFamilyField({\n  id,\n  labelledBy,\n  stored,\n  tokens,\n  faces,\n  fromCode,\n  onCommit,\n  onPreview,\n  onManageFonts,\n}: FontFamilyFieldProps): React.JSX.Element {\n  const choices = React.useMemo(\n    () => choicesFor(tokens, faces, fromCode),\n    [tokens, faces, fromCode]\n  );\n  const current = currentChoice(stored, choices);\n  const unknown = stored !== undefined && current === undefined;\n  const { open, setOpen, close, activeProps, manage } = useFontList(\n    onPreview,\n    onManageFonts\n  );\n  // The trigger, which stays when Unlink makes the family plain: focus\n  // returns to it from the Unlink that goes.\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const inheritedFamily = useInheritedFamily(choices);\n  const shownValue = shownFamily(unknown, stored, current, inheritedFamily);\n  const held = useHeldFont(stored, tokens);\n\n  return (\n    <div\n      className=\"nx-font-pick\"\n      data-unknown={unknown ? \"\" : undefined}\n      data-bound={held === undefined ? undefined : \"\"}\n    >\n      <Popover open={open} onOpenChange={setOpen} modal={false}>\n        {/* What a held font variable is, in the trigger's tooltip. */}\n        <VariableTipped\n          tip={\n            held === undefined\n              ? undefined\n              : variableTip(held, shownValue, tokens)\n          }\n        >\n          <PopoverTrigger asChild>\n            <FontTrigger\n              ref={triggerRef}\n              id={id}\n              labelledBy={labelledBy}\n              open={open}\n              shownValue={shownValue}\n              placeholder={current === undefined && !unknown}\n              drawn={current?.drawn}\n            />\n          </PopoverTrigger>\n        </VariableTipped>\n        {/* Aligned to the control's right edge: the list may be wider than\n            the control, and the inspector sits at the window's right edge. */}\n        <PopoverContent\n          align=\"end\"\n          sideOffset={4}\n          className=\"nx-font-pick__popover\"\n          onOpenAutoFocus={event => event.preventDefault()}\n        >\n          <FontList\n            choices={choices}\n            current={current}\n            onPick={choice => {\n              close();\n              onCommit(choice.value);\n            }}\n            {...activeProps}\n            onManageFonts={manage}\n          />\n        </PopoverContent>\n      </Popover>\n      {held === undefined ? null : (\n        <UnlinkButton\n          label=\"Font\"\n          // The family the variable gives in the mode the canvas shows, kept\n          // as a plain one in one commit.\n          onUnlink={() => {\n            onCommit(held.value);\n            focusAfterUnlink(() => triggerRef.current);\n          }}\n        />\n      )}\n    </div>\n  );\n}\n\n/**\n * Whether the list is open, and the preview of what it is on: the family the\n * author moves to is drawn, and the list closing, by a pick or not, ends the\n * drawing, before a pick's commit.\n */\nfunction useFontList(\n  onPreview: ((value: StyleValue | null) => void) | undefined,\n  onManageFonts: (() => void) | undefined\n): {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  close: () => void;\n  activeProps: { onActive?: (choice: FontChoice) => void };\n  /** \"Manage fonts…\", which closes the list first; absent without a way. */\n  manage: (() => void) | undefined;\n} {\n  const [open, show] = React.useState(false);\n  const setOpen = (next: boolean): void => {\n    show(next);\n    // Closed without a pick: what is stored is drawn again.\n    if (!next) onPreview?.(null);\n  };\n  const close = (): void => setOpen(false);\n  return {\n    open,\n    setOpen,\n    close,\n    activeProps:\n      onPreview === undefined\n        ? {}\n        : { onActive: choice => onPreview(choice.value) },\n    manage:\n      onManageFonts === undefined\n        ? undefined\n        : () => {\n            close();\n            onManageFonts();\n          },\n  };\n}\n\n/**\n * What the trigger says: the choice in force, a stored value the list does\n * not hold as it is, or the family reaching the field from elsewhere.\n */\nfunction shownFamily(\n  unknown: boolean,\n  stored: StyleValue | undefined,\n  current: FontChoice | undefined,\n  inheritedFamily: string | undefined\n): string {\n  if (unknown && stored !== undefined) {\n    return `${storedText(stored)} · not on this site`;\n  }\n  return current?.label ?? inheritedFamily ?? \"Default\";\n}\n\n/** Ids that describe an element, joined, or `undefined` for none. */\nfunction describedBy(\n  ...ids: readonly (string | undefined)[]\n): string | undefined {\n  const joined = ids.filter(Boolean).join(\" \");\n  return joined === \"\" ? undefined : joined;\n}\n\n/**\n * What opens the list: the choice in force, drawn in itself, or the inherited\n * family greyed as a placeholder. Handed the popover's trigger props.\n */\nfunction FontTrigger({\n  id,\n  labelledBy,\n  open,\n  shownValue,\n  placeholder,\n  drawn,\n  ...trigger\n}: React.ComponentProps<\"button\"> & {\n  labelledBy: string | undefined;\n  open: boolean;\n  shownValue: string;\n  placeholder: boolean;\n  drawn: string | undefined;\n}): React.JSX.Element {\n  return (\n    <button\n      {...trigger}\n      type=\"button\"\n      id={id}\n      className=\"nx-font-pick__trigger\"\n      aria-haspopup=\"listbox\"\n      aria-expanded={open}\n      aria-label={`Font, ${shownValue}`}\n      // The label's words, and the tooltip's while it shows: the tooltip\n      // hands its id in through the trigger props, and the label's alone\n      // would replace it.\n      aria-describedby={describedBy(trigger[\"aria-describedby\"], labelledBy)}\n    >\n      <span\n        className=\"nx-font-pick__value\"\n        data-placeholder={placeholder ? \"\" : undefined}\n        style={drawn === undefined ? undefined : { fontFamily: drawn }}\n      >\n        {shownValue}\n      </span>\n      <ChevronDown aria-hidden=\"true\" size={14} />\n    </button>\n  );\n}\n\n/**\n * The font variable a field holds, as the canvas shows it, or `undefined` for\n * a family, none, or a variable the site no longer has.\n */\nfunction useHeldFont(\n  stored: StyleValue | undefined,\n  tokens: SiteTokenSet | undefined\n): SiteVariable | undefined {\n  const mode = useCanvasTokenMode();\n  return isTokenRef(stored)\n    ? variableFor(stored.$token, tokens, mode)\n    : undefined;\n}\n\n/**\n * The open list: the three groups, searchable once long, and the link to\n * Design's fonts.\n */\nfunction FontList({\n  choices,\n  current,\n  onPick,\n  onActive,\n  onManageFonts,\n}: {\n  choices: readonly FontChoice[];\n  current: FontChoice | undefined;\n  onPick: (choice: FontChoice) => void;\n  /** The author moved onto `choice`, by key or pointer. */\n  onActive?: (choice: FontChoice) => void;\n  onManageFonts: (() => void) | undefined;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-font-pick__body\">\n      <ChoiceList\n        choices={choices}\n        currentKey={current?.key}\n        onPick={onPick}\n        {...(onActive === undefined ? {} : { onActive })}\n        label=\"Fonts\"\n        searchLabel=\"Search fonts\"\n        noMatch=\"No fonts match this search.\"\n        groups={GROUPS}\n        // Each entry is drawn in itself.\n        choiceStyle={choice =>\n          choice.drawn === undefined ? undefined : { fontFamily: choice.drawn }\n        }\n      />\n      {onManageFonts === undefined ? null : (\n        <div className=\"nx-font-pick__footer\">\n          <button\n            type=\"button\"\n            className=\"nx-vars__link\"\n            onClick={onManageFonts}\n          >\n            Manage fonts…\n          </button>\n        </div>\n      )}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * What every part of the Style tab reads: the surroundings a field is drawn\n * in, the address an edit is made at, where a control's value came from,\n * what a commit answers, and the contexts that carry the edited target, the\n * token prefix, the value applied at another tier and a form toggle drawn\n * above a field.\n *\n * @module style-field-surroundings\n */\nimport {\n  DEFAULT_TOKEN_PREFIX,\n  type BreakpointId,\n  type BreakpointSet,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport type { PageStyleCascade } from \"@nextlyhq/blocks-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport type { SideOrientation } from \"../../styles/side-orientation\";\nimport type {\n  BreakpointBadge,\n  StyleProvenance,\n} from \"../../styles/style-provenance\";\nimport type { StylePolicy } from \"../../styles/style-values\";\n\nimport type { StyleTarget } from \"./style-target\";\n\n/** What one control knows about where its value came from, and what to do. */\nexport interface ProvenanceAnswer {\n  provenance: StyleProvenance;\n  badge: BreakpointBadge;\n  /**\n   * Move the canvas to the tier this control's value came from.\n   *\n   * Carried per LEAF rather than threaded as its own prop, because the\n   * target is this control's own source: a different control on the same\n   * panel jumps somewhere else. Bundling it here also keeps three\n   * intermediate components from gaining a prop they only pass on.\n   *\n   * Absent when the host supplies no handler, which is a host that cannot\n   * move its canvas — and a button that does nothing reads as broken rather\n   * than as missing.\n   */\n  jump?: () => void;\n  /**\n   * What the control would show without the block's own value at the\n   * position being edited, judged at the edited tier: the source the\n   * \"overrides\" line names, and what its Reset shows again.\n   */\n  beneath: StyleProvenance;\n}\n\n/**\n * Where one control's value came from, asked per control against a subject and a\n * trace the panel resolved ONCE.\n *\n * A function rather than a precomputed map because the key would have to be the\n * control's CSS property AND its descendant selector — the catalog writes\n * `color` from three different controls — and a map keyed on that pair is a\n * second spelling of the filter `styleProvenance` already applies.\n *\n * `undefined` means nothing can answer, which is not the same as \"unset\".\n */\nexport type ProvenanceOf = (leaf: StyleLeaf) => ProvenanceAnswer | undefined;\n\n/** Editing the block itself, wearing nothing: the target when none is given. */\nexport const BLOCK_TARGET: StyleTarget = { kind: \"block\", worn: [] };\n\n/**\n * What the controls edit, for the field that reads and writes a value.\n *\n * A context rather than one more prop threaded through every section and row\n * between the panel and the field: none of them reads it.\n */\nexport const StyleTargetContext: React.Context<StyleTarget> =\n  React.createContext<StyleTarget>(BLOCK_TARGET);\n\n/**\n * Whether the style fields drawn here write as they are typed, so the canvas\n * follows each keystroke. A block's own fields do, and the panels that draw\n * them say so: off by default, so a field reused elsewhere still writes only\n * when it is left. A site variable's size or a shadow variable's colour turns\n * it on with a write of its own for the keystrokes (the field's `onType`),\n * which draws the value on the canvas and stores nothing: a variable is\n * stored once, when its edit ends, as a change to every page that uses it\n * should be.\n */\nexport const TypesLiveContext: React.Context<boolean> =\n  React.createContext<boolean>(false);\n\n/**\n * The prefix the cascade's token references were written under, for a reader\n * matching a value reaching from elsewhere to one token exactly; the default\n * prefix while no cascade answers.\n */\nexport const TokenPrefixContext: React.Context<string> =\n  React.createContext<string>(DEFAULT_TOKEN_PREFIX);\n\n/** The cascade's token prefix, or the default while no cascade answers. */\nexport function tokenPrefixOf(cascade: PageStyleCascade | undefined): string {\n  return cascade?.tokenPrefix ?? DEFAULT_TOKEN_PREFIX;\n}\n\n/**\n * Everything a style field needs from the panel around it.\n *\n * Named once because the section and the property list pass the identical set\n * down, and two copies of ten props drift the moment one gains an eleventh —\n * silently, since the section would simply stop forwarding what it no longer\n * declares.\n */\nexport interface StyleFieldSurroundings {\n  /**\n   * How the edited element runs, or `undefined` when the canvas could not say.\n   *\n   * Only the per-side box reads it, and `undefined` means NOT KNOWN rather than\n   * left-to-right: a box drawn on an unknown orientation is a positional claim\n   * with nothing behind it.\n   */\n  orientation: SideOrientation | undefined;\n  nodeId: string;\n  state: StyleState;\n  breakpoint: BreakpointId;\n  editor: EditorState;\n  policy: StylePolicy | undefined;\n  tokens: SiteTokenSet | undefined;\n  prefersDark: boolean;\n  provenanceOf: ProvenanceOf;\n  editing: EditedAddress;\n  onChooseForm: ChooseForm;\n  /** The site's devices, for a control that writes at another one. */\n  breakpoints: BreakpointSet | undefined;\n}\n\n/**\n * What the cascade applies to the edited block at another tier, lent to a\n * control that writes at tiers other than the one being edited (where a row\n * stacks). Absent where the host compiles no cascade.\n */\nexport const AppliedAtTier: React.Context<CascadeAt | undefined> =\n  React.createContext<CascadeAt | undefined>(undefined);\n\n/**\n * What the cascade applies to the edited block at a tier beneath its own\n * values, for a control that clears one and must undo what lies beneath.\n * Absent where the host compiles no cascade.\n */\nexport const BeneathAtTier: React.Context<CascadeAt | undefined> =\n  React.createContext<CascadeAt | undefined>(undefined);\n\n/**\n * What the cascade applies to the edited block at a tier, for any CSS\n * property: the value, the tier that sets it, and whether the block itself\n * stores it. `undefined` where nothing sets it.\n */\nexport type CascadeAt = (\n  tier: string,\n  cssProperty: string\n) => { value: string; breakpoint: string; own: boolean } | undefined;\n\n/**\n * Whether this field's form toggle is drawn just above it. A single control\n * there keeps its label for assistive technology and drops the visible copy:\n * the toggle's row already says the name.\n */\nexport const NamedAbove: React.Context<boolean> = React.createContext(false);\n\n/** How an author says which form they mean to write a value in. */\nexport type ChooseForm = (\n  property: string,\n  path: readonly string[],\n  arm: number\n) => void;\n\n/**\n * What a commit did to the document.\n *\n * Three outcomes rather than a boolean, because the surface showing the value\n * has to do something different in each and two of them are easy to conflate.\n * `refused` KEEPS what the author typed, so they can correct it beside the\n * message. `unchanged` means the write was valid and the document already held\n * that value — `01` where it holds `1` — so the field has to go back to what\n * the document says, and nothing else will make it: the stored value never\n * moved, so no effect keyed on it fires.\n */\nexport type CommitOutcome = \"applied\" | \"refused\" | \"unchanged\";\n\n/** Which node, state and breakpoint the panel is editing, to say what DIFFERS. */\nexport interface EditedAddress {\n  readonly nodeId: string;\n  /** The selected block's type, to tell its own defaults from an ancestor's. */\n  readonly blockType: string | undefined;\n  readonly state: StyleState;\n  readonly breakpoint: BreakpointId;\n  /** A breakpoint's author-facing name, for saying which one a value came from. */\n  readonly labelOf: (breakpoint: BreakpointId) => string;\n  /**\n   * A shared style's name by its class name, for saying a value comes from\n   * it: \"From Card\". The class name itself when omitted or unknown.\n   */\n  readonly sharedStyleName?: (slug: string) => string | undefined;\n  /**\n   * A block's name as the Layers panel shows it, for saying which enclosing\n   * block a value came from. Absent, it is \"an enclosing block\".\n   */\n  readonly nameOf?: (nodeId: string) => string | undefined;\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 * 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 * The four sides of a per-side property, recognised so they can be drawn as a\n * box rather than as four rows.\n *\n * `margin` and `padding` are ONE catalog property each, whose `logicalSides`\n * shape the control walk flattens into four independent controls. That is the\n * right model — each side commits on its own, and undo stays per side — and it\n * is the wrong picture: four stacked rows say nothing about which edge each one\n * is, so an author reads four labels to answer a question a diagram answers at\n * a glance.\n *\n * This groups them for the DRAWING only. Nothing about how a side is stored,\n * committed or undone changes.\n *\n * ## The vocabulary is DERIVED, not restated\n *\n * `LogicalSide` is `keyof LogicalSidesShape[\"sides\"]`, so the engine's catalog\n * decides what the sides are and this module only decides what ORDER to draw\n * them in. `DRAW_ORDER` is a `Record` over that union rather than a list, which\n * is what makes the derivation load-bearing: a side added to the engine leaves\n * a missing key and a side renamed leaves both a missing and an excess one, and\n * either fails `check-types` here. A list would have gone on compiling while\n * quietly dropping the new side out of the box.\n *\n * ## LOGICAL, not physical\n *\n * The sides are block/inline, not top/left, and the difference is not pedantry:\n * in a right-to-left context the inline start is on the RIGHT, and in a\n * vertical writing mode the block axis is horizontal. Which physical edge each\n * one lands on is NOT decided here — it is a property of the element being\n * edited, and `side-orientation.ts` resolves it from that element.\n *\n * @module style-sides\n */\nimport type { LogicalSidesShape } from \"@nextlyhq/blocks-engine\";\n\nimport type { SideOrientation } from \"./side-orientation\";\nimport type { StyleControl } from \"./style-controls\";\n\n/** One of the four sides, as the engine's catalog names them. */\nexport type LogicalSide = keyof LogicalSidesShape[\"sides\"];\n\n/**\n * The order the sides come in the document, which is the order Tab visits\n * them: the CSS shorthand's, top, then the inline end (right in a\n * left-to-right page), bottom, and the inline start. An author typing a box\n * from the keyboard goes round it as they would write `margin: 1px 2px 3px\n * 4px`.\n *\n * Where each side is DRAWN is not decided here: the stylesheet places every\n * side by which side it is, so this order moves no side on screen.\n *\n * A `Record` over the engine's own union, so this cannot fall out of step with\n * the catalog without failing to compile. The numbers are this module's\n * decision, which the engine has no opinion about.\n */\nconst DRAW_ORDER: Record<LogicalSide, number> = {\n  blockStart: 0,\n  inlineEnd: 1,\n  blockEnd: 2,\n  inlineStart: 3,\n};\n\n/**\n * The four sides, in the order they come in the document and Tab visits them.\n *\n * Derived from `DRAW_ORDER` rather than written out a second time: two lists of\n * the same four names is exactly the drift this module exists to avoid.\n */\nexport const LOGICAL_SIDES: readonly LogicalSide[] = (\n  Object.keys(DRAW_ORDER) as LogicalSide[]\n).sort((a, b) => DRAW_ORDER[a] - DRAW_ORDER[b]);\n\n/**\n * The controls of a per-side property, in box order, or `undefined`.\n *\n * All four or none. Drawing three sides in a box arrangement would position\n * them as edges while leaving one edge missing and unexplained, which is worse\n * than four honest rows — so a property that does not offer the whole set keeps\n * the ordinary layout.\n *\n * @param controls - every control the property expanded into\n * @returns the four side controls in draw order, or `undefined` if not per-side\n */\nexport function logicalSideGroup(\n  controls: readonly StyleControl[]\n): readonly StyleControl[] | undefined {\n  if (controls.length !== LOGICAL_SIDES.length) return undefined;\n\n  const bySide = new Map<string, StyleControl>();\n  for (const control of controls) {\n    // Depth one only. A side reached through a union arm or an object field is\n    // a different address, and treating it as a side would place a control in\n    // an edge it does not describe.\n    if (control.path.length !== 1) return undefined;\n    const side = control.path[0];\n    if (side === undefined) return undefined;\n    bySide.set(side, control);\n  }\n\n  const ordered = LOGICAL_SIDES.map(side => bySide.get(side));\n  if (ordered.some(control => control === undefined)) return undefined;\n  return ordered as readonly StyleControl[];\n}\n\n/** How a property's controls should be drawn, once the box question is settled. */\nexport interface SideBox {\n  /** The controls in the order to draw them: box order when boxed. */\n  readonly controls: readonly StyleControl[];\n  /** Whether to draw a box at all. */\n  readonly boxed: boolean;\n  /**\n   * The axes to put on the box, or `undefined` when it is not one.\n   *\n   * The EDITED ELEMENT's, so the grid's own placement resolves in them: columns\n   * run along the inline axis, so column one is the inline start in either\n   * direction and a vertical mode transposes the pair.\n   */\n  readonly axes: SideOrientation | undefined;\n}\n\n/**\n * Settle whether a property is drawn as a box, and in what order.\n *\n * A pure question, lifted out of the panel so the component reads as markup:\n * the four branches it replaces — is this per-side, is the orientation known,\n * which order do the controls go in, which side is this one — are one decision\n * with one answer, and each of them was a place the component could disagree\n * with itself.\n *\n * A box is drawn ONLY when its arrangement can be justified. The picture makes\n * a positional claim — this control is the leading edge — and the mapping from\n * a logical side to a physical one belongs to the element being edited. Unknown\n * orientation therefore keeps the rows, which name their side in words and are\n * true whichever way the element runs.\n *\n * @param controls - every control the property expanded into\n * @param orientation - the edited element's axes, or `undefined` if unreadable\n * @returns what to draw, and what to put on it\n */\nexport function sideBoxFor(\n  controls: readonly StyleControl[],\n  orientation: SideOrientation | undefined\n): SideBox {\n  const sides = logicalSideGroup(controls);\n  if (sides === undefined || orientation === undefined) {\n    return { controls, boxed: false, axes: undefined };\n  }\n  return { controls: sides, boxed: true, axes: orientation };\n}\n\n/**\n * The side one control draws in a box, or `undefined` outside one.\n *\n * @param box - the settled drawing decision\n * @param control - one of its controls\n * @returns the side name, for the stylesheet to place by\n */\nexport function sideOf(\n  box: SideBox,\n  control: StyleControl\n): LogicalSide | undefined {\n  if (!box.boxed) return undefined;\n  const side = control.path[0];\n  return side === undefined ? undefined : (side as LogicalSide);\n}\n\n/**\n * A side's plain name, \"top\" or \"left\", for an element whose axes make it one.\n *\n * Only for a horizontal writing mode, where the block axis runs top to bottom\n * and the inline axis follows the direction, so a right-to-left element's\n * inline start is its right. In a vertical mode the physical edge depends on\n * more than this pair reads, so there is no plain name, and the caller keeps\n * the logical one.\n *\n * @param side - the logical side\n * @param axes - the edited element's writing mode and direction\n * @returns \"top\", \"right\", \"bottom\" or \"left\", or `undefined`\n */\nexport function physicalSideName(\n  side: LogicalSide,\n  axes: SideOrientation\n): \"top\" | \"right\" | \"bottom\" | \"left\" | undefined {\n  if (axes.writingMode !== \"horizontal-tb\") return undefined;\n  const rtl = axes.direction === \"rtl\";\n  switch (side) {\n    case \"blockStart\":\n      return \"top\";\n    case \"blockEnd\":\n      return \"bottom\";\n    case \"inlineStart\":\n      return rtl ? \"right\" : \"left\";\n    case \"inlineEnd\":\n      return rtl ? \"left\" : \"right\";\n    default:\n      return undefined;\n  }\n}\n\n/** Whether a key names one of the four logical sides. */\nexport function isLogicalSide(key: string): key is LogicalSide {\n  return (LOGICAL_SIDES as readonly string[]).includes(key);\n}\n\n/**\n * A corner's plain name, \"top left\" or \"bottom right\", for an element whose\n * axes make it one: the block side, then the inline side, each named as\n * {@link physicalSideName} names it.\n *\n * @param corner - the logical corner, block side first (`startEnd`)\n * @param axes - the edited element's writing mode and direction\n * @returns the corner in plain words, or `undefined` in a vertical mode\n */\nexport function physicalCornerName(\n  corner: string,\n  axes: SideOrientation\n): string | undefined {\n  const match = /^(start|end)(Start|End)$/.exec(corner);\n  if (match === null) return undefined;\n  const block = physicalSideName(\n    match[1] === \"start\" ? \"blockStart\" : \"blockEnd\",\n    axes\n  );\n  const inline = physicalSideName(\n    match[2] === \"Start\" ? \"inlineStart\" : \"inlineEnd\",\n    axes\n  );\n  return block === undefined || inline === undefined\n    ? undefined\n    : `${block} ${inline}`;\n}\n","\"use client\";\n\n/**\n * What a Style tab field reads and writes: the selected block or a shared\n * style it wears, the styles and cascade of that target, whether it can be\n * edited, and the writes that set a value or move it to a shared style.\n *\n * @module style-field-target\n */\nimport {\n  findNode,\n  type NodeStyles,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { isElement } from \"../../canvas/dom-kind\";\nimport type { EditorState } from \"../../editor-state\";\nimport { useSurvivingReport } from \"../../shell/builder-notices\";\nimport {\n  batchStyleClearOps,\n  batchStyleWriteOps,\n  batchStyleWritesOps,\n} from \"../../styles/batch-style\";\nimport {\n  moveToSharedStyleClear,\n  planMoveToSharedStyle,\n  sharedStyleChanges,\n  type SharedStyleSet,\n} from \"../../styles/shared-style-target\";\nimport {\n  readStyleValue,\n  type StyleAddress,\n  type StylePolicy,\n  type StyleWriteRequest,\n} from \"../../styles/style-values\";\nimport {\n  designIsWritable,\n  designReadOnlyReason,\n  lockViewOf,\n} from \"../inspector\";\n\nimport {\n  type ProvenanceOf,\n  StyleTargetContext,\n  type CommitOutcome,\n} from \"./style-field-surroundings\";\nimport type { StyleTarget } from \"./style-target\";\n\n/**\n * Apply one control's edit to the document, and say what happened to it.\n *\n * Lifted out of the field because it is a different question from drawing one:\n * the field owns what the author is looking at, and this owns the write — which\n * of two ops to build, which refusals are reportable, and which of the three\n * outcomes each produces.\n *\n * Read the node at COMMIT TIME rather than closing over one. A field committing\n * on blur can fire after another edit has already replaced the node, and\n * writing from the older copy would resurrect its styles.\n */\nfunction writeStyleValue({\n  editor,\n  nodeId,\n  address,\n  policy,\n  value,\n  setIssue,\n  also = [],\n  pairFor,\n}: {\n  editor: EditorState;\n  nodeId: string;\n  address: StyleAddress;\n  policy: StylePolicy | undefined;\n  /** `null` clears, which is not the same as writing an empty value. */\n  value: StyleValue | null;\n  setIssue: (message: string | null) => void;\n  /**\n   * Other addresses written in the same op, each with its value: the sides of\n   * a margin set together. A clear is of `address` alone.\n   */\n  also?: readonly StyleWriteRequest[];\n  /** A second value the same edit writes with this one, read from the block. */\n  pairFor?: PairFor | undefined;\n}): CommitOutcome {\n  const current = findNode(editor.document.nodes, nodeId);\n  if (current === undefined) return \"refused\";\n  /*\n   * Refused here as well as drawn read-only: the controls are disabled while a\n   * lock holds, but a lock set from Layers after the panel drew must stop the\n   * next write too, so the live document is asked at the moment of the write.\n   */\n  if (!designIsWritable(editor.document, nodeId, lockViewOf(editor))) {\n    setIssue(\"This block's design is locked, so it can't be changed here.\");\n    return \"refused\";\n  }\n  /*\n   * A ONE-NODE BATCH, and the single write path for a style edit in this\n   * builder.\n   *\n   * Not because this panel needs batching — it edits one block — but because\n   * the alternative is two implementations of \"what ops set this address\".\n   * They agree the day they are written: `batchStyleWriteOps` was in fact\n   * written from this function. Then one of them learns something — a policy\n   * that varies, a refusal worded differently, a value the other still\n   * accepts — and the surface an author reaches through a multi-selection\n   * behaves unlike the one they reach through a single click, for a reason no\n   * test names because each path passes its own.\n   *\n   * A group of one is exactly the single-op case: `applyAll(ops)` and\n   * `apply(op)` are both `run(ops, \"new\")` in the store, so one op through\n   * here costs one history entry and behaves identically. The batch layer is\n   * therefore not a detour around the simple case — it IS the simple case,\n   * with the count left open.\n   */\n  // A type size picked where the block has no line height of its own\n  // writes the line height with it, in the same op, so one undo takes both.\n  const extra = [...also, ...pairedWrite(value, current.styles, pairFor)];\n  const write = styleWrite(current, address, extra, value, policy);\n  if (write.refused !== undefined) {\n    setIssue(write.refused);\n    return \"refused\";\n  }\n  setIssue(null);\n  // No ops is the document already holding this value, which is the ordinary\n  // case for a field blurred without being changed. Applying an empty group\n  // would ask the op store for a history entry that undoes to no visible\n  // effect, which it refuses.\n  if (write.ops.length === 0) return \"unchanged\";\n  // The store's own refusal, which the validator cannot anticipate: it judges\n  // the edited leaf, while `applyOp` judges the whole document — a page at its\n  // byte limit rejects an edit whose value is perfectly valid. Unreported, the\n  // field goes on showing the draft and reads as saved while neither the\n  // document nor the undo history moved.\n  if (editor.applyAll(write.ops) === null) {\n    setIssue(\"This edit could not be applied to the document.\");\n    return \"refused\";\n  }\n  return \"applied\";\n}\n\n/**\n * A second value an edit writes with its own, given the value and the\n * block's styles before the edit, or `undefined` for none.\n */\nexport type PairFor = (\n  value: StyleValue,\n  styles: NodeStyles | undefined\n) => { address: StyleAddress; value: StyleValue } | undefined;\n\n/** The second write an edit brings with its value, where it brings one. */\nfunction pairedWrite(\n  value: StyleValue | null,\n  styles: NodeStyles | undefined,\n  pairFor: PairFor | undefined\n): StyleWriteRequest[] {\n  if (value === null || pairFor === undefined) return [];\n  const paired = pairFor(value, styles);\n  return paired === undefined ? [] : [paired];\n}\n\n/** The ops that write one address, or several in one op, or clear one. */\nfunction styleWrite(\n  current: Parameters<typeof batchStyleClearOps>[0][number],\n  address: StyleAddress,\n  also: readonly StyleWriteRequest[],\n  value: StyleValue | null,\n  policy: StylePolicy | undefined\n): ReturnType<typeof batchStyleClearOps> {\n  if (value === null) return batchStyleClearOps([current], address, policy);\n  if (also.length === 0) {\n    return batchStyleWriteOps([current], address, value, policy);\n  }\n  return batchStyleWritesOps([current], [{ address, value }, ...also], policy);\n}\n\n/** A value at one path of a field's property, for {@link useFieldTarget}'s `commitPaths`. */\nexport interface PathWrite {\n  readonly path: readonly string[];\n  readonly value: StyleValue;\n}\n\n/** A shared style's name by its class name, from the styles the block wears. */\nexport function sharedStyleNamer(\n  target: StyleTarget\n): (slug: string) => string | undefined {\n  return slug => target.worn.find(row => row.slug === slug)?.name;\n}\n\n/**\n * The provenance dots for the target: the block's, from the cascade, or none\n * for a shared target, whose values say where they come from in their own line.\n */\nexport function targetProvenance(\n  target: StyleTarget,\n  block: ProvenanceOf\n): ProvenanceOf {\n  return target.kind === \"shared\" ? () => undefined : block;\n}\n\n/**\n * Why the target's values can't be changed. The block's own locks for the\n * block; a shared target has its own reasons (locked, or no right to change\n * design), and the block's lock does not hold a site-wide style.\n */\nexport function targetReadOnly(\n  target: StyleTarget,\n  editor: EditorState,\n  nodeId: string\n): string | undefined {\n  return target.kind === \"shared\"\n    ? target.readOnly\n    : designReadOnlyReason(editor.document, nodeId, lockViewOf(editor));\n}\n\n/**\n * The cascade the inspection judges which controls show by: the block's, or\n * none for a shared target, whose display is read from the style's own\n * styles, not from the block's cascade, which the block or a later style may\n * override.\n */\nexport function targetCascade<T>(\n  target: StyleTarget,\n  cascade: T\n): T | undefined {\n  return target.kind === \"shared\" ? undefined : cascade;\n}\n\n/** The values a shared target shows, or `undefined` while the block is the target. */\nexport function targetStyles(target: StyleTarget): NodeStyles | undefined {\n  return target.kind === \"shared\" ? target.style.styles : undefined;\n}\n\n/** The block's own styles, and the styles a field shows for the target. */\nexport function fieldStyles(\n  target: StyleTarget,\n  editor: EditorState,\n  nodeId: string\n): { nodeStyles: NodeStyles | undefined; styles: NodeStyles | undefined } {\n  const nodeStyles = findNode(editor.document.nodes, nodeId)?.styles;\n  return { nodeStyles, styles: targetStyles(target) ?? nodeStyles };\n}\n\n/**\n * What one field edits (the block, or the shared style that is the target),\n * the value it shows, its refusal, and the writes it makes: a value (into the block, or into\n * the shared style), the block's Reset of an override, and Move to.\n */\n/** Which target a write was made for: the block, or one shared style. */\nexport function targetKey(target: StyleTarget): string {\n  return target.kind === \"shared\" ? `shared:${target.style.id}` : \"block\";\n}\n\nexport function useFieldTarget({\n  editor,\n  nodeId,\n  address,\n  policy,\n  pairFor,\n}: {\n  editor: EditorState;\n  nodeId: string;\n  address: StyleAddress;\n  policy: StylePolicy | undefined;\n  /** A second value a write to the block makes with this field's. */\n  pairFor?: PairFor | undefined;\n}): {\n  target: StyleTarget;\n  nodeStyles: NodeStyles | undefined;\n  styles: NodeStyles | undefined;\n  stored: StyleValue | undefined;\n  issue: string | null;\n  setIssue: (message: string | null) => void;\n  /** The field's caption hold, spread onto its row. */\n  caption: {\n    \"data-provenance-quiet\": string | undefined;\n    style: React.CSSProperties | undefined;\n    onFocus: () => void;\n    onBlur: (event: React.FocusEvent<HTMLElement>) => void;\n  };\n  commit: (value: StyleValue | null) => CommitOutcome;\n  /**\n   * This field's value written at other paths of its property as well, as one\n   * edit: \"Apply to: All sides\" from a side of the spacing box.\n   */\n  commitSides: (\n    paths: readonly (readonly string[])[],\n    value: StyleValue\n  ) => CommitOutcome;\n  /**\n   * Values at several paths of this field's property, each its own, written\n   * as one edit: the one write path for any gesture that sets more than one.\n   * The first is the field's own address's value or another path's; none is\n   * a clear.\n   */\n  commitPaths: (writes: readonly PathWrite[]) => CommitOutcome;\n  resetBlock: () => void;\n  moveTo: (shared: Extract<StyleTarget, { kind: \"shared\" }>) => void;\n} {\n  const target = React.useContext(StyleTargetContext);\n  // Read ONCE and shared by every lookup the field makes, so the control's\n  // own value and its contrast partner cannot come from two different reads\n  // of the document. A shared target's values are the style's own.\n  const { nodeStyles, styles } = fieldStyles(target, editor, nodeId);\n  const stored = readStyleValue(styles, address);\n  const [issue, setIssue] = React.useState<string | null>(null);\n  /*\n   * Whether the provenance caption is held back. It is revealed while the\n   * field has focus, and typing a value leaves focus there, so after a commit\n   * the caption would linger over the row above; it waits for the field to be\n   * focused again.\n   */\n  const [quiet, setQuiet] = React.useState(false);\n  /*\n   * Whether focus has left the field since the caption was held back. Only a\n   * return after leaving is the author focusing it again: a pick or a clear\n   * moves focus into the field by itself, and that must not bring the caption\n   * back over the row above.\n   */\n  const left = React.useRef(false);\n  const quieten = (): void => {\n    left.current = false;\n    setQuiet(true);\n  };\n  // Held back once the value here changes, however it changed: a pick, a\n  // typed name, an undo or an edit from elsewhere, as well as a commit here.\n  const opened = React.useRef(true);\n  React.useEffect(() => {\n    if (opened.current) {\n      opened.current = false;\n      return;\n    }\n    left.current = false;\n    setQuiet(true);\n  }, [stored]);\n  // A refusal describes the draft that produced it, so it stops describing\n  // anything the moment the document holds a different value here. Clearing on\n  // the stored value rather than only on the next commit is what covers an undo\n  // or an edit applied from elsewhere: the remount key changes with the\n  // SELECTION, and neither of those changes the selection.\n  React.useEffect(() => {\n    setIssue(null);\n  }, [stored]);\n  const survive = useSurvivingReport();\n  // The target and the editor as they are now, for a write that answers later.\n  const current = React.useRef(target);\n  current.current = target;\n  const liveEditor = React.useRef(editor);\n  liveEditor.current = editor;\n  /*\n   * A refusal of a write that answers later, for the target that made it:\n   * said beside the field while the field is on screen AND still edits that\n   * target, and through the shell otherwise. The field stays mounted across a\n   * switch of target, and a refusal shown there would describe a write the new\n   * target never made.\n   */\n  const reportFor =\n    (submitted: StyleTarget) =>\n    (reason: string): void =>\n      survive(reason, () => {\n        if (targetKey(current.current) !== targetKey(submitted)) return false;\n        setIssue(reason);\n        return true;\n      });\n  const writeBlock = (\n    value: StyleValue | null,\n    also?: readonly StyleWriteRequest[],\n    at: StyleAddress = address\n  ): CommitOutcome =>\n    writeStyleValue({\n      editor,\n      nodeId,\n      address: at,\n      policy,\n      value,\n      setIssue,\n      ...(also === undefined ? {} : { also }),\n      pairFor,\n    });\n  const commitPaths = (writes: readonly PathWrite[]): CommitOutcome => {\n    quieten();\n    const [first, ...rest] = writes.map(write => ({\n      address: { ...address, path: write.path },\n      value: write.value,\n    }));\n    if (first === undefined) return \"unchanged\";\n    return writeTarget(first.value, rest, first.address);\n  };\n  return {\n    target,\n    nodeStyles,\n    styles,\n    stored,\n    issue,\n    setIssue,\n    caption: {\n      \"data-provenance-quiet\": quiet ? \"\" : undefined,\n      // Read by the caption's reveal rule, which then draws nothing.\n      style: quiet\n        ? ({ \"--nx-provenance-caption\": \"none\" } as React.CSSProperties)\n        : undefined,\n      onFocus: () => {\n        if (left.current) setQuiet(false);\n      },\n      onBlur: event => {\n        // Leaving for somewhere outside the field, while what had focus is\n        // still on the page: an element removed under focus, such as a\n        // picked list closing, has not taken the author anywhere.\n        const to = event.relatedTarget;\n        const inside = isElement(to) && event.currentTarget.contains(to);\n        if (!inside && isElement(event.target) && event.target.isConnected) {\n          left.current = true;\n        }\n      },\n    },\n    commit: value => {\n      quieten();\n      return writeTarget(value);\n    },\n    // The same value at each path: the one write path's commonest case.\n    commitSides: (paths, value) =>\n      commitPaths(paths.map(path => ({ path, value }))),\n    commitPaths,\n    resetBlock: () => {\n      writeBlock(null);\n    },\n    moveTo: shared =>\n      moveToSharedStyle({\n        editor,\n        live: () => liveEditor.current,\n        nodeId,\n        target: shared,\n        address,\n        policy,\n        setIssue,\n        report: reportFor(shared),\n      }),\n  };\n  function writeTarget(\n    value: StyleValue | null,\n    also: readonly StyleWriteRequest[] = [],\n    at: StyleAddress = address\n  ): CommitOutcome {\n    if (target.kind !== \"shared\") return writeBlock(value, also, at);\n    // A shared style's writes go to the host as ONE change, so one undo\n    // takes the whole gesture back, as it does on the block.\n    return writeSharedStyleValue({\n      target,\n      sets: [{ address: at, value }, ...also],\n      policy,\n      setIssue,\n      report: reportFor(target),\n    });\n  }\n}\n\n/**\n * One control's value written into the shared style that is the target.\n *\n * Through the block's own write rule (`sharedStyleWrite`), judged under the\n * same policy, so the style may hold what a block may. The style is stored by\n * the host, over the network: the field answers at once and a refusal that\n * comes back later is reported where the author can still read it.\n */\nfunction writeSharedStyleValue({\n  target,\n  sets,\n  policy,\n  setIssue,\n  report,\n}: {\n  target: Extract<StyleTarget, { kind: \"shared\" }>;\n  /** The addresses written, as one change the host stores and undoes once. */\n  sets: readonly SharedStyleSet[];\n  policy: StylePolicy | undefined;\n  setIssue: (message: string | null) => void;\n  report: (reason: string) => void;\n}): CommitOutcome {\n  // Refused here as well as drawn read-only, for a lock set after the\n  // controls drew.\n  if (target.readOnly !== undefined) {\n    setIssue(target.readOnly);\n    return \"refused\";\n  }\n  const change = sharedStyleChanges(sets, policy);\n  const write = change(target.style.styles);\n  if (write.kind === \"refused\") {\n    setIssue(write.reason);\n    return \"refused\";\n  }\n  setIssue(null);\n  /*\n   * Queued even when the read in hand already holds the value: an edit still\n   * on its way may have changed it since, so whether this one changes\n   * anything is the host's to decide against what it has queued. The change,\n   * not the styles just computed, so none is lost.\n   */\n  void target.write(change).then(refused => {\n    if (refused !== undefined) report(refused);\n  });\n  return \"applied\";\n}\n\n/**\n * \"Move to Card\": the block's value at this control written into the style,\n * then cleared from the block once the style has it, so a refused style\n * leaves the block as it was.\n */\nfunction moveToSharedStyle({\n  editor,\n  live,\n  nodeId,\n  target,\n  address,\n  policy,\n  setIssue,\n  report,\n}: {\n  editor: EditorState;\n  /** The editor as it stands when the style's write answers. */\n  live: () => EditorState;\n  nodeId: string;\n  target: Extract<StyleTarget, { kind: \"shared\" }>;\n  address: StyleAddress;\n  policy: StylePolicy | undefined;\n  setIssue: (message: string | null) => void;\n  report: (reason: string) => void;\n}): void {\n  const node = findNode(editor.document.nodes, nodeId);\n  if (node === undefined) return;\n  if (target.readOnly !== undefined) {\n    setIssue(target.readOnly);\n    return;\n  }\n  if (!designIsWritable(editor.document, nodeId, lockViewOf(editor))) {\n    setIssue(\"This block's design is locked, so it can't be changed here.\");\n    return;\n  }\n  const plan = planMoveToSharedStyle(node, target.style, address, policy);\n  if (!plan.ok) {\n    setIssue(plan.reason);\n    return;\n  }\n  setIssue(null);\n  void target.write(plan.change).then(refused => {\n    if (refused !== undefined) {\n      report(refused);\n      return;\n    }\n    /*\n     * The block's value cleared at this one address, from the block as it\n     * stands NOW: an edit made to it while the style's write was on its way\n     * is kept, where a clear built before the write would put it back.\n     */\n    const now = live();\n    const ops = moveToSharedStyleClear(\n      findNode(now.document.nodes, nodeId),\n      address,\n      plan.moved,\n      policy\n    );\n    if (ops.length > 0 && now.applyAll(ops) === null) {\n      report(\n        `${target.style.name} has the value, but it could not be cleared from this block.`\n      );\n    }\n  });\n}\n","\"use client\";\n\n/**\n * \"Play\", beside \"Animation when it appears\": the block's animation played\n * once on the canvas, on a press and whenever the animation changes.\n *\n * The canvas otherwise shows every block in its final state, so an author\n * sees the animation only when they ask for it or have just changed it, and\n * never while scrolling or as the page redraws.\n *\n * A change is a different value where the panel is looking: the same block,\n * target, state and device. Selecting another block, or switching the device,\n * the state or what the panel edits (the block or one of its shared styles),\n * shows another value without anyone changing one, so it plays nothing.\n *\n * @module appear-play\n */\nimport type { BreakpointId, StyleState } from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport { Play } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { playAppear } from \"../../canvas/appear-replay\";\nimport { useCanvasFrame } from \"../../canvas/canvas-frame-context\";\nimport type { EditorState } from \"../../editor-state\";\nimport { readStyleValue } from \"../../styles/style-values\";\n\nimport { StyleTargetContext } from \"./style-field-surroundings\";\nimport { fieldStyles, targetKey } from \"./style-field-target\";\n\n/** The style property the button plays. */\nexport const APPEAR_PROPERTY = \"appear\";\n\n/**\n * Calls `play` when `value` changes while `where` stays the same; never on\n * the first render, nor when `where` moves.\n */\nfunction usePlayOnChange(where: string, value: string, play: () => void): void {\n  const last = React.useRef({ where, value });\n  React.useEffect(() => {\n    const before = last.current;\n    last.current = { where, value };\n    if (before.where === where && before.value !== value) play();\n  }, [where, value, play]);\n}\n\n/**\n * The Play button for the animation of block `nodeId`, which also plays the\n * animation once each time the value the panel shows for it changes.\n */\nexport function AppearPlay({\n  nodeId,\n  state,\n  breakpoint,\n  editor,\n}: {\n  nodeId: string;\n  state: StyleState;\n  breakpoint: BreakpointId;\n  editor: EditorState;\n}): React.JSX.Element {\n  const canvas = useCanvasFrame().document;\n  const target = React.useContext(StyleTargetContext);\n  const value = readStyleValue(fieldStyles(target, editor, nodeId).styles, {\n    state,\n    breakpoint,\n    property: APPEAR_PROPERTY,\n    path: [],\n  });\n  const play = React.useCallback(() => {\n    if (canvas !== null) playAppear(canvas, nodeId);\n  }, [canvas, nodeId]);\n  usePlayOnChange(\n    [nodeId, targetKey(target), state, breakpoint].join(\"\\u0000\"),\n    JSON.stringify(value ?? null),\n    play\n  );\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"sm\"\n      className=\"nx-style-inspector__play\"\n      onClick={play}\n    >\n      <Play size={14} aria-hidden=\"true\" />\n      Play\n    </Button>\n  );\n}\n","/**\n * The words a block gives one of its Style properties' fields, where the\n * catalog's are wrong for what the block draws. A Divider draws one line,\n * which is its top border: \"Top\", \"Bottom\", \"Left\", \"Right\", \"Style\" and\n * \"Colour\" name a box it does not have. It names its own fields (Thickness,\n * Line style, Line colour), draws only those, and says where the line comes\n * from. What is stored, and where, is the catalog's as ever.\n *\n * @module block-style-words\n */\nimport type { StyleControl } from \"../../styles/style-controls\";\n\nimport type { InspectedStyleProperty } from \"./style-inspector\";\n\n/** A block's words for one Style property. */\nexport interface PropertyWords {\n  /** Each field's label, by its path (`width.blockStart`). */\n  readonly labels: Readonly<Record<string, string>>;\n  /** The fields drawn, by path, in this order; the rest are left out. */\n  readonly fields: readonly string[];\n  /** A line under the property, saying what it is on this block. */\n  readonly hint?: string;\n}\n\n/** The blocks that word a property their own way, by block and property. */\nconst BLOCK_STYLE_WORDS: Readonly<\n  Record<string, Readonly<Record<string, PropertyWords>>>\n> = {\n  \"core/divider\": {\n    border: {\n      labels: {\n        color: \"Line colour\",\n        \"width.blockStart\": \"Thickness\",\n        style: \"Line style\",\n      },\n      fields: [\"color\", \"width.blockStart\", \"style\"],\n      hint: \"The divider's line is its top border.\",\n    },\n  },\n};\n\n/** A block's words for a property, or none where the catalog's stand. */\nexport function propertyWordsFor(\n  blockType: string | undefined,\n  property: string\n): PropertyWords | undefined {\n  return blockType === undefined\n    ? undefined\n    : BLOCK_STYLE_WORDS[blockType]?.[property];\n}\n\n/**\n * The property with only the fields the block's words draw, in their order;\n * a field holding a value here stays, so a value set any other way can still\n * be seen and cleared.\n */\nexport function wordedProperty(\n  property: InspectedStyleProperty,\n  words: PropertyWords | undefined\n): InspectedStyleProperty {\n  if (words === undefined) return property;\n  const at = (control: StyleControl) => control.path.join(\".\");\n  const named = words.fields.flatMap(path =>\n    property.controls.filter(control => at(control) === path)\n  );\n  const held = property.controls.filter(\n    control =>\n      !words.fields.includes(at(control)) &&\n      valueAt(property.value, control.path) !== undefined\n  );\n  return { ...property, controls: [...named, ...held] };\n}\n\n/** What a stored value holds at a path, or none. */\nfunction valueAt(value: unknown, path: readonly string[]): unknown {\n  let here = value;\n  for (const key of path) {\n    if (\n      typeof here !== \"object\" ||\n      here === null ||\n      !Object.hasOwn(here, key)\n    ) {\n      return undefined;\n    }\n    here = (here as Record<string, unknown>)[key];\n  }\n  return here;\n}\n","/**\n * Where a block's default value comes from when it is one of the site's own\n * settings: a Section's padding, which reads the site's section spacing\n * variables (its Normal pair, or its Compact or Roomy one), says \"Site\n * default: Section spacing\" rather than \"From block defaults\".\n *\n * @module site-default-source\n */\nimport {\n  tokenCustomProperty,\n  type StyleOrigin,\n  type StyleTraceEntry,\n} from \"@nextlyhq/blocks-engine\";\n\n/**\n * The site settings a block's defaults read, by the variable they read, in\n * the words the Style tab names them by. A Section's Compact and Roomy pairs\n * are its section spacing too, as Normal's pair is.\n */\nconst SITE_DEFAULTS: Readonly<Record<string, string>> = {\n  \"space.section-y\": \"Section spacing\",\n  \"space.gutter\": \"Section spacing\",\n  \"space.section-y-compact\": \"Section spacing\",\n  \"space.gutter-compact\": \"Section spacing\",\n  \"space.section-y-roomy\": \"Section spacing\",\n  \"space.gutter-roomy\": \"Section spacing\",\n};\n\n/** The variable a written value reads whole, `var(--site-space-gutter)`. */\nexport function variableRead(\n  value: string,\n  tokenPrefix: string\n): string | undefined {\n  const match = /^var\\((--[a-z0-9-]+)\\)$/.exec(value.trim());\n  if (match === null) return undefined;\n  const property = match[1] ?? \"\";\n  if (!property.startsWith(tokenPrefix)) return undefined;\n  // A token name is dotted where its custom property is dashed, so the name\n  // is found by reading the property back from each candidate.\n  return Object.keys(SITE_DEFAULTS).find(\n    name => tokenCustomProperty(name, tokenPrefix) === property\n  );\n}\n\n/**\n * The site setting a value comes from, as the Style tab names it (\"Site\n * default: Section spacing\"), or `undefined` for a value that is not a\n * block's default reading one.\n *\n * @param origin - the tier the value was written by\n * @param entry - the declaration as the compiler wrote it\n * @param tokenPrefix - the prefix the compile wrote variables under\n */\nexport function siteDefaultSource(\n  origin: StyleOrigin,\n  entry: StyleTraceEntry,\n  tokenPrefix: string\n): string | undefined {\n  if (origin.kind !== \"blockType\" || origin.part !== undefined) {\n    return undefined;\n  }\n  const name = variableRead(entry.value, tokenPrefix);\n  return name === undefined\n    ? undefined\n    : `Site default: ${SITE_DEFAULTS[name]}`;\n}\n","/**\n * The spacing box: margin and padding drawn as one box in the Style tab.\n * Which properties form it, and the keyboard half of its sides.\n *\n * A side resets by key rather than by Tab: its reset is out of the Tab order,\n * so typing round the box goes side to side, and Alt+Backspace in the side\n * does what its reset does. The key, the reset leaving the Tab order and the\n * side's description of the key are all decided from one question, whether\n * the field is drawn inside the spacing box, so they cannot disagree.\n *\n * @module spacing-box\n */\n\nimport type { StyleValue } from \"@nextlyhq/blocks-engine\";\nimport { detectApplePlatform } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { spokenKeyHint } from \"../../shell/key-hint\";\nimport type { SideOrientation } from \"../../styles/side-orientation\";\nimport { sideBoxFor } from \"../../styles/style-sides\";\n\nimport type { InspectedStyleProperty } from \"./style-inspector\";\n\n/** Margin and padding drawn as one box, and what the section shows besides. */\ninterface SpacingRings {\n  readonly margin: InspectedStyleProperty | undefined;\n  readonly padding: InspectedStyleProperty;\n  readonly rest: readonly InspectedStyleProperty[];\n}\n\n/**\n * Whether the spacing section draws its box model, and from which properties.\n *\n * Drawn when padding is shown, offered and drawn as a box, which needs the\n * element's axes; margin joins as the outer ring under the same conditions.\n * Anything else the section shows is drawn as before, beneath the box.\n */\nexport function spacingRings(\n  shown: readonly InspectedStyleProperty[],\n  orientation: SideOrientation | undefined\n): SpacingRings | undefined {\n  const ring = (key: string) =>\n    shown.find(\n      property =>\n        property.property === key &&\n        property.offered &&\n        sideBoxFor(property.controls, orientation).boxed\n    );\n  const padding = ring(\"padding\");\n  if (padding === undefined) return undefined;\n  const margin = ring(\"margin\");\n  return {\n    margin,\n    padding,\n    rest: shown.filter(property => property !== padding && property !== margin),\n  };\n}\n\n/**\n * Fields drawn compact: the spacing box's sides, which take a value typed\n * with its unit, show no unit menu, say \"–\" while unset rather than a hint\n * there is no room for, and reset by key.\n */\nexport const CompactSides: React.Context<boolean> = React.createContext(false);\n\n/**\n * The id of a spacing-box side's description, which names its reset key: one\n * spelling for the field that writes it and the input that reads it.\n */\nfunction sideKeysId(fieldId: string): string {\n  return `${fieldId}-keys`;\n}\n\n/** The side a field draws, when it is drawn inside the spacing box. */\nfunction spacingBoxSide(\n  side: string | undefined,\n  inSpacingBox: boolean\n): string | undefined {\n  return inSpacingBox ? side : undefined;\n}\n\n/**\n * The key handler of a spacing-box side, which resets by key rather than by\n * Tab: its reset is out of the Tab order, so typing round the box goes side\n * to side, and Alt+Backspace in the side does what the reset does when there\n * is a value here to reset. Named in the side's description. `undefined` for\n * a field that is not a side.\n */\nfunction sideResetKeyDown(\n  side: string | undefined,\n  stored: StyleValue | undefined,\n  readOnly: boolean,\n  reset: () => void\n): ((event: React.KeyboardEvent<HTMLDivElement>) => void) | undefined {\n  if (side === undefined) return undefined;\n  const resettable = stored !== undefined && !readOnly;\n  return event => {\n    if (!resettable || !isResetKey(event)) return;\n    // From this field only. React carries a key press out of a portal to the\n    // component that opened it, so Alt+Backspace (delete a word) in the\n    // variables list's search would otherwise reset the side behind it.\n    if (!event.currentTarget.contains(event.target as Node)) return;\n    // Taken from the field, where Alt+Backspace would otherwise delete the\n    // word before the caret: here it is the side's reset.\n    event.preventDefault();\n    reset();\n  };\n}\n\n/**\n * A spacing-box side's description, which its input names: how to reset it\n * from the keyboard now that its reset is not a Tab stop. Hidden, so it is\n * read as the side's description and not again, between the fields, by a\n * screen reader reading the panel through. Nothing for a field that is not a\n * side.\n */\nfunction SideResetKeys({\n  side,\n  fieldId,\n}: {\n  side: string | undefined;\n  fieldId: string;\n}): React.JSX.Element | null {\n  /*\n   * The key in words as this keyboard names it (Option+Delete on Apple,\n   * Alt+Backspace elsewhere): spoken text, where glyphs are skipped. Resolved after mounting:\n   * a server render has no platform to ask, and a hint naming the wrong key\n   * is worse than none for the moment before it is known.\n   */\n  const [apple, setApple] = React.useState<boolean | null>(null);\n  React.useEffect(() => {\n    setApple(detectApplePlatform());\n  }, []);\n  if (side === undefined) return null;\n  const keys = apple === null ? null : spokenKeyHint(RESET_KEYS, apple);\n  return (\n    <span id={sideKeysId(fieldId)} hidden>\n      {keys === null ? null : `${keys} resets this side.`}\n    </span>\n  );\n}\n\n/** A side's reset key, as the shortcut grammar spells it. */\nconst RESET_KEYS = \"alt+Backspace\";\n\n/** Alt+Backspace and no other modifier: a side's reset key. */\nfunction isResetKey(event: React.KeyboardEvent): boolean {\n  return (\n    event.key === \"Backspace\" &&\n    event.altKey &&\n    !event.ctrlKey &&\n    !event.metaKey &&\n    !event.shiftKey\n  );\n}\n\n/**\n * What a value field is described by: the refusal of what was typed, if any,\n * and for a side of the spacing box its reset key as well.\n */\nexport function fieldDescribedBy(\n  refusal: string | undefined,\n  side: boolean,\n  fieldId: string\n): string | undefined {\n  const ids = side ? [refusal, sideKeysId(fieldId)] : [refusal];\n  const joined = ids.filter(id => id !== undefined).join(\" \");\n  return joined === \"\" ? undefined : joined;\n}\n\n/**\n * A field's side-of-the-spacing-box keys, in one: its key handler, whether its\n * reset leaves the Tab order, and the description naming the key. Decided\n * once, from whether the field is drawn in the spacing box, so the three\n * agree; a side box drawn on its own keeps a reset to Tab to.\n */\nexport function sideKeysFor(\n  side: string | undefined,\n  /** Whether the field is drawn in the spacing box: {@link CompactSides}. */\n  inSpacingBox: boolean,\n  stored: StyleValue | undefined,\n  readOnly: boolean,\n  fieldId: string,\n  /** The field's write, which a reset calls with `null`. */\n  commit: (value: null) => unknown\n): {\n  onKeyDown: ((event: React.KeyboardEvent<HTMLDivElement>) => void) | undefined;\n  resetByKey: boolean;\n  hint: React.JSX.Element | null;\n} {\n  const boxSide = spacingBoxSide(side, inSpacingBox);\n  return {\n    onKeyDown: sideResetKeyDown(boxSide, stored, readOnly, () => commit(null)),\n    resetByKey: boxSide !== undefined,\n    hint: <SideResetKeys side={boxSide} fieldId={fieldId} />,\n  };\n}\n","/**\n * How fast the canvas scrolls while a drag rests near its edge.\n *\n * A page is taller than the canvas shows, and a drag can only drop where it can\n * point. Without this, a block cannot be moved to anywhere outside the visible\n * band at all — not slowly, not awkwardly, not at all — because the position it\n * would be dropped at never comes on screen. Every drag surface solves it the\n * same way, and the part worth getting right is the SPEED CURVE rather than the\n * plumbing.\n *\n * **Proportional, not constant.** A fixed speed forces a choice between one that\n * is too slow to cross a long page and one that overshoots a target near the\n * edge. Ramping from nothing at the band's inner boundary to full speed at the\n * rim gives both: the author controls the rate by how far in they push, so a\n * long haul and a one-line nudge are the same gesture at different depths.\n *\n * **Pure, and in client coordinates.** No DOM, no timers, no element. The caller\n * owns the frame loop and the scrolling; this decides only how far this frame\n * should move. That split is what lets the curve be asserted at sizes and\n * positions a jsdom test cannot produce, since every rectangle there is zero.\n *\n * @module autoscroll\n */\n\n/** How deep the band at each edge reaches, in CSS pixels. */\nexport const AUTOSCROLL_ZONE_PX = 64;\n\n/**\n * The most one frame may scroll, in CSS pixels.\n *\n * At 60fps this is a little over 1,000px per second at the rim — brisk enough to\n * cross a long page without waiting, and slow enough that releasing within a few\n * frames of the intended block is still accurate.\n */\nexport const AUTOSCROLL_MAX_STEP_PX = 18;\n\n/**\n * How far the canvas should scroll this frame, in CSS pixels.\n *\n * Negative scrolls towards the top of the document, positive towards the bottom,\n * and `0` means the pointer is in the middle where nothing should move.\n *\n * **Past the edge behaves like the edge.** A drag captures the pointer, so it\n * goes on reporting positions after it has left the container entirely. Those\n * arrive as coordinates beyond `top` or `bottom`, and letting them scale would\n * make the speed depend on how far outside the window the author's hand happens\n * to be — unbounded, and not a distance they can judge. Clamped, leaving the\n * container simply means \"as fast as this goes\".\n *\n * **A short container cannot scroll both ways at once.** When the two bands\n * would overlap — a canvas less than twice the band deep — the effective band\n * shrinks to half the height, so the midpoint stays a place where nothing moves.\n * Without that, the same pointer sits inside both bands and whichever is tested\n * first wins, which reads as a canvas that scrolls in whichever direction the\n * code happened to check.\n *\n * @param pointerY - the pointer's client Y\n * @param top - the container's client top edge\n * @param bottom - the container's client bottom edge\n * @param zone - how deep the band reaches from each edge\n * @param maxStep - the speed at the rim\n * @returns pixels to scroll this frame; negative is up\n */\nexport function autoscrollStep(\n  pointerY: number,\n  top: number,\n  bottom: number,\n  zone: number = AUTOSCROLL_ZONE_PX,\n  maxStep: number = AUTOSCROLL_MAX_STEP_PX\n): number {\n  const height = bottom - top;\n  // A container with no height has no inside, so no position within it can be\n  // near an edge. Returning 0 rather than dividing by it.\n  if (height <= 0 || zone <= 0 || maxStep <= 0) return 0;\n\n  const band = Math.min(zone, height / 2);\n\n  const intoTop = top + band - pointerY;\n  if (intoTop > 0) return -ramp(intoTop, band, maxStep);\n\n  const intoBottom = pointerY - (bottom - band);\n  if (intoBottom > 0) return ramp(intoBottom, band, maxStep);\n\n  return 0;\n}\n\n/**\n * The speed at a given depth into a band: linear, and never past `maxStep`.\n *\n * Linear rather than eased, because the author is aiming rather than watching an\n * animation — a curve that accelerates makes the same hand movement mean\n * different things at different depths, which is the opposite of controllable.\n */\nfunction ramp(depth: number, band: number, maxStep: number): number {\n  return Math.min(depth / band, 1) * maxStep;\n}\n","/**\n * What a canvas drag hands its callers: the thresholds, the subject in flight,\n * the state the canvas draws, the handlers it carries, and the options the hook\n * takes. `useCanvasDrag` in `canvas-drag.tsx` answers in these, and that module\n * still exports every one of them.\n *\n * @module canvas-drag-types\n */\n\nimport type {\n  BlockNode,\n  ComponentLookup,\n  NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport type * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { LockDropRefusal } from \"../lock-refusal\";\nimport type { SlotSource } from \"../panels/add/inserter\";\n\nimport type { DropRefusal, DropTarget } from \"./drop-targets\";\n\n/**\n * How far the pointer travels before a press becomes a drag.\n *\n * Large enough that the hand-shake in a deliberate click never reaches it, small\n * enough that a short drag still starts. The same order as the field's other\n * editors; the exact figure is not load-bearing, because the threshold only has\n * to separate a click from an intent to move.\n */\nexport const DEFAULT_ACTIVATION_PX = 4;\n\n/**\n * How far a rival target must be held before it replaces the committed one.\n *\n * Measured as pointer TRAVEL rather than as a property of the blocks, which is\n * the whole reason this canvas can have hysteresis at all: `core/spacer` takes\n * its height from an author-set prop with no lower bound and `core/divider`\n * renders one pixel tall, so any rule keyed on a block's size makes some\n * authored block impossible to drop beside. Travel is a property of the gesture\n * and treats a 1px divider and a 900px hero identically.\n */\nexport const DEFAULT_SWITCH_PX = 8;\n\n/**\n * What a drag is carrying: a node the document already holds, or a block type\n * that has no node yet.\n *\n * The two differ in exactly two places — whether anything is being detached,\n * and what the release commits — and are identical everywhere between. Holding\n * that as a payload rather than a second hook is what makes \"one engine\"\n * checkable rather than aspirational: `resolveDrop`, the switch rule,\n * autoscroll and the indicator cannot tell the kinds apart, because they are\n * never given the chance to.\n *\n * An insert builds its node from a THUNK the caller supplies rather than\n * resolving the type here. The palette reads its definitions from one snapshot\n * per mount and a block arrives with the children it declares, so resolving\n * again at drop would answer from a second reading — and the row the author\n * dragged could differ from the subtree that lands.\n */\nexport type DragSubject =\n  | { readonly kind: \"move\"; readonly nodeId: string }\n  | {\n      readonly kind: \"insert\";\n      readonly blockName: string;\n      readonly makeNode: () => BlockNode | null;\n      /**\n       * Notified with the node that landed, after a drop the editor accepted.\n       *\n       * Carried on the subject so the two ways a palette inserts report the\n       * same event. The panel already tells its host about a click insert, and\n       * a host reacting to that — scrolling to the block, opening its settings\n       * — would silently miss every insert made by dragging.\n       */\n      readonly onInserted?: (node: BlockNode) => void;\n    };\n\n/**\n * What a palette hands the drag when a row is pressed.\n *\n * Named rather than written inline at both the type and the implementation:\n * the two used to state it separately, and adding a field to one left the\n * other rejecting it.\n */\nexport interface InsertDragEntry {\n  /** The block type in flight, which the drop position is resolved for. */\n  blockName: string;\n  /** Builds the node at the release, from the palette's own snapshot. */\n  makeNode: () => BlockNode | null;\n  /** Notified with the node that landed, after a drop the editor accepted. */\n  onInserted?: (node: BlockNode) => void;\n}\n\n/** What a drag is doing right now, for the canvas to draw. */\nexport interface CanvasDragState {\n  /**\n   * The node being dragged, or null when no MOVE-drag is in flight.\n   *\n   * Null for the whole of an insert-drag as well as between drags: the block\n   * has no node until the release makes one, and minting an id early to fill\n   * this would hand the canvas an id addressing nothing in the document.\n   */\n  readonly draggingId: string | null;\n  /**\n   * The block type in flight, whichever kind of drag it is, or null when none\n   * is.\n   *\n   * This is the field to ask \"is a drag happening\", because it is the only one\n   * that does not assume the subject has a node. Anything gated on the id\n   * instead is blind to a drag from the palette.\n   */\n  readonly draggingBlockName: string | null;\n  /** Where a drop would land, or null when nowhere would accept it. */\n  readonly target: DropTarget | null;\n  /**\n   * Why the region under the pointer will not take the block, or null.\n   *\n   * Distinct from a null target: the author has aimed at something, and saying\n   * nothing tells them the editor did not notice.\n   */\n  readonly refusal: DropRefusal | LockDropRefusal | null;\n}\n\n/** The handlers the canvas root must carry for a drag to work. */\nexport interface CanvasDragHandlers {\n  readonly onPointerDown: React.PointerEventHandler<HTMLElement>;\n  readonly onPointerMove: React.PointerEventHandler<HTMLElement>;\n  readonly onPointerUp: React.PointerEventHandler<HTMLElement>;\n  readonly onPointerCancel: React.PointerEventHandler<HTMLElement>;\n}\n\nexport interface CanvasDrag extends CanvasDragState {\n  readonly handlers: CanvasDragHandlers;\n  /**\n   * Begin a drag whose subject is not in the document yet.\n   *\n   * Called from a PALETTE row's own `onPointerDown`, which is why it cannot be\n   * {@link CanvasDragHandlers.onPointerDown}: that one takes the canvas root\n   * from `event.currentTarget`, and for a press on a palette row the current\n   * target is the row.\n   *\n   * Does nothing when no canvas root was supplied, which leaves the press\n   * exactly as it was — the row's click still inserts, and that click is the\n   * non-drag route WCAG 2.2 SC 2.5.7 requires. This only ever supplements it.\n   */\n  readonly beginInsertDrag: (\n    event: React.PointerEvent<HTMLElement>,\n    entry: InsertDragEntry\n  ) => void;\n}\n\nexport interface UseCanvasDragOptions {\n  /** The editor whose document a drop edits. */\n  editor: EditorState;\n  /** Which child regions each block type declares. */\n  slots: SlotSource;\n  /** The nesting rule, asked before any position is offered. */\n  nesting: NestingSource;\n  /**\n   * The definitions the canvas draws instances from, so a MOVED instance is\n   * judged by the roots of the definition it draws rather than by its own\n   * type, which the nesting rule cannot restrict. Absent, an instance moves\n   * anywhere — the posture of a host that resolves nothing.\n   */\n  definitions?: ComponentLookup;\n  /**\n   * The canvas root, for a drag that begins outside it.\n   *\n   * Optional, and its absence means only that {@link CanvasDrag.beginInsertDrag}\n   * does nothing: a host that never drags from a palette has no use for the\n   * ref, and requiring it would make every existing caller supply a value to\n   * satisfy a feature it does not mount.\n   */\n  canvasRoot?: React.RefObject<HTMLElement | null>;\n  activationPx?: number;\n  switchPx?: number;\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","\"use client\";\n\n/**\n * Dragging a block on the canvas: the pointer, and the line that answers it.\n *\n * Decides nothing about WHERE a block may land — {@link resolveDrop} does that,\n * and {@link nextTargetSwitchState} decides when the answer is allowed to\n * change. This module is the seam between those rules and a browser: it reads\n * rectangles, tracks a gesture, and draws.\n *\n * ## Drag is an enhancement, never the only way\n *\n * WCAG 2.2 SC 2.5.7 requires any function operated by dragging to be reachable\n * without dragging, and SC 2.1.1 requires keyboard operability. Both are already\n * satisfied before this file exists: a block is selected by clicking and moved\n * with `alt+Arrow`, and each move is announced. So nothing here is a sole route\n * to anything, and nothing here announces — `keyboard-actions` owns the one\n * live region, and a second one would read one author's action twice.\n *\n * ## A press is not a drag\n *\n * The pointer must travel {@link DEFAULT_ACTIVATION_PX} before a press becomes a\n * drag. Without that threshold every click on a block is a zero-length drag that\n * commits a move to the position it already occupies, and the undo history fills\n * with edits the author never made.\n *\n * ## Rectangles are measured ONCE, when the drag begins\n *\n * The document cannot change mid-drag — this is the only gesture in flight — and\n * blocks do not move out of the way as the pointer passes, so the layout that\n * was measured is the layout the whole gesture sees. Re-reading every\n * `getBoundingClientRect` on each pointer move would force a reflow per frame to\n * learn nothing.\n *\n * They are stored in the canvas's own CONTENT coordinates — viewport rectangle\n * minus the root's, plus the root's scroll — so the snapshot survives the page\n * scrolling under it, and an indicator positioned absolutely inside the root\n * lands where the rectangles say. **Not** handled: content that reflows during a\n * drag, such as a lazily-loaded image resizing above the pointer.\n *\n * ## Where the parts live\n *\n * This module is the hook, `useCanvasDrag`, and the entry for the rest: the\n * shapes it hands its callers are in `canvas-drag-types.ts`, one gesture's\n * record and the questions asked of it in `canvas-drag-gesture.ts`, and the\n * drop line in `drop-indicator.tsx`. Every name it exported, it still exports.\n *\n * @module canvas-drag\n */\n\nimport { findNode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { layersLockFacts } from \"../lock-refusal\";\nimport { lockBlockingMove } from \"../locking\";\nimport type { OpPosition } from \"../op-vocabulary\";\nimport { placementTypesOf } from \"../panels/add/inserter\";\n\nimport { numberedForPlace } from \"./accordion-questions\";\nimport {\n  AUTOSCROLL_MAX_STEP_PX,\n  AUTOSCROLL_ZONE_PX,\n  autoscrollStep,\n} from \"./autoscroll\";\nimport { nodeIdFromEvent } from \"./canvas\";\nimport {\n  admitsPress,\n  builtOnce,\n  canvasClientPoint,\n  committedTarget,\n  drawnSubject,\n  frameLoopOf,\n  type Gesture,\n  gestureOwnedBy,\n  handScaleOf,\n  type HeldPress,\n  listenOn,\n  releaseCapture,\n  slotsOfNode,\n  snapshotRects,\n  withLockVerdict,\n} from \"./canvas-drag-gesture\";\nimport {\n  type CanvasDrag,\n  type CanvasDragState,\n  DEFAULT_ACTIVATION_PX,\n  DEFAULT_SWITCH_PX,\n  type DragSubject,\n  type InsertDragEntry,\n  type UseCanvasDragOptions,\n} from \"./canvas-drag-types\";\nimport {\n  inputDocuments,\n  useCanvasFrame,\n  type CanvasFrame,\n} from \"./canvas-frame-context\";\nimport {\n  collectRegions,\n  movingSubtree,\n  placementSources,\n  resolveDrop,\n} from \"./drop-targets\";\nimport {\n  canvasContentPoint,\n  canvasPointerPoints,\n  canvasScroller,\n  containerEdges,\n  type CanvasPointerPoints,\n} from \"./geometry-dom\";\nimport { nextTargetSwitchState, NO_TARGET } from \"./target-switch\";\n\n// The public shapes, one gesture's record and the drop line live in modules of\n// their own beside this hook; every name this module exported still is.\nexport {\n  type CanvasDrag,\n  type CanvasDragHandlers,\n  type CanvasDragState,\n  DEFAULT_ACTIVATION_PX,\n  DEFAULT_SWITCH_PX,\n  type DragSubject,\n  type InsertDragEntry,\n  type UseCanvasDragOptions,\n} from \"./canvas-drag-types\";\nexport { DropIndicator, type DropIndicatorProps } from \"./drop-indicator\";\n\n/**\n * Wire pointer events on the canvas root to the drop rules.\n *\n * Returns handlers to spread onto the root and the state to draw. The canvas\n * owns the element; this owns the gesture.\n */\nexport function useCanvasDrag({\n  editor,\n  slots,\n  nesting,\n  definitions,\n  canvasRoot,\n  activationPx = DEFAULT_ACTIVATION_PX,\n  switchPx = DEFAULT_SWITCH_PX,\n}: UseCanvasDragOptions): CanvasDrag {\n  const gesture = React.useRef<Gesture | null>(null);\n  const [state, setState] = React.useState<CanvasDragState>({\n    draggingId: null,\n    draggingBlockName: null,\n    target: null,\n    refusal: null,\n  });\n\n  // Read at event time rather than closed over, so a handler bound on one render\n  // never patches a document that a later edit has already replaced.\n  /** A press on a block a Layers lock holds in place, if one is down. */\n  const heldPress = React.useRef<HeldPress | null>(null);\n  const latest = React.useRef({ editor, slots, nesting, definitions });\n  latest.current = { editor, slots, nesting, definitions };\n\n  /*\n   * The document the canvas is in, read at event time like the rest. Every\n   * listener a drag adds outside the canvas root goes on the documents this\n   * names, because a pointer or a key inside a frame is dispatched in the\n   * frame's document and never reaches the editor's.\n   */\n  const canvasFrame = useCanvasFrame();\n  const frameRef = React.useRef<CanvasFrame>(canvasFrame);\n  frameRef.current = canvasFrame;\n\n  /**\n   * Undo the document-level listening an insert-drag needs, or nothing.\n   *\n   * Held as a closure rather than as three named handlers, because the\n   * functions to remove are the exact ones that were added — re-deriving them\n   * would remove nothing and leave the gesture listening for ever.\n   */\n  const detachDocument = React.useRef<(() => void) | null>(null);\n  const stopTrackingDocument = React.useCallback(() => {\n    detachDocument.current?.();\n    detachDocument.current = null;\n  }, []);\n\n  /** The document listeners a held press's drawn reason ends on, if any. */\n  const detachHeld = React.useRef<(() => void) | null>(null);\n\n  /** Forget the held press, and stop listening for its release. */\n  const stopHolding = React.useCallback(() => {\n    detachHeld.current?.();\n    detachHeld.current = null;\n    heldPress.current = null;\n  }, []);\n\n  /**\n   * End the gesture and release everything it holds, WITHOUT drawing.\n   *\n   * Split from {@link reset} for the one ending that cannot draw: a host\n   * unmounting mid-drag, where a `setState` would be an update to a component\n   * that no longer exists. Every other ending wants the redraw and goes through\n   * `reset`, which is this plus that.\n   *\n   * Cancelling the frame here rather than in each ending is what stops a scroll\n   * loop outliving the gesture it scrolls for: `pump` reschedules itself every\n   * frame and only stops when it finds no active gesture, so leaving\n   * `gesture.current` populated on unmount keeps it running — holding the\n   * editor and the DOM, and still scrolling a canvas whose editor has closed.\n   */\n  const teardown = React.useCallback(() => {\n    const drag = gesture.current;\n    if (drag !== null && drag.frame !== null) {\n      // Cancelled on the window that scheduled it: a handle is only meaningful\n      // to the clock that issued it.\n      frameLoopOf(drag)?.cancelAnimationFrame(drag.frame);\n    }\n    gesture.current = null;\n    // A palette drag listens on the document, and every way one can end arrives\n    // here. So does a held press's drawn reason, which Escape abandons too.\n    stopTrackingDocument();\n    stopHolding();\n  }, [stopTrackingDocument, stopHolding]);\n\n  const reset = React.useCallback(() => {\n    teardown();\n    setState({\n      draggingId: null,\n      draggingBlockName: null,\n      target: null,\n      refusal: null,\n    });\n  }, [teardown]);\n\n  /** The held press ends, and its reason with it, when its pointer lifts. */\n  const releaseHeld = React.useCallback(\n    (pointerId: number) => {\n      const press = heldPress.current;\n      if (press === null || press.owner !== pointerId) return;\n      stopHolding();\n      if (!press.shown) return;\n      setState({\n        draggingId: null,\n        draggingBlockName: null,\n        target: null,\n        refusal: null,\n      });\n    },\n    [stopHolding]\n  );\n\n  /**\n   * Follow a held press on the documents from the moment it is recorded, as a\n   * palette drag is followed: the hand may leave the canvas before or after\n   * the reason is drawn, and its release there must still end the press, or a\n   * later hover would draw the reason for a press long over. Escape ends it\n   * through `reset`.\n   */\n  const holdUntilReleased = React.useCallback(() => {\n    const lifted = (native: PointerEvent): void => {\n      releaseHeld(native.pointerId);\n    };\n    const documents = inputDocuments(frameRef.current);\n    const ups = listenOn(documents, \"pointerup\", lifted);\n    const cancels = listenOn(documents, \"pointercancel\", lifted);\n    detachHeld.current = () => {\n      ups();\n      cancels();\n    };\n  }, [releaseHeld]);\n\n  const onPointerDown = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      // The primary button only. A right-click opens a context menu and a\n      // middle-click scrolls, and starting a drag from either takes a gesture\n      // the browser has already given a meaning.\n      if (event.button !== 0) return;\n      // One drag at a time, asked through the shared rule. Ignored rather than\n      // cancelled, so the drag already in flight survives a stray touch, and\n      // the pressed element keeps its own click because nothing here consumed\n      // the press.\n      if (!admitsPress(gesture.current)) return;\n\n      const root = event.currentTarget;\n      const nodeId = nodeIdFromEvent(event.target);\n      if (nodeId === null) return;\n\n      const { editor: current } = latest.current;\n      const node = findNode(current.document.nodes, nodeId);\n      if (node === undefined) return;\n\n      // A block a Layers lock holds in place: locked itself, holding a locked\n      // block, or inside one. The press is left alone rather than swallowed,\n      // so it still selects, and is remembered so that, if the hand goes on to\n      // drag, the reason is drawn over the block rather than nothing happening.\n      //\n      // Asked through the shared rule rather than by reading the flag here, so\n      // this answers as the keyboard moves, the toolbar and Layers do.\n      const held = lockBlockingMove(current.document, nodeId);\n      // A held press still down ends with this one: its reason and its\n      // listeners go, rather than being overwritten and left listening.\n      if (heldPress.current !== null) releaseHeld(heldPress.current.owner);\n      if (held !== undefined) {\n        heldPress.current = {\n          owner: event.pointerId,\n          originClient: { x: event.clientX, y: event.clientY },\n          nodeId,\n          blockName: node.type,\n          lock: layersLockFacts(held, nodeId, \"move\"),\n          shown: false,\n        };\n        holdUntilReleased();\n        return;\n      }\n\n      const rects = snapshotRects(root);\n      gesture.current = {\n        subject: { kind: \"move\", nodeId },\n        owner: event.pointerId,\n        origin: canvasContentPoint(event.clientX, event.clientY, root),\n        originClient: { x: event.clientX, y: event.clientY },\n        regions: collectRegions(\n          current.document,\n          latest.current.slots,\n          rects,\n          slotsOfNode(placementSources(latest.current))\n        ),\n        rects,\n        forbiddenParents: movingSubtree(current.document, nodeId),\n        blockName: node.type,\n        blockNames: placementTypesOf(node, latest.current.definitions),\n        placing: () => [node],\n        placementVerdicts: new Map(),\n        active: false,\n        switchState: NO_TARGET,\n        targets: new Map(),\n        lockVerdicts: new Map(),\n        root,\n        scroller: canvasScroller(root, frameRef.current.frame !== null),\n        handScale: handScaleOf(frameRef.current),\n        clientX: event.clientX,\n        clientY: event.clientY,\n        frame: null,\n      };\n      // NOT captured here. See the activation branch in `onPointerMove`.\n    },\n    [releaseHeld, holdUntilReleased]\n  );\n\n  /**\n   * Re-aim the drag at a pointer position, and draw the result.\n   *\n   * Shared by the pointer handler and the autoscroll frame because they ask the\n   * same question at different moments: a move changes where the pointer is, and\n   * a scroll changes what is under it. Computing the answer twice is how the\n   * indicator and the committed target come apart — the frame would draw one\n   * thing and the release would apply another.\n   *\n   * Takes the pointer already MAPPED, in both spaces, rather than mapping it\n   * here. Both callers hold a rectangle of the root at the instant they aim —\n   * the move because it has just measured, the frame because it has just\n   * scrolled — and measuring again inside would answer this one drag step from\n   * two rectangles: `resolveDrop` placing the pointer among the snapshotted\n   * blocks by one, and the switch rule measuring travel by the other.\n   */\n  const aim = React.useCallback(\n    (drag: Gesture, pointer: CanvasPointerPoints) => {\n      const resolution = withLockVerdict(\n        drag,\n        latest.current.editor,\n        resolveDrop(\n          {\n            blockNames: drag.blockNames,\n            forbiddenParents: drag.forbiddenParents,\n            regions: drag.regions,\n            rects: drag.rects,\n            nesting: latest.current.nesting,\n            placement: {\n              nodes: latest.current.editor.document.nodes,\n              placing: drag.placing,\n              sources: placementSources(latest.current),\n              verdicts: drag.placementVerdicts,\n            },\n          },\n          // CONTENT coordinates: the rects were snapshotted in that space at drag\n          // start, and a scroll deliberately does not invalidate them.\n          pointer.content\n        )\n      );\n\n      if (resolution.kind === \"none\") {\n        // The pointer has left every region, which ENDS the aim rather than\n        // proposing a different one — so it is not put through the switch rule.\n        //\n        // That rule exists to stop the committed target flickering between\n        // RIVALS at a boundary, and it withholds any change until the pointer\n        // has travelled: a target lost this way would go on being drawn, and a\n        // release would commit it. Dragging a block off the canvas would then\n        // drop it back onto the page, which is the opposite of what leaving\n        // means. There are no rivals here, so there is nothing to smooth.\n        drag.switchState = NO_TARGET;\n        setState({ ...drawnSubject(drag), target: null, refusal: null });\n        return;\n      }\n\n      const candidate = resolution.kind === \"target\" ? resolution.target : null;\n      if (candidate !== null) drag.targets.set(candidate.id, candidate);\n\n      // A REFUSAL still goes through the switch rule as a null candidate. The\n      // pointer is over something, so a boundary between a region that accepts\n      // the block and one that does not is exactly the jitter the rule is for.\n      drag.switchState = nextTargetSwitchState(\n        drag.switchState,\n        candidate === null ? null : candidate.id,\n        /*\n         * PAINTED pixels relative to the canvas, which is the only space that\n         * answers both halves of this rule.\n         *\n         * The threshold is how far a HAND must move to overrule a committed\n         * target, so it cannot be measured in canvas coordinates: those are\n         * divided by the scale, and the hysteresis would loosen as the canvas\n         * zoomed out. But it cannot be measured in client coordinates either —\n         * autoscroll moves the page under a STATIONARY pointer, so the distance\n         * from the anchor would stay zero however far the page travelled, and\n         * the committed target would never advance off a position that has\n         * scrolled away.\n         *\n         * Painted coordinates are undivided, so the threshold stays about the\n         * hand, and they move with the scroll because the root's own rectangle\n         * does.\n         *\n         * The same measurement the content point above came from, so the\n         * position this rule anchors on and the position the drop was resolved\n         * at are one pointer rather than two.\n         */\n        pointer.painted,\n        switchPx\n      );\n\n      const committed = drag.switchState.committed;\n      setState({\n        ...drawnSubject(drag),\n        target:\n          committed === null ? null : (drag.targets.get(committed) ?? null),\n        // The refusal is NOT held to the threshold. It says why the region under\n        // the pointer refuses the block, and delaying that would leave the\n        // sentence describing a region the pointer has left.\n        refusal: resolution.kind === \"refused\" ? resolution.refusal : null,\n      });\n    },\n    [switchPx]\n  );\n\n  /**\n   * Scroll the canvas while the pointer rests near an edge, and keep aiming.\n   *\n   * A drag can only drop where it can point, so without this a block cannot be\n   * moved anywhere outside the visible band of a long page — the position it\n   * would land at never comes on screen.\n   *\n   * **Re-aiming is not optional.** The pointer may not move at all while this\n   * runs, and the rects were measured once at drag start in CONTENT coordinates,\n   * which scrolling deliberately does not invalidate. What changes is which of\n   * them the pointer is over, so a frame that scrolled without re-aiming would\n   * slide the page beneath a frozen indicator.\n   *\n   * The loop runs for as long as the drag does rather than starting and stopping\n   * with the band, because a pointer held still inside it produces no events to\n   * restart on.\n   */\n  const pump = React.useCallback(() => {\n    const drag = gesture.current;\n    if (drag === null || !drag.active) return;\n\n    const scroller = drag.scroller;\n    if (scroller === null) return;\n\n    // The SCROLLER's edges, not the canvas root's. The root grows to its\n    // content, so once a page is long enough to need scrolling its bottom edge\n    // is somewhere below the window and a band measured against it never\n    // contains the pointer — the case autoscroll exists for is exactly the case\n    // that would stop working.\n    const edges = containerEdges(scroller);\n    // The band and the speed are the author's pixels, carried into the canvas\n    // document's by the hand scale: in a frame painted at a quarter size, the\n    // 64-pixel band is 256 of the frame's pixels and the step four times as\n    // many of them, so both look the same on screen at every zoom.\n    const step = autoscrollStep(\n      drag.clientY,\n      edges.top,\n      edges.bottom,\n      AUTOSCROLL_ZONE_PX / drag.handScale,\n      AUTOSCROLL_MAX_STEP_PX / drag.handScale\n    );\n    if (step !== 0) {\n      const before = scroller.scrollTop;\n      scroller.scrollTop = before + step;\n      // Only when the scroll actually moved. At either end of the content the\n      // assignment is clamped to what it already was, and re-aiming then costs\n      // a full resolve per frame to arrive at the answer already on screen.\n      if (scroller.scrollTop !== before) {\n        // Measured AFTER the assignment above, which is the one thing in this\n        // module that moves the canvas: the root's rectangle has just travelled\n        // and the pointer has to be placed against where it is now.\n        aim(\n          drag,\n          canvasPointerPoints(\n            drag.clientX,\n            drag.clientY,\n            drag.root,\n            drag.handScale\n          )\n        );\n      }\n    }\n    drag.frame = frameLoopOf(drag)?.requestAnimationFrame(pump) ?? null;\n  }, [aim]);\n\n  /**\n   * Advance the gesture to a pointer position, activating it first if the\n   * pointer has now travelled far enough to mean a drag.\n   *\n   * Takes the position, the pointer and the capturing element as arguments\n   * rather than an event, because one gesture is fed from two transports:\n   * React's handlers on the canvas root for a drag that began on a block, and\n   * document-level listeners for one that began on a palette row, whose events\n   * never reach the canvas at all. Both arrive here, and nothing below can tell\n   * which did — which is the whole of what \"one engine\" buys.\n   */\n  /**\n   * A press on a held block that has travelled far enough to mean a drag: the\n   * lock's reason, drawn over the block the way a refused drop is drawn over\n   * the container that refused it. Once per press.\n   */\n  const showHeld = React.useCallback(\n    (clientX: number, clientY: number, pointerId: number) => {\n      const press = heldPress.current;\n      if (press === null || press.owner !== pointerId || press.shown) return;\n      const travelled = Math.hypot(\n        clientX - press.originClient.x,\n        clientY - press.originClient.y\n      );\n      if (travelled < activationPx) return;\n      press.shown = true;\n      setState({\n        draggingId: null,\n        draggingBlockName: press.blockName,\n        target: null,\n        refusal: {\n          regionId: `held:${press.nodeId}`,\n          parentId: press.nodeId,\n          lock: press.lock,\n        },\n      });\n    },\n    [activationPx]\n  );\n\n  const trackMove = React.useCallback(\n    (\n      clientX: number,\n      clientY: number,\n      pointerId: number,\n      captureHost: HTMLElement | null\n    ) => {\n      const drag = gestureOwnedBy(gesture.current, pointerId);\n      // Null for no gesture at all, and for another finger moving anywhere:\n      // neither may re-aim this one.\n      if (drag === null) return;\n\n      /*\n       * ONE measurement of the root, answering this move in both spaces.\n       *\n       * Against `drag.root`, not `event.currentTarget`: the rects were\n       * snapshotted against the element the press landed on, and the frame loop\n       * re-aims against it too, so that is the element this pointer has to be\n       * expressed relative to. Capture makes the two the same element for the\n       * whole of a drag, which is why reading either used to work.\n       *\n       * The pair stays true for the rest of this handler because nothing below\n       * moves the canvas: the assignments are bookkeeping, `setPointerCapture`\n       * retargets events rather than laying anything out, `requestAnimationFrame`\n       * only schedules, and `select` and the draw inside `aim` are React state\n       * that flushes after this returns. The one thing that DOES move layout is\n       * `pump`'s scroll, and it runs in a frame callback of its own, so it\n       * cannot land between this read and the aim below. Anything added here\n       * that scrolls, resizes or writes a style invalidates the pair and has to\n       * measure again.\n       */\n      const pointer = canvasPointerPoints(\n        clientX,\n        clientY,\n        drag.root,\n        drag.handScale\n      );\n      // Recorded for the frame loop, which runs between moves and has no event\n      // of its own to read a position from.\n      drag.clientX = clientX;\n      drag.clientY = clientY;\n\n      if (!drag.active) {\n        // CLIENT pixels: the threshold separates a click from an intent to\n        // move, which is a property of the hand rather than of the canvas's\n        // scale. Measured in content pixels it shrinks with the canvas.\n        const travelled =\n          Math.hypot(\n            clientX - drag.originClient.x,\n            clientY - drag.originClient.y\n          ) * drag.handScale;\n        if (travelled < activationPx) return;\n        drag.active = true;\n        /*\n         * Capture the pointer HERE rather than on the press, so that a press\n         * which stays a click never captures at all.\n         *\n         * Capture retargets every later pointer event to the capturing element,\n         * and the browser derives a `click`'s target from where the press and\n         * the release landed — so capturing on `pointerdown` makes every click\n         * on the canvas report the CANVAS ROOT as its target. The canvas\n         * resolves a click by walking up from the target to the nearest block,\n         * finds none above the root, and reads that as \"the author clicked the\n         * background\": selecting a block by clicking it cleared the selection\n         * instead.\n         *\n         * A drag needs capture because it may leave the canvas and must keep\n         * receiving moves. A click does not, and until the pointer has travelled\n         * far enough there is no way to tell which one this is — so the capture\n         * waits for the answer.\n         */\n        //\n        // Only when there IS a host to capture on. A drag from the palette is\n        // followed on the document instead, and must NOT capture: the browser\n        // derives a click's target from the capturing element, so capturing on\n        // a palette row would report a click on that row wherever the author\n        // released — and the row inserts on click.\n        captureHost?.setPointerCapture(pointerId);\n        // Started once, at activation. A press that stays a click never scrolls.\n        drag.frame = frameLoopOf(drag)?.requestAnimationFrame(pump) ?? null;\n        // Selecting on activation rather than on press: a press that turns out\n        // to be a click is handled by the canvas's own click handler, and\n        // selecting here as well would run the same decision twice.\n        //\n        // Only a move has something to select. An insert's node does not exist\n        // until the release commits it, and it is selected there instead.\n        if (drag.subject.kind === \"move\") {\n          latest.current.editor.select(drag.subject.nodeId);\n        }\n      }\n\n      aim(drag, pointer);\n    },\n    [activationPx, aim, pump]\n  );\n\n  const onPointerMove = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      showHeld(event.clientX, event.clientY, event.pointerId);\n      trackMove(\n        event.clientX,\n        event.clientY,\n        event.pointerId,\n        event.currentTarget\n      );\n    },\n    [showHeld, trackMove]\n  );\n\n  /**\n   * Write the drop, and it is the ONE place the two subjects diverge.\n   *\n   * Everything that decided WHERE — `resolveDrop`, the switch rule, autoscroll,\n   * the indicator — ran without being told which kind this was. That is the\n   * testable content of the claim that the palette and the canvas share an\n   * engine: a second implementation would have to reach this same call, and a\n   * fork announces itself by not doing so.\n   *\n   * Exactly ONE op either way, applied at the release. Materialising a node at\n   * drag-start and moving it instead would leave two entries on the undo stack\n   * and put a block into the document mid-gesture, where every autosave and\n   * unsaved-work signal reads a document reference that changed.\n   */\n  const commitDrop = React.useCallback(\n    (subject: DragSubject, at: OpPosition) => {\n      const { editor: current } = latest.current;\n      if (subject.kind === \"move\") {\n        // Whether the PAGE still composes with the node there — an instance\n        // carried ahead of another takes the budget that one had — is the\n        // editor's own apply's to refuse, and to say why; a null here is that\n        // refusal.\n        current.apply({ kind: \"move\", id: subject.nodeId, to: at });\n        return;\n      }\n\n      // From the caller's own snapshot of the palette, built once per gesture:\n      // the same node the locks were asked about while the pointer aimed.\n      const made = subject.makeNode();\n      if (made === null) return;\n      // A Question dropped into an Accordion takes the next number there.\n      const node = numberedForPlace(made, at, current.document);\n      // The position and the nesting verdict were both computed for the type\n      // the gesture ADVERTISED. A node of some other type was never asked\n      // about, so inserting it here would place a block into a parent or slot\n      // that may forbid it — and the op layer checks structural shape, not the\n      // nesting rule, so nothing downstream would catch it.\n      //\n      // Declined rather than re-resolved: the target was chosen for a different\n      // block, so there is no position here that was ever offered for this one.\n      if (node.type !== subject.blockName) return;\n      // `apply` answers null when the op is refused, and a refusal must not be\n      // followed by a select: the panel offers only placements the rule\n      // permits, so a null here means the document moved under the gesture.\n      if (current.apply({ kind: \"insert\", node, at }) === null) return;\n      // Selecting what was just added is what makes a SECOND insert land after\n      // it rather than stacking at one point — the same rule the panel's click\n      // path states. It holds because `apply` publishes the document the next\n      // `select` resolves against before it returns.\n      current.select(node.id);\n      // After the select, so a host reacting to this sees the editor in the\n      // state the click path leaves it in — the same event, whichever way the\n      // block arrived.\n      subject.onInserted?.(node);\n    },\n    []\n  );\n\n  /**\n   * Detaches whatever click suppression is armed, or null when none is.\n   *\n   * Held in a ref rather than left to each closure so that only ONE can be\n   * armed: a second arming replaces the first instead of stacking listeners\n   * that would each swallow a click.\n   */\n  const detachClickSwallow = React.useRef<(() => void) | null>(null);\n\n  const stopSwallowingClick = React.useCallback(() => {\n    detachClickSwallow.current?.();\n    detachClickSwallow.current = null;\n  }, []);\n\n  /**\n   * Swallow the click the browser synthesises after an activated palette drag.\n   *\n   * A palette row inserts on click and must go on doing so — that click is the\n   * non-drag route. But a drag that begins and ends on the same row is still a\n   * press and a release on one element, so a click is reported, and the row\n   * would insert a SECOND block at the panel's own position beside the one the\n   * drop just committed.\n   *\n   * Registered for one event in the capture phase, and removed whether or not\n   * it fires: a drag released over the canvas produces no click on the row at\n   * all, and a listener left waiting would eat the author's next unrelated\n   * click. The release and its click belong to one task, so anything still\n   * listening a task later was never going to fire.\n   */\n  const swallowNextClick = React.useCallback(() => {\n    stopSwallowingClick();\n    let unlisten = (): void => {};\n    const stop = (): void => {\n      unlisten();\n      detachClickSwallow.current = null;\n    };\n    const swallow = (event: MouseEvent): void => {\n      event.preventDefault();\n      event.stopPropagation();\n      stop();\n    };\n    unlisten = listenOn(inputDocuments(frameRef.current), \"click\", swallow);\n    setTimeout(stop, 0);\n    detachClickSwallow.current = stop;\n  }, [stopSwallowingClick]);\n\n  /**\n   * Swallow the click that will follow a pointer STILL DOWN when it releases.\n   *\n   * {@link swallowNextClick} arms for one task, which is right when the release\n   * has already happened: the click the browser synthesises belongs to the same\n   * task, so anything still listening a task later was never going to fire.\n   *\n   * Escape is the other case, and the one-task version is wrong for it. The\n   * author cancels while the finger is still on the row, and the release — with\n   * its click — arrives in some later task of their choosing. Expiring after\n   * the keydown leaves the row's own handler to insert a block from a drag that\n   * was visibly cancelled.\n   *\n   * So this waits for THAT pointer's release, and only then gives the click its\n   * one task. Scoped to the pointer for the same reason the gesture is: another\n   * finger lifting says nothing about this one.\n   */\n  const swallowClickAfterRelease = React.useCallback(\n    (pointerId: number) => {\n      stopSwallowingClick();\n      const documents = inputDocuments(frameRef.current);\n      let unlistenClick = (): void => {};\n      let unlistenRelease = (): void => {};\n      const stop = (): void => {\n        unlistenClick();\n        unlistenRelease();\n        detachClickSwallow.current = null;\n      };\n      const swallow = (event: MouseEvent): void => {\n        event.preventDefault();\n        event.stopPropagation();\n        stop();\n      };\n      const released = (event: PointerEvent): void => {\n        if (event.pointerId !== pointerId) return;\n        unlistenRelease();\n        // The click belongs to the release's task. Given it, and no longer:\n        // a suppressor left armed would eat an unrelated click later.\n        setTimeout(stop, 0);\n      };\n      unlistenClick = listenOn(documents, \"click\", swallow);\n      const ups = listenOn(documents, \"pointerup\", released);\n      const cancels = listenOn(documents, \"pointercancel\", released);\n      unlistenRelease = () => {\n        ups();\n        cancels();\n      };\n      detachClickSwallow.current = stop;\n    },\n    [stopSwallowingClick]\n  );\n\n  /**\n   * End the gesture, committing an edit only if it reached a target.\n   *\n   * Fed from both transports for the same reason {@link trackMove} is.\n   */\n  const endGesture = React.useCallback(\n    (pointerId: number, captureHost: HTMLElement | null) => {\n      // Null for another finger lifting, too: ending here would commit THIS\n      // gesture's target while the finger that owns it is still down.\n      const drag = gestureOwnedBy(gesture.current, pointerId);\n      if (drag === null) return;\n      releaseCapture(captureHost, pointerId);\n\n      const target = committedTarget(drag);\n      // A press that never became a drag, or one released where nothing accepts\n      // the block, ends without an edit. Committing \"the last valid target\" from\n      // a pointer that has since moved off it would drop the block somewhere the\n      // author was not pointing when they let go.\n      if (drag.active && target !== undefined) {\n        commitDrop(drag.subject, target.at);\n      }\n      // Only after a drag that ACTIVATED. A press that stayed a click must keep\n      // its click — that is the row's ordinary insert, and eating it would take\n      // away the non-drag path rather than the duplicate.\n      if (drag.active && drag.subject.kind === \"insert\") swallowNextClick();\n      reset();\n    },\n    [commitDrop, reset, swallowNextClick]\n  );\n\n  /**\n   * Abandon the gesture, but only for the pointer that owns it.\n   *\n   * A cancel is the browser withdrawing a contact — captured by something else,\n   * or the touch became a scroll. That is a fact about ONE pointer, so a second\n   * finger being withdrawn says nothing about the drag a first finger is still\n   * performing. Resetting unconditionally would undo the gesture the press\n   * guard exists to protect: a stray touch on a block, cancelled by the browser\n   * a moment later, would end a palette drag the author is mid-way through.\n   */\n  const cancelGesture = React.useCallback(\n    (pointerId: number) => {\n      if (gestureOwnedBy(gesture.current, pointerId) === null) return;\n      reset();\n    },\n    [reset]\n  );\n\n  const onPointerUp = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      releaseHeld(event.pointerId);\n      endGesture(event.pointerId, event.currentTarget);\n    },\n    [endGesture, releaseHeld]\n  );\n\n  const beginInsertDrag = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>, entry: InsertDragEntry) => {\n      // The primary button only, for the reason `onPointerDown` gives.\n      if (event.button !== 0) return;\n      // One drag at a time, asked through the shared rule. Ignored rather than\n      // cancelled, so the drag already in flight survives a stray touch, and\n      // the pressed element keeps its own click because nothing here consumed\n      // the press.\n      if (!admitsPress(gesture.current)) return;\n      const root = canvasRoot?.current ?? null;\n      // Nothing to drop onto. The press is left entirely alone rather than\n      // half-started, so the row's click still inserts by the ordinary path.\n      if (root === null) return;\n\n      const { editor: current, slots } = latest.current;\n      const rects = snapshotRects(root);\n      // Built once for the gesture: the node the placement rule and the locks\n      // judge while the pointer aims is the node the release inserts.\n      const makeNode = builtOnce(entry.makeNode);\n      // The press, in the canvas's coordinates like every later point of the\n      // gesture: the row is in the editor's document, and the travel that\n      // activates the drag is measured from here.\n      const pressed = canvasClientPoint(\n        frameRef.current,\n        event.currentTarget.ownerDocument,\n        event.clientX,\n        event.clientY\n      );\n      gesture.current = {\n        owner: event.pointerId,\n        subject: {\n          kind: \"insert\",\n          blockName: entry.blockName,\n          makeNode,\n          onInserted: entry.onInserted,\n        },\n        origin: canvasContentPoint(pressed.x, pressed.y, root),\n        originClient: pressed,\n        regions: collectRegions(\n          current.document,\n          slots,\n          rects,\n          slotsOfNode(placementSources(latest.current))\n        ),\n        rects,\n        // EMPTY, and this is the other place the kinds differ. Forbidden\n        // parents exist to stop a node being dropped inside itself; nothing is\n        // being detached here, so there is no subtree to exclude.\n        forbiddenParents: new Set<string>(),\n        blockName: entry.blockName,\n        blockNames: [entry.blockName],\n        // The node the palette builds, its variation's props and its seeded\n        // children included, rather than the type's defaults: that node is\n        // what lands. Asked for only once a region is judged, so a press that\n        // never becomes a drag builds nothing.\n        placing: () => {\n          const made = makeNode();\n          return made === null ? [] : [made];\n        },\n        placementVerdicts: new Map(),\n        active: false,\n        switchState: NO_TARGET,\n        targets: new Map(),\n        lockVerdicts: new Map(),\n        root,\n        scroller: canvasScroller(root, frameRef.current.frame !== null),\n        handScale: handScaleOf(frameRef.current),\n        clientX: pressed.x,\n        clientY: pressed.y,\n        frame: null,\n      };\n\n      /*\n       * Followed on the DOCUMENT for the whole gesture, not merely once it\n       * activates.\n       *\n       * The press landed on a palette row, and that row is not an ancestor of\n       * the canvas — so the canvas root's handlers never see this pointer, and\n       * the row itself stops seeing it the moment the pointer leaves. Capture\n       * would fix the second half and cost something worse, for the reason\n       * given at the capture in `trackMove`.\n       *\n       * The same conclusion the Escape listener below already reached, whose\n       * docblock names a drag begun from the inserter as its reason for\n       * listening here rather than on the canvas.\n       */\n      /*\n       * These three forward the pointer id and decide nothing.\n       *\n       * Ownership is enforced inside `trackMove`, `endGesture` and\n       * `cancelGesture`, which is where BOTH transports converge — the canvas's\n       * React handlers for a pointer over the canvas, and these listeners for\n       * one anywhere else. Checking here as well would state the same rule in\n       * two places, and the copy that mattered would be the one somebody forgot\n       * when a third transport arrived.\n       */\n      /*\n       * On the editor's document AND the canvas's, which are two while the\n       * canvas is in a frame: a pointer over the panels is delivered to the\n       * editor's and one over the page to the frame's, so a drag from a row to\n       * the page is heard whole only by both. Each point is carried into the\n       * canvas's coordinates by the document that delivered it.\n       */\n      const canvas = frameRef.current;\n      const detachers = inputDocuments(canvas).map(doc => {\n        const move = (native: PointerEvent): void => {\n          const at = canvasClientPoint(\n            canvas,\n            doc,\n            native.clientX,\n            native.clientY\n          );\n          trackMove(at.x, at.y, native.pointerId, null);\n        };\n        const up = (native: PointerEvent): void => {\n          endGesture(native.pointerId, null);\n        };\n        const cancel = (native: PointerEvent): void => {\n          cancelGesture(native.pointerId);\n        };\n        const unlistenMove = listenOn([doc], \"pointermove\", move);\n        const unlistenUp = listenOn([doc], \"pointerup\", up);\n        const unlistenCancel = listenOn([doc], \"pointercancel\", cancel);\n        return () => {\n          unlistenMove();\n          unlistenUp();\n          unlistenCancel();\n        };\n      });\n      detachDocument.current = () => {\n        for (const detach of detachers) detach();\n      };\n    },\n    [canvasRoot, cancelGesture, endGesture, trackMove]\n  );\n\n  /*\n   * A drag in flight when the canvas's document is replaced — the frame\n   * loading its content, or reloading — is abandoned. Its listeners are on\n   * the document that went, so the release in the new one would never be\n   * heard, and its root and frame loop belong to a page no longer on screen.\n   */\n  const gestureDocument = React.useRef(canvasFrame.document);\n  React.useEffect(() => {\n    if (gestureDocument.current === canvasFrame.document) return;\n    gestureDocument.current = canvasFrame.document;\n    const drag = gesture.current;\n    if (drag === null) return;\n    /*\n     * A palette drag the reload cancelled still ends in a release, and if the\n     * pointer has come back to the row it started on, that press and release\n     * are one click — which the row inserts on. Suppressed exactly as Escape\n     * suppresses it, so a drag that visibly ended adds nothing.\n     */\n    if (drag.active && drag.subject.kind === \"insert\") {\n      swallowClickAfterRelease(drag.owner);\n    }\n    reset();\n  }, [canvasFrame.document, reset, swallowClickAfterRelease]);\n\n  // Every ordinary ending funnels through `reset`. This covers the one that\n  // does not: a host unmounting mid-drag, which would otherwise leave a running\n  // frame loop and three document listeners holding a gesture nothing can end.\n  // `teardown` rather than `reset`, because a state update here would be one on\n  // a component that has gone.\n  React.useEffect(() => {\n    return () => {\n      teardown();\n      // Cleared HERE and not in `teardown`: Escape arms the suppression and\n      // then resets, so disarming on every ending would undo it in the one\n      // case it exists for.\n      stopSwallowingClick();\n    };\n  }, [teardown, stopSwallowingClick]);\n\n  /*\n   * Escape abandons the drag, listened for on the DOCUMENT rather than on the\n   * canvas root.\n   *\n   * A key event goes to the FOCUSED element, and pointer capture does not move\n   * focus — so during a drag the keyboard is still wherever it was, which for a\n   * drag begun from the inserter is a search field. A handler on the canvas\n   * would therefore never run for the gesture it exists to cancel.\n   *\n   * Registered only WHILE a drag is in flight, and in the capture phase so it\n   * runs before whatever else claims Escape — the editor's chrome closes on it,\n   * and closing the editor mid-drag is exactly what an author pressing Escape is\n   * trying to avoid. Both are the reason `stopPropagation` is warranted here and\n   * would not be on an always-registered listener.\n   */\n  // Gated on the block name rather than the id: an insert-drag has no node, so\n  // a gate on `draggingId` would leave the palette's own drag — the very\n  // gesture the docblock above names as its reason for existing — with no way\n  // to be cancelled.\n  const dragging = state.draggingBlockName !== null;\n  React.useEffect(() => {\n    if (!dragging) return;\n    const abandon = (event: KeyboardEvent): void => {\n      if (event.key !== \"Escape\") return;\n      event.preventDefault();\n      event.stopPropagation();\n      // An abandoned palette drag still ends in a release, and if the pointer\n      // has come back to the row it started on, that press and release are one\n      // click — which the row inserts on. Escape would visibly cancel the drag\n      // and add a block anyway, so this ending needs the same suppression the\n      // committed one gets.\n      const drag = gesture.current;\n      if (drag?.active === true && drag.subject.kind === \"insert\") {\n        swallowClickAfterRelease(drag.owner);\n      }\n      reset();\n    };\n    // Every document a key can be pressed in: focus may be in a panel's\n    // search field or inside the canvas's frame.\n    return listenOn(inputDocuments(canvasFrame), \"keydown\", abandon);\n  }, [dragging, reset, swallowClickAfterRelease, canvasFrame]);\n\n  return {\n    ...state,\n    beginInsertDrag,\n    handlers: {\n      onPointerDown,\n      onPointerMove,\n      onPointerUp,\n      // Routed through the same ownership check every other ending uses, so a\n      // second contact being withdrawn cannot end a drag it does not own.\n      onPointerCancel: event => {\n        releaseHeld(event.pointerId);\n        cancelGesture(event.pointerId);\n      },\n    },\n  };\n}\n","/**\n * One drag gesture that changes a number, shared by every surface that scrubs.\n *\n * The canvas's spacing handles and the inspector's field labels are the same\n * gesture: a press that becomes a drag only once the hand has travelled, a\n * value shown live while the pointer is down, one write on release, and Escape\n * to abandon it. What differs is what the modifiers MEAN — on a handle Shift\n * moves every side and Alt the opposite pair, in a field they change the size\n * of a step — so this module owns the gesture and the reading of the keys, and\n * each surface decides what a held key does.\n *\n * ## The pointer is followed on the DOCUMENT, not on the element pressed\n *\n * A handle is a strip a few pixels thick and a label is a word: a pointer that\n * has travelled far enough to mean a drag has usually left either one. Capture\n * keeps later moves coming back, but capture waits for activation, and\n * activation needs the very moves that stopped arriving — listening on the\n * element alone deadlocks and the control reads as inert. So the listeners are\n * the document's for the life of the gesture, and capture is taken at\n * activation only to hold the cursor and the hover states still.\n *\n * Captured at activation rather than at the press because the browser derives\n * a click's target from where the press and the release landed: capturing on\n * `pointerdown` would make every press report the pressed element as the\n * target of a click the author may have meant for something else.\n *\n * Deliberately free of React, so the lifecycle is one implementation whatever\n * draws the control, and the step arithmetic below is testable without a DOM.\n *\n * @module scrub-gesture\n */\n\nimport { DEFAULT_ACTIVATION_PX } from \"./canvas/canvas-drag\";\n\n/**\n * How far the pointer travels before a press becomes a drag.\n *\n * The canvas's own figure: two thresholds in one editor are two answers to\n * \"did the hand mean to move\", and an author who learned one on the canvas\n * would meet a different one an inch away in the inspector. Below it, a press\n * on a label is a click, which focuses the field.\n */\nexport const SCRUB_ACTIVATION_PX: typeof DEFAULT_ACTIVATION_PX =\n  DEFAULT_ACTIVATION_PX;\n\n/** The keys that only steer a drag, which it leaves to reach the page. */\nconst MODIFIER_KEYS: ReadonlySet<string> = new Set([\n  \"Shift\",\n  \"Alt\",\n  \"Control\",\n  \"Meta\",\n]);\n\n/** What the author is holding down while dragging or pressing a key. */\nexport interface ScrubModifiers {\n  readonly shift: boolean;\n  readonly alt: boolean;\n}\n\n/** What is held down, from whichever event is in hand. */\nexport function scrubModifiersOf(event: {\n  readonly shiftKey: boolean;\n  readonly altKey: boolean;\n}): ScrubModifiers {\n  return { shift: event.shiftKey, alt: event.altKey };\n}\n\n/** How far the pointer has moved since the press, in client pixels. */\nexport interface ScrubTravel {\n  readonly dx: number;\n  readonly dy: number;\n}\n\n/** The press a gesture starts from. */\nexport interface ScrubPress {\n  readonly pointerId: number;\n  readonly clientX: number;\n  readonly clientY: number;\n  /** The element pressed, which takes capture once the drag starts. */\n  readonly host: HTMLElement;\n}\n\n/** What a surface does at each point of the gesture. */\nexport interface ScrubHandlers {\n  /** Each move once the pointer has passed the threshold. */\n  readonly onMove: (moved: PointerEvent, travel: ScrubTravel) => void;\n  /** The release of a press that became a drag: the one place to write. */\n  readonly onRelease: (lifted: PointerEvent, travel: ScrubTravel) => void;\n  /** Escape during the gesture, which then ends without a release. */\n  readonly onEscape?: (pressed: KeyboardEvent) => void;\n  /** The gesture is over, however it ended. Called exactly once. */\n  readonly onEnd: () => void;\n}\n\n/** A gesture in flight. */\nexport interface ScrubSession {\n  /** Whether the press has become a drag. */\n  readonly active: boolean;\n  /** End it now, without a release. Safe to call more than once. */\n  readonly end: () => void;\n}\n\n/**\n * Follow a press until it is released, cancelled or abandoned with Escape.\n *\n * Every pointer event is filtered by the pressing pointer's id: a second touch\n * or a pen beside the mouse says nothing about this gesture, and ending on its\n * cancel would erase the preview and leave the real release nothing to commit.\n *\n * The keyboard is heard on the document as well, in the capture phase, for\n * the life of the gesture. A surface that keeps focus where it was — a press\n * that prevents the default so text is not selected — would otherwise send a\n * key to whatever had focus: Escape there would not abandon the drag, and an\n * arrow or Enter on a focused field would write while the pointer still owns\n * the value. So Escape ends the gesture, the modifiers pass, and no other key\n * reaches anything until the gesture is over.\n */\nexport function followScrub(\n  press: ScrubPress,\n  handlers: ScrubHandlers\n): ScrubSession {\n  const { host, pointerId } = press;\n  const owner = host.ownerDocument;\n  let active = false;\n  let ended = false;\n\n  const travelOf = (event: PointerEvent): ScrubTravel => ({\n    dx: event.clientX - press.clientX,\n    dy: event.clientY - press.clientY,\n  });\n\n  const end = (): void => {\n    if (ended) return;\n    ended = true;\n    owner.removeEventListener(\"pointermove\", onMove);\n    owner.removeEventListener(\"pointerup\", onUp);\n    owner.removeEventListener(\"pointercancel\", onCancel);\n    owner.removeEventListener(\"keydown\", onKey, true);\n    if (active && host.hasPointerCapture?.(pointerId) === true) {\n      host.releasePointerCapture(pointerId);\n    }\n    handlers.onEnd();\n  };\n\n  function onMove(moved: PointerEvent): void {\n    if (moved.pointerId !== pointerId) return;\n    const travel = travelOf(moved);\n    if (!active) {\n      // Client pixels: whether a press was meant as a drag is a property of\n      // the hand, and measured in a zoomed canvas's pixels it would shrink.\n      if (Math.hypot(travel.dx, travel.dy) < SCRUB_ACTIVATION_PX) return;\n      active = true;\n      host.setPointerCapture?.(pointerId);\n    }\n    handlers.onMove(moved, travel);\n  }\n\n  function onUp(lifted: PointerEvent): void {\n    if (lifted.pointerId !== pointerId) return;\n    if (active) handlers.onRelease(lifted, travelOf(lifted));\n    end();\n  }\n\n  function onCancel(cancelled: PointerEvent): void {\n    if (cancelled.pointerId !== pointerId) return;\n    end();\n  }\n\n  function onKey(pressed: KeyboardEvent): void {\n    // A modifier is how the drag is steered, and its state reaches the\n    // gesture on the pointer events, so its own key is left alone. A Control\n    // or Meta chord is the editor's (Undo among them), which a surface folds\n    // into its release, and never a keystroke a focused field would type.\n    if (MODIFIER_KEYS.has(pressed.key)) return;\n    if (pressed.key !== \"Escape\" && (pressed.ctrlKey || pressed.metaKey)) {\n      return;\n    }\n    // Every other key is stopped here, in the capture phase, before anything\n    // else hears it. The pointer owns the value until it is released: an\n    // arrow or Enter on a focused field would write mid-drag, and the\n    // editor's own Escape moves the selection up, which would take the value\n    // being dragged off screen along with the edit it abandons.\n    pressed.preventDefault();\n    pressed.stopPropagation();\n    if (pressed.key !== \"Escape\") return;\n    handlers.onEscape?.(pressed);\n    end();\n  }\n\n  owner.addEventListener(\"pointermove\", onMove);\n  owner.addEventListener(\"pointerup\", onUp);\n  owner.addEventListener(\"pointercancel\", onCancel);\n  owner.addEventListener(\"keydown\", onKey, true);\n\n  return {\n    get active() {\n      return active;\n    },\n    end,\n  };\n}\n\n/**\n * How far the pointer travels for one step of a field's value, in client\n * pixels. One, as in Figma and Webflow: a value moves with the hand.\n */\nconst FIELD_SCRUB_PX_PER_STEP = 1;\n\n/**\n * The size of one step in a number field, from what is held.\n *\n * Shift ×10 and Alt ×0.1, the same on the arrow keys and on a drag, so a\n * modifier learned on one is right on the other. Shift wins when both are\n * held, as it does on the canvas handles: it is the larger of the two.\n */\nexport function fieldStep(modifiers: ScrubModifiers): number {\n  if (modifiers.shift) return 10;\n  if (modifiers.alt) return 0.1;\n  return 1;\n}\n\n/** A field drag's progress: how far it has moved the value, and at what precision. */\nexport interface FieldScrub {\n  /** The pointer's horizontal travel at the last move. */\n  readonly dx: number;\n  /** The change so far, unrounded. */\n  readonly amount: number;\n  /** The decimals the change is shown at; widened once a fine step is taken. */\n  readonly decimals: number;\n  /** The change to the value it now stands for, at those decimals. */\n  readonly delta: number;\n}\n\n/** A drag that has not moved yet. */\nexport const FIELD_SCRUB_START: FieldScrub = {\n  dx: 0,\n  amount: 0,\n  decimals: 0,\n  delta: 0,\n};\n\n/**\n * The drag after one more move, and the change to the value it now stands for.\n *\n * Accumulated move by move with the modifiers held AT that move, rather than\n * recomputed from the whole travel: pressing Shift halfway through then speeds\n * up the rest of the drag instead of multiplying what was already done, so the\n * value never jumps under the hand.\n *\n * The precision only widens. A drag that took a fine step keeps its tenth when\n * Alt is let go, where rounding back to a whole number would undo the fine\n * adjustment the author just made.\n */\nexport function fieldScrubMove(\n  state: FieldScrub,\n  dx: number,\n  modifiers: ScrubModifiers\n): FieldScrub {\n  const step = fieldStep(modifiers);\n  const decimals = Math.max(state.decimals, step < 1 ? 1 : 0);\n  // A precision that widens continues from the change ON SCREEN, not from the\n  // unrounded amount under it: a fraction of a pixel rounded away at whole\n  // steps would otherwise appear as the drag steps back.\n  const from = decimals > state.decimals ? state.delta : state.amount;\n  const amount = from + ((dx - state.dx) / FIELD_SCRUB_PX_PER_STEP) * step;\n  const rounded = Number(amount.toFixed(decimals));\n  // `-0` normalised: it passes every comparison and then prints as a value\n  // nobody wrote.\n  return { dx, amount, decimals, delta: rounded === 0 ? 0 : rounded };\n}\n","\"use client\";\n\n/**\n * The text field every typed value is edited in: the draft over the stored\n * value, written as it is typed and settled on blur, arrow-key steps, and how\n * a stored value is shown, edited and hinted.\n *\n * @module style-text-field\n */\nimport {\n  isTokenRef,\n  trimCssWhitespace,\n  type SiteTokenSet,\n  type TokenMode,\n  type StyleLeaf,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport { Input } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { isElement } from \"../../canvas/dom-kind\";\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport { typedStyleText, useLiveDraft, type LiveDraft } from \"../../live-draft\";\nimport { fieldStep, scrubModifiersOf } from \"../../scrub-gesture\";\nimport type {\n  StyleControl,\n  StyleControlKind,\n} from \"../../styles/style-controls\";\nimport { CSS_NUMBER } from \"../../styles/style-numeric\";\nimport { tokenForTypedName } from \"../../styles/style-variables\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport { useFieldDescription } from \"../css-hint\";\n\nimport { useUnsetHint } from \"./inherited-value\";\nimport { CompactSides, fieldDescribedBy } from \"./spacing-box\";\nimport {\n  StyleTargetContext,\n  TypesLiveContext,\n  type CommitOutcome,\n} from \"./style-field-surroundings\";\n\n/**\n * The text a control is editing, over the value the document holds.\n *\n * One implementation for both fields that need it. A draft is not just local\n * state: it has to be REPLACED whenever the stored value moves underneath — an\n * undo, an edit applied from elsewhere — or the control goes on showing a value\n * the document no longer has, and the remount key changes with the SELECTION,\n * which neither of those changes.\n *\n * `edited` is the same comparison every caller was making to decide whether a\n * commit is worth attempting, so it is answered here rather than at each.\n * `live` is the same draft written as it is typed (`live-draft.ts`), for the\n * text field to type through.\n */\nexport function useDraft(\n  stored: StyleValue | undefined,\n  putBackDone?: () => void\n): {\n  draft: string;\n  setDraft: (value: string) => void;\n  edited: boolean;\n  reset: () => void;\n  live: LiveDraft;\n} {\n  const text = storedText(stored);\n  const live = useLiveDraft(text, putBackDone);\n  return {\n    draft: live.draft,\n    setDraft: live.setDraft,\n    edited: live.draft !== text,\n    reset: () => live.setDraft(text),\n    live,\n  };\n}\n\n/** A blur's commit, held while focus moves within one control. */\ninterface HoldBlur {\n  /** Whether focus moving to `next` stays within the control. */\n  readonly within: (next: EventTarget | null) => boolean;\n  /** The commit held meanwhile, if any. */\n  readonly held: React.RefObject<(() => void) | null>;\n}\n\n/**\n * Holds the number field's commit while focus moves to its own unit menu.\n *\n * Committed on that blur, a number typed and then given a unit was written\n * twice — \"20px\", then \"20rem\" — so one Undo left a value nobody asked for.\n * Held, the choice writes the number with its unit as one step; closing the\n * menu without a choice, or moving past it, writes the number as typed.\n */\nexport function useHeldBlur(\n  /** The stored value as text; a held commit is dropped once it moves. */\n  storedKey: string\n): {\n  holdBlur: HoldBlur;\n  trigger: React.RefObject<HTMLButtonElement | null>;\n  content: React.RefObject<HTMLDivElement | null>;\n  choosing: (choose: (choice: string) => void) => (choice: string) => void;\n  onOpenChange: (open: boolean) => void;\n  onTriggerBlur: (event: React.FocusEvent) => void;\n} {\n  const held = React.useRef<(() => void) | null>(null);\n  const open = React.useRef(false);\n  const trigger = React.useRef<HTMLButtonElement | null>(null);\n  const content = React.useRef<HTMLDivElement | null>(null);\n  // A value that moved under the held commit — an undo while the menu is\n  // open — wins: writing the older typed text over it would reverse it.\n  React.useEffect(() => {\n    held.current = null;\n  }, [storedKey]);\n  // A field taken away with its menu open, as selecting another block does,\n  // gets no close from the menu: the typed number is written as it goes.\n  React.useEffect(\n    () => () => {\n      const commit = held.current;\n      held.current = null;\n      commit?.();\n    },\n    []\n  );\n  const within = (next: EventTarget | null): boolean =>\n    isElement(next) &&\n    (trigger.current?.contains(next) === true ||\n      content.current?.contains(next) === true);\n  const flush = () => {\n    const commit = held.current;\n    held.current = null;\n    commit?.();\n  };\n  return {\n    holdBlur: { within, held },\n    trigger,\n    content,\n    // A choice writes the typed number with its unit, so the commit held on\n    // the way to the menu is dropped rather than written first.\n    choosing: choose => choice => {\n      held.current = null;\n      choose(choice);\n    },\n    onOpenChange: next => {\n      open.current = next;\n      if (!next) flush();\n    },\n    // Opening moves focus into the menu, which is not leaving the control.\n    onTriggerBlur: event => {\n      if (!open.current && !within(event.relatedTarget)) flush();\n    },\n  };\n}\n\n/**\n * A side's tooltip: its whole value, for one the narrow cell cannot show, or\n * none where there is nothing to show or the field is not a side.\n */\nfunction sideTitle(compact: boolean, draft: string): string | undefined {\n  return compact && draft !== \"\" ? draft : undefined;\n}\n\n/**\n * A text field's commit: the draft written, a variable's typed name matched\n * in the mode the canvas shows, as the field's variables list offers them.\n * Written in the edit's run of typing, where it was typed live, which the\n * commit then ends. A draft the last keystroke already wrote is not written\n * again, unless the field's end-of-edit write does more than its keystrokes\n * (`settles`: a colour joining Recent colours).\n */\nfunction useDraftCommit({\n  draft,\n  stored,\n  control,\n  tokens,\n  onCommit,\n  setDraft,\n  setTyping,\n  live,\n  settles,\n}: {\n  draft: string;\n  stored: StyleValue | undefined;\n  control: StyleControl;\n  tokens: SiteTokenSet | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  setDraft: (value: string) => void;\n  setTyping: (typing: boolean) => void;\n  live: LiveDraft | undefined;\n  settles: boolean;\n}): () => void {\n  const mode = useCanvasTokenMode();\n  return () => {\n    // Written or not, the text is no longer mid-edit.\n    setTyping(false);\n    const commit = (settling: boolean) =>\n      commitDraft({\n        draft,\n        stored,\n        kind: control.kind,\n        leaf: control.leaf,\n        tokens,\n        mode,\n        onCommit,\n        setDraft,\n        settling,\n      });\n    if (live === undefined) return commit(false);\n    // Typed live, the text left in the field is usually the stored value\n    // already. A field whose end-of-edit write does more (a colour joining\n    // Recent colours) still makes it, once; one that only re-wrote the same\n    // text writes nothing more.\n    const typedLive = live.written(draft);\n    if (!typedLive) live.join(() => commit(false));\n    else if (settles) live.join(() => commit(true));\n    live.end();\n  };\n}\n\n/**\n * A keystroke's write while the field is typed live, answering whether it\n * moved the document. Nothing is written for an emptied field, which clears\n * only when it is left, nor for text the field's commit refuses (`12p`, half\n * a hex colour): the document, and so the canvas, keeps the last valid value,\n * and the refusal is shown beside the field as it is on blur.\n */\nfunction typedWrite({\n  control,\n  tokens,\n  mode,\n  onType,\n}: {\n  control: StyleControl;\n  tokens: SiteTokenSet | undefined;\n  mode: TokenMode;\n  onType: (value: StyleValue | null) => CommitOutcome;\n}): (text: string) => boolean {\n  return text => {\n    const typed = typedStyleText(text);\n    if (typed === undefined) return false;\n    // Asked even where the text reads as what is stored (\"24px\" after\n    // \"24p\"), so the refusal of the text before it is cleared.\n    const value = draftValue(control.kind, control.leaf, tokens, mode, typed);\n    // A variable's name is matched once, when the field is left. Written live,\n    // a whole name on the way to a longer one (\"color.brand\" before\n    // \"color.brand.dark\") would store that variable mid-word, and a field\n    // showing a variable is a chip, not the text being typed.\n    if (isTokenRef(value)) return false;\n    return onType(value) === \"applied\";\n  };\n}\n\n/**\n * The value a draft writes: `null` to clear an emptied one, a variable for\n * its typed name, otherwise the text as its kind reads it.\n */\nfunction draftValue(\n  kind: StyleControlKind | undefined,\n  leaf: StyleLeaf,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode,\n  draft: string\n): StyleValue | null {\n  // CSS whitespace here too, not JavaScript's. `String.prototype.trim` also\n  // strips NBSP and the Unicode spaces, so a draft of nothing but a\n  // non-breaking space would read as empty and DELETE the declaration —\n  // where the engine treats it as a value and refuses it.\n  if (trimCssWhitespace(draft) === \"\") return null;\n  // A variable's name typed in, \"Display\" or \"Text\", is that variable, asked\n  // BEFORE the text is read as a value: read first, the word is refused as\n  // \"not a length\" or stored as a literal no page can use.\n  const named = tokenForTypedName(leaf, tokens, draft, mode);\n  return named === undefined ? committedValue(kind, draft) : { $token: named };\n}\n\n/** Write a text field's draft, when it differs from what is stored. */\nexport function commitDraft({\n  draft,\n  stored,\n  kind,\n  leaf,\n  tokens,\n  mode,\n  onCommit,\n  setDraft,\n  settling = false,\n}: {\n  draft: string;\n  stored: StyleValue | undefined;\n  kind: StyleControlKind | undefined;\n  /** The leaf the field edits, whose variables a typed name may pick. */\n  leaf: StyleLeaf;\n  /** The site's variables, so a variable's name typed here picks it. */\n  tokens: SiteTokenSet | undefined;\n  /** The mode the canvas shows, so typing matches what the list offers. */\n  mode: TokenMode;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  setDraft: (value: string) => void;\n  /**\n   * The end-of-edit write of text already written live: made even though the\n   * document holds the text, for what the commit does beyond writing it.\n   */\n  settling?: boolean;\n}): void {\n  if (!settling && draft === storedText(stored)) return;\n  const outcome = onCommit(draftValue(kind, leaf, tokens, mode, draft));\n  // The document did not move because it already holds this value in another\n  // spelling: `01`, `+1` and `1e0` all commit as the `1` that is stored. The\n  // effect above cannot cover it — `stored` is identical, so it does not fire\n  // — and without this the field goes on showing text the document does not\n  // contain until something remounts it. A REFUSAL deliberately keeps the\n  // draft: the author has to be able to correct what they typed.\n  if (outcome === \"unchanged\") setDraft(storedText(stored));\n}\n\n/**\n * What a number field shares with its text field: the commit it holds while\n * focus moves to its unit menu, and whether text was typed since focus, which\n * its unit suffix reads.\n */\ninterface FieldEditing {\n  readonly holdBlur: HoldBlur;\n  readonly typing: boolean;\n  readonly setTyping: (typing: boolean) => void;\n}\n\n/**\n * The field's text and hint as shown: through `display` (which leaves out a\n * unit shown beside the field), except text typed since focus, shown as\n * typed.\n */\nfunction shownText(\n  display: ((text: string) => string) | undefined,\n  typing: boolean,\n  draft: string,\n  hint: string\n): { value: string; placeholder: string } {\n  if (display === undefined) return { value: draft, placeholder: hint };\n  return { value: typing ? draft : display(draft), placeholder: display(hint) };\n}\n\n/** Whether text was typed since focus: the caller's, else the field's own. */\nfunction useTyping(\n  editing: FieldEditing | undefined\n): [boolean, (typing: boolean) => void] {\n  const [own, setOwn] = React.useState(false);\n  return editing === undefined\n    ? [own, setOwn]\n    : [editing.typing, editing.setTyping];\n}\n\n/**\n * The field's focus and blur: back in the field, a commit held for the unit\n * menu is superseded by the one this field's own blur makes; leaving for the\n * menu holds the commit; leaving elsewhere commits.\n */\nfunction focusHandlers(\n  holdBlur: HoldBlur | undefined,\n  setTyping: (typing: boolean) => void,\n  commit: () => void\n): {\n  onFocus: () => void;\n  onBlur: (event: React.FocusEvent) => void;\n} {\n  return {\n    onFocus: () => {\n      if (holdBlur !== undefined) holdBlur.held.current = null;\n    },\n    onBlur: event => {\n      if (holdBlur?.within(event.relatedTarget) === true) {\n        setTyping(false);\n        holdBlur.held.current = commit;\n        return;\n      }\n      commit();\n    },\n  };\n}\n\n/** How a text field types live: see {@link TextField}. */\ninterface TypedLive {\n  /**\n   * The caller's draft written as it is typed, from {@link useDraft}, so the\n   * canvas follows the typing. Without it the field writes on blur and Enter\n   * only. A shared style is written on blur and Enter either way: it is\n   * stored on the site at once, so a write per keystroke would put\n   * half-typed values on every page that wears it.\n   */\n  live?: LiveDraft | undefined;\n  /**\n   * The write a keystroke makes, where it differs from the commit: a colour\n   * is remembered among Recent colours once, when the edit ends, not for\n   * every value on the way. `onCommit` when omitted.\n   */\n  onType?: (value: StyleValue | null) => CommitOutcome;\n}\n\n/**\n * A text field over one stored value.\n *\n * The draft is local so a half-typed value — `16` on the way to `16px` — is not\n * sent to the validator on every keystroke and refused four times while the\n * author is still typing.\n */\nexport function TextField({\n  id,\n  control,\n  stored,\n  draft,\n  setDraft,\n  tokens,\n  describedBy,\n  invalid,\n  onCommit,\n  onStep,\n  display,\n  fallbackHint,\n  editing,\n  ...typed\n}: {\n  id: string;\n  control: StyleControl;\n  stored: StyleValue | undefined;\n  /**\n   * The text being edited, owned by the caller.\n   *\n   * Lifted because a numeric row has TWO controls over one value — the field\n   * and the unit menu — and a draft private to this one leaves the other\n   * reading the stored value instead, which is a different and usually older\n   * answer to what the author is editing.\n   */\n  draft: string;\n  setDraft: (value: string) => void;\n  /** The site's variables, so a variable's name typed here picks it. */\n  tokens: SiteTokenSet | undefined;\n  /**\n   * Everything describing this field: a refusal message, a contrast verdict, or\n   * both.\n   *\n   * Separate from {@link invalid}, and that separation is the point. A\n   * description is not a complaint — a passing 21:1 contrast note is\n   * supplementary text — so a field that inferred invalidity from having a\n   * description would announce a perfectly good colour as invalid.\n   */\n  describedBy: string | undefined;\n  /** Whether the LAST value was refused, which is the only thing that invalidates. */\n  invalid: boolean;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  /**\n   * Applies one arrow-key step to the text currently shown, answering the text\n   * that was written or `null` when nothing was.\n   *\n   * `null` leaves the key to its default behaviour, which is what keeps a value\n   * that is not a single measurement — a shorthand, a function, a keyword —\n   * behaving like ordinary text under the caret. The DRAFT is passed rather\n   * than read from the store, so a step lands on what the author is looking at.\n   */\n  onStep?: (draft: string, delta: number) => string | null;\n  /**\n   * How the draft and the hint read in the field, where a unit shown beside\n   * it is left out of both (\"2\" beside \"rem\"). The draft itself, which is\n   * what commits and steps, is unchanged.\n   */\n  display?: (text: string) => string;\n  /** The hint while nothing applies, in place of the leaf's own. */\n  fallbackHint?: string;\n  /** The number field's part in the edit; see {@link FieldEditing}. */\n  editing?: FieldEditing | undefined;\n} & TypedLive): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  // Typed since focus: the text is then shown as typed, since a unit on its\n  // way in (\"2c\" for \"2ch\") would read as a unit to leave out and be cut.\n  const [typing, setTyping] = useTyping(editing);\n  // A side of the spacing box says \"–\" while unset: a hint would not fit.\n  const compact = React.useContext(CompactSides);\n  const hint = useUnsetHint(unsetWords(compact, fallbackHint, control));\n  const { commit, onChange } = useFieldWrites({\n    draft,\n    stored,\n    control,\n    tokens,\n    onCommit,\n    setDraft,\n    setTyping,\n    ...typed,\n  });\n\n  return (\n    <Input\n      id={id}\n      {...shownText(display, typing, draft, hint)}\n      // A side of the spacing box is narrow: its whole value is in its\n      // tooltip, for one the cell cannot show.\n      title={sideTitle(compact, draft)}\n      // A value, not words: no list of earlier entries over the field.\n      autoComplete=\"off\"\n      aria-describedby={fieldDescribedBy(described, compact, id)}\n      aria-invalid={invalid ? true : undefined}\n      // Written as it is typed, so the canvas follows; the stretch of typing\n      // is one undo step, which blur and Enter end.\n      onChange={onChange}\n      {...focusHandlers(editing?.holdBlur, setTyping, commit)}\n      onKeyDown={keyHandler({ commit, onStep, draft, setDraft, setTyping })}\n    />\n  );\n}\n\n/** The field's keys: Enter commits, and an arrow steps the draft. */\nfunction keyHandler({\n  commit,\n  onStep,\n  draft,\n  setDraft,\n  setTyping,\n}: {\n  commit: () => void;\n  onStep: ((draft: string, delta: number) => string | null) | undefined;\n  draft: string;\n  setDraft: (value: string) => void;\n  setTyping: (typing: boolean) => void;\n}): (event: React.KeyboardEvent<HTMLInputElement>) => void {\n  return event => {\n    if (commitOnEnter(event, commit)) return;\n    // The draft follows the value that was written, so the field shows the\n    // step immediately rather than waiting for `stored` to come back.\n    stepOnKey(event, onStep, draft, next => {\n      setDraft(next);\n      setTyping(false);\n    });\n  };\n}\n\n/**\n * The field's two writes: the commit that ends an edit, and each keystroke's,\n * both through the live draft where the field types live.\n */\nfunction useFieldWrites({\n  live,\n  onType,\n  ...field\n}: {\n  draft: string;\n  stored: StyleValue | undefined;\n  control: StyleControl;\n  tokens: SiteTokenSet | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  setDraft: (value: string) => void;\n  setTyping: (typing: boolean) => void;\n} & TypedLive): {\n  commit: () => void;\n  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;\n} {\n  const typedLive = useTypedLive(live);\n  const commit = useDraftCommit({\n    ...field,\n    live: typedLive,\n    settles: onType !== undefined,\n  });\n  const onChange = useTypedChange({\n    live: typedLive,\n    control: field.control,\n    tokens: field.tokens,\n    onType: onType ?? field.onCommit,\n    setDraft: field.setDraft,\n    setTyping: field.setTyping,\n  });\n  return { commit, onChange };\n}\n\n/**\n * What a keystroke in the field does: the text is shown as typed, and, where\n * the field types live, written in the edit's run of typing.\n */\nfunction useTypedChange({\n  live,\n  control,\n  tokens,\n  onType,\n  setDraft,\n  setTyping,\n}: {\n  live: LiveDraft | undefined;\n  control: StyleControl;\n  tokens: SiteTokenSet | undefined;\n  onType: (value: StyleValue | null) => CommitOutcome;\n  setDraft: (value: string) => void;\n  setTyping: (typing: boolean) => void;\n}): (event: React.ChangeEvent<HTMLInputElement>) => void {\n  const mode = useCanvasTokenMode();\n  const write = typedWrite({ control, tokens, mode, onType });\n  return event => {\n    setTyping(true);\n    if (live === undefined) setDraft(event.target.value);\n    else live.type(event.target.value, write);\n  };\n}\n\n/**\n * The live draft a field types through: none for a shared style, which is\n * written when the edit ends (see the `live` prop of {@link TextField}).\n */\nfunction useTypedLive(live: LiveDraft | undefined): LiveDraft | undefined {\n  return useTypesLive() ? live : undefined;\n}\n\n/**\n * Whether a field here writes as it is typed: where the panel drawing it\n * says so, and never for a shared style, which changes every page using it.\n */\nexport function useTypesLive(): boolean {\n  const target = React.useContext(StyleTargetContext);\n  return React.useContext(TypesLiveContext) && target.kind !== \"shared\";\n}\n\n/**\n * An arrow key's step on the draft, where the field steps and the value can\n * be stepped; `written` receives the text that was written.\n */\nfunction stepOnKey(\n  event: React.KeyboardEvent,\n  onStep: ((draft: string, delta: number) => string | null) | undefined,\n  draft: string,\n  written: (next: string) => void\n): void {\n  if (onStep === undefined) return;\n  const delta = arrowStep(event);\n  if (delta === null) return;\n  // Stepped from the DRAFT rather than from what is stored, so the key works\n  // while an author is mid-edit — which is most of when they reach for it.\n  // Reading `stored` instead would either discard an uncommitted edit or, if\n  // it declined to act, leave the arrow doing nothing in a text input that has\n  // no numeric fallback: an affordance that appears broken exactly while it is\n  // being used.\n  const next = onStep(draft, delta);\n  if (next === null) return;\n  written(next);\n  // Only once the step was applied, so an unsteppable value keeps the caret\n  // movement the key would otherwise perform.\n  event.preventDefault();\n}\n\n/**\n * The step one key press asks for, or `null` when it asks for none.\n *\n * Separated from the handler so that WHICH keys are claimed is one readable\n * answer rather than a run of early returns inside an event callback — and so\n * the two rules it encodes sit together, since they are easy to change apart\n * and wrong apart.\n *\n * Arrow steps by one, Shift by ten and Alt by a tenth, which is what Figma,\n * Framer and Webflow all do: an author arrives already knowing it, and a\n * different scale here would cost them for no gain. The sizes are the label\n * drag's own (`fieldStep`), so a modifier means the same on both.\n *\n * Alt+Up and Alt+Down are claimed only here, inside a number field: the\n * editor's block moves on those keys stay out of fields, where they would be\n * caret movement in a text field and are a step in this one.\n *\n * Control and Meta are refused outright. Those chords are platform, browser\n * and assistive-navigation shortcuts, so claiming one would mutate a style\n * and add an undo entry from a keystroke aimed somewhere else entirely.\n */\nexport function arrowStep(event: React.KeyboardEvent): number | null {\n  // A keystroke arriving mid-composition belongs to the IME, which uses the\n  // arrows to move through conversion candidates. Stepping there would edit the\n  // style AND suppress the candidate move, so the author loses both. The\n  // shortcut manager states the same rule for the same reason, and this is the\n  // second reader of a keyboard event in this repository that has to know it.\n  if (event.nativeEvent.isComposing) return null;\n  if (event.ctrlKey || event.metaKey) return null;\n  const direction =\n    event.key === \"ArrowUp\" ? 1 : event.key === \"ArrowDown\" ? -1 : 0;\n  if (direction === 0) return null;\n  return direction * fieldStep(scrubModifiersOf(event));\n}\n\n/** A stored value as a text field shows it. */\nexport function storedText(value: StyleValue | undefined): string {\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\") return String(value);\n  return \"\";\n}\n\n/** How much of an unrepresentable value is worth showing before it stops helping. */\nconst DISPLAY_LIMIT = 80;\n\n/**\n * A stored value as a READ-ONLY surface shows it, including one no field can\n * edit.\n *\n * Separate from {@link storedText}, which answers what a text field's draft\n * starts as and is right to give `\"\"` for a shape it cannot type. Here `\"\"`\n * would be a lie: the surface exists precisely because something IS stored, and\n * a blank one beside a Clear button tells an author to remove they-cannot-see-\n * what.\n */\nexport function displayText(value: StyleValue | undefined): string {\n  if (value === undefined) return \"\";\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\") return String(value);\n  if (isTokenRef(value)) return value.$token;\n  // Its own JSON, because there is nothing else honest to show: the value is\n  // live on the page and the author is being asked whether to remove it.\n  // Truncated because a panel column is not a document viewer, and a value long\n  // enough to need this is already one nothing here can repair.\n  const json = jsonText(value);\n  return json.length > DISPLAY_LIMIT\n    ? `${json.slice(0, DISPLAY_LIMIT)}…`\n    : json;\n}\n\n/**\n * A value's JSON, or a stand-in when it has none.\n *\n * `JSON.stringify` THROWS on a circular reference rather than declining to\n * answer, and a panel that throws while rendering leaves the author with no\n * Clear button at all — which is the exact failure this surface exists to\n * prevent, arrived at from the other direction. Nothing in the document\n * pipeline can produce one today, since a stored document is parsed from JSON;\n * the guard is here because it costs one branch on a path that already decided\n * the value is unrepresentable.\n *\n * The fallback makes no claim about the value beyond being unable to show it,\n * which is what keeps it honest: the Clear beside it still works.\n */\nfunction jsonText(value: StyleValue): string {\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return \"(value cannot be shown)\";\n  }\n}\n\n/**\n * A stored value as this control's EDITING surface shows it, or `undefined`\n * when that surface cannot show it at all.\n *\n * Two shapes reach this. An object at a scalar position — `fontSize: {value:\n * \"12px\"}` from an import or the API — has no text spelling, and a text field\n * given `\"\"` for it reads as UNSET while the value compiles; worse, the one\n * keystroke that would clear it is refused, because an emptied draft already\n * equals that empty projection. And a number stored where the leaf's vocabulary\n * is keywords has no item to be current, so the select renders its \"Not set\"\n * placeholder over a value that is doing something.\n *\n * Both are the same question — can the author see and change this here — so\n * they get one answer rather than a check in each control.\n */\nexport function editableText(\n  control: StyleControl,\n  value: StyleValue | undefined\n): string | undefined {\n  if (value === undefined) return \"\";\n  if (typeof value === \"string\") return value;\n  if (typeof value !== \"number\") return undefined;\n  return control.kind === \"select\" ? undefined : String(value);\n}\n\n/**\n * What a typed string is stored as.\n *\n * A `number` leaf takes a NUMBER, and accepts a string only as one of the\n * CSS-wide keywords — measured: `opacity: \"0.5\"` is refused where `opacity: 0.5`\n * is accepted. So a numeric-looking draft is converted and anything else is\n * passed through, which is what lets `inherit` reach a numeric property and\n * lets every other refusal carry the catalog's own message.\n *\n * Every other kind stores its value as written: a `dimension` accepts the\n * string `\"0\"` as readily as the number, so converting there would change what\n * is stored without changing what is valid.\n */\nfunction committedValue(\n  kind: StyleControlKind | undefined,\n  draft: string\n): StyleValue {\n  if (kind !== \"number\") return draft;\n  // The engine's own trim, not `String.prototype.trim`, which also strips NBSP\n  // and the Unicode spaces where CSS strips neither. Trimming wider than CSS\n  // does turns a spelling the engine REFUSES into a number it accepts: pasting\n  // a non-breaking space before a digit would silently store the digit.\n  const trimmed = trimCssWhitespace(draft);\n  // `Number` reads spellings CSS does not: `0x10` becomes 16, `0b10` becomes 2,\n  // `0o10` becomes 8. Converting those would store a number the author never\n  // typed and pass validation, so only the grammar CSS calls a <number> is\n  // converted and everything else is left for the catalog to judge.\n  if (!CSS_NUMBER.test(trimmed)) return draft;\n  const parsed = Number(trimmed);\n  return Number.isFinite(parsed) ? parsed : draft;\n}\n\n/**\n * The hint for a kind whose form does not vary with the leaf's own fields.\n *\n * Partial on purpose, and the one place in this lane where a fallthrough is the\n * right answer: a placeholder is advisory text, so a leaf kind this build has\n * not learned about gets a generic hint rather than a compile error. Whether\n * the kind can be DRAWN at all is a different question, and `style-controls.ts`\n * already answers it with a mapped type that does fail to compile.\n */\nconst FIXED_PLACEHOLDER: Partial<Record<StyleLeaf[\"kind\"], string>> = {\n  keyword: \"Not set\",\n  cssValue: \"Not set\",\n  // The FORM rather than an example, as the length and number hints are. A\n  // literal here would also be a hardcoded colour, which this repository bans\n  // outright — the rule reads source, not intent, and it is right to: a hex in\n  // a placeholder is one copy away from a hex in a style.\n  // Short enough to read inside the field beside its swatch at the default\n  // panel width, where \"Name, hex or rgb()\" was cut off mid-word. rgb() and\n  // the other forms stay valid to type.\n  color: \"Name or hex\",\n  url: \"https://…\",\n};\n\n/**\n * A length's hint, which depends on what the catalog lets this one hold.\n *\n * The form alone, never the keyword list: a field shows about twenty\n * characters, and a hint cut off mid-word (\"16px or 50%, or xx-sm…\") says\n * less than a short one. The keywords stay valid to type.\n */\nfunction dimensionHint(\n  leaf: Extract<StyleLeaf, { kind: \"dimension\" }>\n): string {\n  // A line's width as a line is usually drawn: \"16px\" read as a heavy frame.\n  if (/^(border|outline)(-.+)?-width$/.test(leaf.cssProperty)) return \"1px\";\n  return leaf.allowPercentage === true ? \"16px or 50%\" : \"16px\";\n}\n\n/** A number's hint, which names its bounds when the catalog gives it both. */\nfunction numberHint(leaf: Extract<StyleLeaf, { kind: \"number\" }>): string {\n  if (leaf.min === undefined || leaf.max === undefined) return \"a number\";\n  return `${leaf.min} to ${leaf.max}`;\n}\n\n/** A hint at the form this leaf takes, from the catalog rather than a list here. */\nexport function placeholderFor(control: StyleControl): string {\n  const { leaf } = control;\n  if (leaf.kind === \"dimension\") return dimensionHint(leaf);\n  if (leaf.kind === \"number\") return numberHint(leaf);\n  return FIXED_PLACEHOLDER[leaf.kind] ?? \"Not set\";\n}\n\n/**\n * What a field says while nothing is set: \"–\" on a side of the spacing box,\n * where a hint would not fit, else its own hint or the control's.\n */\nfunction unsetWords(\n  compact: boolean,\n  fallbackHint: string | undefined,\n  control: StyleControl\n): string {\n  return compact ? \"–\" : (fallbackHint ?? placeholderFor(control));\n}\n","/**\n * The site's spacing variables as presets: which a spacing value offers,\n * smallest first, which one a stored value holds, and how each is named. The\n * one reading both a spacing-box side's popover and a Spacer's Height\n * presets take, so the two offer the same scale the same way.\n *\n * @module spacing-presets\n */\nimport {\n  isTokenRef,\n  type SiteTokenSet,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport { variableGroupOf } from \"../../panels/design/tokens-studio\";\nimport {\n  variableLabel,\n  variablesFor,\n  type SiteVariable,\n} from \"../../styles/style-colour\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport { lengthInPx, variableValueText } from \"../../styles/style-variables\";\n\nimport { storedText } from \"./style-text-field\";\n\n/** \"None\", the preset that writes nothing between the edges. */\nexport const NONE = \"zero\";\n\n/**\n * A preset's key in the radio group: a variable's under a prefix, so no\n * variable's identity (\"none\", \"zero\") can be taken for the zero preset.\n */\nexport function presetKey(identity: string): string {\n  return `token:${identity}`;\n}\n\n/** The variable a preset's key stands for, or none for the zero preset. */\nexport function identityOfKey(key: string): string | undefined {\n  return key.startsWith(\"token:\") ? key.slice(\"token:\".length) : undefined;\n}\n\n/** A zero length as it may be stored: \"0\", \"0px\", \"0rem\". */\nconst ZERO = /^[+-]?0*(?:\\.0*)?(?:[a-z%]+)?$/i;\n\n/**\n * The site's spacing variables, smallest first, the order a scale is read\n * in. One with no single size (fluid, or through a function) goes last.\n */\nexport function spacingPresets(\n  control: StyleControl,\n  tokens: SiteTokenSet | undefined,\n  mode: ReturnType<typeof useCanvasTokenMode>\n): readonly SiteVariable[] {\n  const size = (variable: SiteVariable): number =>\n    lengthInPx(variable.value) ?? Number.POSITIVE_INFINITY;\n  return variablesFor(control.leaf, tokens, mode)\n    .filter(\n      variable =>\n        variable.kind === \"dimension\" && variableGroupOf(variable) === \"spacing\"\n    )\n    .sort((a, b) => size(a) - size(b));\n}\n\n/**\n * The preset to mark: the one the side holds, where the popover offers it. A\n * variable that is not a spacing preset (a radius) marks none, so the first\n * preset keeps the group's Tab stop.\n */\nexport function offeredPreset(\n  stored: StyleValue | undefined,\n  presets: readonly SiteVariable[]\n): string | undefined {\n  const held = heldPreset(stored);\n  return held === NONE ||\n    presets.some(preset => presetKey(preset.identity) === held)\n    ? held\n    : undefined;\n}\n\n/** The preset a side holds: its variable, \"None\" for a zero, else none. */\nfunction heldPreset(stored: StyleValue | undefined): string | undefined {\n  if (isTokenRef(stored)) return presetKey(stored.$token);\n  if (stored === undefined) return undefined;\n  return ZERO.test(storedText(stored)) && /\\d/.test(storedText(stored))\n    ? NONE\n    : undefined;\n}\n\n/** Each preset's name, then its value in a quieter tone; \"None\" first. */\nexport function presetLabels(\n  presets: readonly SiteVariable[]\n): Readonly<Record<string, React.ReactNode>> {\n  const labels: Record<string, React.ReactNode> = {\n    [NONE]: (\n      <>\n        None <span className=\"nx-spacing-popover__preset-value\">0</span>\n      </>\n    ),\n  };\n  for (const preset of presets) {\n    labels[presetKey(preset.identity)] = (\n      <>\n        {/* Qualified where two presets share a name, as every variable\n            list here qualifies it. */}\n        {variableLabel(preset, presets)}{\" \"}\n        <span className=\"nx-spacing-popover__preset-value\">\n          {variableValueText(preset)}\n        </span>\n      </>\n    );\n  }\n  return labels;\n}\n","/**\n * A drag that writes as the pointer moves, so the canvas follows it: a\n * number label dragged, a colour dragged across the picker, a slider moved.\n *\n * Every write the drag makes is part of one run of typing (`typing-run.ts`),\n * so the history keeps the whole drag as ONE step: undo takes it back to the\n * value from before the press. Letting go writes the last value in the same\n * run and ends it; the next drag is a step of its own. Abandoning the drag\n * (Escape, a cancelled pointer) puts back everything it wrote through the\n * editor's `cancelTyping`, and records nothing.\n *\n * At most one write a frame. A pointer reports far more often than a screen\n * draws, and each write redraws the canvas, so moves are held until the next\n * frame and only the latest of them is written: the canvas keeps up with the\n * pointer, and the work a drag costs is set by the screen's rate rather than\n * by the mouse's.\n *\n * @module live-gesture\n */\n\nimport * as React from \"react\";\n\nimport { TypingCancel } from \"./live-draft\";\nimport { joinTyping } from \"./typing-run\";\n\n/** A drag's writes, as one step of the editor's history. */\nexport interface LiveGesture {\n  /**\n   * The pointer moved: write with `write` at the next frame, in the drag's\n   * run. A later move before that frame replaces it.\n   */\n  readonly move: (write: () => void) => void;\n  /**\n   * The drag was let go of: a move still waiting for its frame is dropped,\n   * and `write`, given, is written now in the same run, so the whole drag is\n   * one step. The next move begins a new drag.\n   */\n  readonly end: (write?: () => void) => void;\n  /**\n   * The drag was abandoned: nothing more is written, and what it wrote is\n   * put back, with nothing recorded.\n   */\n  readonly cancel: () => void;\n}\n\n/** What one drag holds between its moves. */\ninterface Drag {\n  /** The run its writes are made in, from its first write. */\n  run: object | null;\n  /** The latest move, waiting for its frame. */\n  pending: (() => void) | null;\n  /** The frame asked for, while one is. */\n  frame: number | null;\n}\n\n/**\n * A drag's writes, for a field drawn over the editor: the block settings\n * panel provides the cancel ({@link TypingCancel}). Outside one, abandoning\n * a drag cannot put its writes back, so a field there writes only on release.\n */\nexport function useLiveGesture(): LiveGesture {\n  const cancelTyping = React.useContext(TypingCancel);\n  const drag = React.useRef<Drag>({\n    run: null,\n    pending: null,\n    frame: null,\n  }).current;\n  // A field taken away mid-drag asks for no frame after it is gone.\n  React.useEffect(\n    () => () => {\n      if (drag.frame !== null) cancelAnimationFrame(drag.frame);\n      drag.frame = null;\n      drag.pending = null;\n    },\n    [drag]\n  );\n  return React.useMemo(() => {\n    const runOf = (): object => {\n      drag.run ??= {};\n      return drag.run;\n    };\n    const drop = (): void => {\n      if (drag.frame !== null) cancelAnimationFrame(drag.frame);\n      drag.frame = null;\n      drag.pending = null;\n    };\n    const draw = (): void => {\n      drag.frame = null;\n      const write = drag.pending;\n      drag.pending = null;\n      if (write !== null) joinTyping(runOf(), write);\n    };\n    return {\n      move: write => {\n        drag.pending = write;\n        drag.frame ??= requestAnimationFrame(draw);\n      },\n      end: write => {\n        drop();\n        if (write !== undefined) joinTyping(runOf(), write);\n        drag.run = null;\n      },\n      cancel: () => {\n        drop();\n        const { run } = drag;\n        drag.run = null;\n        if (run !== null) cancelTyping?.(run);\n      },\n    };\n  }, [drag, cancelTyping]);\n}\n","/**\n * Dragging a number field's LABEL to change its value: the inspector's half of\n * the scrub gesture `scrub-gesture.ts` owns.\n *\n * The label and the field are drawn by different components — the row draws\n * the label, the control kind decides the field — so the two meet through a\n * slot the row provides: the field says what a drag may do to its value, and\n * the label carries the pointer handling. Nothing else about either changes,\n * which is what keeps a field that does not scrub exactly as it was.\n *\n * ## Live where the field types live, one undo step either way\n *\n * While the pointer is down the field SHOWS each value. A field whose panel\n * writes as it is typed (`preview`) also writes it, at most once a frame, so\n * the canvas follows the pointer (`live-gesture.ts`); letting go writes the\n * last value through the field's own commit in the same run, so one drag is\n * one undo step. A field that writes when it is left touches the document\n * only on release. Escape puts the field's text back as it was before the\n * press, and the document with it, recording nothing.\n *\n * ## A click is still a click\n *\n * Until the pointer passes the shared dead zone a press is a click, and a click\n * on a label focuses its field as it always has. Touch never scrubs: a finger\n * on a label is a tap that should focus, or the start of a scroll. A press is\n * kept from selecting text, and the click a finished drag produces is\n * swallowed, so letting go does not also put a caret in the field.\n *\n * The keyboard path is the field's own: its arrow keys step by the same\n * amounts, with the same modifiers, as a drag.\n *\n * @module label-scrub\n */\nimport * as React from \"react\";\n\nimport { useLiveGesture } from \"../../live-gesture\";\nimport {\n  FIELD_SCRUB_START,\n  fieldScrubMove,\n  followScrub,\n  scrubModifiersOf,\n  type ScrubSession,\n} from \"../../scrub-gesture\";\n\n/**\n * A value a drag moves: one measurement as text, or a bare number. Never a\n * token or a record, which a drag has no quantity to change in.\n */\nexport type ScrubbedValue = string | number;\n\n/** What a field lets its label do to its value. */\nexport interface LabelScrubField {\n  /** The value a drag starts from, or `undefined` while the field cannot be dragged. */\n  readonly origin: ScrubbedValue | undefined;\n  /** The value `delta` from `origin`, held to what the property takes, or `undefined`. */\n  readonly at: (\n    origin: ScrubbedValue,\n    delta: number\n  ) => ScrubbedValue | undefined;\n  /** The field's text now, put back when a drag is abandoned. */\n  readonly draft: string;\n  /** Shows text in the field while the pointer is down. */\n  readonly show: (text: string) => void;\n  /** Writes the value, once, on release. */\n  readonly commit: (value: ScrubbedValue) => void;\n  /**\n   * Writes the value while the pointer moves, where the field's panel writes\n   * as it is typed; absent, the drag writes only on release.\n   */\n  readonly preview?: (value: ScrubbedValue) => void;\n  /** Shows the field's stored value, for a drag its subject changed under. */\n  readonly reset: () => void;\n}\n\n/** The row's slot between its label and its field. */\ninterface LabelScrubSlot {\n  readonly field: React.RefObject<LabelScrubField | null>;\n  readonly setEnabled: (enabled: boolean) => void;\n  /** Whether a drag holds the value now, so the field's own writes wait. */\n  readonly owning: React.RefObject<boolean>;\n}\n\n/** What a row shares: the slot its field fills, and the props its label takes. */\ninterface LabelScrubRowValue {\n  readonly slot: LabelScrubSlot;\n  readonly labelProps: LabelScrubProps | undefined;\n}\n\nconst LabelScrubContext = React.createContext<LabelScrubRowValue | null>(null);\n\n/**\n * What the label spreads while its field can be dragged.\n *\n * `data-slot` is cleared because the admin gives every `[data-slot=\"label\"]`\n * a pointer cursor marked important, which would hide the resize cursor that\n * says the label drags. The element stays the field's `<label>`, so its\n * association with the input and its accessible name are unchanged.\n */\nexport interface LabelScrubProps {\n  readonly \"data-slot\": undefined;\n  readonly \"data-scrub\": \"\" | \"active\";\n  readonly onPointerDown: (event: React.PointerEvent<HTMLElement>) => void;\n  readonly onClickCapture: (event: React.MouseEvent<HTMLElement>) => void;\n}\n\n/**\n * One style row: its label and its field meet through this, wherever each is\n * drawn inside it.\n */\nexport function LabelScrubRow({\n  subject,\n  children,\n}: {\n  /**\n   * What the row edits: the block and the style target. A drag began on one\n   * subject ends, unwritten, when the row is reused for another, as selecting\n   * another block does — its value came from the subject it started on.\n   */\n  readonly subject: string;\n  readonly children: React.ReactNode;\n}): React.JSX.Element {\n  const row = useLabelScrubSlot(subject);\n  return (\n    <LabelScrubContext.Provider value={row}>\n      {children}\n    </LabelScrubContext.Provider>\n  );\n}\n\n/**\n * The label's half: the props it spreads, or `undefined` while its field\n * cannot be dragged, so a colour, a menu or a keyword's label keeps its plain\n * cursor and handlers. Outside a row, always `undefined`.\n */\nexport function useLabelScrubProps(): LabelScrubProps | undefined {\n  return React.useContext(LabelScrubContext)?.labelProps;\n}\n\n/** The row's state: a slot for its field, and the props its label takes. */\nfunction useLabelScrubSlot(subject: string): LabelScrubRowValue {\n  const field = React.useRef<LabelScrubField | null>(null);\n  const [enabled, setEnabled] = React.useState(false);\n  const [dragging, setDragging] = React.useState(false);\n  const session = React.useRef<ScrubSession | null>(null);\n  const swallowClick = React.useRef(false);\n  const owning = React.useRef(false);\n  const gesture = useLiveGesture();\n  const slot = React.useMemo<LabelScrubSlot>(\n    () => ({ field, setEnabled, owning }),\n    []\n  );\n  // Set when a drag ends because its subject changed, so the field shows its\n  // new subject's value rather than the old one's text.\n  const superseded = React.useRef(false);\n  // A drag does not outlive its row or its subject: taken away mid-drag, or\n  // reused for another block, it ends without writing.\n  React.useEffect(\n    () => () => {\n      superseded.current = true;\n      session.current?.end();\n      superseded.current = false;\n    },\n    [subject]\n  );\n\n  const onPointerDown = (event: React.PointerEvent<HTMLElement>): void => {\n    // A click only ever follows a press, so a flag a drag released elsewhere\n    // left behind cannot swallow this one.\n    swallowClick.current = false;\n    if (event.button !== 0 || event.pointerType === \"touch\") return;\n    if (session.current !== null) return;\n    const origin = field.current?.origin;\n    const before = field.current?.draft;\n    if (origin === undefined || before === undefined) return;\n    // No text is selected by the drag. The click a press below the dead zone\n    // becomes still reaches the label, which focuses the field.\n    event.preventDefault();\n    let progress = FIELD_SCRUB_START;\n    let shown: ScrubbedValue = origin;\n    // The modifiers the field last showed a value with. The release uses\n    // these rather than its own: letting go of Shift before the button is\n    // ordinary, and the write must be the value on screen.\n    let held = scrubModifiersOf(event);\n    // Whether the field shows a value of the drag's that is not written.\n    let previewing = false;\n    const showAt = (dx: number): void => {\n      progress = fieldScrubMove(progress, dx, held);\n      const live = field.current;\n      if (live === null) return;\n      const next =\n        progress.delta === 0 ? origin : live.at(origin, progress.delta);\n      // A step the property refuses outright keeps the last value shown.\n      if (next === undefined) return;\n      shown = next;\n      live.show(String(next));\n      // Written at the next frame where the field writes as it is typed;\n      // read from the field then, so a field reused meanwhile writes nothing.\n      if (live.preview !== undefined) {\n        gesture.move(() => field.current?.preview?.(next));\n      }\n    };\n    session.current = followScrub(\n      {\n        pointerId: event.pointerId,\n        clientX: event.clientX,\n        clientY: event.clientY,\n        host: event.currentTarget,\n      },\n      {\n        onMove: (moved, travel) => {\n          // From here the drag owns the value: the field writes nothing of\n          // its own (a blur, a key) until the drag is released or abandoned.\n          owning.current = true;\n          previewing = true;\n          setDragging(true);\n          held = scrubModifiersOf(moved);\n          showAt(travel.dx);\n        },\n        onRelease: (_lifted, travel) => {\n          swallowClick.current = true;\n          // The release's own position: the last move delivered can be short\n          // of it when the browser coalesces pointer movement.\n          showAt(travel.dx);\n          owning.current = false;\n          previewing = false;\n          const live = field.current;\n          if (live === null) {\n            gesture.cancel();\n            return;\n          }\n          // Back where it started, the field shows what it did before the\n          // press, and what the drag wrote is put back.\n          if (shown === origin) {\n            gesture.cancel();\n            live.show(before);\n            return;\n          }\n          // The release's value, in the run the drag wrote in: one step.\n          const value = shown;\n          gesture.end(() => live.commit(value));\n        },\n        // Escape, a cancelled pointer and a row taken away all end here\n        // without a release: the field goes back to its text before the press.\n        onEnd: () => {\n          owning.current = false;\n          session.current = null;\n          setDragging(false);\n          if (!previewing) return;\n          // What the drag wrote goes back with the text.\n          gesture.cancel();\n          if (superseded.current) field.current?.reset();\n          else field.current?.show(before);\n        },\n      }\n    );\n  };\n\n  return {\n    slot,\n    labelProps: enabled\n      ? {\n          \"data-slot\": undefined,\n          \"data-scrub\": dragging ? \"active\" : \"\",\n          onPointerDown,\n          onClickCapture: event => {\n            if (!swallowClick.current) return;\n            swallowClick.current = false;\n            // The label would otherwise focus its field as the drag ends.\n            event.preventDefault();\n            event.stopPropagation();\n          },\n        }\n      : undefined,\n  };\n}\n\n/**\n * The field's half: offer this value to the row's label.\n *\n * Outside a row that provides a slot it does nothing, so a field drawn on its\n * own keeps only its keyboard stepping.\n *\n * @returns whether a drag owns the value now. The field's own commits — a\n *   blur, Enter, an arrow — must write nothing then: the drag writes once on\n *   release, and a write mid-drag is one Escape could no longer take back.\n */\nexport function useLabelScrub(field: LabelScrubField): () => boolean {\n  const slot = React.useContext(LabelScrubContext)?.slot ?? null;\n  // The latest closures, for a drag that reads them as the pointer moves.\n  React.useLayoutEffect(() => {\n    if (slot !== null) slot.field.current = field;\n  });\n  const enabled = field.origin !== undefined;\n  React.useEffect(() => {\n    slot?.setEnabled(enabled);\n  }, [slot, enabled]);\n  React.useEffect(\n    () => () => {\n      if (slot === null) return;\n      slot.field.current = null;\n      slot.setEnabled(false);\n    },\n    [slot]\n  );\n  return () => slot?.owning.current === true;\n}\n","\"use client\";\n\n/**\n * The numeric field: a number with its unit, the keywords offered beside\n * it, scrubbing its label, and how a unit is read, shown and described.\n *\n * @module style-numeric-field\n */\nimport {\n  trimCssWhitespace,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectSeparator,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport {\n  focusVariableAfterPick,\n  pickedVariable,\n  useOfferedVariables,\n  VariableSelectItems,\n} from \"../../panels/design/variable-choice\";\nimport type { SiteVariable } from \"../../styles/style-colour\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport {\n  CSS_NUMBER,\n  measurementOf,\n  measurementOfText,\n  scrubbedValue,\n  scrubOrigin,\n  steppedValue,\n  unitChoicesFor,\n  withDefaultUnit,\n  withUnit,\n} from \"../../styles/style-numeric\";\nimport { useFieldDescription } from \"../css-hint\";\n\nimport { InheritedValue } from \"./inherited-value\";\nimport { useLabelScrub } from \"./label-scrub\";\nimport { CompactSides } from \"./spacing-box\";\nimport type { CommitOutcome } from \"./style-field-surroundings\";\nimport { keywordLabel } from \"./style-keyword-labels\";\nimport {\n  useDraft,\n  useHeldBlur,\n  commitDraft,\n  TextField,\n  storedText,\n  placeholderFor,\n  useTypesLive,\n} from \"./style-text-field\";\n\n/**\n * Keywords a menu leaves out, still accepted when typed and still shown when\n * stored: a font size's absolute sizes say no size an author can picture\n * (\"x-large\"), where the type scale above them does.\n */\nconst UNOFFERED_KEYWORDS: Readonly<Record<string, readonly string[]>> = {\n  \"font-size\": [\n    \"xx-small\",\n    \"x-small\",\n    \"small\",\n    \"medium\",\n    \"large\",\n    \"x-large\",\n    \"xx-large\",\n    \"xxx-large\",\n  ],\n};\n\n/**\n * A number written as text, as CSS reads one (`0.5`, `1e-7`), with only the\n * whitespace CSS trims around it: not JavaScript's `\\s`, which also takes a\n * no-break space the engine refuses. `undefined` for anything else.\n */\nexport function textNumber(text: string): number | undefined {\n  const trimmed = trimCssWhitespace(text);\n  return CSS_NUMBER.test(trimmed) ? Number(trimmed) : undefined;\n}\n\n/**\n * What describes a number field: its own description, and the words for its\n * unit while what it shows is a number, or nothing at all. What it shows is\n * the draft, or, while that is empty, the inherited value it hints. A keyword\n * such as `inherit` has no unit to be said in.\n */\nexport function describedWithUnit(\n  describedBy: string | undefined,\n  unitWords: string | undefined,\n  draft: string,\n  inherited: string | undefined\n): string | undefined {\n  const shown = trimCssWhitespace(draft) === \"\" ? (inherited ?? \"\") : draft;\n  const keyword =\n    trimCssWhitespace(shown) !== \"\" && textNumber(shown) === undefined;\n  return unitWords === undefined || keyword\n    ? describedBy\n    : [describedBy, unitWords].filter(Boolean).join(\" \");\n}\n\n/**\n * The id of words naming a field's unit for a screen reader, where the unit\n * shows only as a sign beside it (opacity's %). Read by the number field and\n * added to what describes it, never to what marks it invalid.\n */\nexport const UnitWords: React.Context<string | undefined> = React.createContext<\n  string | undefined\n>(undefined);\n\n/**\n * The text field, plus the affordances a value that is one measurement earns.\n *\n * The input stays a TEXT field whatever the value is, which is the whole design:\n * `auto`, `clamp(...)`, a shorthand and a token all remain typeable and none is\n * rewritten. The numeric behaviour is LAYERED on — arrow keys step the quantity\n * and a menu swaps the unit — and both disengage silently when the current value\n * is not a single measurement, so nothing an author can express is taken away by\n * the field being clever about the common case.\n */\nexport function NumericField({\n  id,\n  control,\n  stored,\n  actionName,\n  tokens,\n  describedBy,\n  onCommit,\n  onType,\n  seed,\n  offerVariables = true,\n}: {\n  id: string;\n  control: StyleControl;\n  stored: StyleValue | undefined;\n  tokens: SiteTokenSet | undefined;\n  /**\n   * What the field starts with in place of the stored value, as if typed:\n   * the digit that opened a spacing side's popover.\n   */\n  seed?: string | undefined;\n  /**\n   * Whether its unit menu lists the site's variables first; a spacing\n   * side's popover lists them as its presets instead.\n   */\n  offerVariables?: boolean;\n  /**\n   * This control's own name, position included.\n   *\n   * Taken from the caller rather than derived from the property here: a\n   * composite draws one of these per side, and a name built from the property\n   * alone would give all four of `padding`'s menus the same accessible name,\n   * leaving a screen reader no way to tell which side one edits.\n   */\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  /**\n   * The write a keystroke or a label drag makes where the panel writes as it\n   * is typed, where it differs from the commit: a Design value is drawn on\n   * the canvas meanwhile and stored once, by the commit, when the edit ends.\n   * `onCommit` when omitted. Given the value as the commit would be: a bare\n   * number with the unit shown.\n   */\n  onType?: ((value: StyleValue | null) => CommitOutcome) | undefined;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  // Words for a unit shown only as a sign beside the field, for its description.\n  const unitWords = React.useContext(UnitWords);\n  // The value reaching the field from another tier, which it shows as a hint.\n  const inheritedHint = React.useContext(InheritedValue);\n  const units = unitChoicesFor(control.leaf);\n  // The draft lives HERE rather than inside the text field, because two\n  // controls edit one value and the unit menu was reading the other copy. An\n  // author who types `20` over `12px` and then picks `rem` had the blur refuse\n  // the unitless draft, leaving `12px` stored — and the menu composed from\n  // THAT, committing `12rem` and discarding the 20 they were looking at.\n  // Owned here rather than by the field, so the suffix can step aside while\n  // the field shows a unit being typed. Escape ends that typing too, so the\n  // value it puts back shows its unit in the suffix again.\n  const [typing, setTyping] = React.useState(false);\n  const { draft, setDraft, live } = useDraft(stored, () => setTyping(false));\n  useSeededDraft(seed, setDraft);\n  // Read from the DRAFT, so the menu offers units for the quantity on screen\n  // and swaps the unit on that quantity rather than on a superseded one.\n  const measurement = measurementOfText(draft);\n  // The menu is shown only where it can act. Rendered against a value it cannot\n  // decompose, every choice in it would be a no-op, and a disabled-looking\n  // control that silently does nothing is worse than one that is not there.\n  //\n  // A UNITLESS draft keeps the menu rather than losing it, because typing the\n  // quantity and then choosing the unit is an ordinary way to write one — and a\n  // control that vanishes mid-edit is worse than one showing no selection. A\n  // leaf with no units to offer never reaches this: `unitChoicesFor` answers\n  // empty for anything that is not a dimension, so `line-height` as a number\n  // has no menu to gain a unit from.\n  // Not in the spacing box, whose sides take the unit as typed.\n  const compact = React.useContext(CompactSides);\n  const unitMenu = useFieldUnit({\n    leaf: control.leaf,\n    stored,\n    draft,\n    setDraft,\n    onCommit,\n  });\n  const { unit, keywords } = unitMenu;\n  const showUnits = !compact && unitMenu.acts;\n  const hold = useHeldBlur(storedText(stored));\n  const suffix = suffixState(unitMenu, typing, measurement);\n  const menu = useValueMenu({\n    // None in a side of the box, or where the caller lists them itself.\n    offered: offerVariables && !compact,\n    control,\n    tokens,\n    showUnits,\n    suffix,\n    hold,\n    // A unit picked straight after typing finishes the same edit: one undo\n    // step takes the number and its unit back together.\n    chooseUnit: choice => {\n      live.join(() => unitMenu.choose(choice));\n      live.end();\n    },\n    onCommit,\n  });\n  // A stored unit the candidate list does not carry — `ch`, or an uppercase\n  // `PX` the validator folds — is live and compiles while matching no item, and\n  // a controlled select over it renders an EMPTY trigger above a value that is\n  // doing something. Offered verbatim as its own item, which is what the\n  // keyword select above already does for a value outside its vocabulary.\n  const extraUnit = unlistedUnit(measurement, units);\n  const typed = typedWrite(onType, control, unit);\n  const commitText = useNumericLabelScrub({\n    control,\n    stored,\n    draft,\n    unit,\n    setDraft,\n    setTyping,\n    onCommit,\n    onType: typed.onType,\n  });\n\n  return (\n    <div className=\"nx-style-inspector__numeric\">\n      <TextField\n        id={id}\n        control={control}\n        stored={stored}\n        draft={draft}\n        setDraft={setDraft}\n        tokens={tokens}\n        describedBy={describedWithUnit(\n          describedBy,\n          unitWords,\n          draft,\n          inheritedHint\n        )}\n        invalid={describedBy !== undefined}\n        // With no menu drawn there is nothing to hold for: its refs are empty.\n        editing={{ holdBlur: hold.holdBlur, typing, setTyping }}\n        live={live}\n        {...typed}\n        onCommit={commitText}\n        // The unit shown in the suffix is left out of the field.\n        {...suffixedText(control, unit, unitMenu.isKeyword, showUnits)}\n        onStep={(draft, delta) => {\n          const next = steppedValue(\n            control.leaf,\n            withDefaultUnit(control.leaf, draft, unit) ?? draft,\n            delta\n          );\n          // `undefined` means this value cannot be stepped or the result would\n          // be refused, so the key does nothing rather than writing a value the\n          // document then rejects.\n          if (next === undefined) return null;\n          onCommit(next);\n          return String(next);\n        }}\n      />\n      <UnitMenu\n        unitsShown={showUnits}\n        {...menu}\n        hold={hold}\n        actionName={actionName}\n        described={described}\n        invalid={describedBy !== undefined}\n        extraUnit={extraUnit}\n        units={units}\n        cssProperty={control.leaf.cssProperty}\n        keywords={keywords}\n        draft={draft}\n      />\n    </div>\n  );\n}\n\n/**\n * Each keystroke's and each drag move's write where it is not the commit\n * (`NumericField`'s `onType`), given the unit the field shows, as the commit\n * is: as props for the text field, empty where there is none.\n */\nfunction typedWrite(\n  onType: ((value: StyleValue | null) => CommitOutcome) | undefined,\n  control: StyleControl,\n  unit: string\n): { onType?: (value: StyleValue | null) => CommitOutcome } {\n  if (onType === undefined) return {};\n  return {\n    onType: value => onType(withDefaultUnit(control.leaf, value, unit)),\n  };\n}\n\n/** No variables, as one value, for a field that offers none. */\nconst NO_VARIABLES: readonly SiteVariable[] = Object.freeze([]);\n\n/**\n * What a numeric field's value menu holds and shows: the site's variables\n * the field takes, first, where it offers them; the unit in its trigger\n * while units are listed, and nothing there while only variables are; and\n * what a choice does: a unit or keyword goes to the unit's own choice, a\n * variable is stored as `{ $token }`, the field becoming its chip.\n */\nfunction useValueMenu({\n  offered,\n  control,\n  tokens,\n  showUnits,\n  suffix,\n  hold,\n  chooseUnit,\n  onCommit,\n}: {\n  offered: boolean;\n  control: StyleControl;\n  tokens: SiteTokenSet | undefined;\n  showUnits: boolean;\n  suffix: { value: string; placeholder: string };\n  hold: ReturnType<typeof useHeldBlur>;\n  chooseUnit: (choice: string) => void;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): {\n  variables: readonly SiteVariable[];\n  value: string;\n  placeholder: string;\n  choose: (choice: string) => void;\n} {\n  const variables = useOfferedVariables(control.leaf, tokens);\n  const shown = showUnits ? suffix : { value: \"\", placeholder: \"\" };\n  return {\n    variables: offered ? variables : NO_VARIABLES,\n    ...shown,\n    choose: choice => {\n      const identity = pickedVariable(choice);\n      if (identity === undefined) {\n        chooseUnit(choice);\n        return;\n      }\n      // The field becomes the variable's chip, and its menu goes with it.\n      focusVariableAfterPick(hold.trigger.current);\n      onCommit({ $token: identity });\n    },\n  };\n}\n\n/**\n * A length field's value menu: the site's variables it takes first (\"Your\n * spacing\", \"Your sizes\"), then its units, a stored unit it doesn't list, and\n * its keywords after a line.\n *\n * The units are listed only where a choice of one could act. Over a value\n * they cannot act on (`calc()`, an inherited `auto`) the menu still opens on\n * the variables, the one way to them; with neither, nothing is drawn.\n */\nfunction UnitMenu({\n  unitsShown,\n  variables,\n  value,\n  placeholder,\n  hold,\n  choose,\n  actionName,\n  described,\n  invalid,\n  extraUnit,\n  units,\n  cssProperty,\n  keywords,\n  draft,\n}: {\n  unitsShown: boolean;\n  variables: readonly SiteVariable[];\n  value: string;\n  placeholder: string;\n  hold: ReturnType<typeof useHeldBlur>;\n  choose: (choice: string) => void;\n  actionName: string;\n  described: string | undefined;\n  invalid: boolean;\n  extraUnit: string | null;\n  units: readonly string[];\n  cssProperty: string;\n  keywords: readonly string[];\n  draft: string;\n}): React.JSX.Element | null {\n  if (!unitsShown && variables.length === 0) return null;\n  return (\n    <Select\n      // The empty string, never `undefined`. Radix reads `\"\"` as \"no\n      // selection\" and shows the placeholder, while `undefined` switches it\n      // from controlled to UNCONTROLLED — where it keeps whatever was last\n      // picked, so a unit added and then undone leaves the trigger still\n      // displaying it while the draft has none. The draft is the only unit\n      // state, and passing `undefined` would give it a second one.\n      value={value}\n      onValueChange={hold.choosing(choose)}\n      onOpenChange={hold.onOpenChange}\n    >\n      <SelectTrigger\n        ref={hold.trigger}\n        onBlur={hold.onTriggerBlur}\n        className=\"nx-style-inspector__unit\"\n        // Named for what it changes: the unit where units are listed, the\n        // variable where only variables are.\n        aria-label={\n          unitsShown ? `Unit for ${actionName}` : `Variables for ${actionName}`\n        }\n        // A unit change can be refused — a document at its byte limit, a\n        // value the validator rejects — and the message that explains it is\n        // rendered once for the field. Pointed at from HERE as well as from\n        // the text input, because a screen-reader user who returns to the\n        // menu is otherwise on the control that failed with nothing saying\n        // so and no way to reach the reason.\n        aria-describedby={described}\n        aria-invalid={invalid ? true : undefined}\n      >\n        <SelectValue placeholder={placeholder} />\n      </SelectTrigger>\n      <SelectContent ref={hold.content}>\n        <VariableSelectItems offered={variables} before={unitsShown} />\n        <UnitItems\n          shown={unitsShown}\n          extraUnit={extraUnit}\n          units={units}\n          cssProperty={cssProperty}\n          keywords={keywords}\n          draft={draft}\n        />\n      </SelectContent>\n    </Select>\n  );\n}\n\n/**\n * A unit menu's own choices: a stored unit it doesn't list, its units, and\n * its keywords after a line. Nothing where no unit choice could act.\n */\nfunction UnitItems({\n  shown,\n  extraUnit,\n  units,\n  cssProperty,\n  keywords,\n  draft,\n}: {\n  shown: boolean;\n  extraUnit: string | null;\n  units: readonly string[];\n  cssProperty: string;\n  keywords: readonly string[];\n  draft: string;\n}): React.JSX.Element | null {\n  if (!shown) return null;\n  return (\n    <>\n      {extraUnit === null ? null : (\n        <SelectItem value={extraUnit}>{extraUnit}</SelectItem>\n      )}\n      {units.map(choice => (\n        <SelectItem key={choice} value={choice}>\n          {choice}\n        </SelectItem>\n      ))}\n      <KeywordItems\n        cssProperty={cssProperty}\n        keywords={keywords}\n        draft={draft}\n      />\n    </>\n  );\n}\n\n/**\n * The seed put in the draft once, after the draft has read the stored value:\n * the first character of a value typed on a spacing side, which opened it.\n */\nfunction useSeededDraft(\n  seed: string | undefined,\n  setDraft: (value: string) => void\n): void {\n  const first = React.useRef(seed);\n  React.useEffect(() => {\n    if (first.current !== undefined) setDraft(first.current);\n  }, [setDraft]);\n}\n\n/**\n * A unit menu's keywords after a line, in words with the CSS spelling in the\n * tooltip; see style-keyword-labels. Those a menu leaves out are left out\n * unless the field holds one.\n */\nfunction KeywordItems({\n  cssProperty,\n  keywords,\n  draft,\n}: {\n  cssProperty: string;\n  keywords: readonly string[];\n  draft: string;\n}): React.JSX.Element | null {\n  const unoffered = UNOFFERED_KEYWORDS[cssProperty] ?? [];\n  const offered = keywords.filter(\n    keyword => keyword === draft || !unoffered.includes(keyword)\n  );\n  if (offered.length === 0) return null;\n  return (\n    <>\n      <SelectSeparator />\n      {offered.map(keyword => (\n        <SelectItem key={keyword} value={keyword} title={keyword}>\n          {keywordLabel(cssProperty, keyword)}\n        </SelectItem>\n      ))}\n    </>\n  );\n}\n\n/**\n * The unit a measurement carries that the menu does not list, or `null`.\n * Its own function so the field reads as what it draws, not as the test.\n */\nfunction unlistedUnit(\n  measurement: ReturnType<typeof measurementOfText>,\n  units: readonly string[]\n): string | null {\n  const unit = unitOf(measurement);\n  return unit !== undefined && !units.includes(unit) ? unit : null;\n}\n\n/**\n * The number field's value, offered to its row's label to drag: shown in the\n * field while the pointer is down, written as it moves where the panel writes\n * as it is typed, and written on release through the same commit as a typed\n * value, the whole drag one undo step.\n *\n * @returns the field's own commit for its text: a bare number given the unit\n *   the field shows (\"24\" is 24px), and nothing written while a drag owns the\n *   value — a blur mid-drag would write the preview, and the release again.\n */\nfunction useNumericLabelScrub({\n  control,\n  stored,\n  draft,\n  unit,\n  setDraft,\n  setTyping,\n  onCommit,\n  onType,\n}: {\n  control: StyleControl;\n  stored: StyleValue | undefined;\n  draft: string;\n  unit: string;\n  setDraft: (value: string) => void;\n  setTyping: (typing: boolean) => void;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  /** A move's write where it is not the commit; see `NumericField`. */\n  onType: ((value: StyleValue | null) => CommitOutcome) | undefined;\n}): (value: StyleValue | null) => CommitOutcome {\n  const inherited = React.useContext(InheritedValue);\n  const mode = useCanvasTokenMode();\n  const commitText = (value: StyleValue | null): CommitOutcome =>\n    onCommit(withDefaultUnit(control.leaf, value, unit));\n  const typesLive = useTypesLive();\n  const writeWith =\n    (commit: (value: StyleValue | null) => CommitOutcome) =>\n    (value: string | number): void => {\n      commitDraft({\n        draft: String(value),\n        stored,\n        kind: control.kind,\n        leaf: control.leaf,\n        // A drag writes a quantity, never a variable's name, so no variable\n        // is matched against it.\n        tokens: undefined,\n        mode,\n        onCommit: commit,\n        setDraft,\n      });\n    };\n  const write = writeWith(commitText);\n  const owning = useLabelScrub({\n    origin: scrubOrigin(control.leaf, draft, unit, inherited),\n    at: (from, delta) => scrubbedValue(control.leaf, from, delta),\n    draft,\n    show: text => {\n      // Shown as a value, not as typing, so the unit stays beside it.\n      setTyping(false);\n      setDraft(text);\n    },\n    reset: () => {\n      setTyping(false);\n      setDraft(storedText(stored));\n    },\n    commit: write,\n    // Through the same commit as the release, past the field's own writes,\n    // which wait while the drag owns the value.\n    // A move is the field's own write unless it has one of its own.\n    ...(typesLive\n      ? { preview: onType === undefined ? write : writeWith(onType) }\n      : {}),\n  });\n  // \"refused\" keeps the text on screen, which is the drag's live value.\n  return value => (owning() ? \"refused\" : commitText(value));\n}\n\n/**\n * A field's hint while it shows its unit: what an unset value IS where the\n * property's initial value is a word (\"Auto\" for a width, a height or an\n * inset, \"None\" for a max size), so the hint never reads like a real default;\n * otherwise the leaf's own hint as a number alone (\"16\", a border's \"1\").\n * Margin allows `auto` but starts at 0, so it keeps a number.\n */\nfunction bareNumberHint(control: StyleControl): string {\n  const { leaf } = control;\n  const keywords = leaf.kind === \"dimension\" ? (leaf.keywords ?? []) : [];\n  const css = leaf.cssProperty;\n  if (keywords.includes(\"none\") && /^max-/.test(css)) return \"None\";\n  if (keywords.includes(\"auto\") && !/^(margin|padding)/.test(css)) {\n    return \"Auto\";\n  }\n  return /^-?[\\d.]+/.exec(placeholderFor(control))?.[0] ?? \"\";\n}\n\n/** A value that is one variable and nothing else: `var(--site-font-size-h2)`. */\nconst VARIABLE_ALONE = /^var\\(\\s*--[\\w-]+\\s*\\)$/;\n\n/**\n * Whether a choice in the unit menu can act: on a measurement, a keyword, or\n * any bare number the commit will give the unit (\".5\", \"1e3\" included, by the\n * same grammar). On an empty field only when what shows there is a\n * measurement or nothing: an inherited \"auto\" or \"clamp(…)\" beside \"px\"\n * would read as one value it is not. An inherited variable alone, a Site text\n * size, acts too: the field never shows it as text, and the next number takes\n * the unit chosen, as on any empty field.\n */\nfunction unitActs(\n  draft: string,\n  measurement: ReturnType<typeof measurementOfText>,\n  inherited: string | undefined,\n  isKeyword: boolean\n): boolean {\n  const text = trimCssWhitespace(draft);\n  if (text === \"\") {\n    return (\n      inherited === undefined ||\n      measurementOfText(inherited) !== undefined ||\n      VARIABLE_ALONE.test(trimCssWhitespace(inherited))\n    );\n  }\n  return measurement !== undefined || isKeyword || CSS_NUMBER.test(text);\n}\n\n/** The first unit that says one, in order of precedence, else px. */\nfunction shownUnit(candidates: readonly (string | undefined)[]): string {\n  return candidates.find(candidate => candidate !== undefined) ?? \"px\";\n}\n\n/**\n * How the field reads beside its unit suffix: the unit left out of the value\n * and the hint (\"2\" beside \"rem\"), a keyword shown once, in the suffix, and a\n * hint that says what an unset value is. Nothing when no suffix is shown.\n */\nfunction suffixedText(\n  control: StyleControl,\n  unit: string,\n  isKeyword: boolean,\n  shown: boolean\n): { display?: (text: string) => string; fallbackHint?: string } {\n  if (!shown) return {};\n  const fallbackHint = bareNumberHint(control);\n  return {\n    display: isKeyword\n      ? () => \"\"\n      : text => {\n          // A length in another unit (an inherited \"2px\" beside a pending\n          // \"rem\") is not shown beside this one, which would read as one\n          // value it is not; the plain hint takes its place.\n          const other = unitOf(measurementOfText(text));\n          return other !== undefined && other !== unit\n            ? fallbackHint\n            : withoutUnit(text, unit);\n        },\n    fallbackHint,\n  };\n}\n\n/** A measurement's unit, or `undefined` for none or a bare number. */\nfunction unitOf(\n  measurement: ReturnType<typeof measurementOfText>\n): string | undefined {\n  return measurement === undefined || measurement.unit === \"\"\n    ? undefined\n    : measurement.unit;\n}\n\n/** A length's text without the unit shown beside it: \"2rem\" beside \"rem\" reads \"2\". */\nfunction withoutUnit(text: string, unit: string): string {\n  const trimmed = trimCssWhitespace(text);\n  const number = trimmed.slice(0, trimmed.length - unit.length);\n  return trimmed.toLowerCase().endsWith(unit.toLowerCase()) &&\n    CSS_NUMBER.test(number)\n    ? number\n    : text;\n}\n\n/**\n * The unit a length field shows and a bare number takes: the one the draft\n * already carries, else the one the author last chose, else the leaf's first\n * (px). Its keywords, `auto` and the rest, are offered after the units.\n *\n * `acts` says whether a choice in the menu can do anything: an empty field,\n * whose bare number will take the unit shown, one measurement, or one of the\n * keywords. Over anything else — `calc()`, scientific notation — every choice\n * would be a no-op, and a control that silently does nothing is worse than\n * none.\n */\nfunction useFieldUnit({\n  leaf,\n  stored,\n  draft,\n  setDraft,\n  onCommit,\n}: {\n  leaf: StyleLeaf;\n  stored: StyleValue | undefined;\n  draft: string;\n  setDraft: (value: string) => void;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): {\n  unit: string;\n  keywords: readonly string[];\n  isKeyword: boolean;\n  acts: boolean;\n  value: string;\n  choose: (choice: string) => void;\n} {\n  const [chosen, setChosen] = React.useState<string | undefined>(undefined);\n  const measurement = measurementOfText(draft);\n  const units = unitChoicesFor(leaf);\n  const keywords = leaf.kind === \"dimension\" ? (leaf.keywords ?? []) : [];\n  const inherited = React.useContext(InheritedValue);\n  // The unit the draft says, else the one just chosen, else the stored\n  // value's, else the inherited value's, so a new number keeps the unit the\n  // author sees; px only when nothing says another.\n  const unit = shownUnit([\n    unitOf(measurement),\n    chosen,\n    unitOf(measurementOf(stored)),\n    unitOf(inherited === undefined ? undefined : measurementOfText(inherited)),\n    units[0],\n  ]);\n  const isKeyword = keywords.includes(draft);\n  const write = (value: string) => {\n    if (onCommit(value) !== \"refused\") setDraft(value);\n  };\n  return {\n    unit,\n    keywords,\n    isKeyword,\n    acts:\n      units.length > 0 && unitActs(draft, measurement, inherited, isKeyword),\n    // A unit chosen over a stored keyword shows at once, though nothing is\n    // written until a number is typed.\n    value: isKeyword && chosen === undefined ? draft : unit,\n    choose: choice => {\n      // A keyword is a whole value, written as chosen.\n      if (keywords.includes(choice)) {\n        setChosen(undefined);\n        return write(choice);\n      }\n      setChosen(choice);\n      // Composed from the draft, which is what the author is looking at;\n      // with no number on screen yet, the unit waits for one.\n      const next = withUnit(leaf, draft, choice);\n      if (next !== undefined) write(next);\n    },\n  };\n}\n\n/**\n * What the unit suffix shows. While the field shows typed text that carries\n * its own unit or a keyword (\"2ch\", \"auto\"), nothing: the text says it once,\n * where the suffix beside it read as \"2ch ch\".\n */\nfunction suffixState(\n  unitMenu: { value: string; isKeyword: boolean },\n  typing: boolean,\n  measurement: ReturnType<typeof measurementOfText>\n): { value: string; placeholder: string } {\n  const typedOwn =\n    typing && (unitMenu.isKeyword || unitOf(measurement) !== undefined);\n  return typedOwn\n    ? { value: \"\", placeholder: \"\" }\n    : { value: unitMenu.value, placeholder: \"unit\" };\n}\n","\"use client\";\n\n/**\n * A spacing-box side's popover: the site's spacing variables as presets, a\n * number with its unit, and \"Apply to\", which writes the value to this side,\n * it and the one across, or all four, as one edit.\n *\n * Non-modal, and never a trap. Opened by a digit, it is quick entry: Tab or\n * Enter commits, and Tab goes on to the next side. Opened by a click or\n * Enter, Tab walks its controls and, past the last, goes on to the next\n * side. Escape closes it and returns to the side.\n *\n * @module spacing-side-popover\n */\nimport type { SiteTokenSet, StyleValue } from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n  PopoverContent,\n} from \"@nextlyhq/ui\";\nimport { MoreHorizontal, X } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { isElement, isInput } from \"../../canvas/dom-kind\";\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport { SegmentChoices } from \"../segment-choices\";\n\nimport { CompactSides } from \"./spacing-box\";\nimport {\n  identityOfKey,\n  NONE,\n  offeredPreset,\n  presetKey,\n  presetLabels,\n  spacingPresets,\n} from \"./spacing-presets\";\nimport type { ApplyTo } from \"./spacing-side\";\nimport type { CommitOutcome } from \"./style-field-surroundings\";\nimport { NumericField } from \"./style-numeric-field\";\n\n/** Where focus goes as the popover closes. */\nexport type SideClose = \"side\" | \"next\" | \"previous\";\n\n/**\n * What the number's commit comes to as the popover closes.\n *\n * Right after an Enter in the number, the commit that Enter made says, and\n * nothing is committed again: a second commit in the same key press is built\n * before the editor has drawn the first, from the document as it was, and is\n * refused. A number still being typed (Tab in quick entry) is committed by\n * taking focus off it, to no other element, so the popover isn't left.\n * Anywhere else nothing is pending, so an earlier refusal never holds the\n * popover open.\n */\nfunction commitTyped(\n  root: HTMLElement | null,\n  outcome: React.RefObject<CommitOutcome | undefined>,\n  afterEnter: boolean\n): CommitOutcome | undefined {\n  if (afterEnter) return outcome.current;\n  const active = root?.ownerDocument.activeElement;\n  if (root === null || !isInput(active) || !root.contains(active)) {\n    return undefined;\n  }\n  outcome.current = undefined;\n  active.blur();\n  const result = outcome.current;\n  if (result === \"refused\") active.focus();\n  return result;\n}\n\n/** What the popover is given. */\nexport interface SpacingSidePopoverProps {\n  /** The side's name, its title: \"Padding top\". */\n  readonly name: string;\n  readonly control: StyleControl;\n  readonly stored: StyleValue | undefined;\n  readonly tokens: SiteTokenSet | undefined;\n  /** The digit it opened typing, for quick entry. */\n  readonly seed: string | undefined;\n  readonly applyTo: ApplyTo;\n  readonly pairLabel: string;\n  readonly pathsFor: (applyTo: ApplyTo) => readonly (readonly string[])[];\n  readonly onApplyTo: (next: ApplyTo) => void;\n  readonly onCommit: (value: StyleValue | null) => CommitOutcome;\n  readonly onCommitSides: (\n    paths: readonly (readonly string[])[],\n    value: StyleValue\n  ) => CommitOutcome;\n  readonly onReset: () => void;\n  readonly onClose: (to: SideClose) => void;\n  /** Why the side's last write was refused, said in the popover. */\n  readonly refusal: string | null;\n  /** The side it opened from, whose own click closes it. */\n  readonly side: React.RefObject<HTMLButtonElement | null>;\n}\n\nexport function SpacingSidePopover(\n  props: SpacingSidePopoverProps\n): React.JSX.Element {\n  const { name, control, stored, seed, applyTo } = props;\n  const id = React.useId();\n  const content = React.useRef<HTMLDivElement>(null);\n  const mode = useCanvasTokenMode();\n  const presets = spacingPresets(control, props.tokens, mode);\n  // What the number's last commit came to: a refused one keeps the popover\n  // open with the draft, so the author can correct it.\n  const outcome = React.useRef<CommitOutcome | undefined>(undefined);\n  const record = (result: CommitOutcome): CommitOutcome => {\n    outcome.current = result;\n    return result;\n  };\n  /*\n   * The write just made, for the rest of the event that made it. Closing\n   * moves focus off a number committed by Enter, and its blur commits it\n   * again in the same key press, before the editor has drawn the first:\n   * built from the page as it was, that second write is refused. A write the\n   * same as the one just made is therefore not made again in that event;\n   * cleared once the event is done, so the same value chosen again later (an\n   * undo between) writes as it should.\n   */\n  const lastWritten = React.useRef<string | null>(null);\n  const write = (value: StyleValue): CommitOutcome => {\n    const paths = props.pathsFor(applyTo);\n    const key = JSON.stringify([paths, value]);\n    if (key === lastWritten.current) return record(\"unchanged\");\n    const result = props.onCommitSides(paths, value);\n    if (result === \"applied\") {\n      lastWritten.current = key;\n      queueMicrotask(() => {\n        lastWritten.current = null;\n      });\n    }\n    return record(result);\n  };\n  /*\n   * Every way of closing moves focus itself, before the popover goes, so\n   * nothing is left to put it back afterwards. A number still being typed is\n   * committed first, by moving focus off it within the popover, and a refused\n   * commit keeps the popover open on it.\n   */\n  const close = (to: SideClose, afterEnter = false): void => {\n    if (commitTyped(content.current, outcome, afterEnter) === \"refused\") {\n      return;\n    }\n    props.onClose(to);\n  };\n  // Escape, ✕ and Reset close whatever the number holds: the author is\n  // leaving it, and its refusal is still said under the side.\n  const leave = (to: SideClose): void => props.onClose(to);\n  return (\n    <PopoverContent\n      ref={content}\n      // Drawn at the page's end, outside the builder's element: the class\n      // brings the builder's tokens (its borders, the shared green) with it.\n      className=\"nx-builder-tokens nx-spacing-popover\"\n      side=\"bottom\"\n      align=\"center\"\n      collisionPadding={8}\n      aria-labelledby={`${id}-title`}\n      onOpenAutoFocus={event => {\n        event.preventDefault();\n        focusStart(content.current, seed);\n      }}\n      onEscapeKeyDown={event => {\n        event.preventDefault();\n        leave(\"side\");\n      }}\n      // A click elsewhere leaves focus where it went.\n      onCloseAutoFocus={event => event.preventDefault()}\n      // A press on the side is the side's own toggle, which closes it.\n      onInteractOutside={event => {\n        const at = event.target;\n        if (isElement(at) && props.side.current?.contains(at) === true) {\n          event.preventDefault();\n        }\n      }}\n      // An Enter in the number starts with no outcome, so the one it reads\n      // after is the commit that Enter made, or none where nothing changed.\n      onKeyDownCapture={event => {\n        if (event.key === \"Enter\" && isInput(event.target)) {\n          outcome.current = undefined;\n        }\n      }}\n      onKeyDown={event =>\n        popoverKeys(event, seed !== undefined, (to, afterEnter) => {\n          event.preventDefault();\n          close(to, afterEnter);\n        })\n      }\n    >\n      <div className=\"nx-spacing-popover__head\">\n        <h3 id={`${id}-title`} className=\"nx-spacing-popover__title\">\n          {name}\n        </h3>\n        <DropdownMenu modal={false}>\n          <DropdownMenuTrigger asChild>\n            <button\n              type=\"button\"\n              className=\"nx-spacing-popover__icon\"\n              aria-label={`More for ${name}`}\n            >\n              <MoreHorizontal size={14} aria-hidden=\"true\" />\n            </button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent align=\"end\">\n            <DropdownMenuItem\n              disabled={stored === undefined}\n              onSelect={() => {\n                props.onReset();\n                leave(\"side\");\n              }}\n            >\n              Reset\n            </DropdownMenuItem>\n          </DropdownMenuContent>\n        </DropdownMenu>\n        <button\n          type=\"button\"\n          className=\"nx-spacing-popover__icon\"\n          aria-label=\"Close\"\n          onClick={() => leave(\"side\")}\n        >\n          <X size={14} aria-hidden=\"true\" />\n        </button>\n      </div>\n      <div className=\"nx-spacing-popover__presets\">\n        <span id={`${id}-presets`} className=\"nx-spacing-popover__label\">\n          Presets\n        </span>\n        <SegmentChoices\n          options={[NONE, ...presets.map(preset => presetKey(preset.identity))]}\n          on={offeredPreset(stored, presets)}\n          labels={presetLabels(presets)}\n          labelId={`${id}-presets`}\n          onChoose={choice => {\n            const identity = identityOfKey(choice);\n            write(identity === undefined ? \"0\" : { $token: identity });\n          }}\n        />\n      </div>\n      <label htmlFor={`${id}-number`} className=\"nx-spacing-popover__hidden\">\n        {`Value for ${name}`}\n      </label>\n      {/* With its unit menu, which the box's own sides have no room for. */}\n      <CompactSides.Provider value={false}>\n        <NumericField\n          id={`${id}-number`}\n          control={control}\n          stored={stored}\n          tokens={props.tokens}\n          actionName={name}\n          describedBy={props.refusal === null ? undefined : `${id}-refusal`}\n          seed={seed}\n          offerVariables={false}\n          onCommit={value =>\n            value === null ? record(props.onCommit(null)) : write(value)\n          }\n        />\n      </CompactSides.Provider>\n      {props.refusal === null ? null : (\n        <p\n          id={`${id}-refusal`}\n          className=\"nx-spacing-popover__refusal\"\n          role=\"alert\"\n        >\n          {props.refusal}\n        </p>\n      )}\n      <span id={`${id}-apply`} className=\"nx-spacing-popover__label\">\n        Apply to\n      </span>\n      <SegmentChoices\n        options={[\"side\", \"pair\", \"all\"] as const}\n        on={applyTo}\n        labels={{\n          side: \"This side\",\n          pair: props.pairLabel,\n          all: \"All sides\",\n        }}\n        labelId={`${id}-apply`}\n        onChoose={next => {\n          props.onApplyTo(next);\n          // The side's value goes to the sides now included, at once.\n          if (stored !== undefined && next !== \"side\") {\n            props.onCommitSides(props.pathsFor(next), stored);\n          }\n        }}\n      />\n    </PopoverContent>\n  );\n}\n\n/**\n * Where focus starts: in the number, after the digit typed, for quick entry;\n * otherwise on the chosen preset, or the first.\n */\nfunction focusStart(root: HTMLElement | null, seed: string | undefined): void {\n  if (root === null) return;\n  if (seed !== undefined) {\n    const input = root.querySelector<HTMLInputElement>(\"input\");\n    input?.focus();\n    // After the seeded draft has drawn, the caret after it.\n    requestAnimationFrame(() => {\n      const end = input?.value.length ?? 0;\n      input?.setSelectionRange(end, end);\n    });\n    return;\n  }\n  // The marked preset, or the first; the number where there is no preset.\n  (\n    root.querySelector<HTMLElement>(\n      '.nx-spacing-popover__presets [role=\"radio\"][tabindex=\"0\"]'\n    ) ?? root.querySelector<HTMLElement>(\"input\")\n  )?.focus();\n}\n\n/** The popover's own keys: Tab past either end, and Enter in the number. */\nfunction popoverKeys(\n  event: React.KeyboardEvent<HTMLDivElement>,\n  quick: boolean,\n  close: (to: SideClose, afterEnter?: boolean) => void\n): void {\n  const target = event.target as HTMLElement;\n  const inNumber = isInput(target);\n  // After the number's own Enter has committed it.\n  if (event.key === \"Enter\" && inNumber) return close(\"side\", true);\n  if (event.key !== \"Tab\") return;\n  const to =\n    quick && inNumber\n      ? quickTab(event.shiftKey)\n      : tabPastEnd(event.currentTarget, target, event.shiftKey);\n  if (to !== undefined) close(to);\n}\n\n/** Tab in quick entry: on to the next side, or back to the one before. */\nfunction quickTab(back: boolean): SideClose {\n  return back ? \"previous\" : \"next\";\n}\n\n/**\n * Tab past the popover's last control goes on to the next side, and Shift+Tab\n * before its first goes back to its own; anywhere else Tab moves as usual.\n */\nfunction tabPastEnd(\n  root: HTMLElement,\n  target: HTMLElement,\n  back: boolean\n): SideClose | undefined {\n  const stops = tabStops(root);\n  if (!back && target === stops[stops.length - 1]) return \"next\";\n  if (back && target === stops[0]) return \"side\";\n  return undefined;\n}\n\n/** The popover's Tab stops, in order. */\nfunction tabStops(root: HTMLElement): readonly HTMLElement[] {\n  return Array.from(\n    root.querySelectorAll<HTMLElement>(\"button, input, [tabindex]\")\n  ).filter(\n    element =>\n      element.tabIndex >= 0 &&\n      !(element as HTMLButtonElement).disabled &&\n      !element.hidden\n  );\n}\n","\"use client\";\n\n/**\n * A side of the spacing box: a button showing the side's value whole, which\n * opens the side's popover (`spacing-side-popover.tsx`) to choose a preset,\n * type a value or apply it to several sides.\n *\n * Its keys: a click or Enter opens the popover on its presets, a digit opens\n * it typing that digit, and Tab from there commits and moves to the next\n * side, so \"4 0 Tab 4 0 Tab\" goes round the box. Alt+Backspace and the\n * side's context menu reset it, as its field's reset does.\n *\n * @module spacing-side\n */\nimport {\n  isTokenRef,\n  type SiteTokenSet,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  ContextMenu,\n  ContextMenuContent,\n  ContextMenuItem,\n  ContextMenuTrigger,\n  Popover,\n  PopoverAnchor,\n  TooltipProvider,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport {\n  variableFor,\n  variableLabel,\n  variablesFor,\n} from \"../../styles/style-colour\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport {\n  sideOf,\n  type LogicalSide,\n  type SideBox,\n} from \"../../styles/style-sides\";\n\nimport { variableRead } from \"./site-default-source\";\nimport { SpacingSidePopover, type SideClose } from \"./spacing-side-popover\";\nimport {\n  TokenPrefixContext,\n  type CommitOutcome,\n} from \"./style-field-surroundings\";\nimport { storedText } from \"./style-text-field\";\n\n/** Which sides a value goes to: this one, it and the one across, or all four. */\nexport type ApplyTo = \"side\" | \"pair\" | \"all\";\n\nconst ApplyToContext = React.createContext<\n  readonly [ApplyTo, (next: ApplyTo) => void] | undefined\n>(undefined);\n\n/**\n * \"Apply to\", remembered while the panel is open: a choice made on one side\n * holds for the next side and the next block, until the panel closes.\n */\nexport function SpacingApplyToProvider({\n  children,\n}: {\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const [applyTo, setApplyTo] = React.useState<ApplyTo>(\"side\");\n  const value = React.useMemo(() => [applyTo, setApplyTo] as const, [applyTo]);\n  return (\n    <ApplyToContext.Provider value={value}>{children}</ApplyToContext.Provider>\n  );\n}\n\n/** \"Apply to\" from the panel, or the side's own where no panel holds it. */\nfunction useApplyTo(): readonly [ApplyTo, (next: ApplyTo) => void] {\n  const shared = React.useContext(ApplyToContext);\n  const local = React.useState<ApplyTo>(\"side\");\n  return shared ?? local;\n}\n\n/** The ring a side is drawn in: its sides, in Tab order, and their axes. */\nexport const SpacingRingContext: React.Context<SideBox | undefined> =\n  React.createContext<SideBox | undefined>(undefined);\n\nconst ACROSS: Readonly<Record<LogicalSide, LogicalSide>> = {\n  blockStart: \"blockEnd\",\n  blockEnd: \"blockStart\",\n  inlineStart: \"inlineEnd\",\n  inlineEnd: \"inlineStart\",\n};\n\n/** The paths a value chosen at this side is written to. */\nfunction appliedPaths(\n  box: SideBox | undefined,\n  control: StyleControl,\n  applyTo: ApplyTo\n): readonly (readonly string[])[] {\n  if (box === undefined || applyTo === \"side\") return [control.path];\n  if (applyTo === \"all\") return box.controls.map(each => each.path);\n  const side = sideOf(box, control);\n  const across = box.controls.find(\n    each => side !== undefined && sideOf(box, each) === ACROSS[side]\n  );\n  return across === undefined ? [control.path] : [control.path, across.path];\n}\n\n/**\n * The words for a side and the one across from it, as the box shows them:\n * the block sides are top and bottom where lines run across, and left and\n * right where they run down.\n */\nfunction pairLabel(\n  box: SideBox | undefined,\n  control: StyleControl\n): \"Top & bottom\" | \"Left & right\" {\n  const side = box === undefined ? undefined : sideOf(box, control);\n  const block = side === undefined || side.startsWith(\"block\");\n  const across =\n    (box?.axes?.writingMode ?? \"horizontal-tb\") === \"horizontal-tb\";\n  return block === across ? \"Top & bottom\" : \"Left & right\";\n}\n\n/** What a side shows: its value, a variable's name, or what reaches it. */\ninterface SideText {\n  readonly text: string;\n  /** The whole value, as it is read out. */\n  readonly spoken: string;\n  readonly bound: boolean;\n  readonly unset: boolean;\n}\n\nfunction useSideText(\n  control: StyleControl,\n  stored: StyleValue | undefined,\n  inherited: string | undefined,\n  tokens: SiteTokenSet | undefined\n): SideText {\n  const mode = useCanvasTokenMode();\n  const tokenPrefix = React.useContext(TokenPrefixContext);\n  if (isTokenRef(stored)) {\n    const variable = variableFor(stored.$token, tokens, mode);\n    const named =\n      variable === undefined\n        ? stored.$token\n        : variableLabel(variable, variablesFor(control.leaf, tokens, mode));\n    const text =\n      stored.times === undefined ? named : `${named} × ${String(stored.times)}`;\n    return { text, spoken: text, bound: true, unset: false };\n  }\n  if (stored === undefined) {\n    if (inherited === undefined) {\n      return { text: \"–\", spoken: \"not set\", bound: false, unset: true };\n    }\n    const text = inheritedText(control, inherited, tokens, mode, tokenPrefix);\n    return { text, spoken: text, bound: false, unset: true };\n  }\n  const text = storedText(stored);\n  return { text, spoken: text, bound: false, unset: false };\n}\n\n/**\n * What a side shows of a value reaching it from another tier: a site setting\n * is named as its variable, as a value set from one is, rather than as the\n * CSS that reads it; anything else as it was written.\n */\nfunction inheritedText(\n  control: StyleControl,\n  inherited: string,\n  tokens: SiteTokenSet | undefined,\n  mode: ReturnType<typeof useCanvasTokenMode>,\n  tokenPrefix: string\n): string {\n  const read = variableRead(inherited, tokenPrefix);\n  const variable =\n    read === undefined ? undefined : variableFor(read, tokens, mode);\n  return variable === undefined\n    ? inherited\n    : variableLabel(variable, variablesFor(control.leaf, tokens, mode));\n}\n\n/** A digit, a point or a minus sign: the start of a value typed on a side. */\nfunction quickKey(event: React.KeyboardEvent): string | undefined {\n  if (event.altKey || event.ctrlKey || event.metaKey) return undefined;\n  return /^[\\d.-]$/.test(event.key) ? event.key : undefined;\n}\n\n/** The side a step away in the box's Tab order, if there is one. */\nfunction sideAfter(from: HTMLElement, step: 1 | -1): HTMLElement | undefined {\n  const sides = Array.from(\n    from\n      .closest(\".nx-spacing-box\")\n      ?.querySelectorAll<HTMLElement>(\".nx-spacing-side\") ?? []\n  );\n  return sides[sides.indexOf(from) + step];\n}\n\n/** What a side is given. */\nexport interface SpacingSideProps {\n  /** The field's id: the side's label is for it. */\n  readonly id: string;\n  /** The id of the side's label, \"Margin top\". */\n  readonly labelledBy: string;\n  /** The side's name, which titles its popover. */\n  readonly name: string;\n  readonly control: StyleControl;\n  readonly stored: StyleValue | undefined;\n  /** The value reaching the side from another tier, while none is set here. */\n  readonly inherited: string | undefined;\n  readonly tokens: SiteTokenSet | undefined;\n  readonly describedBy: string | undefined;\n  /** Why the side's last write was refused, if it was. */\n  readonly refusal: string | null;\n  readonly onCommit: (value: StyleValue | null) => CommitOutcome;\n  readonly onCommitSides: (\n    paths: readonly (readonly string[])[],\n    value: StyleValue\n  ) => CommitOutcome;\n}\n\n/** Whether the popover is open, and the digit it opened typing. */\ntype Opened = false | { readonly seed: string | undefined };\n\nexport function SpacingSide(props: SpacingSideProps): React.JSX.Element {\n  const { id, labelledBy, name, control, stored, describedBy } = props;\n  const box = React.useContext(SpacingRingContext);\n  const [applyTo, setApplyTo] = useApplyTo();\n  const shown = useSideText(control, stored, props.inherited, props.tokens);\n  const [opened, setOpened] = React.useState<Opened>(false);\n  const button = React.useRef<HTMLButtonElement>(null);\n  const truncated = useTruncated();\n  const valueId = `${id}-value`;\n  const reset = (): void => {\n    props.onCommit(null);\n  };\n  const close = (to: SideClose): void => {\n    const side = button.current;\n    // Focus moves first, so a number still being typed commits on its blur.\n    const next =\n      side === null || to === \"side\"\n        ? side\n        : (sideAfter(side, to === \"next\" ? 1 : -1) ?? side);\n    next?.focus();\n    setOpened(false);\n  };\n  return (\n    <Popover\n      open={opened !== false}\n      onOpenChange={open => {\n        if (!open) setOpened(false);\n      }}\n      modal={false}\n    >\n      <ContextMenu>\n        <TooltipProvider delayDuration={300}>\n          <ChromeTooltip content={shown.text} disabled={!truncated.is}>\n            <PopoverAnchor asChild>\n              <ContextMenuTrigger asChild>\n                <button\n                  ref={button}\n                  id={id}\n                  type=\"button\"\n                  className=\"nx-spacing-side\"\n                  data-bound={shown.bound ? \"\" : undefined}\n                  data-unset={shown.unset ? \"\" : undefined}\n                  data-open={opened === false ? undefined : \"\"}\n                  aria-labelledby={`${labelledBy} ${valueId}`}\n                  aria-describedby={describedBy}\n                  aria-haspopup=\"dialog\"\n                  aria-expanded={opened !== false}\n                  onPointerEnter={truncated.measure}\n                  onFocus={truncated.measure}\n                  onClick={() =>\n                    setOpened(opened === false ? { seed: undefined } : false)\n                  }\n                  onKeyDown={event => {\n                    const seed = quickKey(event);\n                    if (seed === undefined) return;\n                    event.preventDefault();\n                    setOpened({ seed });\n                  }}\n                >\n                  <span className=\"nx-spacing-side__text\">{shown.text}</span>\n                </button>\n              </ContextMenuTrigger>\n            </PopoverAnchor>\n          </ChromeTooltip>\n        </TooltipProvider>\n        <ContextMenuContent>\n          <ContextMenuItem disabled={stored === undefined} onSelect={reset}>\n            Reset\n          </ContextMenuItem>\n        </ContextMenuContent>\n      </ContextMenu>\n      {/* The whole value, which the side's name ends with. */}\n      <span id={valueId} hidden>\n        {shown.spoken}\n      </span>\n      {opened === false ? null : (\n        <SpacingSidePopover\n          name={name}\n          control={control}\n          stored={stored}\n          tokens={props.tokens}\n          seed={opened.seed}\n          applyTo={applyTo}\n          pairLabel={pairLabel(box, control)}\n          pathsFor={to => appliedPaths(box, control, to)}\n          onApplyTo={setApplyTo}\n          onCommit={props.onCommit}\n          onCommitSides={props.onCommitSides}\n          onReset={reset}\n          onClose={close}\n          refusal={props.refusal}\n          side={button}\n        />\n      )}\n    </Popover>\n  );\n}\n\n/**\n * Whether a side's text is cut short, measured when it is pointed at or\n * focused: only then does its tooltip say the whole value.\n */\nfunction useTruncated(): {\n  is: boolean;\n  measure: (event: React.SyntheticEvent<HTMLElement>) => void;\n} {\n  const [is, setIs] = React.useState(false);\n  return {\n    is,\n    measure: event => {\n      const text = event.currentTarget.querySelector(\".nx-spacing-side__text\");\n      setIs(text !== null && text.scrollWidth > text.clientWidth);\n    },\n  };\n}\n","/**\n * A style field's write of several paths of its property as one edit, handed\n * to a control drawn below the field's shell.\n *\n * Its own module, holding only the context, so a control can read it without\n * importing the field's whole write path.\n *\n * @module field-path-writes\n */\nimport * as React from \"react\";\n\nimport type { CommitOutcome } from \"./style-field-surroundings\";\nimport type { PathWrite } from \"./style-field-target\";\n\n/**\n * The field's `commitPaths`, for a control that sets more than its own path\n * in one press: a background size choice writes the size and the repeat\n * together, so one undo takes both back. `undefined` outside a field.\n */\nexport const FieldPathWrites: React.Context<\n  ((writes: readonly PathWrite[]) => CommitOutcome) | undefined\n> = React.createContext<\n  ((writes: readonly PathWrite[]) => CommitOutcome) | undefined\n>(undefined);\n","/**\n * Which colours the Colours tab's usage filter lists, by what the site's\n * usage count says of each (`variable-usage`) and what the open page uses.\n *\n * @module colour-usage\n */\nimport type { UsageState } from \"./variable-usage\";\n\n/** Which colours the Colours tab lists: all, the unused, or this page's. */\nexport type ColourFilter = \"all\" | \"unused\" | \"page\";\n\n/**\n * Whether a colour is listed under a filter: under Unused only where the\n * site's count has shown it unused, never while it is still counting.\n */\nexport function keepsColour(\n  filter: ColourFilter,\n  state: UsageState,\n  onPage: boolean\n): boolean {\n  if (filter === \"all\") return true;\n  return filter === \"unused\" ? state === \"unused\" : onPage;\n}\n\n/**\n * The colours \"Clean up unused…\" lists, in the order given: each one the\n * site made (its code and the engine supply none of them) that the site's\n * count has shown unused and the open page does not use, since a colour\n * applied on the canvas is a use before any save says so. A built-in colour\n * is never listed: it is never removed. `counting` says one of the site's\n * own colours is still being counted, so the list may grow.\n */\nexport function cleanUpCandidates<E extends { readonly identity: string }>(\n  colours: readonly E[],\n  rule: {\n    readonly stateOf: (identity: string) => UsageState;\n    readonly builtIn: (identity: string) => boolean;\n    readonly onPage: ReadonlySet<string> | undefined;\n  }\n): { listed: E[]; counting: boolean } {\n  const own = colours.filter(entry => !rule.builtIn(entry.identity));\n  return {\n    listed: own.filter(\n      entry =>\n        rule.stateOf(entry.identity) === \"unused\" &&\n        rule.onPage?.has(entry.identity) !== true\n    ),\n    counting: own.some(entry => rule.stateOf(entry.identity) === \"counting\"),\n  };\n}\n\n/**\n * The colours a site that hides its unused built-in colours leaves out of\n * the Colours tab and every colour picker: each built-in one (its code or\n * the engine supplies it) that the site's count has shown unused and the\n * open page does not use. None while they are shown. A colour still being\n * counted is kept, as Unused claims nothing for it; one that becomes used\n * is listed again, since this is asked afresh on every read.\n *\n * The one rule for both: the Colours tab and the pickers each ask it.\n */\nexport function hiddenColours(\n  identities: readonly string[],\n  rule: {\n    /** Whether the site shows its built-in colours (unset reads as shown). */\n    readonly shown: boolean;\n    readonly stateOf: (identity: string) => UsageState;\n    readonly builtIn: (identity: string) => boolean;\n    readonly onPage: ReadonlySet<string> | undefined;\n  }\n): ReadonlySet<string> {\n  if (rule.shown) return NONE_HIDDEN;\n  return new Set(\n    identities.filter(\n      identity =>\n        rule.builtIn(identity) &&\n        rule.stateOf(identity) === \"unused\" &&\n        rule.onPage?.has(identity) !== true\n    )\n  );\n}\n\n/** No colour hidden. */\nconst NONE_HIDDEN: ReadonlySet<string> = new Set();\n","/**\n * How widely a variable is used, and what the Variables tab says about it:\n * the host's reads, the count at the end of each row, the editor's status\n * line, whether Remove may go ahead, and what a shared style using the\n * variable sets with it.\n *\n * Rules here, presentation in {@link variable-usage-view}, so each is tested\n * without a DOM.\n *\n * ## Places\n *\n * A variable is used in documents (pages, components, sections, layouts)\n * whose blocks or settings name it, in shared styles whose own styles name\n * it, and in block types whose default styles name it. The places it is used\n * are the three together. While some pages are\n * still being counted the documents are a floor, and so are the places.\n *\n * @module variable-usage\n */\nimport {\n  isLook,\n  isPlainRecord,\n  isTokenRef,\n  type NamedClass,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { storedContexts } from \"../../styles/class-library\";\nimport {\n  listedWords,\n  type SharedStyleKind,\n  type SharedStylesCount,\n  type SharedStyleUsesPage,\n} from \"../../styles/shared-style-library\";\n\n/**\n * How widely one variable is used across the site.\n *\n * @experimental Settles with the Variables tab's usage.\n */\nexport interface VariableReach {\n  /** How many documents use it. */\n  readonly documents: number;\n  /** The same documents, by kind. */\n  readonly byKind: Readonly<Record<SharedStyleKind, number>>;\n  /** The ids of the shared styles whose own styles name it. */\n  readonly sharedStyles: readonly string[];\n  /**\n   * The block types (`core/button`) whose own default styles name it: each\n   * a place, though there is no document to open.\n   */\n  readonly blockDefaults: readonly string[];\n  /**\n   * The site's variables whose own values name it through `var()`, by\n   * identity: a shadow variable keeps its colour that way. Absent where the\n   * host does not say.\n   */\n  readonly variables?: readonly string[];\n  /** The Site text rows using it (`link`, `h2`). Absent where not said. */\n  readonly siteText?: readonly string[];\n  /** False makes `documents`, and so the places, a floor: \"at least\". */\n  readonly complete: boolean;\n}\n\n/**\n * One read of how widely some variables are used.\n *\n * @experimental Settles with the Variables tab's usage.\n */\nexport interface VariablesUsage {\n  /** Whether every page has been counted, so counts can be exact. */\n  readonly whole: boolean;\n  /** Whether counts that are not whole may still become whole. */\n  readonly counting?: boolean;\n  /** Whether this author may ask for the pages to be counted now. */\n  readonly mayCount?: boolean;\n  /** Each variable asked about, by identity (`tokenIdentity`). */\n  readonly variables: ReadonlyMap<string, VariableReach>;\n}\n\n/**\n * How many documents some variables are used in together, each document\n * once however many of them it names: the host's own count, numbers alone.\n *\n * @experimental Settles with the Variables tab's usage.\n */\nexport interface VariablesTogether {\n  /** How many documents use any of the variables. */\n  readonly documents: number;\n  /** The same documents, by kind. */\n  readonly byKind: Readonly<Record<SharedStyleKind, number>>;\n  /** False makes `documents`, and so the places, a floor: \"at least\". */\n  readonly complete: boolean;\n}\n\n/**\n * Which kind of place a variable is used in: a document's kind, a shared\n * style, or a block type's default style.\n *\n * @experimental Settles with the Variables tab's usage.\n */\nexport type VariableUseKind =\n  | SharedStyleKind\n  | \"shared-style\"\n  | \"block-default\";\n\n/**\n * One place a variable is used.\n *\n * @experimental Settles with the Variables tab's usage.\n */\nexport interface VariableUse {\n  /**\n   * A document's id, unique within its collection; a shared style's id; or a\n   * block type (`core/button`).\n   */\n  readonly id: string;\n  readonly title: string;\n  /** The collection holding the document, the site style's, or empty for a block type. */\n  readonly collection: string;\n  readonly kind: VariableUseKind;\n  /**\n   * For a shared style that is a block look, the block type it is bound to:\n   * two types' own looks may share an id, so a look is named by the pair.\n   */\n  readonly blockType?: string;\n  /**\n   * Where a document opens, when the host can say. A shared style and a\n   * block type's default style have none.\n   */\n  readonly href?: string;\n}\n\n/**\n * One page of the places a variable is used: the shared styles first, then\n * the documents this author may open.\n *\n * @experimental Settles with the Variables tab's usage.\n */\nexport interface VariableUsesPage extends Omit<SharedStyleUsesPage, \"items\"> {\n  readonly items: readonly VariableUse[];\n}\n\n/**\n * The host's reads of how widely variables are used, and the way to a shared\n * style that uses one.\n *\n * @experimental Settles with the Variables tab's usage.\n */\nexport interface VariablesAccess {\n  /** How widely each of these variables is used: at most fifty per read. */\n  readonly usage: (\n    identities: readonly string[],\n    signal: AbortSignal\n  ) => Promise<VariablesUsage>;\n  /**\n   * How many documents each group of variables is used in together, each\n   * document once, answered in the order asked: at most fifty groups, naming\n   * at most fifty variables in all, per read. Optional: without it, or while\n   * it fails, a group's documents are its variables' added up.\n   */\n  readonly usageTogether?: (\n    groups: readonly (readonly string[])[],\n    signal: AbortSignal\n  ) => Promise<readonly VariablesTogether[]>;\n  /** One page, from 1, of the places a variable is used. */\n  readonly uses: (\n    identity: string,\n    page: number,\n    signal: AbortSignal\n  ) => Promise<VariableUsesPage>;\n  /**\n   * Count the site's pages now, for a bounded time, rather than waiting for\n   * the site's background jobs. Optional: without it the tab says the jobs\n   * count them.\n   */\n  readonly count?: () => Promise<SharedStylesCount>;\n  /**\n   * Open a shared style in the Design panel's Shared styles tab. Optional:\n   * without it a shared style using a variable is named, not opened.\n   */\n  readonly openSharedStyle?: (classId: string) => void;\n  /**\n   * Edit a block look in the inspector: a look is a shared style bound to\n   * one block type, which the Shared styles tab does not list. Optional:\n   * without it a look using a variable is named, not opened.\n   */\n  readonly openLook?: (look: {\n    readonly id: string;\n    readonly blockType: string;\n  }) => void;\n}\n\n/**\n * One reach for the variables a row stands for, or a removal takes away\n * together: a type size and its line height. Each variable's places are\n * counted, so a block naming both counts once for each; shared styles and\n * block types are named by id, so each counts once. A floor when any part\n * is; nothing until every part is read.\n */\nexport function combinedReach(\n  reaches: readonly (VariableReach | undefined)[]\n): VariableReach | undefined {\n  const read = reaches.filter(\n    (reach): reach is VariableReach => reach !== undefined\n  );\n  if (read.length === 0 || read.length !== reaches.length) return undefined;\n  const [only] = read;\n  if (read.length === 1) return only;\n  const sum = (count: (reach: VariableReach) => number): number =>\n    read.reduce((total, reach) => total + count(reach), 0);\n  return {\n    documents: sum(reach => reach.documents),\n    byKind: {\n      pages: sum(reach => reach.byKind.pages),\n      components: sum(reach => reach.byKind.components),\n      patterns: sum(reach => reach.byKind.patterns),\n      layouts: sum(reach => reach.byKind.layouts),\n    },\n    sharedStyles: [...new Set(read.flatMap(reach => reach.sharedStyles))],\n    blockDefaults: [...new Set(read.flatMap(reach => reach.blockDefaults))],\n    complete: read.every(reach => reach.complete),\n  };\n}\n\n/**\n * One reach for variables counted together: {@link combinedReach}, with the\n * documents the host counted for them together, each once, in place of\n * their sum. The sum where the host gave no count of its own.\n */\nexport function reachTogether(\n  reaches: readonly (VariableReach | undefined)[],\n  together: VariablesTogether | undefined\n): VariableReach | undefined {\n  const combined = combinedReach(reaches);\n  if (combined === undefined || together === undefined) return combined;\n  return {\n    ...combined,\n    documents: together.documents,\n    byKind: together.byKind,\n    complete: together.complete,\n  };\n}\n\n/**\n * How many places use a variable: its documents, its shared styles, and the\n * block types whose default styles name it.\n */\nfunction variablePlaces(reach: VariableReach): number {\n  return (\n    reach.documents + reach.sharedStyles.length + reach.blockDefaults.length\n  );\n}\n\n/** \"1 place\", \"14 places\". */\nfunction placesWords(count: number): string {\n  return `${String(count)} ${count === 1 ? \"place\" : \"places\"}`;\n}\n\n/** What a floor adds: why the number is a minimum. */\nconst NOT_COUNTED_YET = \"Some pages aren't counted yet.\";\n\n/**\n * How widely a variable is used, in the words its row's tooltip says and\n * its name says to a screen reader: \"Used in 14 places\", \"Not used\", or,\n * while some pages are not counted, \"Not counted yet\" or a floor (\"Used in\n * at least 2 places\").\n */\nexport function variableCountWords(reach: VariableReach): string {\n  const places = variablePlaces(reach);\n  if (!reach.complete) {\n    return places === 0\n      ? \"Not counted yet\"\n      : `Used in at least ${placesWords(places)}. ${NOT_COUNTED_YET}`;\n  }\n  return places === 0 ? \"Not used\" : `Used in ${placesWords(places)}`;\n}\n\n/** What an unused variable's row and editor say. */\nconst NOT_USED = \"Not used anywhere\";\n\n/**\n * What Remove does for a variable the site added: go ahead behind the\n * confirm (`free`), or refuse while a use is known (`in-use`). `unread` while\n * nothing has been read, when Remove confirms as well. A zero not counted\n * across every page is `free` too: the save counts the pages before it\n * decides, and refuses a use it finds, so the editor never refuses one for\n * want of a count.\n */\nexport type VariableRemoval = \"free\" | \"in-use\" | \"unread\";\n\nexport function variableRemoval(\n  reach: VariableReach | undefined\n): VariableRemoval {\n  if (reach === undefined) return \"unread\";\n  return variablePlaces(reach) > 0 ? \"in-use\" : \"free\";\n}\n\n/**\n * Whether a variable is used, for the usage filter: \"counting\" until the\n * site's documents are all counted, since an absence proves nothing before.\n *\n * Used means something the site stores names it: a document, a shared or\n * block style, a Site text row, or another variable through `var()`. A block type's own\n * built-in look does not count: a built-in colour only a core block uses is\n * one the site never chose.\n */\nexport type UsageState = \"used\" | \"unused\" | \"counting\";\n\nexport function usageState(reach: VariableReach | undefined): UsageState {\n  if (reach === undefined) return \"counting\";\n  const named =\n    (reach.variables?.length ?? 0) > 0 || (reach.siteText?.length ?? 0) > 0;\n  if (named || reach.documents > 0 || reach.sharedStyles.length > 0) {\n    return \"used\";\n  }\n  // A count that says nothing of the variables or rows naming it, as an\n  // older host's does, has not shown it unused.\n  const said = reach.variables !== undefined && reach.siteText !== undefined;\n  return reach.complete && said ? \"unused\" : \"counting\";\n}\n\n/** The editor's line beside Remove: how widely the variable is used. */\nexport function variableStatus(reach: VariableReach | undefined): string {\n  if (reach === undefined) return \"\";\n  const places = variablePlaces(reach);\n  if (places > 0) {\n    return `Used in ${reach.complete ? \"\" : \"at least \"}${placesWords(places)}`;\n  }\n  // Not \"counting\": nothing may be counting, and the row says the same.\n  return reach.complete ? NOT_USED : \"Not counted yet\";\n}\n\n/** \"It's used in 14 places, and they would lose this colour:\". */\nexport function variableLossSentence(\n  reach: VariableReach,\n  loss: string\n): string {\n  const floor = reach.complete ? \"\" : \"at least \";\n  return `It's used in ${floor}${placesWords(variablePlaces(reach))}, and they would lose this ${loss}:`;\n}\n\n/**\n * What a shared style sets with a variable, in the author's words, by the\n * style property that names it. A property not listed is said as \"uses it\".\n */\nconst PROPERTY_WORDS: Readonly<Record<string, string>> = {\n  color: \"text colour\",\n  linkColor: \"link colour\",\n  linkColorHover: \"hovered link colour\",\n  backgroundColor: \"background colour\",\n  background: \"background\",\n  backgroundGradient: \"background gradient\",\n  border: \"border\",\n  borderRadius: \"corner radius\",\n  boxShadow: \"shadow\",\n  textShadow: \"text shadow\",\n  padding: \"padding\",\n  margin: \"margin\",\n  gap: \"gap\",\n  rowGap: \"row gap\",\n  columnGap: \"column gap\",\n  width: \"width\",\n  height: \"height\",\n  minWidth: \"minimum width\",\n  minHeight: \"minimum height\",\n  maxWidth: \"maximum width\",\n  maxHeight: \"maximum height\",\n  fontFamily: \"font\",\n  fontSize: \"text size\",\n  fontWeight: \"font weight\",\n  lineHeight: \"line height\",\n  letterSpacing: \"letter spacing\",\n  wordSpacing: \"word spacing\",\n  transition: \"transition\",\n};\n\n/** Whether a style value names this variable, inside a structured value too. */\nfunction namesVariable(value: unknown, identity: string): boolean {\n  if (isTokenRef(value)) return value.$token === identity;\n  if (!isPlainRecord(value)) return false;\n  return Object.values(value).some(inner => namesVariable(inner, identity));\n}\n\n/**\n * The style properties of a shared style that name a variable, under any\n * state or breakpoint, each once, in the order first met.\n */\nfunction propertiesNaming(style: NamedClass, identity: string): string[] {\n  const found = new Set<string>();\n  for (const { values } of storedContexts(style.styles)) {\n    for (const [property, value] of Object.entries(values)) {\n      if (namesVariable(value, identity)) found.add(property);\n    }\n  }\n  return [...found];\n}\n\n/** The block type a class is a look of, or nothing for a shared style. */\nfunction lookTypeOf(entry: NamedClass): string | undefined {\n  return isLook(entry) && typeof entry.blockType === \"string\"\n    ? entry.blockType\n    : undefined;\n}\n\n/**\n * What a shared style does with a variable, said in a list of places:\n * \"sets text colour\", \"sets padding and margin\", or \"uses it\" when the style\n * is not in hand or names it only in properties without plainer words.\n */\nexport function sharedStyleSets(\n  classes: readonly NamedClass[] | undefined,\n  classId: string,\n  identity: string,\n  /** A look's block type: two types' own looks may share an id. */\n  blockType?: string\n): string {\n  const style = classes?.find(\n    entry => entry.id === classId && lookTypeOf(entry) === blockType\n  );\n  if (style === undefined) return \"uses it\";\n  const words = [\n    ...new Set(\n      // Read as own entries: a property key is stored data, and\n      // `__proto__` must not read the table's prototype.\n      propertiesNaming(style, identity).flatMap(property =>\n        Object.hasOwn(PROPERTY_WORDS, property)\n          ? [PROPERTY_WORDS[property] ?? \"\"]\n          : []\n      )\n    ),\n  ];\n  return words.length === 0 ? \"uses it\" : `sets ${listedWords(words)}`;\n}\n","/**\n * Pieces the Design panel's tabs share: the Keep / Remove pair a removal is\n * confirmed with, \"Show N more\" under a long list, the open row drawn past\n * a page, and a write that answers with a refusal or nothing.\n *\n * One copy each, so the Variables, Fonts and Shared styles tabs confirm,\n * page and report a refusal the same way.\n *\n * @module panel-actions\n */\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\n/** The Keep and Remove buttons under a confirmation. */\nexport function KeepOrRemove({\n  busy,\n  onKeep,\n  onRemove,\n  removeLabel,\n  removeHeld = false,\n  removeDescribedBy,\n}: {\n  busy: boolean;\n  onKeep: () => void;\n  onRemove: () => void;\n  /** The destructive button's words: \"Remove Inter\", \"Remove 3\". */\n  removeLabel: string;\n  /**\n   * Remove waits while another write is pending, Keep does not: the author\n   * can always back out. The caller says why beside it.\n   */\n  removeHeld?: boolean;\n  /** The id of the words saying why Remove waits. */\n  removeDescribedBy?: string;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-vars-editor__actions\">\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"sm\"\n        className=\"nx-vars-editor__button\"\n        disabled={busy}\n        onClick={onKeep}\n      >\n        Keep\n      </Button>\n      <Button\n        type=\"button\"\n        variant=\"destructive\"\n        size=\"sm\"\n        className=\"nx-vars-editor__button\"\n        disabled={busy || removeHeld}\n        aria-describedby={removeHeld ? removeDescribedBy : undefined}\n        onClick={onRemove}\n      >\n        {removeLabel}\n      </Button>\n    </div>\n  );\n}\n\n/** \"Show N more\" under a list a page long, or nothing when all are shown. */\nexport function ShowMore({\n  hidden,\n  pageSize,\n  onMore,\n}: {\n  /** How many rows are not shown yet. */\n  hidden: number;\n  pageSize: number;\n  onMore: () => void;\n}): React.JSX.Element | null {\n  if (hidden <= 0) return null;\n  return (\n    <button type=\"button\" className=\"nx-vars__link\" onClick={onMore}>\n      {`Show ${String(Math.min(hidden, pageSize))} more`}\n    </button>\n  );\n}\n\n/**\n * The rows a page shows, and the open row as well when it lies past them.\n *\n * A row whose editor is open can lie past the page: a variable added at the\n * end of a long group, or a shared style opened from another tab. Its row is\n * drawn on its own after the page rather than by raising the page, which\n * would mount every row before it.\n */\nexport function withOpenRow<T>(\n  rows: readonly T[],\n  limit: number,\n  isOpen: (row: T) => boolean\n): readonly T[] {\n  const page = rows.slice(0, limit);\n  const at = rows.findIndex(isOpen);\n  const open = at >= limit ? rows[at] : undefined;\n  return open === undefined ? page : [...page, open];\n}\n\n/**\n * A write that answers with its refusal, or nothing once it is stored: busy\n * while it runs, and the last refusal kept to be shown.\n */\nexport function useRefusableWrite(): {\n  busy: boolean;\n  refusal: string | null;\n  run: (write: () => Promise<string | undefined>) => Promise<boolean>;\n} {\n  const [busy, setBusy] = React.useState(false);\n  const [refusal, setRefusal] = React.useState<string | null>(null);\n  const run = React.useCallback(\n    async (write: () => Promise<string | undefined>): Promise<boolean> => {\n      setBusy(true);\n      setRefusal(null);\n      try {\n        const refused = await write();\n        if (refused !== undefined) setRefusal(refused);\n        return refused === undefined;\n      } finally {\n        setBusy(false);\n      }\n    },\n    []\n  );\n  return { busy, refusal, run };\n}\n\n/** A refusal, said where the author is, or nothing. */\nexport function Refusal({\n  refusal,\n  id,\n}: {\n  refusal: string | null;\n  id?: string;\n}): React.JSX.Element | null {\n  if (refusal === null) return null;\n  return (\n    <p className=\"nx-vars-editor__issue\" id={id} role=\"alert\">\n      {refusal}\n    </p>\n  );\n}\n","/**\n * A where-used list, read a page at a time from a host's route: the places a\n * shared style or a variable is used, for each tab that lists them.\n *\n * @module uses-read\n */\nimport * as React from \"react\";\n\n/** How many places one where-used page names. */\nexport const USES_PAGE_SIZE = 20;\n\n/** What one where-used page answers, whatever it lists. */\nexport interface UsesPage<I> {\n  readonly items: readonly I[];\n  /** Every place this author may open, across all pages. */\n  readonly total: number;\n  /** Places 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/** The places one page of a where-used list names. */\ntype PlaceOf<P extends UsesPage<unknown>> = P[\"items\"][number];\n\n/** The where-used pages read so far, and how the last read went. */\nexport interface UsesRead<P extends UsesPage<unknown>> {\n  readonly items: readonly PlaceOf<P>[];\n  readonly last: P | undefined;\n  readonly page: number;\n  /** The last page that arrived; behind `page` while that one is coming. */\n  readonly loaded: number;\n  readonly failed: boolean;\n}\n\n/**\n * The places `id` is used, read a page at a time through `uses`, the host's\n * read; none while there is no read. `uses` is read by identity, so a host\n * hands the same function across renders.\n */\nexport function useUses<P extends UsesPage<unknown>>(\n  uses:\n    | ((id: string, page: number, signal: AbortSignal) => Promise<P>)\n    | undefined,\n  id: string\n): { read: UsesRead<P>; more: () => void } {\n  const [read, setRead] = React.useState<UsesRead<P>>({\n    items: [],\n    last: undefined,\n    page: 1,\n    loaded: 0,\n    failed: false,\n  });\n  React.useEffect(() => {\n    if (uses === undefined) return;\n    const controller = new AbortController();\n    uses(id, read.page, controller.signal).then(\n      answer => {\n        if (controller.signal.aborted) return;\n        setRead(current => ({\n          ...current,\n          items: [...current.items, ...answer.items],\n          last: answer,\n          loaded: current.page,\n        }));\n      },\n      () => {\n        if (controller.signal.aborted) return;\n        setRead(current => ({ ...current, failed: true }));\n      }\n    );\n    return () => controller.abort();\n  }, [uses, id, read.page]);\n  // The next page follows the last one that arrived, and only once the one\n  // asked for has: a second press while a page is coming would otherwise\n  // abort it and append the page after it, losing a page of places.\n  const more = React.useCallback(\n    () =>\n      setRead(current =>\n        current.loaded < current.page\n          ? current\n          : { ...current, page: current.loaded + 1 }\n      ),\n    []\n  );\n  return { read, more };\n}\n","/**\n * A shared style's details, in the popover beside its row in the Shared\n * styles tab: its name and class name, what it declares, where it is used,\n * its lock, and removing it while nothing uses it.\n *\n * Drawn in the Variables tab's popover editor (`nx-vars-editor`).\n *\n * @module shared-style-details\n */\nimport {\n  namedClassName,\n  type StyleCompileContext,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button, Input } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  sharedStyleDeclares,\n  sharedStyleKindName,\n  sharedStyleRefusalOf,\n  sharedStyleRemoval,\n  sharedStyleSlug,\n  sharedStyleUse,\n  SHARED_STYLE_NOT_WHOLE_NOTE,\n  SHARED_STYLE_RENAME_PENDING,\n  SHARED_STYLE_UNCOUNTED_USES,\n  type BlocksOnThisPage,\n  type SharedStyleRefusal,\n  type SharedStyleRemoval,\n  type SharedStyleReach,\n  type SharedStyleRow,\n  type SharedStyleUsesPage,\n} from \"../../styles/shared-style-library\";\n\nimport {\n  KeepOrRemove,\n  Refusal,\n  ShowMore,\n  useRefusableWrite,\n} from \"./panel-actions\";\nimport type { SharedStylesAccess } from \"./shared-styles-panel\";\nimport {\n  useUses,\n  USES_PAGE_SIZE,\n  type UsesPage,\n  type UsesRead,\n} from \"./uses-read\";\n\n/**\n * Remove through the host, with the in-use signal where it gives one: its\n * `removeWithReason`, else `remove`, whose words say nothing of use.\n */\nexport async function removeSharedStylesThrough(\n  access: SharedStylesAccess,\n  ids: readonly string[]\n): Promise<SharedStyleRefusal | undefined> {\n  if (access.removeWithReason !== undefined) {\n    return access.removeWithReason(ids);\n  }\n  return sharedStyleRefusalOf(await access.remove(ids));\n}\n\nexport interface SharedStyleDetailsProps {\n  row: SharedStyleRow;\n  /** The name shown: the one a rename is heading for, else the stored one. */\n  name: string;\n  styleContext: StyleCompileContext | undefined;\n  blocks: BlocksOnThisPage;\n  reach: SharedStyleReach | undefined;\n  /** The reach in words, as the row says it. */\n  sentence: string;\n  whole: boolean | undefined;\n  mayLock: boolean;\n  readOnly: boolean;\n  access: SharedStylesAccess | undefined;\n  /**\n   * A rename of any style is still being stored. Lock and Remove each write\n   * the whole list of styles too, so they wait for it, whichever row it is.\n   */\n  held: boolean;\n  /** A rename refused for this style, shown under its name. */\n  issue: string | null;\n  onRename: (value: string) => void;\n  onRemoved: () => void;\n  /**\n   * The server refused to remove it. The refusal says why (still used, a\n   * lock, a count no longer whole), not whether it is used: the host reads\n   * its usage again to decide that.\n   */\n  onRefused: () => void;\n}\n\nexport function SharedStyleDetails(\n  props: SharedStyleDetailsProps\n): React.JSX.Element {\n  const { row, name, access, readOnly } = props;\n  const removal = sharedStyleRemoval(\n    row,\n    props.blocks,\n    props.reach,\n    props.whole\n  );\n  const holdId = React.useId();\n  const heldBy = props.held ? holdId : undefined;\n  // The server's words for a removal it refused. Kept here, above the\n  // removal, so they stay whatever the usage read again says of the row,\n  // and the confirmation that said nothing uses it is gone.\n  const [refused, setRefused] = React.useState<SharedStyleRefusal | null>(null);\n  return (\n    <div className=\"nx-vars-editor__body nx-shared-styles__details\">\n      {/* Kept at the top while the rest scrolls inside the window's height. */}\n      <div className=\"nx-shared-styles__details-head\">\n        <NameField\n          row={row}\n          name={name}\n          fixed={readOnly || row.locked || row.inCode}\n          issue={props.issue}\n          onRename={props.onRename}\n        />\n      </div>\n      <HoldReason\n        // Said once, above the controls it holds, which both point to.\n        held={props.held && holdsAControl(props, removal)}\n        id={holdId}\n      />\n      <LockLine\n        row={row}\n        name={name}\n        mayLock={props.mayLock}\n        access={access}\n        heldBy={heldBy}\n      />\n      <Declares row={row} styleContext={props.styleContext} />\n      <WhereUsed\n        id={row.id}\n        sentence={sentenceBeside(props, refused)}\n        access={access}\n      />\n      {row.inCode ? (\n        <p className=\"nx-shared-styles__meta\">Set in your site&rsquo;s code</p>\n      ) : null}\n      {refused !== null ? (\n        <Refusal refusal={refused.reason} />\n      ) : readOnly || access === undefined ? null : (\n        <Removal\n          removal={removal}\n          id={row.id}\n          name={name}\n          access={access}\n          heldBy={heldBy}\n          onRemoved={props.onRemoved}\n          onRefused={refusal => {\n            setRefused(refusal);\n            props.onRefused();\n          }}\n        />\n      )}\n    </div>\n  );\n}\n\n/**\n * The reach in words, unless the server has just refused a removal while the\n * index counts no use: then \"Not used anywhere\" would sit over a refusal\n * saying it is used, and the refusal is the truer statement.\n */\nfunction sentenceBeside(\n  props: SharedStyleDetailsProps,\n  refused: SharedStyleRefusal | null\n): string {\n  // Only the route's in-use refusal contradicts the index: a lock, or a\n  // count no longer whole, says nothing of use, so the sentence stays.\n  const counted = sharedStyleUse(props.blocks, props.reach) === \"used\";\n  return refused?.inUse === true && !counted ? \"\" : props.sentence;\n}\n\n/** Whether the popover shows a control a pending rename holds: Lock or Remove. */\nfunction holdsAControl(\n  props: SharedStyleDetailsProps,\n  removal: SharedStyleRemoval\n): boolean {\n  const removable =\n    !props.readOnly &&\n    props.access !== undefined &&\n    removal.kind === \"removable\";\n  return removable || mayLockRow(props.row, props.mayLock, props.access);\n}\n\n/** Why a style can't be removed, or Remove, or nothing when said elsewhere. */\nfunction Removal({\n  removal,\n  ...remove\n}: {\n  removal: SharedStyleRemoval;\n} & React.ComponentProps<typeof RemoveOne>): React.JSX.Element | null {\n  if (removal.kind === \"refused\") {\n    return <p className=\"nx-shared-styles__meta\">{removal.reason}</p>;\n  }\n  return removal.kind === \"removable\" ? <RemoveOne {...remove} /> : null;\n}\n\n/** The class name a typed name gives, or the style's own while it is unchanged. */\nfunction typedClassName(\n  row: SharedStyleRow,\n  name: string,\n  draft: string\n): string {\n  if (draft.trim() === name) return row.slug;\n  return sharedStyleSlug(draft);\n}\n\n/** The Name field: committed on Enter or blur, with the class name it gives. */\nfunction NameField({\n  row,\n  name,\n  fixed,\n  issue,\n  onRename,\n}: {\n  row: SharedStyleRow;\n  name: string;\n  /** Shown, never changed: a read-only role, a lock, or the site's code. */\n  fixed: boolean;\n  issue: string | null;\n  onRename: (value: string) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  const [draft, setDraft] = React.useState(name);\n  const typed = typedClassName(row, name, draft);\n  const commit = (value: string): void => {\n    if (!fixed) onRename(value);\n  };\n  return (\n    <>\n      <div className=\"nx-vars-editor__field\">\n        <label className=\"nx-vars-editor__label\" htmlFor={`${id}-name`}>\n          Name\n        </label>\n        <Input\n          id={`${id}-name`}\n          value={draft}\n          readOnly={fixed}\n          aria-invalid={issue === null ? undefined : true}\n          aria-describedby={issue === null ? `${id}-code` : `${id}-issue`}\n          onChange={event => setDraft(event.currentTarget.value)}\n          onBlur={event => commit(event.currentTarget.value)}\n          onKeyDown={event => {\n            if (event.key === \"Enter\") commit(event.currentTarget.value);\n          }}\n        />\n        <p className=\"nx-vars-editor__code\" id={`${id}-code`}>\n          {typed === \"\" ? row.className : `.${namedClassName(typed)}`}\n        </p>\n        {typed === \"\" || typed === row.slug ? null : (\n          // A class name is what hand-written CSS selects, so a change to it\n          // is said before it is made.\n          <p className=\"nx-shared-styles__hint\">\n            {`Pages update at once. CSS written by hand for ${row.className} must be updated too.`}\n          </p>\n        )}\n      </div>\n      <Refusal refusal={issue} id={`${id}-issue`} />\n    </>\n  );\n}\n\n/** What a lock says to an author who may lift it, and to one who may not. */\nfunction lockMessage(name: string, may: boolean): string {\n  return may\n    ? `${name} is locked, so it can’t be changed, renamed or removed. Unlock it to change it.`\n    : \"Locked by your site’s designers. Ask someone who can unlock shared styles.\";\n}\n\n/**\n * Why a write waits while a rename is stored, said beside the control it\n * holds, or nothing.\n */\nexport function HoldReason({\n  held,\n  id,\n}: {\n  held: boolean;\n  id: string;\n}): React.JSX.Element | null {\n  if (!held) return null;\n  return (\n    <p className=\"nx-shared-styles__meta\" id={id}>\n      {SHARED_STYLE_RENAME_PENDING}\n    </p>\n  );\n}\n\n/** Whether this author may move this style's lock here. */\nfunction mayLockRow(\n  row: SharedStyleRow,\n  mayLock: boolean,\n  access: SharedStylesAccess | undefined\n): access is SharedStylesAccess {\n  return mayLock && access !== undefined && !row.inCode;\n}\n\n/** What a lock says, and Lock or Unlock for an author the server says may. */\nfunction LockLine({\n  row,\n  name,\n  mayLock,\n  access,\n  heldBy,\n}: {\n  row: SharedStyleRow;\n  name: string;\n  mayLock: boolean;\n  access: SharedStylesAccess | undefined;\n  /** While a rename is stored: the id of the words saying Lock waits. */\n  heldBy: string | undefined;\n}): React.JSX.Element | null {\n  const may = mayLockRow(row, mayLock, access);\n  if (!row.locked && !may) return null;\n  return (\n    <div className=\"nx-vars-editor__field\">\n      {row.locked ? (\n        <p className=\"nx-shared-styles__meta\">{lockMessage(name, may)}</p>\n      ) : null}\n      {may ? (\n        <LockButton row={row} name={name} access={access} heldBy={heldBy} />\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * Lock or Unlock, with the route's refusal. Held while a rename is stored: a\n * lock and a rename each write the whole list of styles, so a lock landing\n * second would put the old name back.\n */\nfunction LockButton({\n  row,\n  name,\n  access,\n  heldBy,\n}: {\n  row: SharedStyleRow;\n  name: string;\n  access: SharedStylesAccess;\n  heldBy: string | undefined;\n}): React.JSX.Element {\n  const { busy, refusal, run } = useRefusableWrite();\n  return (\n    <>\n      <Refusal refusal={refusal} />\n      <div className=\"nx-vars-editor__actions\">\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button\"\n          disabled={busy || heldBy !== undefined}\n          aria-describedby={heldBy}\n          onClick={() => void run(() => access.lock(row.id, !row.locked))}\n        >\n          {row.locked ? `Unlock ${name}` : `Lock ${name}`}\n        </Button>\n      </div>\n    </>\n  );\n}\n\n/** What a style declares at the base size, and how much more elsewhere. */\nfunction Declares({\n  row,\n  styleContext,\n}: {\n  row: SharedStyleRow;\n  styleContext: StyleCompileContext | undefined;\n}): React.JSX.Element {\n  const declares = sharedStyleDeclares(row.styles, styleContext);\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\">Declares</span>\n      {declares.lines.length === 0 ? (\n        <p className=\"nx-shared-styles__meta\">Nothing at the base size yet.</p>\n      ) : (\n        <ul className=\"nx-shared-styles__declares\">\n          {declares.lines.map(line => (\n            <li key={line}>{line}</li>\n          ))}\n        </ul>\n      )}\n      {declares.elsewhere > 0 ? (\n        <p className=\"nx-shared-styles__meta\">\n          {`and ${declares.elsewhere} more on other devices and states`}\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\n/** Where a style is used: the reach in words, then the documents by name. */\nfunction WhereUsed({\n  id,\n  sentence,\n  access,\n}: {\n  id: string;\n  sentence: string;\n  access: SharedStylesAccess | undefined;\n}): React.JSX.Element {\n  const { read, more } = useUses(access?.uses, id);\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\">Where it&rsquo;s used</span>\n      {sentence === \"\" ? null : (\n        <p className=\"nx-shared-styles__reach\">{sentence}</p>\n      )}\n      {access === undefined ? null : <UsesList read={read} onMore={more} />}\n    </div>\n  );\n}\n\n/** The documents read so far, \"Show N more\", and the ones counted unnamed. */\nfunction UsesList({\n  read,\n  onMore,\n}: {\n  read: UsesRead<SharedStyleUsesPage>;\n  onMore: () => void;\n}): React.JSX.Element {\n  const { last, items } = read;\n  if (last === undefined || read.failed) return <UsesUnread read={read} />;\n  return (\n    <>\n      {items.length === 0 ? null : (\n        <ul className=\"nx-shared-styles__uses\">\n          {items.map(use => (\n            // An id is unique only within its collection, so both key a row.\n            <li key={JSON.stringify([use.collection, use.id])}>\n              <span className=\"nx-shared-styles__use-title\">{use.title}</span>\n              <span className=\"nx-shared-styles__meta\">\n                {sharedStyleKindName(use.kind)}\n              </span>\n            </li>\n          ))}\n        </ul>\n      )}\n      <UsesTail last={last} listed={items.length} onMore={onMore} />\n    </>\n  );\n}\n\n/**\n * A where-used list not read yet: that it is being read, or that the read\n * failed. Shared by every tab that lists where something is used.\n */\nexport function UsesUnread({\n  read,\n}: {\n  read: { readonly failed: boolean };\n}): React.JSX.Element {\n  if (read.failed) {\n    return <Refusal refusal=\"Where it’s used could not be read.\" />;\n  }\n  return (\n    <p className=\"nx-shared-styles__meta\" role=\"status\">\n      Reading where it&rsquo;s used&hellip;\n    </p>\n  );\n}\n\n/**\n * Under a where-used list: \"Show N more\" while pages follow, that the list\n * may be short while pages are being counted, and the places counted but\n * not named because this author may not open them.\n */\nexport function UsesTail({\n  last,\n  listed,\n  onMore,\n}: {\n  last: UsesPage<unknown>;\n  /** How many places the list names so far. */\n  listed: number;\n  /** The next page. Absent: the list is a first few, and offers no more. */\n  onMore?: () => void;\n}): React.JSX.Element {\n  return (\n    <>\n      {onMore === undefined ? null : (\n        <ShowMore\n          hidden={last.hasNext ? last.total - listed : 0}\n          pageSize={USES_PAGE_SIZE}\n          onMore={onMore}\n        />\n      )}\n      {last.complete ? null : (\n        <p className=\"nx-shared-styles__meta\">{SHARED_STYLE_NOT_WHOLE_NOTE}</p>\n      )}\n      {last.hidden > 0 ? (\n        <p className=\"nx-shared-styles__meta\">\n          {`and ${last.hidden} you can’t open`}\n        </p>\n      ) : null}\n    </>\n  );\n}\n\n/** Remove one unused style, behind a confirmation. */\nfunction RemoveOne({\n  id,\n  name,\n  access,\n  heldBy,\n  onRemoved,\n  onRefused,\n}: {\n  id: string;\n  name: string;\n  access: SharedStylesAccess;\n  /** The server refused: its words, and whether it said the style is used. */\n  onRefused: (refusal: SharedStyleRefusal) => void;\n  /**\n   * While a rename is stored: the id of the words saying Remove waits, since\n   * it writes the whole list of styles too.\n   */\n  heldBy: string | undefined;\n  onRemoved: () => void;\n}): React.JSX.Element {\n  const [confirming, setConfirming] = React.useState(false);\n  const { busy, refusal, run } = useRefusableWrite();\n  const held = heldBy !== undefined;\n  const remove = async (): Promise<void> => {\n    let said: SharedStyleRefusal | undefined;\n    const stored = await run(async () => {\n      said = await removeSharedStylesThrough(access, [id]);\n      return said?.reason;\n    });\n    if (stored) onRemoved();\n    else {\n      onRefused(\n        said ?? {\n          reason: \"This shared style could not be removed.\",\n          inUse: false,\n        }\n      );\n    }\n  };\n  return (\n    <>\n      <Refusal refusal={refusal} />\n      {confirming ? (\n        <div\n          className=\"nx-vars-editor__confirm\"\n          role=\"group\"\n          aria-label={`Remove ${name}`}\n        >\n          {/* What the count knows, and what it cannot see: it asks even at\n              a count of zero, since a zero is not permission. */}\n          <p>\n            Remove <strong>{name}</strong>? No page uses it in the editor.\n          </p>\n          <p className=\"nx-shared-styles__meta\">\n            {SHARED_STYLE_UNCOUNTED_USES}\n          </p>\n          <KeepOrRemove\n            busy={busy}\n            onKeep={() => setConfirming(false)}\n            onRemove={() => void remove()}\n            removeLabel={`Remove ${name}`}\n            removeHeld={held}\n            removeDescribedBy={heldBy}\n          />\n        </div>\n      ) : (\n        <div className=\"nx-vars-editor__actions\">\n          <Button\n            type=\"button\"\n            variant=\"ghost\"\n            size=\"sm\"\n            className=\"nx-vars-editor__button nx-vars-editor__remove\"\n            disabled={held}\n            aria-describedby={heldBy}\n            onClick={() => setConfirming(true)}\n          >\n            Remove\n          </Button>\n        </div>\n      )}\n    </>\n  );\n}\n","/**\n * How widely the rows on screen are used, read from a host's usage route and\n * kept as the reads answer: one machine for every Design tab that shows\n * counts, the Shared styles tab and the Variables tab, generic over what one\n * id's usage is.\n *\n * ## Reads\n *\n * Each id is asked about once, at most {@link USAGE_READ_SIZE} to a read, as\n * rows come on screen; a row already read is not asked again while the\n * counts are whole. While some pages are still being counted, every row on\n * screen is asked again each {@link USAGE_RECOUNT_MS}, until the counts are\n * whole or {@link USAGE_RECOUNT_IDLE_MAX} recounts in a row changed nothing.\n *\n * ## Count now\n *\n * Where the host can count the site's pages now and the author may, the\n * reads offer it ({@link CountNow}); its answer reads the rows again.\n *\n * @module usage-reads\n */\nimport * as React from \"react\";\n\nimport { BACKGROUND_JOBS_DOCS_HREF } from \"../../shell/docs-links\";\nimport type { SharedStylesCount } from \"../../styles/shared-style-library\";\n\n/** The most ids one usage read asks about. */\nconst USAGE_READ_SIZE = 50;\n\n/**\n * How long the rows on screen wait before their usage is asked again while\n * some pages are still being counted, so the counts become whole, and a\n * removal becomes possible, without reopening the tab.\n */\nexport const USAGE_RECOUNT_MS = 15_000;\n\n/**\n * How many times in a row the rows are asked again with nothing changing:\n * five minutes of recounts. A site says it is counting when the backfill\n * still has pages to count, but only a scheduler running the site's jobs\n * counts them, so on a site with none it says so for ever; and a host\n * written before `counting` existed does not say at all. Either way the tab\n * stops asking rather than polling for as long as it stays open, and any\n * change in the counts, or an id not read before, renews it.\n */\nexport const USAGE_RECOUNT_IDLE_MAX = 20;\n\n/** One read of how widely some ids are used, as the reads take it. */\nexport interface UsageRead<R> {\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. Absent means\n   * unknown, asked again as while counting.\n   */\n  readonly counting?: boolean;\n  /** Whether this author may ask for the pages to be counted now. Absent: no. */\n  readonly mayCount?: boolean;\n  /** Each id asked about. */\n  readonly values: ReadonlyMap<string, R>;\n}\n\n/** Where the reads come from: the host's usage read, and its count. */\nexport interface UsageSource<R, Read extends UsageRead<R> = UsageRead<R>> {\n  readonly usage: (\n    ids: readonly string[],\n    signal: AbortSignal\n  ) => Promise<Read>;\n  readonly count?: () => Promise<SharedStylesCount>;\n}\n\n/**\n * A list of ids as one string an effect or a memo can depend on. JSON, since\n * an id is any string, a newline or a comma included, so no separator could\n * be told apart from an id.\n */\nexport function idsKey(ids: readonly string[]): string {\n  return JSON.stringify(ids);\n}\n\n/** The ids a key made by {@link idsKey} holds. */\nexport function idsOf(key: string): string[] {\n  const parsed: unknown = JSON.parse(key);\n  return Array.isArray(parsed)\n    ? parsed.filter((id): id is string => typeof id === \"string\")\n    : [];\n}\n\n/**\n * Counting the pages now, offered when the host can and this author may:\n * the way out for a site whose background jobs no scheduler runs.\n */\nexport interface CountNow {\n  readonly busy: boolean;\n  /** What the last count found, when it found something to say. */\n  readonly said: string | undefined;\n  /** Whether a count left pages to count, so the next one goes on. */\n  readonly again: boolean;\n  /**\n   * Whether the last count said no further count can get anywhere: what is\n   * left cannot be counted, so none is offered until the counts are read\n   * again and say otherwise.\n   */\n  readonly final: boolean;\n  readonly run: () => void;\n}\n\n/** The count button's words: what it will do, or that it is doing it. */\nexport function countNowWords(counter: CountNow): string {\n  if (counter.busy) return \"Counting…\";\n  return counter.again ? \"Count again\" : \"Count now\";\n}\n\n/** Where a count is offered nowhere: what counts the pages, and a link to how. */\nexport function CountedByJobs(): React.JSX.Element {\n  return (\n    <p className=\"nx-vars__note\">\n      {\"Pages are counted by the site's background jobs. \"}\n      <BackgroundJobsLink />\n    </p>\n  );\n}\n\n/** The link to how the site's background jobs are run. */\nexport function BackgroundJobsLink(): React.JSX.Element {\n  return (\n    <a\n      className=\"nx-vars__link\"\n      href={BACKGROUND_JOBS_DOCS_HREF}\n      target=\"_blank\"\n      rel=\"noreferrer\"\n    >\n      How background jobs run\n    </a>\n  );\n}\n\n/** What a count says when what is left cannot be counted at all. */\nconst CANNOT_COUNT_MORE = \"The pages left can't be counted.\";\n\n/** What a count that failed with no words of its own says. */\nconst COUNT_FAILED = \"The pages could not be counted.\";\n\n/** What a count leaves to say when the pages are not all counted yet. */\nconst STILL_TO_COUNT = \"Some pages are still to count.\";\n\n/** What a count found to say, and whether no further count can help. */\ninterface CountFound {\n  readonly said: string;\n  readonly again: boolean;\n  readonly final?: true;\n}\n\n/** What the row says after a count: nothing once every page is counted. */\nfunction countFound(answer: {\n  readonly whole: boolean;\n  readonly counting: boolean;\n}): CountFound | undefined {\n  if (answer.whole) return undefined;\n  return answer.counting\n    ? { said: STILL_TO_COUNT, again: true }\n    : { said: CANNOT_COUNT_MORE, again: false, final: true };\n}\n\n/**\n * The count, run once at a time: on an answer the rows on screen are read\n * again, so their counts and the notes follow; a refusal says why, and a\n * count that left pages says so and offers the next.\n */\nfunction useCountNow(\n  count: (() => Promise<SharedStylesCount>) | undefined,\n  mayCount: boolean,\n  recountNow: () => void,\n  /** The reads so far, and whether the latest say the site is counting. */\n  reads: {\n    readonly answered: number;\n    readonly counting: \"yes\" | \"unknown\" | \"no\";\n  }\n): CountNow | undefined {\n  const [busy, setBusy] = React.useState(false);\n  const [found, setFound] = React.useState<\n    | (CountFound & {\n        /** How many reads had answered when it was said. */\n        readonly at: number;\n      })\n    | undefined\n  >(undefined);\n  // A final word gives way to a later read that says the site is counting\n  // again: something new to count has turned up since the count.\n  const stale =\n    found?.final === true &&\n    reads.answered > found.at &&\n    reads.counting === \"yes\";\n  React.useEffect(() => {\n    if (stale) setFound(undefined);\n  }, [stale]);\n  const answeredNow = React.useRef(reads.answered);\n  answeredNow.current = reads.answered;\n  const run = React.useCallback(() => {\n    if (count === undefined || busy) return;\n    setBusy(true);\n    setFound(undefined);\n    count()\n      .then(answer => {\n        setBusy(false);\n        if (answer.kind === \"refused\") {\n          setFound({\n            said: answer.reason,\n            again: false,\n            at: answeredNow.current,\n          });\n          return;\n        }\n        recountNow();\n        // Another count is offered only when the answer says one would get\n        // further: pages left that cannot be counted are not \"still to\n        // count\", whatever the panel last read.\n        const said = countFound(answer);\n        // Stamped with the reads answered so far. The read the count sets\n        // off is not counted as answered, since it can tell this answer\n        // nothing newer than itself, so the first other read moves past it.\n        setFound(\n          said === undefined ? undefined : { ...said, at: answeredNow.current }\n        );\n      })\n      // A host that throws rather than answering a refusal: said all the\n      // same, so the button is not left saying it is counting.\n      .catch(() => {\n        setBusy(false);\n        setFound({ said: COUNT_FAILED, again: false, at: answeredNow.current });\n      });\n  }, [count, busy, recountNow]);\n  if (count === undefined || !mayCount) return undefined;\n  return {\n    busy,\n    said: found?.said,\n    again: found?.again === true,\n    final: found?.final === true,\n    run,\n  };\n}\n\n/** The health an id's usage was read under: its read's `whole` and `counting`. */\ninterface Reading {\n  readonly whole: boolean;\n  /** Undefined where the host did not say. */\n  readonly counting: boolean | undefined;\n}\n\n/**\n * Whether the listed ids' floors are worth asking for again: \"yes\" when an\n * id read before the count was whole was read while the site was still being\n * counted, \"unknown\" when such a reading did not say, \"no\" otherwise. Per id,\n * like {@link wholeOf}, since one scan is several reads and the count can\n * finish between them: a later read saying it is done says nothing of the\n * floors an earlier read left.\n */\nfunction countingOf(\n  readings: ReadonlyMap<string, Reading>,\n  ids: readonly string[]\n): \"yes\" | \"unknown\" | \"no\" {\n  const floors = ids.flatMap(id => {\n    const reading = readings.get(id);\n    return reading === undefined || reading.whole ? [] : [reading.counting];\n  });\n  if (floors.includes(true)) return \"yes\";\n  return floors.includes(undefined) ? \"unknown\" : \"no\";\n}\n\n/**\n * Whether the rows on screen are due another read on the recount timer: while\n * their counts are floors the site is still counting, or may be, and fewer\n * than {@link USAGE_RECOUNT_IDLE_MAX} recounts have changed nothing.\n */\nfunction recountDue(args: {\n  readable: boolean;\n  whole: boolean | undefined;\n  counting: \"yes\" | \"unknown\" | \"no\";\n  failed: boolean;\n  recounts: number;\n}): boolean {\n  if (!args.readable || args.whole !== false || args.failed) return false;\n  return args.counting !== \"no\" && args.recounts < USAGE_RECOUNT_IDLE_MAX;\n}\n\n/**\n * The usage of `ids` as one value, so a recount that moved any of it is told\n * from one that changed nothing. Each id's whole answer, not a summary of\n * it: a page use added as a component use goes keeps the total and changes\n * what the row says. JSON, for the reason {@link idsKey} is.\n */\nfunction progressKey<R>(\n  values: ReadonlyMap<string, R>,\n  ids: readonly string[]\n): string {\n  return JSON.stringify(ids.map(id => values.get(id) ?? null));\n}\n\n/** What the reads kept: each id's usage, and the health it was read under. */\ninterface KeptReads<R, Read> {\n  readonly values: ReadonlyMap<string, R>;\n  /** Per id, the health of the read that counted it. */\n  readonly readings: ReadonlyMap<string, Reading>;\n  /** The latest read that answered, for what a tab reads beside the counts. */\n  readonly latest: Read | undefined;\n  readonly mayCount: boolean;\n  readonly failed: boolean;\n  /** How many reads have answered, so a later one can be told from an earlier. */\n  readonly answered: number;\n}\n\n/**\n * Whether the counts of `ids` are whole: every one read so far was read under\n * a whole index. Derived per id rather than from the last read, since one\n * scan is several reads and the index can finish counting between them: an\n * earlier read's floors stay floors until that id is read again. Only the\n * ids listed now are asked, so an id since removed cannot hold it false.\n */\nfunction wholeOf(\n  readings: ReadonlyMap<string, Reading>,\n  ids: readonly string[]\n): boolean | undefined {\n  const read = ids.flatMap(id => {\n    const reading = readings.get(id);\n    return reading === undefined ? [] : [reading.whole];\n  });\n  return read.length === 0 ? undefined : read.every(Boolean);\n}\n\n/** Usage for some ids, read at most a read's size at a time, each handed on. */\nasync function readUsage<R, Read extends UsageRead<R>>(\n  source: UsageSource<R, Read>,\n  ids: readonly string[],\n  signal: AbortSignal,\n  onRead: (read: Read) => void\n): Promise<void> {\n  for (let at = 0; at < ids.length; at += USAGE_READ_SIZE) {\n    const read = await source.usage(\n      ids.slice(at, at + USAGE_READ_SIZE),\n      signal\n    );\n    if (signal.aborted) return;\n    onRead(read);\n  }\n}\n\n/** One read's answer folded into what the reads kept. */\nfunction mergedReads<R, Read extends UsageRead<R>>(\n  current: KeptReads<R, Read>,\n  read: Read,\n  ownCount = false\n): KeptReads<R, Read> {\n  return {\n    values: new Map([...current.values, ...read.values]),\n    readings: new Map([\n      ...current.readings,\n      ...[...read.values.keys()].map(\n        id => [id, { whole: read.whole, counting: read.counting }] as const\n      ),\n    ]),\n    latest: read,\n    // Absent from a host written before it existed: no.\n    mayCount: read.mayCount === true,\n    failed: false,\n    // Not a later word for a count when it is the count's own read: a final\n    // word is stamped with the reads answered before it, and only another\n    // read may move past it, whether or not the count's own ever answers.\n    answered: ownCount ? current.answered : current.answered + 1,\n  };\n}\n\n/**\n * Read some ids' usage into the kept reads, a failure marked; answers the\n * effect's cleanup, which drops a read the effect no longer wants.\n */\nfunction readInto<R, Read extends UsageRead<R>>(\n  source: UsageSource<R, Read>,\n  ids: readonly string[],\n  setState: React.Dispatch<React.SetStateAction<KeptReads<R, Read>>>,\n  /** The read a count sets off, which tells the count nothing newer. */\n  ownCount = false\n): () => void {\n  const controller = new AbortController();\n  readUsage(source, ids, controller.signal, read =>\n    setState(current => mergedReads(current, read, ownCount))\n  ).catch(() => {\n    if (!controller.signal.aborted) {\n      setState(current => ({ ...current, failed: true }));\n    }\n  });\n  return () => controller.abort();\n}\n\n/** The usage of the rows on screen, as the reads have answered so far. */\nexport interface UsageReads<R, Read> {\n  /** Each id's usage, once read. */\n  readonly values: ReadonlyMap<string, R>;\n  /**\n   * Whether every listed id's usage was read while every page had been\n   * counted. Undefined until a read has answered.\n   */\n  readonly whole: boolean | undefined;\n  /** Whether floors among them may still become whole; see `countingOf`. */\n  readonly counting: \"yes\" | \"unknown\" | \"no\";\n  /** The latest read that answered, for what a tab reads beside the counts. */\n  readonly latest: Read | undefined;\n  /** Whether this author may ask for the pages to be counted now. */\n  readonly mayCount: boolean;\n  readonly failed: boolean;\n  /** Ask about these ids again, as after a write the server refused. */\n  readonly reread: (ids: readonly string[]) => void;\n  /**\n   * Ask about these ids again and settle once every answer is kept, for a\n   * caller that acts on the fresh answer: a removal judged on counts read\n   * earlier. Rejects when a read fails, the counts kept as they were.\n   */\n  readonly readAgain: (ids: readonly string[]) => Promise<void>;\n  /**\n   * Counting the pages now, when this author may and the host can; its\n   * answer reads the rows on screen again.\n   */\n  readonly counter: CountNow | undefined;\n}\n\n/**\n * The recount timer: while the counts of `ids` are floors and the site may\n * still be counting, a recount each {@link USAGE_RECOUNT_MS}, its budget\n * renewed whenever the counts move. Answers the recount number and a\n * recount now, with the recount a count set off.\n */\nfunction useRecounts<R, Read>(\n  readable: boolean,\n  state: KeptReads<R, Read>,\n  ids: readonly string[],\n  whole: boolean | undefined,\n  counting: \"yes\" | \"unknown\" | \"no\"\n): {\n  recount: number;\n  recountNow: () => void;\n  /** Where the budget runs from, renewed when ids not read before are read. */\n  budgetFrom: React.RefObject<number>;\n  /** The recount a count set off, so its read is told from every other. */\n  countRead: React.RefObject<number | undefined>;\n} {\n  const [recount, setRecount] = React.useState(0);\n  const countRead = React.useRef<number | undefined>(undefined);\n  // The recount the budget runs from: renewed whenever ids not read before\n  // are read, so an id made after the budget was spent is still asked about\n  // again, not only once, and whenever the counts change, so a site still\n  // getting on with its counting is asked until it is done.\n  const budgetFrom = React.useRef(0);\n  const progress = progressKey(state.values, ids);\n  const progressSeen = React.useRef(progress);\n  // Before the timer's effect, which reads the budget this may renew.\n  React.useEffect(() => {\n    if (progressSeen.current === progress) return;\n    progressSeen.current = progress;\n    budgetFrom.current = recount;\n  }, [progress, recount]);\n  React.useEffect(() => {\n    // Only while the site is still being counted, or may be: floors that\n    // nothing will make whole (content the index cannot reach) are not asked\n    // for again.\n    const due = recountDue({\n      readable,\n      whole,\n      counting,\n      failed: state.failed,\n      recounts: recount - budgetFrom.current,\n    });\n    if (!due) return;\n    const timer = setTimeout(\n      () => setRecount(count => count + 1),\n      USAGE_RECOUNT_MS\n    );\n    return () => clearTimeout(timer);\n  }, [readable, whole, counting, state, recount]);\n  // A recount now, its budget renewed: the author just asked for the pages\n  // to be counted, so what follows is worth following again.\n  const latest = React.useRef(recount);\n  latest.current = recount;\n  const recountNow = React.useCallback(() => {\n    const next = latest.current + 1;\n    countRead.current = next;\n    budgetFrom.current = next;\n    setRecount(next);\n  }, []);\n  return { recount, recountNow, budgetFrom, countRead };\n}\n\n/**\n * How widely the rows on screen are used: each id is read once, at most a\n * read's size at a time, as rows come on screen; a row already read is not\n * asked again while the counts are whole. While some pages are still being\n * counted, every row on screen is asked again each {@link USAGE_RECOUNT_MS},\n * until they are.\n *\n * `source` is read by identity, so a host's adapter around its access is\n * memoised by the caller.\n */\nexport function useUsageReads<R, Read extends UsageRead<R>>(\n  source: UsageSource<R, Read> | undefined,\n  ids: readonly string[]\n): UsageReads<R, Read> {\n  const [state, setState] = React.useState<KeptReads<R, Read>>({\n    values: new Map(),\n    readings: new Map(),\n    latest: undefined,\n    mayCount: false,\n    failed: false,\n    answered: 0,\n  });\n  const known = React.useRef(state.values);\n  known.current = state.values;\n  const key = idsKey(ids);\n  const whole = wholeOf(state.readings, ids);\n  const counting = countingOf(state.readings, ids);\n  const { recount, recountNow, budgetFrom, countRead } = useRecounts(\n    source !== undefined,\n    state,\n    ids,\n    whole,\n    counting\n  );\n  const recounted = React.useRef(recount);\n  React.useEffect(() => {\n    if (source === undefined) return;\n    // A recount asks for every row on screen; otherwise only the rows that\n    // have come on screen since the last read.\n    const again = recounted.current !== recount;\n    recounted.current = recount;\n    // An empty id names nothing, and the routes refuse one.\n    const unread = idsOf(key).filter(\n      id => id !== \"\" && (again || !known.current.has(id))\n    );\n    if (unread.length === 0) return;\n    if (!again) budgetFrom.current = recount;\n    return readInto(\n      source,\n      unread,\n      setState,\n      again && recount === countRead.current\n    );\n  }, [source, key, recount, budgetFrom, countRead]);\n  // Ids asked about again on their own, after a write the server refused.\n  const [asked, reread] = React.useState<readonly string[]>([]);\n  React.useEffect(() => {\n    if (source === undefined || asked.length === 0) return;\n    return readInto(source, asked, setState);\n  }, [source, asked]);\n  const readAgain = React.useCallback(\n    async (ids: readonly string[]): Promise<void> => {\n      if (source === undefined) return;\n      // Not dropped with the view: what it settles is the caller's to use.\n      await readUsage(source, ids, new AbortController().signal, read =>\n        setState(current => mergedReads(current, read))\n      );\n    },\n    [source]\n  );\n  const counter = useCountNow(source?.count, state.mayCount, recountNow, {\n    answered: state.answered,\n    counting,\n  });\n  return {\n    values: state.values,\n    whole,\n    counting,\n    latest: state.latest,\n    mayCount: state.mayCount,\n    failed: state.failed,\n    reread,\n    readAgain,\n    counter,\n  };\n}\n","/**\n * How widely a variable is used, as the Variables tab draws it: the reads\n * behind every row's count, the count itself, and the box Remove opens in a\n * variable's editor while it cannot be removed.\n *\n * The rules are {@link variable-usage}'s; the reads are the Design panel's\n * one usage machine ({@link usage-reads}), as the Shared styles tab reads\n * its counts.\n *\n * @module variable-usage-view\n */\nimport type { NamedClass } from \"@nextlyhq/blocks-engine\";\nimport { TooltipProvider } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport { sharedStyleKindName } from \"../../styles/shared-style-library\";\nimport { blockLabel } from \"../add/inserter\";\n\nimport { UsesTail, UsesUnread } from \"./shared-style-details\";\nimport {\n  useUsageReads,\n  type UsageRead,\n  type UsageReads,\n  type UsageSource,\n} from \"./usage-reads\";\nimport { useUses, type UsesRead } from \"./uses-read\";\nimport {\n  sharedStyleSets,\n  variableCountWords,\n  variableLossSentence,\n  variableRemoval,\n  type VariableReach,\n  type VariablesAccess,\n  type VariablesUsage,\n  type VariableUse,\n  type VariableUsesPage,\n} from \"./variable-usage\";\n\n/** A variables usage read, in the shape the usage reads take. */\ntype VariablesRead = UsageRead<VariableReach> & VariablesUsage;\n\n/** The host's access as a usage source: each read's variables are its values. */\nfunction variablesSource(\n  access: VariablesAccess\n): UsageSource<VariableReach, VariablesRead> {\n  return {\n    usage: async (ids, signal) => {\n      const read = await access.usage(ids, signal);\n      return { ...read, values: read.variables };\n    },\n    ...(access.count === undefined ? {} : { count: access.count }),\n  };\n}\n\n/**\n * How widely the listed variables are used, by identity, read as the Shared\n * styles tab reads its styles'. None read without `access`.\n */\nexport function useVariableUsage(\n  access: VariablesAccess | undefined,\n  identities: readonly string[]\n): UsageReads<VariableReach, VariablesRead> {\n  const source = React.useMemo(\n    () => (access === undefined ? undefined : variablesSource(access)),\n    [access]\n  );\n  return useUsageReads(source, identities);\n}\n\n/** What a variable's row and editor know of usage. */\nexport interface VariableUsageHere {\n  /** A variable's usage by identity, once read. */\n  readonly reachOf: (identity: string) => VariableReach | undefined;\n  /**\n   * Some variables' usage as one count, each document once where the host\n   * can count them so ({@link useReachTogether}): a type size and its line\n   * height. Undefined until read.\n   */\n  readonly reachTogether: (\n    identities: readonly string[]\n  ) => VariableReach | undefined;\n  /** Read these variables' usage again, settling once it is kept. */\n  readonly readAgain: (identities: readonly string[]) => Promise<void>;\n  readonly access: VariablesAccess;\n  /** The site's shared styles, so one using it says what it sets. */\n  readonly classes: readonly NamedClass[] | undefined;\n}\n\n/**\n * How widely the row's variable is used, as its tooltip: shown when the row\n * is pointed at or takes focus, so keyboard and touch users meet it too.\n * Above the row and at its end. Closed until its usage is read, and while\n * the row's editor or menu is open: opened\n * by the row's focus, it stayed up over the editor in a browser and took the\n * first Escape meant for the editor.\n */\nexport function CountTip({\n  reach,\n  quiet = false,\n  children,\n}: {\n  reach: VariableReach | undefined;\n  /** True while the row's editor is open. */\n  quiet?: boolean;\n  children: React.ReactElement;\n}): React.JSX.Element {\n  // Wrapped whether or not the count has arrived, and only closed until it\n  // has: wrapping the row once its count arrived replaced the row's button,\n  // and the keyboard's focus on the row went with it.\n  return (\n    <TooltipProvider delayDuration={300}>\n      <ChromeTooltip\n        side=\"top\"\n        align=\"end\"\n        content={reach === undefined ? null : variableCountWords(reach)}\n        disabled={reach === undefined || quiet}\n      >\n        {children}\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/** How many places the in-use box names before \"Show all\". */\nconst FIRST_USES = 5;\n\n/** One variable a removal takes away: its identity, and its name in a list. */\nexport interface RemovedPart {\n  readonly identity: string;\n  /** What the part is called beside another: \"size\", \"line height\". */\n  readonly name: string;\n}\n\n/**\n * Why Remove cannot go ahead, opened in place by Remove: the places using\n * what it would take away, and the way forward. Focus moves to its heading,\n * so the reason is what is read next. Shown only while a use is known; a\n * removal the counts cannot judge goes to its confirm, and the save decides.\n */\nexport function VariableRefusal({\n  name,\n  loss,\n  parts,\n  reach,\n  usage,\n}: {\n  /**\n   * What Remove takes away, named: the variable, or the half of a type size\n   * that goes (\"Body's line height\").\n   */\n  name: string;\n  /** What the places would lose, in words: \"colour\", \"line height\". */\n  loss: string;\n  /** What Remove takes away: the variable, or a type size and its line height. */\n  parts: readonly RemovedPart[];\n  /** Their usage together. */\n  reach: VariableReach;\n  usage: VariableUsageHere;\n}): React.JSX.Element {\n  const id = React.useId();\n  const heading = React.useRef<HTMLHeadingElement>(null);\n  React.useEffect(() => {\n    heading.current?.focus();\n  }, []);\n  return (\n    <section className=\"nx-vars-refusal\" aria-labelledby={id}>\n      <h4\n        className=\"nx-vars-refusal__heading\"\n        id={id}\n        ref={heading}\n        tabIndex={-1}\n      >\n        {`${name} can't be removed while it's in use.`}\n      </h4>\n      <InUse\n        name={name}\n        loss={loss}\n        parts={parts}\n        reach={reach}\n        usage={usage}\n      />\n    </section>\n  );\n}\n\n/**\n * The places using what Remove would take away, a list for each part in\n * use, each named when there are two, and what to do.\n */\nfunction InUse({\n  name,\n  loss,\n  parts,\n  reach,\n  usage,\n}: {\n  name: string;\n  loss: string;\n  parts: readonly RemovedPart[];\n  reach: VariableReach;\n  usage: VariableUsageHere;\n}): React.JSX.Element {\n  return (\n    <>\n      <p className=\"nx-vars-refusal__text\">\n        {variableLossSentence(reach, loss)}\n      </p>\n      <VariableUses parts={parts} usage={usage} />\n      <p className=\"nx-vars-refusal__text\">\n        {`Change those blocks and styles to another variable, or clear the value there, then remove ${name}.`}\n      </p>\n    </>\n  );\n}\n\n/**\n * Where a variable is used: a list for each of its parts in use (a type\n * size and its line height are two), each named when there are two, the\n * first few places and then every one on \"Show all\". The one listing for\n * the variable's editor and for the reason Remove waits.\n */\nexport function VariableUses({\n  parts,\n  usage,\n}: {\n  parts: readonly RemovedPart[];\n  usage: VariableUsageHere;\n}): React.JSX.Element {\n  // Only the parts something uses have places to list.\n  const used = parts.filter(\n    part => variableRemoval(usage.reachOf(part.identity)) === \"in-use\"\n  );\n  return (\n    <>\n      {used.map(part => (\n        <PartUses\n          key={part.identity}\n          identity={part.identity}\n          heading={used.length > 1 ? part.name : undefined}\n          usage={usage}\n        />\n      ))}\n    </>\n  );\n}\n\n/**\n * The places one variable is used: the first few, then, on \"Show all\", every\n * page the route lists, read one after another with the progress said.\n */\nfunction PartUses({\n  identity,\n  heading,\n  usage,\n}: {\n  identity: string;\n  /** Said above the list when another part's list is beside it. */\n  heading: string | undefined;\n  usage: VariableUsageHere;\n}): React.JSX.Element {\n  const { read, all, showAll, reading } = useAllUses(usage.access, identity);\n  const { last, items } = read;\n  return (\n    <>\n      {heading === undefined ? null : (\n        <p className=\"nx-vars-refusal__part\">{capitalised(heading)}</p>\n      )}\n      {last === undefined || read.failed ? (\n        <UsesUnread read={read} />\n      ) : (\n        <>\n          <PlaceList\n            uses={all ? items : items.slice(0, FIRST_USES)}\n            identity={identity}\n            usage={usage}\n          />\n          {!all && last.total > FIRST_USES ? (\n            <button type=\"button\" className=\"nx-vars__link\" onClick={showAll}>\n              {`Show all ${String(last.total)}`}\n            </button>\n          ) : null}\n          <AllRead\n            reading={reading}\n            listed={items.length}\n            total={last.total}\n            done={all && !reading}\n          />\n          <UsesTail last={last} listed={items.length} />\n        </>\n      )}\n    </>\n  );\n}\n\n/** \"Line height\" from \"line height\". */\nfunction capitalised(words: string): string {\n  return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n/**\n * The places one variable is used, read a page at a time; once all are\n * asked for, every page that follows is read in turn, each once the one\n * before has arrived, until the route says none follows.\n */\nfunction useAllUses(\n  access: VariablesAccess,\n  identity: string\n): {\n  read: UsesRead<VariableUsesPage>;\n  all: boolean;\n  showAll: () => void;\n  /** Whether pages are still being read for \"Show all\". */\n  reading: boolean;\n} {\n  const { read, more } = useUses(access.uses, identity);\n  const [all, setAll] = React.useState(false);\n  const reading =\n    all && !read.failed && read.last !== undefined && read.last.hasNext;\n  const arrived = read.loaded === read.page;\n  React.useEffect(() => {\n    if (reading && arrived) more();\n  }, [reading, arrived, more]);\n  return { read, all, showAll: () => setAll(true), reading };\n}\n\n/**\n * While \"Show all\" reads the pages that follow, how far it has got; once it\n * is done, the places the route would not list, past the most it names.\n */\nfunction AllRead({\n  reading,\n  listed,\n  total,\n  done,\n}: {\n  reading: boolean;\n  listed: number;\n  total: number;\n  done: boolean;\n}): React.JSX.Element | null {\n  if (reading) {\n    return (\n      <p className=\"nx-shared-styles__meta\" role=\"status\">\n        {`Reading ${String(listed)} of ${String(total)}…`}\n      </p>\n    );\n  }\n  if (done && total > listed) {\n    return (\n      <p className=\"nx-shared-styles__meta\">\n        {`and ${String(total - listed)} more not listed`}\n      </p>\n    );\n  }\n  return null;\n}\n\n/** The places, each on its own line. */\nfunction PlaceList({\n  uses,\n  identity,\n  usage,\n}: {\n  uses: readonly VariableUse[];\n  identity: string;\n  usage: VariableUsageHere;\n}): React.JSX.Element | null {\n  if (uses.length === 0) return null;\n  return (\n    <ul className=\"nx-shared-styles__uses nx-vars-refusal__uses\">\n      {uses.map(use => (\n        // An id is unique only within its collection, so both key a row.\n        <li key={JSON.stringify([use.collection, use.id])}>\n          <UseRow use={use} identity={identity} usage={usage} />\n        </li>\n      ))}\n    </ul>\n  );\n}\n\n/**\n * One place: a page or component as a link to it, \"Homepage · page\"; a\n * shared style as a way to it in Shared styles, with what it sets with the\n * variable, \"Card · shared style · sets text colour\"; a block look as a way\n * to it in the inspector, \"Primary · Button look · sets text colour\"; a\n * block type's default style by name alone, \"Button · block default style\".\n */\nfunction UseRow({\n  use,\n  identity,\n  usage,\n}: {\n  use: VariableUse;\n  identity: string;\n  usage: VariableUsageHere;\n}): React.JSX.Element {\n  if (use.kind === \"block-default\") {\n    // A block type's own default style: named, with nowhere to open.\n    return (\n      <Place name={<Named title={use.title} />} chip=\"block default style\" />\n    );\n  }\n  if (use.kind === \"shared-style\") {\n    return <StyleRow use={use} identity={identity} usage={usage} />;\n  }\n  return (\n    <Place\n      name={\n        use.href === undefined ? (\n          <Named title={use.title} />\n        ) : (\n          // A new tab, so the page open here keeps its own undo history.\n          <a\n            className=\"nx-vars__link nx-shared-styles__use-title\"\n            href={use.href}\n            target=\"_blank\"\n            rel=\"noopener noreferrer\"\n          >\n            {use.title}\n          </a>\n        )\n      }\n      detail={sharedStyleKindName(use.kind).toLowerCase()}\n    />\n  );\n}\n\n/**\n * A shared style using the variable, or a block look, which is a shared\n * style bound to one block type: the Shared styles tab lists no looks, so a\n * look opens in the inspector's look editor. Each is plain text where the\n * host offers no way to open it.\n */\nfunction StyleRow({\n  use,\n  identity,\n  usage,\n}: {\n  use: VariableUse;\n  identity: string;\n  usage: VariableUsageHere;\n}): React.JSX.Element {\n  // A look is named by its id and its block type together, as the route\n  // names it: two types' own looks may share an id.\n  const { blockType } = use;\n  const sets = sharedStyleSets(usage.classes, use.id, identity, blockType);\n  if (blockType !== undefined) {\n    const { openLook } = usage.access;\n    return (\n      <Place\n        name={\n          <Opens\n            title={use.title}\n            open={\n              openLook === undefined\n                ? undefined\n                : () => openLook({ id: use.id, blockType })\n            }\n          />\n        }\n        chip={`${blockLabel(blockType)} look`}\n        detail={sets}\n      />\n    );\n  }\n  const { openSharedStyle } = usage.access;\n  return (\n    <Place\n      name={\n        <Opens\n          title={use.title}\n          open={\n            openSharedStyle === undefined\n              ? undefined\n              : () => openSharedStyle(use.id)\n          }\n        />\n      }\n      chip=\"shared style\"\n      detail={sets}\n    />\n  );\n}\n\n/** A place's name: a button where it can be opened, else its name alone. */\nfunction Opens({\n  title,\n  open,\n}: {\n  title: string;\n  open: (() => void) | undefined;\n}): React.JSX.Element {\n  if (open === undefined) return <Named title={title} />;\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-vars__link nx-shared-styles__use-title\"\n      onClick={open}\n    >\n      {title}\n    </button>\n  );\n}\n\n/** A place's name where there is nowhere to open it. */\nfunction Named({ title }: { title: string }): React.JSX.Element {\n  return <span className=\"nx-shared-styles__use-title\">{title}</span>;\n}\n\n/**\n * One place's line: its name and what kind of place it is beside it, what\n * it does with the variable at the end. Read as one phrase, \"Card · shared\n * style · sets text colour\": the dots are said, not drawn.\n */\nfunction Place({\n  name,\n  chip,\n  detail,\n}: {\n  name: React.ReactNode;\n  /** What kind of place it is, drawn as a small label beside the name. */\n  chip?: string;\n  /** What it is, or what it does with the variable, at the line's end. */\n  detail?: string;\n}): React.JSX.Element {\n  return (\n    <>\n      <span className=\"nx-vars-refusal__place\">\n        {name}\n        {chip === undefined ? null : (\n          <>\n            <span className=\"nx-sr-only\"> · </span>\n            <span className=\"nx-vars-refusal__kind\">{chip}</span>\n          </>\n        )}\n      </span>\n      {detail === undefined ? null : (\n        <>\n          <span className=\"nx-sr-only\"> · </span>\n          <span className=\"nx-shared-styles__meta\">{detail}</span>\n        </>\n      )}\n    </>\n  );\n}\n","\"use client\";\n\n/**\n * \"Show built-in colours\": the site setting that ends the Colours tab, and\n * the colours it hides from every colour picker in the builder.\n *\n * Off, a built-in colour (one the site's code or the engine supplies) that\n * nothing the site stores uses is left out of the Colours list and out of\n * the pickers. It is never removed: it is still a variable, and still\n * written on every page, because core blocks read the built-in colours.\n * What is hidden is asked afresh on every read ({@link hiddenColours}), so\n * a colour that becomes used is listed again with no write of its own.\n *\n * The Colours tab asks the rule from the counts it reads for its rows. The\n * pickers sit in the inspector and elsewhere, away from the tab, so a host\n * reads the same rule once with {@link useHiddenColoursRead} and hands it\n * down through {@link HiddenColours}.\n *\n * @module built-in-colours\n */\nimport { tokenIdentity, type SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport { Checkbox, Label } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { hiddenColours } from \"./colour-usage\";\nimport { usageState, type VariablesAccess } from \"./variable-usage\";\nimport { useVariableUsage } from \"./variable-usage-view\";\n\n/** The setting's label and hint, word for word. */\nconst LABEL = \"Show built-in colours\";\nconst HINT = \"Hidden colours still work where core blocks use them\";\n\n/** No colour hidden. */\nconst NONE: ReadonlySet<string> = new Set();\n\n/**\n * The colours every colour picker in the builder leaves out, by identity: a\n * host provides it around the builder. None where no host does.\n *\n * @experimental Settles with the built-in colours setting.\n */\nexport const HiddenColours: React.Context<ReadonlySet<string>> =\n  React.createContext<ReadonlySet<string>>(NONE);\n\n/** Whether the site lists the built-in colours it does not use: unset is yes. */\nexport function builtInColoursShown(tokens: SiteTokenSet | undefined): boolean {\n  return tokens?.builtInColoursShown !== false;\n}\n\n/** The site's variables with the setting changed, everything else as it was. */\nfunction withBuiltInColoursShown(\n  tokens: SiteTokenSet,\n  shown: boolean\n): SiteTokenSet {\n  return { ...tokens, builtInColoursShown: shown };\n}\n\n/** The identities of the built-in colours: those `supplied` supplies. */\nfunction builtInColourIds(supplied: SiteTokenSet | undefined): string[] {\n  return (supplied?.tokens ?? [])\n    .filter(token => token.kind === \"color\")\n    .map(tokenIdentity);\n}\n\n/** How long after a change of the variables their use is read again. */\nconst READ_AGAIN_AFTER_MS = 800;\n\n/**\n * The colours the pickers leave out, for a host to provide through\n * {@link HiddenColours}: each built-in colour the site's count has shown\n * unused and the open page does not use, while the site hides them. Reads\n * the built-in colours' use only then, and again a moment after the site's\n * variables change, since a variable naming one makes it used.\n *\n * @experimental Settles with the built-in colours setting.\n */\nexport function useHiddenColoursRead({\n  tokens,\n  supplied,\n  access,\n  usedOnPage,\n}: {\n  /** The site's variables, the setting among them. */\n  tokens: SiteTokenSet | undefined;\n  /** What the site's code and the engine supply: the built-in variables. */\n  supplied: SiteTokenSet | undefined;\n  /** The host's reads of how widely variables are used. */\n  access: VariablesAccess | undefined;\n  /** The variables the open page uses, before any save. */\n  usedOnPage?: ReadonlySet<string> | undefined;\n}): ReadonlySet<string> {\n  const shown = builtInColoursShown(tokens);\n  const builtIns = React.useMemo(\n    () => (shown ? [] : builtInColourIds(supplied)),\n    [shown, supplied]\n  );\n  const { values, readAgain } = useVariableUsage(access, builtIns);\n  useHiddenReadAgain(shown, tokens, builtIns, readAgain);\n  return React.useMemo(\n    () =>\n      hiddenColours(builtIns, {\n        shown,\n        stateOf: identity => usageState(values.get(identity)),\n        builtIn: () => true,\n        onPage: usedOnPage,\n      }),\n    [builtIns, shown, values, usedOnPage]\n  );\n}\n\n/**\n * Reads the built-in colours' use again a moment after the site's variables\n * change, while the site hides them: a variable or a style made to name a\n * hidden colour makes it used once saved, and it is then listed again.\n */\nexport function useHiddenReadAgain(\n  shown: boolean,\n  tokens: SiteTokenSet | undefined,\n  builtIns: readonly string[],\n  readAgain: ((identities: readonly string[]) => Promise<void>) | undefined\n): void {\n  const seen = React.useRef(tokens);\n  const latest = React.useRef({ builtIns, readAgain });\n  latest.current = { builtIns, readAgain };\n  React.useEffect(() => {\n    const changed = seen.current !== tokens;\n    seen.current = tokens;\n    if (shown || !changed) return undefined;\n    const timer = window.setTimeout(() => {\n      // A failed read keeps the counts as they were: nothing to say here.\n      latest.current\n        .readAgain?.(latest.current.builtIns)\n        .catch(() => undefined);\n    }, READ_AGAIN_AFTER_MS);\n    return () => window.clearTimeout(timer);\n  }, [shown, tokens]);\n}\n\n/**\n * The checkbox that ends the Colours tab, with its hint. A site setting:\n * the change goes to the site's variables, for every author, and is saved\n * at once by the commit it is handed.\n */\nexport function BuiltInColoursSetting({\n  tokens,\n  readOnly,\n  onChange,\n}: {\n  tokens: SiteTokenSet;\n  readOnly: boolean;\n  /** Writes the changed variables and saves them at once. */\n  onChange: (tokens: SiteTokenSet) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <div className=\"nx-built-in-colours\">\n      <div className=\"nx-built-in-colours__line\">\n        <Checkbox\n          id={id}\n          checked={builtInColoursShown(tokens)}\n          disabled={readOnly}\n          aria-describedby={`${id}-hint`}\n          onCheckedChange={checked =>\n            onChange(withBuiltInColoursShown(tokens, checked === true))\n          }\n        />\n        <Label htmlFor={id} className=\"nx-built-in-colours__label\">\n          {LABEL}\n        </Label>\n      </div>\n      <p id={`${id}-hint`} className=\"nx-built-in-colours__hint\">\n        {HINT}\n      </p>\n    </div>\n  );\n}\n","/**\n * Recent colours: the last colours an author typed or picked, newest first,\n * offered by every colour picker in the builder after the site's colour\n * variables. A convenience of the author's own, never part of the site: the\n * host keeps it in its store for that author, provided here once, so a block's\n * picker and a variable's picker read the one list.\n *\n * Eight, each once, newest first, written as the Icon control writes its\n * recent icons. Unlike that list there is no copy held for the session: the\n * host's store holds the list for the page itself where storage refuses.\n *\n * @module recent-colours\n */\nimport { isRawColour } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport {\n  readRecentIcons,\n  rememberIcon,\n} from \"../../inspector/content/recent-icons\";\nimport type { PreferenceStore } from \"../../shell-state\";\n\n/**\n * Where the host keeps this author's Recent colours. Absent, the pickers show\n * an empty list and remember nothing.\n */\nexport const RecentColoursStore: React.Context<PreferenceStore | undefined> =\n  React.createContext<PreferenceStore | undefined>(undefined);\n\n/**\n * The colour to remember for a value written, or `undefined` for one that is\n * not a colour of its own: a variable, `var()`, a keyword that borrows a\n * colour, or nothing. Kept as it was written, so a recent colour is stored in\n * the form the author typed it.\n */\nfunction rememberable(value: unknown): string | undefined {\n  if (typeof value !== \"string\" || !isRawColour(value)) return undefined;\n  return value.trim();\n}\n\n/*\n * Who is drawing each store's list, so a colour remembered in one picker\n * reaches every other on screen at once.\n */\nconst watchers = new WeakMap<PreferenceStore, Set<() => void>>();\n\nfunction watch(\n  store: PreferenceStore | undefined,\n  onChange: () => void\n): () => void {\n  if (store === undefined) return () => undefined;\n  const set = watchers.get(store) ?? new Set<() => void>();\n  watchers.set(store, set);\n  set.add(onChange);\n  return () => {\n    set.delete(onChange);\n  };\n}\n\n/** The stored text, or `null` for none or a store that refuses to read. */\nfunction storedText(store: PreferenceStore | undefined): string | null {\n  try {\n    return store?.read() ?? null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Remember a value just written, as the newest of the author's Recent\n * colours, and redraw every picker reading the list. Anything but a raw\n * colour, and any value without a store, is ignored.\n */\nexport function rememberColour(\n  store: PreferenceStore | undefined,\n  value: unknown\n): void {\n  const colour = rememberable(value);\n  if (store === undefined || colour === undefined) return;\n  rememberIcon(store, readRecentIcons(store), colour);\n  for (const onChange of watchers.get(store) ?? []) onChange();\n}\n\n/** A store that reads back one text, for reading a snapshot by the same rules. */\nconst textStore = (text: string | null): PreferenceStore => ({\n  read: () => text,\n  write: () => undefined,\n});\n\n/**\n * The author's Recent colours, newest first, and a way to remember a value\n * just written; anything but a raw colour is ignored.\n */\nexport function useRecentColours(): readonly [\n  readonly string[],\n  (value: unknown) => void,\n] {\n  const store = React.useContext(RecentColoursStore);\n  // The stored text is the snapshot: a string compares by value, so a picker\n  // redraws only when the list changed.\n  const raw = React.useSyncExternalStore(\n    React.useCallback(\n      (onChange: () => void) => watch(store, onChange),\n      [store]\n    ),\n    () => storedText(store),\n    () => null\n  );\n  // Read by the rule it was written by, so nothing else under the key is\n  // offered as a colour.\n  const colours = React.useMemo(\n    () =>\n      readRecentIcons(textStore(raw)).filter(\n        colour => rememberable(colour) !== undefined\n      ),\n    [raw]\n  );\n  const remember = React.useCallback(\n    (value: unknown) => rememberColour(store, value),\n    [store]\n  );\n  return [colours, remember] as const;\n}\n","/**\n * How a colour variable's two values are drawn beside its name: a small\n * swatch for light and one for dark, in that order.\n *\n * One drawing for every list of colour variables, Design's Variables tab and\n * the inspector's colour picker among them, so a variable looks the same\n * wherever an author meets it.\n *\n * @module variable-swatch\n */\nimport type * as React from \"react\";\n\n/** A swatch painted through a custom property, or the empty swatch. */\nexport function swatchStyle(\n  colour: string | undefined\n): React.CSSProperties | undefined {\n  return colour === undefined\n    ? undefined\n    : ({ \"--nx-swatch\": colour } as React.CSSProperties);\n}\n\n/**\n * The light and dark swatches, each painted with a colour resolved by the\n * caller, or left as the empty swatch when nothing could be resolved. For\n * sight only: a list that draws these says the values in words itself.\n */\nexport function ColourPair({\n  light,\n  dark,\n}: {\n  light: string | undefined;\n  dark: string | undefined;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-vars__pair\" aria-hidden=\"true\">\n      <span\n        className=\"nx-vars__swatch nx-vars__swatch--mode\"\n        data-mode=\"light\"\n        style={swatchStyle(light)}\n      />\n      <span\n        className=\"nx-vars__swatch nx-vars__swatch--mode\"\n        data-mode=\"dark\"\n        style={swatchStyle(dark)}\n      />\n    </span>\n  );\n}\n","\"use client\";\n\n/**\n * The colour field: its picker, trigger, custom colour and colour variables,\n * the contrast note against its partner colour, and the rules for how the\n * picker closes when another control writes the same value.\n *\n * @module style-colour-field\n */\nimport {\n  isRawColour,\n  isTokenRef,\n  type ContrastResult,\n  type NodeStyles,\n  type SiteTokenSet,\n  type TokenMode,\n  type StyleLeaf,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  ColorPicker,\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@nextlyhq/ui\";\nimport { ChevronDown } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { isElement } from \"../../canvas/dom-kind\";\nimport { ChoiceList } from \"../../choice-list\";\nimport { useLiveGesture } from \"../../live-gesture\";\nimport { HiddenColours } from \"../../panels/design/built-in-colours\";\nimport {\n  RecentColoursStore,\n  rememberColour,\n  useRecentColours,\n} from \"../../panels/design/recent-colours\";\nimport {\n  focusAfterUnlink,\n  UnlinkButton,\n  VariableTipped,\n  variableTip,\n} from \"../../panels/design/variable-choice\";\nimport { ColourPair, swatchStyle } from \"../../panels/design/variable-swatch\";\nimport type { PreferenceStore } from \"../../shell-state\";\nimport {\n  activeTokenMode,\n  colourHexOf,\n  variableFor,\n  variableLabel,\n  shownVariables,\n  variablesFor,\n  contrastAtLeaf,\n  contrastPartnerOf,\n  contrastRatioText,\n  type SiteVariable,\n} from \"../../styles/style-colour\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport { readStyleValue, type StyleAddress } from \"../../styles/style-values\";\nimport { useFieldDescription } from \"../css-hint\";\n\nimport { InheritedValue } from \"./inherited-value\";\nimport type { CommitOutcome } from \"./style-field-surroundings\";\nimport { useDraft, TextField, useTypesLive } from \"./style-text-field\";\n\n/**\n * Whether Control held with a primary press means a CONTEXT MENU here.\n *\n * It does on macOS and nowhere else: there the platform opens a menu and no\n * click follows, while on Windows and Linux a Control-click is an ordinary\n * modified click and the button runs exactly as it always does.\n *\n * So this cannot be answered without asking the platform, and the platform is\n * asked by NAME because nothing else decides it. There is no structural probe\n * for \"will a click follow this press\" that can be run before the click either\n * arrives or does not — which is the same reason the whole supersede is\n * predicted at press time rather than confirmed.\n *\n * `userAgentData` first because `platform` is deprecated, and both because the\n * modern one is Chromium-only. Neither present — a non-browser runtime —\n * answers `false`, which is the ordinary-click reading and the one that keeps\n * the two-write defect closed.\n */\nfunction contextMenuModifier(): boolean {\n  const agent: { platform?: string } | undefined = (\n    navigator as Navigator & { userAgentData?: { platform?: string } }\n  ).userAgentData;\n  const name = agent?.platform ?? navigator.platform ?? \"\";\n  return /mac/i.test(name);\n}\n\n/**\n * Whether a press can actually RUN the control it landed on.\n *\n * Only a press that will be followed by a click can, and two gestures report a\n * pointer press while invoking nothing: a secondary press anywhere, and a\n * Control-held primary press on macOS.\n *\n * Both directions cost something, which is why the platform is asked rather\n * than the modifier alone. Reading a context menu as an activation discards the\n * colour an author was composing on behalf of a button that never ran. Reading\n * an ordinary Control-click as a context menu does the opposite: the picker\n * commits its draft on dismissal AND the button's click writes, so one gesture\n * becomes two edits and the first undo restores the colour they pressed Reset\n * to be rid of — the defect the supersede exists to prevent, reintroduced.\n *\n * The remainder is stated rather than left to be discovered: a primary press\n * that DRAGS OFF the control and releases elsewhere fires no click either, and\n * is still read here as an activation. Closing that needs the write to confirm\n * the discard instead of the press predicting it — either holding the draft for\n * a later signal, which is the timer this module removed and whose cancellation\n * cost a race, or routing the marked control's write back through this field,\n * which the declaration exists to avoid.\n */\nfunction activates(event: PointerEvent): boolean {\n  if (event.button !== 0) return false;\n  return !(event.ctrlKey && contextMenuModifier());\n}\n\n/**\n * Which field a control writes the value of, when it is not that field.\n *\n * The colour picker commits its gesture when the popover closes, and pressing\n * anything outside it closes the popover first. A control that writes the SAME\n * value the picker is composing therefore has to say so, or one intent produces\n * two edits and the first undo restores the value the author pressed the\n * control to be rid of.\n *\n * Stated as the field's id rather than as a bare flag, because the question is\n * not \"does this control write\" — every control does — but \"does it write what\n * this picker is holding\". A bare flag makes Reset on `background-color`\n * supersede an open picker on `color`, discarding a gesture nothing replaced.\n *\n * Declared on the element rather than handed down as a ref, because the\n * controls making the promise live in components with no path to the picker:\n * a breakpoint Reset is drawn beside the control, not inside it.\n */\nconst COMMITS_FOR = \"data-nx-commits-for\";\n\n/**\n * How a picker's popover closed: with its gesture written, or superseded.\n *\n * Named rather than left as a boolean, because the two are not \"did something\n * happen\" — both are outcomes the host must ACT on, and the discard is the one\n * a boolean invites a caller to express by doing nothing.\n */\ntype PickerClose = \"committed\" | \"superseded\";\n\n/**\n * The attributes marking a control as writing `fieldId`'s value itself.\n *\n * Exported with {@link supersedes} so the pair can be checked together.\n */\nexport function commitsFor(fieldId: string): Record<string, string> {\n  return { [COMMITS_FOR]: fieldId };\n}\n\n/**\n * Whether an interaction outside the picker writes `fieldId`'s value itself.\n *\n * Asked of the ancestor chain rather than of the target alone: the press lands\n * on whatever the control renders inside its button, and a control that puts a\n * span or an icon in there would otherwise stop making the promise.\n *\n * The target is classified by `dom-kind` rather than by `instanceof Element`,\n * which answers only for elements this window built.\n */\nexport function supersedes(\n  target: EventTarget | null,\n  fieldId: string\n): boolean {\n  if (!isElement(target)) return false;\n  return (\n    target.closest(`[${COMMITS_FOR}]`)?.getAttribute(COMMITS_FOR) === fieldId\n  );\n}\n\n/**\n * The other half of a contrast pair, for a leaf that has one.\n *\n * Read from THIS node at the same state and breakpoint the control edits,\n * which is narrower than the cascade and is the honest limit of what this panel\n * can answer today: a background arriving from a named class, a block default\n * or a wider breakpoint is not seen, so the readout reports nothing rather than\n * measuring against a background that is not the one on the page.\n *\n * Answering it properly means asking `styleProvenance`, which has already\n * settled tier order, both breakpoint axes, states and specificity — and which\n * needs a `trace` of compiled declarations that nothing supplies to this panel.\n * Walking the cascade a second time HERE is the thing that must not happen.\n *\n * The address is reused rather than rebuilt so the state and breakpoint cannot\n * drift from the ones the control is reading its own value at — a pair measured\n * across two breakpoints is two colours that are never drawn together.\n */\nexport function partnerColour(\n  leaf: StyleLeaf,\n  styles: NodeStyles | undefined,\n  address: StyleAddress\n): StyleValue | undefined {\n  const property = contrastPartnerOf(leaf);\n  if (property === undefined) return undefined;\n  return readStyleValue(styles, { ...address, property, path: [] });\n}\n\n/**\n * Every id describing one control, or `undefined` when nothing does.\n *\n * A refusal message and a contrast verdict are both descriptions and neither\n * replaces the other: a control pointed only at the refusal never announces the\n * verdict, and one pointed only at the verdict drops the reason its last value\n * was refused. Joined here so the two cannot be traded off at a call site.\n *\n * Note what this deliberately does NOT decide: whether the control is INVALID.\n * A passing 21:1 contrast note is supplementary text, and a control inferring\n * invalidity from having a description announced a perfectly good colour as an\n * error.\n */\nfunction describedByAll(\n  refusal: string | undefined,\n  verdict: string | undefined\n): string | undefined {\n  return (\n    [refusal, verdict].filter(part => part !== undefined).join(\" \") || undefined\n  );\n}\n\n/**\n * Whether opening the picker here would REPLACE something the author has.\n *\n * True when the surface cannot show the stored value and there is a stored\n * value to lose — a reference, or non-empty text. The picker then starts at its\n * fallback rather than at the value, so the first movement writes something\n * unrelated to what was there, and the author is owed a warning first.\n *\n * The reference has to be tested explicitly: `storedText` answers `\"\"` for one,\n * so a predicate reading the draft alone missed every token — including the two\n * that most need the warning, a token the site no longer defines and one whose\n * value this package cannot resolve.\n */\nfunction wouldReplace(\n  shown: string | undefined,\n  reference: string | null,\n  draft: string\n): boolean {\n  if (shown !== undefined) return false;\n  return reference !== null || draft !== \"\";\n}\n\n/**\n * The hex a picker opens on when the stored value cannot be decomposed.\n *\n * Black, and it is never WRITTEN by being shown: the picker reports a colour\n * only when the author moves something. So this is where the surface starts for\n * a value it cannot represent, not a value substituted for one.\n */\nconst PICKER_FALLBACK = \"#000000\";\n\n/**\n * A colour: a swatch that opens a picker, beside the field that owns the value.\n *\n * **The text field remains the control**, exactly as it does for a length. A\n * stored colour may be `oklch()`, `color-mix()`, a named colour, `currentcolor`,\n * a CSS-wide keyword or a `var()`, and a control that modelled the value as\n * RGBA would write every one of them away the moment it opened. The picker is\n * an affordance on top, and it reports nothing until the author moves it.\n *\n * **A token reference is EDITABLE here rather than read-only**, which is the\n * other half of what this control adds: it shows the token's CURRENT name on\n * its own trigger, in green with its swatch, and lets the author swap it, or\n * Unlink it to the colour it gives now. Every other field shows a held\n * variable as a green chip, its name the way to choose another, instead.\n *\n * **A token is stored by IDENTITY, never by the name shown.** The two differ\n * after a rename, and `SiteVariable` carries both for that reason — the list\n * hands back the variable it was given, so the identity travels with it and\n * the label never reaches the document.\n *\n * **Literal and token are exclusive**, which is what the two layouts express.\n * The same rule Gutenberg's palette follows: a value is a reference or a\n * colour, and nothing sensible reads as both at once.\n */\nexport function ColourField({\n  id,\n  labelledBy,\n  control,\n  stored,\n  actionName,\n  tokens,\n  prefersDark,\n  pairedColour,\n  obscuredBy,\n  describedBy,\n  onCommit,\n  onType,\n}: {\n  id: string;\n  labelledBy: string;\n  control: StyleControl & { leaf: Extract<StyleLeaf, { kind: \"color\" }> };\n  stored: StyleValue | undefined;\n  actionName: string;\n  tokens: SiteTokenSet | undefined;\n  prefersDark: boolean;\n  pairedColour: StyleValue | undefined;\n  /**\n   * A property on this node that puts something between the pair, or\n   * `undefined` when none does. A verdict is withheld while one is set.\n   */\n  obscuredBy: string | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  /**\n   * The write a keystroke or a picker move makes where the panel writes as\n   * it is typed, where it is not the field's own: a shadow variable's colour\n   * is drawn on the canvas meanwhile and stored once, by the commit, when the\n   * edit ends. `onCommit` when omitted.\n   */\n  onType?: ((value: StyleValue | null) => CommitOutcome) | undefined;\n}): React.JSX.Element {\n  const noteId = React.useId();\n  // Lifted out of the text field because two controls edit one value: a draft\n  // private to the field would leave the swatch painting a superseded one.\n  const { draft, setDraft, edited, reset, live } = useDraft(stored);\n  const commitColour = rememberingCommit(\n    onCommit,\n    React.useContext(RecentColoursStore)\n  );\n\n  const reference = isTokenRef(stored) ? stored.$token : null;\n  const mode = activeTokenMode(prefersDark);\n  // Without the built-in colours the site hides, as every picker lists them.\n  const choices = shownVariables(\n    variablesFor(control.leaf, tokens, mode),\n    React.useContext(HiddenColours),\n    reference\n  );\n  // A keystroke's and a picker move's write.\n  const typed = typedOrCommitted(onType, onCommit);\n  const { commitInstead, closed, onColour } = usePickerWrites({\n    commitColour,\n    onMove: typed,\n    reset,\n    setDraft,\n  });\n  // What the surface is currently SHOWING: the draft while a literal is being\n  // typed, so the swatch follows the field, and the stored value for a\n  // reference, which no field is editing. Named once and resolved once, rather\n  // than resolved in each branch — two calls to the same resolver is the shape\n  // that drifts.\n  // Once the draft has MOVED, it is what the surface shows — including over a\n  // stored token. Pinned to `stored` for a reference, the picker was handed the\n  // token's own hex again on every render, and its prop-sync effect reset the\n  // surface to it: the controls snapped back mid-drag and a token could not be\n  // replaced with a literal by using the picker at all.\n  const storedLabel = storedTokenLabel(reference, tokens, mode, choices);\n  // The variable held, as the canvas shows it, for the trigger's tooltip and\n  // for Unlink; `undefined` for a value, none, or a variable the site lacks.\n  const held = heldVariable(reference, tokens, mode);\n  const showing = reference === null || edited ? draft : stored;\n  const shown = colourHexOf(showing, tokens, mode);\n  // Measured from what the surface is SHOWING, which is the same value the\n  // swatch is painted from. Reading `stored` instead left the verdict describing\n  // the old colour for the whole of a picker gesture — stale exactly while an\n  // author is choosing, which is when a contrast readout is for — and put the\n  // swatch and the figure beside it on two different colours.\n  const { contrast, describes } = contrastReading({\n    leaf: control.leaf,\n    showing,\n    pairedColour,\n    tokens,\n    mode,\n    obscuredBy,\n    describedBy,\n    noteId,\n  });\n\n  return (\n    <>\n      <div\n        className=\"nx-style-inspector__colour\"\n        // Named as a GROUP only where there is no field to carry the name: with\n        // a text input present the label points at it directly, and a group\n        // wrapping a named control announces the property twice.\n        {...(reference === null\n          ? {}\n          : { role: \"group\", \"aria-labelledby\": labelledBy })}\n      >\n        <ColourPicker\n          shown={shown}\n          choices={choices}\n          tokensRead={tokens !== undefined}\n          reference={reference}\n          referenceLabel={storedLabel}\n          referenceTip={heldTip(held, storedLabel, tokens)}\n          customFirst={writtenAsValue(stored)}\n          actionName={actionName}\n          describedBy={describes}\n          invalid={describedBy !== undefined}\n          unrepresented={wouldReplace(shown, reference, draft)}\n          // The draft moves with the pointer, and the document follows at most\n          // once a frame where the panel writes as it is typed, as ONE step of\n          // undo however many moves the gesture makes (`usePickerWrites`).\n          onColour={onColour}\n          // The gesture ends where the picker closes, whichever way it closed.\n          onClosed={closed}\n          /*\n           * Any control that writes THIS field's value for itself, declared on\n           * the element. The Unlink beside a held variable is one; a\n           * breakpoint Reset is another, and it lives in a different component\n           * that has no way to hand a ref down here.\n           */\n          supersededBy={target => supersedes(target, id)}\n          // A variable, or a recent colour, is one discrete choice rather\n          // than a gesture, so it commits immediately, exactly as the select\n          // and toggle controls do.\n          onChoose={commitInstead}\n        />\n        {reference === null ? (\n          // The SAME field every other text control uses, rather than one\n          // written here. Commit on blur, Enter, the empty draft that clears\n          // instead of storing `\"\"`, and the `unchanged` case that puts back\n          // what the document holds are one contract — and a second copy of it\n          // beside the first is what drifts, silently, in the direction of\n          // losing an edit.\n          <TextField\n            id={id}\n            control={control}\n            stored={stored}\n            draft={draft}\n            setDraft={setDraft}\n            tokens={tokens}\n            describedBy={describes}\n            // The REFUSAL alone. `describes` also carries the contrast verdict,\n            // which is supplementary text and never a complaint.\n            invalid={describedBy !== undefined}\n            live={live}\n            // Remembered among Recent colours once, when the edit ends.\n            onType={typed}\n            onCommit={commitColour}\n          />\n        ) : (\n          <ColourUnlink\n            held={held}\n            fieldId={id}\n            actionName={actionName}\n            onUnlink={value => {\n              commitInstead(value);\n              // The typed field takes Unlink's place, holding the colour.\n              focusAfterUnlink(() => document.getElementById(id));\n            }}\n          />\n        )}\n      </div>\n      <ContrastNote id={noteId} contrast={contrast} />\n      <RawColourNote stored={stored} />\n    </>\n  );\n}\n\n/**\n * The trigger, and the surface it opens onto: the site's colour variables\n * first, then the author's Recent colours, and a custom colour behind its own\n * button at the end.\n *\n * The variables lead because a variable carries a light and a dark value and a\n * colour written as a value carries one, which the visitor's dark mode cannot\n * change. So the list an author meets first is the one that keeps a page right\n * in both modes, by the names the Variables tab gives them, each with its pair.\n *\n * Its own component because CHOOSING a colour is a different question from\n * showing one: the row owns the stored value and its text, and this owns the\n * list, the raw picker and what the trigger is painted with.\n *\n * The two callbacks stay separate for the reason `ColorPicker` keeps them\n * separate: only the host knows what a choice MEANS. A variable hands back its\n * identity and never the colour it currently resolves to — storing that would\n * turn a reference into a literal and stop the page following the variable.\n */\nfunction ColourPicker({\n  shown,\n  choices,\n  tokensRead,\n  reference,\n  referenceLabel,\n  referenceTip,\n  customFirst,\n  actionName,\n  describedBy,\n  invalid,\n  unrepresented,\n  onColour,\n  onClosed,\n  supersededBy,\n  onChoose,\n}: {\n  /** The resolved colour, or `undefined` when nothing here can resolve one. */\n  shown: string | undefined;\n  choices: readonly SiteVariable[];\n  /** Whether the site's variables have arrived; until then the list waits. */\n  tokensRead: boolean;\n  /** The identity the value refers to, or `null` for a value or none. */\n  reference: string | null;\n  /** What that reference is called, for the trigger. */\n  referenceLabel: string;\n  /** What the held variable is, for the trigger's tooltip; see `variableTip`. */\n  referenceTip: string | undefined;\n  /** Whether the custom colour opens already showing. */\n  customFirst: boolean;\n  actionName: string;\n  /** Everything describing the control: a refusal, a contrast verdict, or both. */\n  describedBy: string | undefined;\n  /** Whether the last value was refused. A contrast verdict is not a refusal. */\n  invalid: boolean;\n  /** Whether the stored value is one the picker cannot show. */\n  unrepresented: boolean;\n  /** The picker moved. Fires on every pointer event during a drag. */\n  onColour: (hex: string) => void;\n  /**\n   * The picker closed, and how.\n   *\n   * The outcome is a value rather than the presence or absence of a call,\n   * because \"superseded\" is an instruction to DISCARD the gesture, not an\n   * absence of one — and a host given only the write path has nowhere to drop\n   * what it was holding.\n   */\n  onClosed: (outcome: PickerClose) => void;\n  /**\n   * Whether the control being PRESSED outside the popover writes THIS field's\n   * value itself.\n   *\n   * Asked before the dismissal is turned into a write, so a control that both\n   * closes this picker and commits the same value does not produce two edits\n   * for one intent — the author would otherwise undo the reset and get back the\n   * colour they pressed it to be rid of.\n   *\n   * The target is a press rather than any interaction, because Radix dismisses\n   * on focus as well and a focused button has not written anything. See where\n   * this is bound.\n   */\n  supersededBy: (target: EventTarget | null) => boolean;\n  /**\n   * A discrete choice: a variable, as a reference to its identity, or a\n   * recent colour, as it is listed.\n   */\n  onChoose: (value: StyleValue) => void;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  // Whether the dismissal in progress belongs to a control that writes for\n  // itself. Read once by the close below and reset there, so it cannot leak\n  // into the next open.\n  const superseded = React.useRef(false);\n  const [open, setOpen] = React.useState(false);\n  const [custom, setCustom] = React.useState(customFirst);\n  // A colour inherited from another tier is painted while none is set here,\n  // and marked so the swatch reads as inherited rather than chosen. Through\n  // the same projection as a stored colour, so a site variable or\n  // `currentcolor`, which resolve against the canvas, leave it unpainted\n  // rather than painted with the panel's own colour.\n  const inherited = React.useContext(InheritedValue);\n  const painted = shown ?? colourHexOf(inherited, undefined);\n  return (\n    <Popover\n      open={open}\n      onOpenChange={next => {\n        setOpen(next);\n        if (next) {\n          setCustom(customFirst);\n          return;\n        }\n        const own = superseded.current;\n        superseded.current = false;\n        onClosed(own ? \"superseded\" : \"committed\");\n      }}\n    >\n      <PickerTrigger\n        painted={painted}\n        inherited={shown === undefined && inherited !== undefined}\n        reference={reference}\n        referenceLabel={referenceLabel}\n        referenceTip={referenceTip}\n        actionName={actionName}\n        described={described}\n        invalid={invalid}\n      />\n      <PopoverContent\n        align=\"end\"\n        className=\"nx-style-inspector__picker\"\n        // Off here as well as on the tab: the picker is drawn outside the tab,\n        // so its hex field does not inherit the tab's setting, and a colour\n        // code is no more a word than a length is.\n        spellCheck={false}\n        // The list takes focus itself, on its search or on its entries; with\n        // no list, the first control, Custom colour, takes it as usual.\n        onOpenAutoFocus={event => {\n          if (choices.length > 0) event.preventDefault();\n        }}\n        /*\n         * A PRESS, not any dismissal whose target happens to be such a control.\n         *\n         * `onInteractOutside` also fires when focus merely LEAVES the popover —\n         * a keyboard author tabbing out lands on the Reset beside this control\n         * and dismisses it without activating anything. Read there, the gesture\n         * they were composing is discarded by a button they never pressed, and\n         * tabbing onward loses it silently.\n         *\n         * The question is not which cause dismissed the popover but whether a\n         * control is about to WRITE, and only a pointer press implies that: the\n         * press is followed by the click that runs the handler. Focus is not,\n         * so a focus dismissal falls through to the ordinary close and the\n         * gesture is committed — which is what leaving a control does\n         * everywhere else in this panel, the text fields included.\n         */\n        onPointerDownOutside={event => {\n          // Only a press that can RUN the control supersedes. See `activates`.\n          superseded.current =\n            activates(event.detail.originalEvent) && supersededBy(event.target);\n        }}\n      >\n        <ColourVariables\n          choices={choices}\n          read={tokensRead}\n          current={reference}\n          onPick={identity => {\n            // One discrete choice, committed at once; the close that follows\n            // has nothing left to write.\n            onChoose({ $token: identity });\n            setOpen(false);\n          }}\n        />\n        <RecentColourChoices\n          onPick={onChoose}\n          // One discrete choice, as a variable is: the picker closes.\n          onPicked={setOpen}\n        />\n        <CustomColour\n          open={custom}\n          onToggle={() => setCustom(was => !was)}\n          // What the swatch paints, an inherited colour included, so a small\n          // adjustment starts from what the author sees.\n          shown={painted}\n          unrepresented={unrepresented}\n          onColour={onColour}\n        />\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/**\n * After a commit the document did not need, the field goes back to what it\n * holds: a picker gesture or a choice that ends where it began leaves no\n * draft behind for a later blur to write.\n */\nfunction settle(outcome: CommitOutcome, reset: () => void): void {\n  if (outcome === \"unchanged\") reset();\n}\n\n/**\n * The contrast a colour field reports for what it shows, withheld while\n * another property comes between the pair, and the ids that describe the\n * field: its own, with the contrast note's while there is one.\n */\nfunction contrastReading({\n  leaf,\n  showing,\n  pairedColour,\n  tokens,\n  mode,\n  obscuredBy,\n  describedBy,\n  noteId,\n}: {\n  leaf: StyleControl[\"leaf\"];\n  showing: StyleValue | undefined;\n  pairedColour: StyleValue | undefined;\n  tokens: SiteTokenSet | undefined;\n  mode: TokenMode;\n  obscuredBy: string | undefined;\n  describedBy: string | undefined;\n  noteId: string;\n}): {\n  contrast: ReturnType<typeof contrastAtLeaf> | undefined;\n  describes: ReturnType<typeof describedByAll>;\n} {\n  const contrast =\n    obscuredBy === undefined\n      ? contrastAtLeaf(leaf, showing, pairedColour, tokens, mode)\n      : undefined;\n  return {\n    contrast,\n    describes: describedByAll(\n      describedBy,\n      contrast === undefined ? undefined : noteId\n    ),\n  };\n}\n\n/** The write a field types live through: its own, or else its commit. */\nfunction typedOrCommitted(\n  onType: ((value: StyleValue | null) => CommitOutcome) | undefined,\n  onCommit: (value: StyleValue | null) => CommitOutcome\n): (value: StyleValue | null) => CommitOutcome {\n  return onType ?? onCommit;\n}\n\n/**\n * What a picker gesture writes, and when: each move shown in the field and,\n * where the panel writes as it is typed, written to the document at most\n * once a frame (`live-gesture.ts`); the colour it ends on written in the same\n * run when the picker closes, and remembered among Recent colours then; and\n * a control writing this field itself putting back what the moves wrote.\n */\nfunction usePickerWrites({\n  commitColour,\n  onMove,\n  reset,\n  setDraft,\n}: {\n  commitColour: (value: StyleValue | null) => CommitOutcome;\n  /** A move's write, where the panel writes as it is typed. */\n  onMove: (value: StyleValue | null) => CommitOutcome;\n  reset: () => void;\n  setDraft: (value: string) => void;\n}): {\n  commitInstead: (value: StyleValue | null) => void;\n  closed: (outcome: PickerClose) => void;\n  onColour: (value: string) => void;\n} {\n  // Where the panel writes as it is typed, a picker gesture writes as it\n  // moves too, at most once a frame, the whole gesture one undo step.\n  const typesLive = useTypesLive();\n  const gesture = useLiveGesture();\n  // What the picker composed, written once the gesture is over. Compared\n  // against the stored text so closing a picker nobody moved writes nothing.\n  // What the picker has produced and not yet written. Held in a ref as well as\n  // in state because the unmount flush below reads it from a cleanup that runs\n  // once, where the closed-over `draft` would be the value at first render.\n  const pending = React.useRef<string | null>(null);\n  /*\n   * A discrete choice, which SUPERSEDES anything the picker was mid-way through.\n   *\n   * Dropping the pending value is the whole of it. Pressing this control also\n   * dismisses the picker, and the close reads `pending.current` to decide what\n   * the gesture produced — so clearing it first leaves that close with nothing\n   * to write, and the discrete choice is the only edit. One rule expressed\n   * once: a second expression of it is what drifts. A recent colour is one\n   * such choice, and joins the front of Recent colours again; a variable or\n   * a clear is no colour of its own and is not remembered.\n   */\n  const commitInstead = (value: StyleValue | null): void => {\n    pending.current = null;\n    // In the gesture's run, so the moves before it and the choice are one\n    // step.\n    gesture.end(() => settle(commitColour(value), reset));\n  };\n  /*\n   * The picker closed, whichever outcome that close had.\n   *\n   * ONE handler for both, because the two differ only in whether the gesture is\n   * written — the pending value is dropped either way. Expressed as two\n   * handlers, the supersede path is the one that silently does nothing: it\n   * would leave the draft queued, and the unmount flush below would write it\n   * back OVER the edit that superseded it, as a later op with no gesture behind\n   * it.\n   *\n   * Synchronous, because an author can leave the editor entirely in the same\n   * interaction that dismisses this popover: the page builder hands the current\n   * document to its host form and unmounts, and a write scheduled for after\n   * that lands on an editor nobody is reading any more. The gesture is simply\n   * gone from the document handed over.\n   *\n   * Which is why the supersede below is decided by WHERE the interaction went\n   * rather than by giving a later handler time to cancel a scheduled write. A\n   * timer bought that cancellation and paid for it with this race.\n   */\n  const closed = (outcome: PickerClose): void => {\n    const unwritten = pending.current;\n    pending.current = null;\n    // A control writing this field itself takes over: what the moves wrote\n    // goes back, so its write is the only edit.\n    if (outcome === \"superseded\") {\n      gesture.cancel();\n      return;\n    }\n    if (unwritten === null) {\n      gesture.end();\n      return;\n    }\n    // Written in the run the moves wrote in, and remembered once, here.\n    gesture.end(() => settle(commitColour(unwritten), reset));\n  };\n  // The current writer, held so the teardown below depends on nothing. A\n  // teardown listing `onCommit` would re-run its cleanup on every render that\n  // gives the field a new callback — which is every render — and flush a\n  // gesture the author is still making.\n  const write = React.useRef(commitColour);\n  // The gesture as it is now, for the same teardown.\n  const finishing = React.useRef(gesture);\n  React.useEffect(() => {\n    write.current = commitColour;\n    finishing.current = gesture;\n  });\n  /*\n   * Write an unfinished gesture when this field goes away, and do it NOW.\n   *\n   * Two ways to leave without closing the popover: selecting another block in\n   * the canvas iframe cannot reach the outside-dismiss handler, and the\n   * selection change remounts this field without firing `onOpenChange`. A\n   * scheduled write would not survive either, so the timer is cancelled and the\n   * value written synchronously rather than left to a callback whose component\n   * has gone.\n   */\n  React.useEffect(\n    () => () => {\n      const unwritten = pending.current;\n      pending.current = null;\n      // The outcome is DROPPED, and that is the honest limit rather than an\n      // oversight. A refusal here — a document at its byte limit, say — is\n      // reported through state belonging to a component that is going away, so\n      // there is nobody left to show it to and nowhere to keep the value: the\n      // ref does not survive the remount either. Writing when the document\n      // accepts strictly improves on not writing at all, and cannot improve the\n      // case where it does not.\n      //\n      // Closing it properly means the pending edit living somewhere that\n      // outlives one field, which is the same thing undo and the unsaved-work\n      // guard need and is tracked with them.\n      // In the gesture's run, as a close writes it, so the moves already\n      // written and this last one are one step of undo. The gesture's own\n      // teardown, which runs first, drops the frame but keeps the run.\n      if (unwritten !== null) {\n        const finish = write.current;\n        finishing.current.end(() => finish(unwritten));\n      }\n    },\n    []\n  );\n  const onColour = (value: string): void => {\n    pending.current = value;\n    setDraft(value);\n    // Not remembered among Recent colours until the gesture ends.\n    if (typesLive) gesture.move(() => onMove(value));\n  };\n  return { commitInstead, closed, onColour };\n}\n\n/**\n * A field's commit that also remembers the raw colour it wrote, or chose\n * again, among the author's Recent colours; a refused value is not one, nor\n * a variable or a clear.\n */\nfunction rememberingCommit(\n  onCommit: (value: StyleValue | null) => CommitOutcome,\n  store: PreferenceStore | undefined\n): (value: StyleValue | null) => CommitOutcome {\n  return value => {\n    const outcome = onCommit(value);\n    if (outcome !== \"refused\") rememberColour(store, value);\n    return outcome;\n  };\n}\n\n/**\n * Recent colours, between the variables and Custom colour: the last colours\n * this author typed or picked, each a swatch named by its value. Shown while\n * there are none too, saying what will appear, so the place is known.\n */\nfunction RecentColourChoices({\n  onPick,\n  onPicked,\n}: {\n  onPick: (colour: string) => void;\n  /** Called with `false` once a colour is picked, to close the picker. */\n  onPicked: (open: false) => void;\n}): React.JSX.Element {\n  const headingId = React.useId();\n  const [colours] = useRecentColours();\n  return (\n    <div\n      className=\"nx-style-inspector__recent\"\n      role=\"group\"\n      aria-labelledby={headingId}\n    >\n      <p className=\"nx-style-inspector__recent-heading\" id={headingId}>\n        Recent colours\n      </p>\n      {colours.length === 0 ? (\n        <p className=\"nx-vars__note nx-style-inspector__recent-none\">\n          Colours you type or pick show here.\n        </p>\n      ) : (\n        <div className=\"nx-style-inspector__recent-list\">\n          {colours.map(colour => (\n            <button\n              key={colour}\n              type=\"button\"\n              className=\"nx-style-inspector__swatch\"\n              aria-label={colour}\n              title={colour}\n              // A colour written as a value paints the same anywhere, so it\n              // is painted as it is listed; no variable is ever listed here.\n              style={{ \"--nx-swatch\": colour } as React.CSSProperties}\n              onClick={() => {\n                onPick(colour);\n                onPicked(false);\n              }}\n            />\n          ))}\n        </div>\n      )}\n    </div>\n  );\n}\n\n/**\n * Whether a stored colour is written as a value rather than as a variable: the\n * picker then opens with the controls that made it showing, under the\n * variables. Nothing stored, or a variable, opens on the variables alone.\n */\nfunction writtenAsValue(stored: StyleValue | undefined): boolean {\n  return stored !== undefined && !isTokenRef(stored);\n}\n\n/**\n * What opens the picker: for a value or none, the swatch beside the field\n * holding it; for a variable, the variable itself, its swatch and its name, as\n * the control an author opens to choose another.\n *\n * Handed the popover's own trigger props, which it spreads on the button.\n */\nfunction ColourTrigger({\n  shown,\n  reference,\n  referenceLabel,\n  actionName,\n  ...trigger\n}: React.ComponentProps<\"button\"> & {\n  shown: string | undefined;\n  reference: string | null;\n  referenceLabel: string;\n  actionName: string;\n}): React.JSX.Element {\n  const paint = {\n    // Painted through a custom property rather than `background-color`\n    // directly, so the chequerboard beneath a translucent colour stays visible\n    // through it. `undefined` leaves the class's own \"nothing here\" appearance\n    // rather than a colour this cannot vouch for.\n    style:\n      shown === undefined\n        ? undefined\n        : ({ \"--nx-swatch\": shown } as React.CSSProperties),\n    \"data-empty\": shown === undefined ? \"\" : undefined,\n  };\n  if (reference === null) {\n    return (\n      <button\n        {...trigger}\n        type=\"button\"\n        className=\"nx-style-inspector__swatch\"\n        aria-label={`Colour for ${actionName}`}\n        {...paint}\n      />\n    );\n  }\n  return (\n    <button\n      {...trigger}\n      type=\"button\"\n      className=\"nx-font-pick__trigger nx-style-inspector__colour-pick\"\n      aria-label={`Colour for ${actionName}: ${referenceLabel}`}\n      // Green, as every value that comes from a variable is.\n      data-bound=\"\"\n      {...paint}\n    >\n      <span className=\"nx-vars__swatch\" aria-hidden=\"true\" />\n      <span className=\"nx-font-pick__value\">{referenceLabel}</span>\n      <ChevronDown aria-hidden=\"true\" size={14} />\n    </button>\n  );\n}\n\n/**\n * The picker's trigger, with what a held variable is in its tooltip: see\n * {@link ColourTrigger} for what it draws.\n */\nfunction PickerTrigger({\n  painted,\n  inherited,\n  reference,\n  referenceLabel,\n  referenceTip,\n  actionName,\n  described,\n  invalid,\n}: {\n  painted: string | undefined;\n  /** Whether the colour painted reaches here from another tier. */\n  inherited: boolean;\n  reference: string | null;\n  referenceLabel: string;\n  referenceTip: string | undefined;\n  actionName: string;\n  described: string | undefined;\n  invalid: boolean;\n}): React.JSX.Element {\n  return (\n    <VariableTipped tip={referenceTip}>\n      <PopoverTrigger asChild>\n        <ColourTrigger\n          shown={painted}\n          data-inherited={inherited ? \"\" : undefined}\n          reference={reference}\n          referenceLabel={referenceLabel}\n          actionName={actionName}\n          aria-describedby={described}\n          aria-invalid={invalid ? true : undefined}\n        />\n      </PopoverTrigger>\n    </VariableTipped>\n  );\n}\n\n/**\n * Custom colour, at the end of the picker: a button that opens the raw\n * picker in place, for the exception a variable does not cover.\n */\nfunction CustomColour({\n  open,\n  onToggle,\n  shown,\n  unrepresented,\n  onColour,\n}: {\n  open: boolean;\n  onToggle: () => void;\n  /** The resolved colour, or `undefined` when nothing here can resolve one. */\n  shown: string | undefined;\n  /** Whether the stored value is one the picker cannot show. */\n  unrepresented: boolean;\n  onColour: (hex: string) => void;\n}): React.JSX.Element {\n  const regionId = React.useId();\n  return (\n    <div className=\"nx-style-inspector__custom\">\n      <button\n        type=\"button\"\n        className=\"nx-style-inspector__custom-toggle\"\n        aria-expanded={open}\n        aria-controls={regionId}\n        onClick={onToggle}\n      >\n        <span>Custom colour</span>\n        <ChevronDown aria-hidden=\"true\" size={14} />\n      </button>\n      {open ? (\n        <div className=\"nx-style-inspector__custom-body\" id={regionId}>\n          {unrepresented ? (\n            <p className=\"nx-inspector__note\">\n              This value cannot be shown on the picker. Choosing here replaces\n              it.\n            </p>\n          ) : null}\n          <ColorPicker\n            // A fallback only where nothing could be resolved, and it is\n            // never WRITTEN by being shown: the picker reports a colour only\n            // once the author moves something, so opening it over a value it\n            // cannot represent changes nothing.\n            color={shown ?? PICKER_FALLBACK}\n            showAlpha\n            onColorChange={onColour}\n          />\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\n/** One colour variable as the picker lists it. */\ninterface ColourChoice {\n  readonly key: string;\n  readonly label: string;\n  readonly token: SiteVariable;\n}\n\n/**\n * The site's colour variables, by name, each with its swatch and its light\n * and dark pair; or, for a site with none, a line saying so.\n */\nfunction ColourVariables({\n  choices,\n  read,\n  current,\n  onPick,\n}: {\n  choices: readonly SiteVariable[];\n  /** Whether the site's variables have arrived. */\n  read: boolean;\n  /** The identity the value refers to, marked in the list. */\n  current: string | null;\n  onPick: (identity: string) => void;\n}): React.JSX.Element {\n  if (!read) {\n    // Not yet arrived is not the same as none: saying \"no variables\" while\n    // the site's style is still on its way would be wrong for a moment.\n    return (\n      <p\n        className=\"nx-vars__note nx-style-inspector__no-variables\"\n        role=\"status\"\n      >\n        Reading this site&rsquo;s colour variables&hellip;\n      </p>\n    );\n  }\n  if (choices.length === 0) {\n    return (\n      <p className=\"nx-vars__note nx-style-inspector__no-variables\">\n        This site has no colour variables yet.\n      </p>\n    );\n  }\n  const listed: ColourChoice[] = choices.map(token => ({\n    // The IDENTITY as the key, which is what keeps the list stable across a\n    // rename: a key built from the label would remount every renamed\n    // variable's row, and would collide between a renamed variable and a new\n    // one that took its old name.\n    key: token.identity,\n    // Qualified with the identity only where another listed variable shares\n    // this name: two under one name with equal colours are otherwise\n    // indistinguishable, and choosing either stores an identity the author\n    // could not have predicted.\n    label: variableLabel(token, choices),\n    token,\n  }));\n  return (\n    <div className=\"nx-style-inspector__variables\">\n      <ChoiceList\n        choices={listed}\n        currentKey={current ?? undefined}\n        onPick={choice => onPick(choice.token.identity)}\n        label=\"Colour variables\"\n        searchLabel=\"Search colour variables\"\n        noMatch=\"No colour variables match this search.\"\n        choiceClassName=\"nx-style-inspector__variable\"\n        renderChoice={choice => (\n          <>\n            <span\n              className=\"nx-vars__swatch nx-vars__swatch--main\"\n              aria-hidden=\"true\"\n              // The RESOLVED colour in the mode the canvas shows, never the\n              // raw value: `var(--brand)` or `currentcolor` painted here would\n              // resolve against the inspector rather than the canvas.\n              style={swatchStyle(choice.token.swatch)}\n            />\n            <span className=\"nx-style-inspector__variable-name\">\n              {choice.label}\n            </span>\n            <ColourPair {...choice.token.pair} />\n          </>\n        )}\n      />\n    </div>\n  );\n}\n\n/**\n * What a STORED reference is called, for the row that displays it.\n *\n * Three answers to one question, which is why it is asked in one place: a\n * reference the site still defines reads as that token's current name; one\n * whose name another offered token shares is qualified with its identity, so\n * the two rows cannot be confused; and one the site no longer defines at all\n * reads as the raw identity the document holds. That last case is a warning\n * rather than an error — the value goes on compiling — so showing the stored\n * string is more use than showing an empty space.\n *\n * Separate from {@link variableLabel} because that one answers about a token\n * in hand, and this one has to find the token first, or account for there being\n * none.\n */\nfunction storedTokenLabel(\n  reference: string | null,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode,\n  among: readonly SiteVariable[]\n): string {\n  if (reference === null) return \"\";\n  const token = variableFor(reference, tokens, mode);\n  return token === undefined ? reference : variableLabel(token, among);\n}\n\n/** The variable a reference holds, or `undefined` for none or one the site lacks. */\nfunction heldVariable(\n  reference: string | null,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): SiteVariable | undefined {\n  return reference === null ? undefined : variableFor(reference, tokens, mode);\n}\n\n/** What a held colour variable is, for its trigger's tooltip; none for none. */\nfunction heldTip(\n  held: SiteVariable | undefined,\n  label: string,\n  tokens: SiteTokenSet | undefined\n): string | undefined {\n  return held === undefined ? undefined : variableTip(held, label, tokens);\n}\n\n/**\n * Unlink beside a held colour variable: the colour it gives in the mode the\n * canvas shows, kept as a plain value in one commit. Nothing for a variable\n * the site no longer has, which has no colour to keep; the row's Reset\n * removes it.\n */\nfunction ColourUnlink({\n  held,\n  fieldId,\n  actionName,\n  onUnlink,\n}: {\n  held: SiteVariable | undefined;\n  /** The field whose value this press writes. See {@link commitsFor}. */\n  fieldId: string;\n  actionName: string;\n  onUnlink: (value: StyleValue) => void;\n}): React.JSX.Element | null {\n  if (held === undefined) return null;\n  return (\n    <UnlinkButton\n      /*\n       * This press writes this field's value: it commits the colour, and the\n       * picker must not also write the draft its dismissal would otherwise\n       * flush. Declared rather than handed up as a ref, so any control making\n       * the same promise says so the same way.\n       */\n      {...commitsFor(fieldId)}\n      label={actionName}\n      onUnlink={() => onUnlink(held.value)}\n    />\n  );\n}\n\n/**\n * How a colour pair fares, or nothing at all.\n *\n * `undefined` renders NOTHING rather than a placeholder, an approximation or a\n * last-known figure. That is the engine's own reasoning carried up one level:\n * a ratio computed from a colour that was misread \"is worse than no figure,\n * because it is a number somebody will act on\", and there is no honest estimate\n * of the contrast against a `var()` whose value the page decides at render.\n *\n * A failing pair is a WARNING and never a refusal — the value is valid, stored\n * and compiling, and the author may have a reason. The same position\n * Gutenberg's contrast checker takes.\n */\n/**\n * The note beside a colour written as a value rather than through a variable.\n *\n * Such a colour keeps its one value when the visitor's device prefers dark,\n * where a variable carries both. Read from what is stored, so a picker gesture\n * still in progress does not make it flicker.\n */\nfunction RawColourNote({\n  stored,\n}: {\n  stored: StyleValue | undefined;\n}): React.JSX.Element | null {\n  if (!isRawColour(stored)) return null;\n  return (\n    <p className=\"nx-inspector__note\">\n      Not adapted to dark mode. Choose a variable to follow light and dark.\n    </p>\n  );\n}\n\nfunction ContrastNote({\n  id,\n  contrast,\n}: {\n  id: string;\n  contrast: ContrastResult | undefined;\n}): React.JSX.Element {\n  return (\n    <p\n      className=\"nx-style-inspector__contrast\"\n      id={id}\n      // Announced as it changes, because the verdict moves while focus is\n      // INSIDE the picker — on the saturation square, the hue strip, the alpha\n      // strip or the hex field — and none of those controls is described by\n      // this note. `aria-describedby` is read when a control receives focus, so\n      // a figure that changes during the interaction is never spoken. Polite\n      // rather than assertive: it coalesces while a drag is moving and speaks\n      // once the author pauses, which is when the number is wanted.\n      aria-live=\"polite\"\n      // Mounted even with nothing to say. A live region announces CHANGES to\n      // its contents, so one that arrives with its text already in place is not\n      // a change and is silent — the state this note is in every time a colour\n      // first becomes measurable. Empty it occupies no space; `:empty` drops\n      // the margin rather than the box, because `display: none` would take it\n      // out of the accessibility tree and stop it announcing at all.\n      {...(contrast === undefined ? {} : { \"data-level\": contrast.level })}\n    >\n      {contrast === undefined\n        ? \"\"\n        : `Contrast ${contrastRatioText(contrast)} — ${\n            contrast.passesBodyText\n              ? `passes AA for body text (${contrast.level})`\n              : \"below AA for body text\"\n          }`}\n    </p>\n  );\n}\n","\"use client\";\n\n/**\n * An aspect ratio, chosen from the ratios an author reaches for, or given as a\n * width and a height.\n *\n * The catalog stores `aspect-ratio` as free CSS, so typing \"16 / 9\" was the\n * only way to set one, and a slip was a value the browser drops. The menu\n * offers the common ratios by name, and Custom asks for the two numbers. What\n * it writes is the CSS ratio (`16 / 9`). A stored value it cannot draw, such\n * as `auto 4 / 3`, is left to the text field, so nothing the CSS can say\n * becomes unreachable.\n *\n * @module aspect-ratio-field\n */\n\nimport { trimCssWhitespace, type StyleValue } from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectSeparator,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\n// Enter commits without submitting the entry form the builder sits in.\nimport { CSS_NUMBER } from \"../../styles/style-numeric\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport { useFieldDescription } from \"../css-hint\";\n\nimport { InheritedValue } from \"./inherited-value\";\n\ntype CommitOutcome = \"applied\" | \"refused\" | \"unchanged\";\n\n/** The ratios offered by name, common first, each as the CSS it writes. */\nconst PRESETS: readonly { value: string; label: string }[] = [\n  { value: \"auto\", label: \"Auto\" },\n  { value: \"1 / 1\", label: \"Square 1:1\" },\n  { value: \"4 / 3\", label: \"4:3\" },\n  { value: \"3 / 2\", label: \"3:2\" },\n  { value: \"16 / 9\", label: \"16:9\" },\n  { value: \"21 / 9\", label: \"21:9\" },\n  { value: \"3 / 4\", label: \"Portrait 3:4\" },\n  { value: \"9 / 16\", label: \"Portrait 9:16\" },\n];\n\n/** The menu's value for a custom ratio, apart from every CSS ratio. */\nconst CUSTOM = \"custom\";\n\n/** The menu's value for a ratio written as CSS, for one it has no words for. */\nconst AS_CSS = \"css\";\n\n/** A positive number as CSS reads one, or `undefined`: never `0x10` or `Infinity`. */\nfunction cssNumber(text: string): number | undefined {\n  const trimmed = trimCssWhitespace(text);\n  if (!CSS_NUMBER.test(trimmed)) return undefined;\n  const number = Number(trimmed);\n  return number > 0 && Number.isFinite(number) ? number : undefined;\n}\n\n/** What a ratio is called in the menu: its preset's name, or `5:4`. */\nfunction choiceLabel(choice: AspectRatioChoice): string {\n  if (choice.kind === \"custom\") return `${choice.width}:${choice.height}`;\n  return PRESETS.find(preset => preset.value === choice.value)?.label ?? \"\";\n}\n\n/** A positive number as CSS writes one, and no more of the text. */\nconst NUMBER = String.raw`(\\d+(?:\\.\\d+)?|\\.\\d+)`;\nconst RATIO = new RegExp(\n  String.raw`^[ \\t\\n\\r\\f]*${NUMBER}(?:[ \\t\\n\\r\\f]*/[ \\t\\n\\r\\f]*${NUMBER})?[ \\t\\n\\r\\f]*$`\n);\n\n/** What a stored ratio is, as the field can draw it. */\nexport type AspectRatioChoice =\n  | { readonly kind: \"preset\"; readonly value: string }\n  | {\n      readonly kind: \"custom\";\n      readonly width: number;\n      readonly height: number;\n    };\n\n/**\n * A stored aspect ratio as the field draws it: the preset it is, however it\n * is spaced; another simple ratio as a custom width and height; or\n * `undefined` for a value this field cannot draw, which the text field keeps.\n */\nexport function aspectRatioChoice(\n  stored: string\n): AspectRatioChoice | undefined {\n  if (/^[ \\t\\n\\r\\f]*auto[ \\t\\n\\r\\f]*$/i.test(stored)) {\n    return { kind: \"preset\", value: \"auto\" };\n  }\n  const match = RATIO.exec(stored);\n  if (match === null) return undefined;\n  const width = Number(match[1]);\n  // A ratio given as one number is that number over 1.\n  const height = match[2] === undefined ? 1 : Number(match[2]);\n  if (!(width > 0 && height > 0)) return undefined;\n  const preset = PRESETS.find(candidate => {\n    const [w, h] = candidate.value.split(\" / \").map(Number);\n    return w !== undefined && h !== undefined && width * h === height * w;\n  });\n  return preset === undefined\n    ? { kind: \"custom\", width, height }\n    : { kind: \"preset\", value: preset.value };\n}\n\n/** Whether the field can draw a stored value; else the text field keeps it. */\nexport function drawsAspectRatio(stored: StyleValue | undefined): boolean {\n  return (\n    stored === undefined ||\n    (typeof stored === \"string\" && aspectRatioChoice(stored) !== undefined)\n  );\n}\n\n/** Which part of the field is open: the menu alone, a custom ratio, or CSS. */\ntype RatioMode = \"menu\" | \"custom\" | \"css\";\n\n/**\n * What the menu shows: the stored ratio as the field draws it, whether the\n * custom numbers are open, and the menu's value.\n */\nfunction ratioMenu(\n  stored: StyleValue | undefined,\n  mode: RatioMode\n): {\n  choice: AspectRatioChoice | undefined;\n  custom: boolean;\n  value: string;\n} {\n  const choice =\n    typeof stored === \"string\" ? aspectRatioChoice(stored) : undefined;\n  const custom = choice?.kind === \"custom\" || mode === \"custom\";\n  const preset = choice?.kind === \"preset\" ? choice.value : \"\";\n  const value = mode === \"css\" ? AS_CSS : custom ? CUSTOM : preset;\n  return { choice, custom, value };\n}\n\n/**\n * The ratio reaching this block from another tier, shown where Not set would\n * while nothing is stored here: by its name, or as written where the menu\n * has no words for it (`auto 4 / 3`).\n */\nfunction inheritedLabel(\n  stored: StyleValue | undefined,\n  inherited: string | undefined\n): string | undefined {\n  if (stored !== undefined || inherited === undefined) return undefined;\n  const choice = aspectRatioChoice(inherited);\n  return choice === undefined ? inherited : choiceLabel(choice);\n}\n\nexport function AspectRatioField({\n  id,\n  labelledBy,\n  stored,\n  actionName,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  labelledBy: string;\n  stored: StyleValue | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const inherited = inheritedLabel(stored, React.useContext(InheritedValue));\n  // Custom and CSS are chosen before anything is typed, so each is the\n  // field's own state until a ratio is stored; a stored change (one written\n  // here, an undo, a shared style's update) closes it, so a stale draft is\n  // never left open over the value that replaced it.\n  const [mode, setMode] = React.useState<RatioMode>(\"menu\");\n  React.useEffect(() => {\n    setMode(\"menu\");\n  }, [stored]);\n  const { choice, custom, value } = ratioMenu(stored, mode);\n  const invalid = describedBy === undefined ? undefined : true;\n  return (\n    <div className=\"nx-style-inspector__ratio\">\n      <Select\n        value={value}\n        onValueChange={next => {\n          if (next === CUSTOM || next === AS_CSS) {\n            setMode(next === CUSTOM ? \"custom\" : \"css\");\n            return;\n          }\n          setMode(\"menu\");\n          onCommit(next);\n        }}\n      >\n        <SelectTrigger\n          id={id}\n          aria-labelledby={labelledBy}\n          aria-describedby={described}\n          aria-invalid={invalid}\n          {...(value === \"\" && inherited !== undefined\n            ? { \"data-inherited\": \"\" }\n            : {})}\n        >\n          <SelectValue placeholder={inherited ?? \"Not set\"} />\n        </SelectTrigger>\n        <SelectContent>\n          {PRESETS.map(preset => (\n            <SelectItem key={preset.value} value={preset.value}>\n              {preset.label}\n            </SelectItem>\n          ))}\n          <SelectSeparator />\n          <SelectItem value={CUSTOM}>Custom…</SelectItem>\n          <SelectItem value={AS_CSS}>Write as CSS…</SelectItem>\n        </SelectContent>\n      </Select>\n      {mode === \"css\" ? (\n        <CssRatio\n          actionName={actionName}\n          describedBy={describedBy}\n          onCommit={onCommit}\n        />\n      ) : custom ? (\n        <CustomRatio\n          actionName={actionName}\n          stored={choice?.kind === \"custom\" ? choice : undefined}\n          describedBy={describedBy}\n          onCommit={onCommit}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * A ratio written as CSS, for one the menu has no words for (`auto 4 / 3`),\n * written once the author leaves the field; the engine judges it.\n */\nfunction CssRatio({\n  actionName,\n  describedBy,\n  onCommit,\n}: {\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const [text, setText] = React.useState(\"\");\n  const commit = () => {\n    if (trimCssWhitespace(text) !== \"\") onCommit(text);\n  };\n  return (\n    <Input\n      aria-label={`${actionName} as CSS`}\n      aria-describedby={described}\n      aria-invalid={describedBy === undefined ? undefined : true}\n      value={text}\n      onChange={event => setText(event.target.value)}\n      onBlur={commit}\n      onKeyDown={event => commitOnEnter(event, commit)}\n    />\n  );\n}\n\n/**\n * A custom ratio's width and height, written as one ratio once both are\n * positive numbers and the author leaves either field.\n */\nfunction CustomRatio({\n  actionName,\n  stored,\n  describedBy,\n  onCommit,\n}: {\n  actionName: string;\n  stored: { width: number; height: number } | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const [width, setWidth] = React.useState(\n    stored === undefined ? \"\" : String(stored.width)\n  );\n  const [height, setHeight] = React.useState(\n    stored === undefined ? \"\" : String(stored.height)\n  );\n  // A stored change (an undo, a shared style's update) moves the numbers\n  // with it, so blurring the field never writes back the ratio it replaced.\n  const storedWidth = stored?.width;\n  const storedHeight = stored?.height;\n  React.useEffect(() => {\n    if (storedWidth === undefined || storedHeight === undefined) return;\n    setWidth(String(storedWidth));\n    setHeight(String(storedHeight));\n  }, [storedWidth, storedHeight]);\n  const commit = () => {\n    const w = cssNumber(width);\n    const h = cssNumber(height);\n    if (w === undefined || h === undefined) return;\n    if (stored !== undefined && stored.width === w && stored.height === h) {\n      return;\n    }\n    onCommit(`${w} / ${h}`);\n  };\n  // A refusal said for the field is said for both numbers, either of which\n  // may hold the focus when it arrives.\n  const refusal = {\n    \"aria-describedby\": described,\n    \"aria-invalid\": describedBy === undefined ? undefined : true,\n  } as const;\n  return (\n    <div className=\"nx-style-inspector__ratio-custom\">\n      <Input\n        aria-label={`${actionName} width`}\n        inputMode=\"decimal\"\n        {...refusal}\n        value={width}\n        onChange={event => setWidth(event.target.value)}\n        onBlur={commit}\n        onKeyDown={event => commitOnEnter(event, commit)}\n      />\n      <span aria-hidden=\"true\">:</span>\n      <Input\n        aria-label={`${actionName} height`}\n        inputMode=\"decimal\"\n        {...refusal}\n        value={height}\n        onChange={event => setHeight(event.target.value)}\n        onBlur={commit}\n        onKeyDown={event => commitOnEnter(event, commit)}\n      />\n    </div>\n  );\n}\n","/**\n * What the Background section's size choices write, and how a stored size\n * reads back to one of them.\n *\n * Each choice writes `background-size` and `background-repeat` together: CSS\n * repeats a background image by default, so \"Fit\" (`contain`) would tile the\n * image unless the same choice also stops it repeating. Where the image sits\n * is the nine-point position picker's, which the object position already uses.\n *\n * @module background-placement\n */\nimport { trimCssWhitespace, type StyleValue } from \"@nextlyhq/blocks-engine\";\n\n/** One size choice: its button's words and what it writes. */\nexport interface BackgroundSizeChoice {\n  readonly label: \"Cover\" | \"Fit\" | \"Tile\";\n  /** Written to `background-size`. */\n  readonly size: string;\n  /** Written to `background-repeat` with it. */\n  readonly repeat: string;\n  /** What it does to the picture, in words, under the buttons. */\n  readonly summary: string;\n}\n\n/** The three choices, in the order the buttons show them. */\nexport const BACKGROUND_SIZE_CHOICES: readonly BackgroundSizeChoice[] = [\n  // Fills the block, cropping the image; one copy, so no repeat.\n  {\n    label: \"Cover\",\n    size: \"cover\",\n    repeat: \"no-repeat\",\n    summary: \"Fills the block; edges may be cropped\",\n  },\n  // The whole image inside the block, once.\n  {\n    label: \"Fit\",\n    size: \"contain\",\n    repeat: \"no-repeat\",\n    summary: \"The whole image shows, once\",\n  },\n  // The image at its own size, repeated across the block.\n  {\n    label: \"Tile\",\n    size: \"auto\",\n    repeat: \"repeat\",\n    summary: \"At its own size, repeated\",\n  },\n];\n\n/**\n * The choice a stored `background-size` is, `\"custom\"` for any other value\n * (`50%`, a variable, two sizes), or `undefined` when none is stored. Read\n * from the size alone, so a size written elsewhere reads the same whatever\n * repeat sits beside it.\n */\nexport function backgroundSizeChoiceOf(\n  stored: StyleValue | undefined\n): BackgroundSizeChoice | \"custom\" | undefined {\n  if (stored === undefined) return undefined;\n  if (typeof stored !== \"string\") return \"custom\";\n  const size = trimCssWhitespace(stored).toLowerCase();\n  return (\n    BACKGROUND_SIZE_CHOICES.find(choice => choice.size === size) ?? \"custom\"\n  );\n}\n","/**\n * A value written as CSS in a field's own text row, committed as typed.\n *\n * @module raw-css\n */\nimport { trimCssWhitespace } from \"@nextlyhq/blocks-engine\";\n\n/**\n * Commit what was typed into a \"Write as CSS\" row: as typed, with CSS's own\n * whitespace deciding only whether the row is empty.\n *\n * Trimmed, a stored value with whitespace around it read as changed when\n * nothing was, and a no-break space, which is no CSS whitespace, cleared the\n * value rather than being judged as the value it is. Emptied, the row clears\n * a value set here; an empty row over nothing writes nothing.\n */\nexport function commitRawCss<Outcome>(\n  text: string,\n  stored: string | undefined,\n  onCommit: (value: string | null) => Outcome\n): Outcome | undefined {\n  if (text === (stored ?? \"\")) return undefined;\n  if (trimCssWhitespace(text) === \"\") {\n    return stored === undefined ? undefined : onCommit(null);\n  }\n  return onCommit(text);\n}\n","\"use client\";\n\n/**\n * An image's focal point: nine points over its own picture, written as\n * `object-position` keywords, and any other point written as CSS.\n *\n * On Cover the point is the part of the picture kept in view as it is\n * cropped; on Contain or None it is where the picture sits in its box. The\n * points are drawn over the block's own picture, fitted the way the block\n * fits it, so an author aims at what the page shows.\n *\n * @module focal-point-field\n */\n\nimport { trimCssWhitespace, type StyleValue } from \"@nextlyhq/blocks-engine\";\nimport { Input } from \"@nextlyhq/ui\";\nimport { MoreHorizontal } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { radioGroupStep } from \"../../roving-radios\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport { CssHint, OptionWrites, useFieldDescription } from \"../css-hint\";\n\nimport { FocalFrame } from \"./focal-frame\";\nimport { InheritedValue } from \"./inherited-value\";\nimport { commitRawCss } from \"./raw-css\";\n\ntype CommitOutcome = \"applied\" | \"refused\" | \"unchanged\";\n\nconst ACROSS = [\"left\", \"center\", \"right\"] as const;\nconst DOWN = [\"top\", \"center\", \"bottom\"] as const;\n\n/** The nine points, row by row, each with its name and what it writes. */\nconst POINTS: readonly {\n  readonly x: number;\n  readonly y: number;\n  readonly label: string;\n  readonly value: string;\n}[] = DOWN.flatMap((vertical, y) =>\n  ACROSS.map((horizontal, x) => ({\n    x,\n    y,\n    label: pointLabel(horizontal, vertical),\n    // Across, then down, as CSS reads two keywords; the middle as one word.\n    value:\n      horizontal === \"center\" && vertical === \"center\"\n        ? \"center\"\n        : `${horizontal} ${vertical}`,\n  }))\n);\n\nfunction pointLabel(horizontal: string, vertical: string): string {\n  const words = [\n    vertical === \"center\" ? \"\" : vertical,\n    horizontal === \"center\" ? \"\" : horizontal,\n  ].filter(word => word !== \"\");\n  const name = words.length === 0 ? \"center\" : words.join(\" \");\n  return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/** Which axis a position keyword places on, and where along it. */\nconst KEYWORDS: Readonly<\n  Record<string, { axis: \"x\" | \"y\" | \"both\"; at: number }>\n> = {\n  left: { axis: \"x\", at: 0 },\n  right: { axis: \"x\", at: 2 },\n  top: { axis: \"y\", at: 0 },\n  bottom: { axis: \"y\", at: 2 },\n  center: { axis: \"both\", at: 1 },\n};\n\n/**\n * The point a stored position names, in any order CSS allows (`top left`,\n * `left top`, `top`), or `undefined` for one that is not a point of the nine\n * (`30% 70%`, a variable).\n */\nfunction pointOf(stored: string): (typeof POINTS)[number] | undefined {\n  const words = trimCssWhitespace(stored).toLowerCase().split(/\\s+/);\n  if (words.length > 2) return undefined;\n  const placed: { x?: number; y?: number } = {};\n  for (const word of words) {\n    const keyword = KEYWORDS[word];\n    if (keyword === undefined) return undefined;\n    // `center` fills whichever axis the other word leaves.\n    if (keyword.axis === \"both\") continue;\n    if (placed[keyword.axis] !== undefined) return undefined;\n    placed[keyword.axis] = keyword.at;\n  }\n  const x = placed.x ?? 1;\n  const y = placed.y ?? 1;\n  return POINTS.find(point => point.x === x && point.y === y);\n}\n\n/**\n * What the readout says: the point set here by name, an exact one as Custom\n * with the value written, what reaches it from elsewhere, or the default when\n * nothing does.\n */\nfunction readoutOf(\n  chosen: (typeof POINTS)[number] | undefined,\n  text: string | undefined,\n  inheritedPoint: (typeof POINTS)[number] | undefined,\n  inherited: string | undefined,\n  fallback: (typeof POINTS)[number]\n): string {\n  if (chosen !== undefined) return chosen.label;\n  if (text !== undefined) return `Custom: ${text}`;\n  return inheritedPoint?.label ?? inherited ?? `${fallback.label} by default`;\n}\n\n/** The point of the nine a fallback names. */\nfunction pointNamed(fallback: FocalFallback): (typeof POINTS)[number] {\n  return POINTS.find(point => point.value === fallback) ?? POINTS[4];\n}\n\n/**\n * The point CSS places at when nothing is set: the middle for an image's\n * object position, the top left for a background's position.\n */\nexport type FocalFallback = \"center\" | \"left top\";\n\n/** What the point does for a fit: kept in view as it crops, or where it sits. */\nfunction hintFor(fit: string | undefined): string {\n  return fit === \"cover\" ? \"Kept in view\" : \"Where it sits\";\n}\n\n/**\n * The point an arrow moves to: along its axis, by the step every radio group\n * here takes for that key, wrapping at an edge to the opposite one rather\n * than holding the key.\n */\nfunction pointAfter(\n  key: string,\n  from: (typeof POINTS)[number]\n): (typeof POINTS)[number] | undefined {\n  const step = radioGroupStep(key);\n  if (step === null) return undefined;\n  const across = key === \"ArrowLeft\" || key === \"ArrowRight\";\n  const x = across ? (from.x + step + 3) % 3 : from.x;\n  const y = across ? from.y : (from.y + step + 3) % 3;\n  return POINTS.find(point => point.x === x && point.y === y);\n}\n\nexport function FocalPointField({\n  id,\n  labelledBy,\n  stored,\n  actionName,\n  describedBy,\n  onCommit,\n  fallback = \"center\",\n}: {\n  id: string;\n  labelledBy: string;\n  stored: StyleValue | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  /** Where CSS places it when nothing is set; the middle unless said. */\n  fallback?: FocalFallback;\n}): React.JSX.Element {\n  const fallbackPoint = pointNamed(fallback);\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  // What each point writes, from the field it is drawn in: its tooltip.\n  const optionWrites = React.useContext(OptionWrites);\n  const { picture, fit, position } = React.useContext(FocalFrame);\n  const inherited = React.useContext(InheritedValue);\n  const text = typeof stored === \"string\" ? stored : undefined;\n  const chosen = text === undefined ? undefined : pointOf(text);\n  const inheritedPoint =\n    text === undefined && inherited !== undefined\n      ? pointOf(inherited)\n      : undefined;\n  // Where the canvas places it, which resolves a point the inspector cannot;\n  // else the point as stored or inherited.\n  const shownPosition = position ?? text ?? inherited;\n  const [writing, setWriting] = React.useState(false);\n  const grid = React.useRef<HTMLDivElement>(null);\n  // One tab stop: the chosen point, else the one shown, else the middle.\n  const focusable = chosen ?? inheritedPoint ?? fallbackPoint;\n  const invalid = refusedBy(describedBy);\n\n  const choose = (point: (typeof POINTS)[number]) =>\n    onCommit(point === chosen ? null : point.value);\n  const move = (event: React.KeyboardEvent, from: (typeof POINTS)[number]) => {\n    const next = pointAfter(event.key, from);\n    if (next === undefined) return;\n    event.preventDefault();\n    // A radio group's arrows choose as they move, as every radio group does.\n    onCommit(next.value);\n    grid.current\n      ?.querySelector<HTMLElement>(`[data-point=\"${next.value}\"]`)\n      ?.focus();\n  };\n\n  const readout = readoutOf(\n    chosen,\n    text,\n    inheritedPoint,\n    inherited,\n    fallbackPoint\n  );\n\n  return (\n    <div className=\"nx-focal\">\n      <div className=\"nx-focal__frame\">\n        {picture === undefined ? (\n          <span className=\"nx-focal__swatch\" aria-hidden=\"true\" />\n        ) : (\n          <img\n            className=\"nx-focal__picture\"\n            src={picture}\n            alt=\"\"\n            aria-hidden=\"true\"\n            style={{\n              objectFit: (fit ?? \"cover\") as React.CSSProperties[\"objectFit\"],\n              // The point in force, so the preview crops as the page does.\n              ...(shownPosition === undefined\n                ? {}\n                : { objectPosition: shownPosition }),\n            }}\n          />\n        )}\n        <div\n          ref={grid}\n          id={id}\n          role=\"radiogroup\"\n          aria-labelledby={labelledBy}\n          aria-describedby={described}\n          className=\"nx-focal__points\"\n        >\n          {POINTS.map(point => {\n            const isChosen = point === chosen;\n            const isInherited = point === inheritedPoint;\n            return (\n              <CssHint key={point.value} writes={optionWrites?.(point.value)}>\n                <button\n                  type=\"button\"\n                  role=\"radio\"\n                  data-point={point.value}\n                  aria-checked={isChosen}\n                  aria-label={\n                    isInherited ? `${point.label}, inherited` : point.label\n                  }\n                  aria-invalid={invalid}\n                  {...(isInherited ? { \"data-inherited\": \"\" } : {})}\n                  tabIndex={point === focusable ? 0 : -1}\n                  className=\"nx-focal__point\"\n                  onClick={() => choose(point)}\n                  onKeyDown={event => move(event, point)}\n                  // The point's own tooltip says what it writes; kept from\n                  // the field's, which would open over it with the stored\n                  // value.\n                  onPointerMove={event => event.stopPropagation()}\n                />\n              </CssHint>\n            );\n          })}\n        </div>\n      </div>\n      <div className=\"nx-focal__readout\">\n        <b>{readout}</b>\n        <span>{hintFor(fit)}</span>\n      </div>\n      <button\n        type=\"button\"\n        className=\"nx-focal__more\"\n        aria-label={`${actionName} as CSS`}\n        aria-expanded={writing}\n        title=\"Write as CSS…\"\n        onClick={() => setWriting(open => !open)}\n      >\n        <MoreHorizontal size={16} aria-hidden=\"true\" />\n      </button>\n      {writing ? (\n        <FocalCss\n          stored={text}\n          actionName={actionName}\n          describedBy={describedBy}\n          onCommit={onCommit}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * A value written as CSS, such as `30% 70%`, once the field is left: the way\n * past a picker's choices, for a point here and a background's size.\n */\nexport function FocalCss({\n  stored,\n  actionName,\n  describedBy,\n  onCommit,\n  placeholder = \"30% 70%\",\n}: {\n  stored: string | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  /** An example of what may be written; a point unless said. */\n  placeholder?: string;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const [text, setText] = React.useState(stored ?? \"\");\n  // A stored change moves the draft with it, so leaving the field never\n  // writes back the value that change replaced.\n  React.useEffect(() => {\n    setText(stored ?? \"\");\n  }, [stored]);\n  const commit = () => {\n    commitRawCss(text, stored, onCommit);\n  };\n  return (\n    <Input\n      className=\"nx-focal__css\"\n      aria-label={`${actionName} as CSS`}\n      aria-describedby={described}\n      aria-invalid={refusedBy(describedBy)}\n      placeholder={placeholder}\n      value={text}\n      onChange={event => setText(event.target.value)}\n      onBlur={commit}\n      onKeyDown={event => commitOnEnter(event, commit)}\n    />\n  );\n}\n\n/** `true` while a refusal describes the field, which is what invalidates it. */\nexport function refusedBy(describedBy: string | undefined): true | undefined {\n  return describedBy === undefined ? undefined : true;\n}\n","/**\n * The Background section's placement fields: where the image sits (the nine\n * points every position picker here uses) and how it is sized.\n *\n * @module background-fields\n */\nimport type { StyleValue } from \"@nextlyhq/blocks-engine\";\nimport { MoreHorizontal } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { radioGroupStep } from \"../../roving-radios\";\nimport { declarationsText } from \"../code-hints\";\nimport { CssHint, OptionWrites, useFieldDescription } from \"../css-hint\";\n\nimport {\n  BACKGROUND_SIZE_CHOICES,\n  backgroundSizeChoiceOf,\n  type BackgroundSizeChoice,\n} from \"./background-placement\";\nimport { FieldPathWrites } from \"./field-path-writes\";\nimport { FocalFrame } from \"./focal-frame\";\nimport { FocalCss, FocalPointField, refusedBy } from \"./focal-point-field\";\nimport { InheritedValue } from \"./inherited-value\";\n\ntype CommitOutcome = \"applied\" | \"refused\" | \"unchanged\";\n\n/** What every own field is given, as `OWN_FIELDS` hands it. */\ninterface OwnFieldProps {\n  id: string;\n  labelledBy: string;\n  stored: StyleValue | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}\n\n/**\n * No picture to preview in the position picker: the frame an Image block\n * provides describes its own picture, not a background, so a background's\n * picker reads none rather than placing points over the wrong image.\n */\nconst NO_PICTURE = {};\n\n/**\n * Where the background image sits: the nine points, or Custom. CSS places a\n * background at its top left when nothing is set, so that is the default\n * the picker reads and focuses.\n */\nexport function BackgroundPositionField(\n  props: OwnFieldProps\n): React.JSX.Element {\n  return (\n    <FocalFrame.Provider value={NO_PICTURE}>\n      <FocalPointField {...props} fallback=\"left top\" />\n    </FocalFrame.Provider>\n  );\n}\n\n/** Where the size field writes: its own path, and the repeat beside it. */\ninterface SizePaths {\n  readonly size: readonly string[];\n  readonly repeat: readonly string[];\n}\n\n/**\n * How the background image is sized: Cover, Fit or Tile, each writing the\n * size AND the repeat in one edit, or any other size written as CSS, which\n * reads as Custom. Without the repeat, Fit's `contain` would tile, since CSS\n * repeats a background image by default.\n *\n * A radio group: one choice is in force, pressing it again changes nothing,\n * and the row's own clear removes the size.\n */\nexport function BackgroundSizeField({\n  id,\n  labelledBy,\n  control,\n  stored,\n  actionName,\n  describedBy,\n  onCommit,\n}: OwnFieldProps & {\n  /** The size control, whose path places the repeat beside it. */\n  control: { readonly path: readonly string[] };\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const optionWrites = React.useContext(OptionWrites);\n  const commitPaths = React.useContext(FieldPathWrites);\n  const inherited = React.useContext(InheritedValue);\n  const [writing, setWriting] = React.useState(false);\n  const group = React.useRef<HTMLDivElement>(null);\n  const text = typeof stored === \"string\" ? stored : undefined;\n  const chosen = backgroundSizeChoiceOf(stored);\n  const inheritedChoice =\n    stored === undefined ? backgroundSizeChoiceOf(inherited) : undefined;\n  const paths = sizePaths(control.path);\n  const invalid = refusedBy(describedBy);\n  // One tab stop: the choice in force, else the one inherited, else the first.\n  const focusable =\n    choiceOrNone(chosen) ?? choiceOrNone(inheritedChoice) ?? FIRST_CHOICE;\n\n  const choose = (choice: BackgroundSizeChoice): void => {\n    if (choice === chosen) return;\n    // Outside a field there is no path write to make both in one edit, so\n    // the size alone is written there.\n    if (commitPaths === undefined) {\n      onCommit(choice.size);\n      return;\n    }\n    commitPaths([\n      { path: paths.size, value: choice.size },\n      { path: paths.repeat, value: choice.repeat },\n    ]);\n  };\n  const move = (event: React.KeyboardEvent, from: BackgroundSizeChoice) => {\n    const step = radioGroupStep(event.key);\n    if (step === null) return;\n    event.preventDefault();\n    const at = BACKGROUND_SIZE_CHOICES.indexOf(from);\n    const count = BACKGROUND_SIZE_CHOICES.length;\n    const next = BACKGROUND_SIZE_CHOICES[(at + step + count) % count];\n    if (next === undefined) return;\n    // A radio group's arrows choose as they move, as every radio group does.\n    choose(next);\n    group.current\n      ?.querySelector<HTMLElement>(`[data-size=\"${next.size}\"]`)\n      ?.focus();\n  };\n\n  return (\n    <div className=\"nx-background-size\">\n      <div\n        ref={group}\n        id={id}\n        role=\"radiogroup\"\n        aria-labelledby={labelledBy}\n        aria-describedby={described}\n        className=\"nx-style-inspector__toggle nx-background-size__choices\"\n      >\n        {BACKGROUND_SIZE_CHOICES.map(choice => {\n          const isInherited = choice === inheritedChoice;\n          return (\n            <CssHint\n              key={choice.label}\n              summary={choice.summary}\n              writes={choiceWrites(choice, optionWrites)}\n            >\n              <button\n                type=\"button\"\n                role=\"radio\"\n                data-size={choice.size}\n                aria-checked={choice === chosen}\n                aria-label={\n                  isInherited ? `${choice.label}, inherited` : choice.label\n                }\n                aria-invalid={invalid}\n                {...(isInherited ? { \"data-inherited\": \"\" } : {})}\n                tabIndex={choice === focusable ? 0 : -1}\n                onClick={() => choose(choice)}\n                onKeyDown={event => move(event, choice)}\n                // The choice's own tooltip says what it writes; kept from the\n                // field's, which would open over it with the stored value.\n                onPointerMove={event => event.stopPropagation()}\n              >\n                {choice.label}\n              </button>\n            </CssHint>\n          );\n        })}\n      </div>\n      <button\n        type=\"button\"\n        className=\"nx-focal__more nx-background-size__more\"\n        aria-label={`${actionName} as CSS`}\n        aria-expanded={writing}\n        title=\"Write as CSS…\"\n        onClick={() => setWriting(open => !open)}\n      >\n        <MoreHorizontal size={16} aria-hidden=\"true\" />\n      </button>\n      <div className=\"nx-focal__readout nx-background-size__readout\">\n        <b>{sizeReadout(chosen, text, inheritedChoice, inherited)}</b>\n        <span>{summaryOf(chosen) ?? summaryOf(inheritedChoice) ?? \"\"}</span>\n      </div>\n      {writing ? (\n        <FocalCss\n          stored={text}\n          actionName={actionName}\n          describedBy={describedBy}\n          onCommit={onCommit}\n          placeholder=\"50% auto\"\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/** The first choice, the group's tab stop while none is in force. */\nconst FIRST_CHOICE = BACKGROUND_SIZE_CHOICES[0];\n\n/** A choice read back, or `undefined` for Custom or nothing. */\nfunction choiceOrNone(\n  read: BackgroundSizeChoice | \"custom\" | undefined\n): BackgroundSizeChoice | undefined {\n  return read === \"custom\" ? undefined : read;\n}\n\n/** What a choice does, in words, or `undefined` for Custom or nothing. */\nfunction summaryOf(\n  read: BackgroundSizeChoice | \"custom\" | undefined\n): string | undefined {\n  return choiceOrNone(read)?.summary;\n}\n\n/** The size's path, and the repeat's beside it in the same property. */\nfunction sizePaths(path: readonly string[]): SizePaths {\n  return { size: path, repeat: [...path.slice(0, -1), \"repeat\"] };\n}\n\n/**\n * What a choice writes, for its tooltip: the size as the engine compiles it,\n * from the field it is drawn in, and the repeat written with it.\n */\nfunction choiceWrites(\n  choice: BackgroundSizeChoice,\n  optionWrites: ((option: string) => string) | undefined\n): string {\n  const size =\n    optionWrites?.(choice.size) ??\n    declarationsText([{ property: \"background-size\", value: choice.size }]);\n  const repeat = declarationsText([\n    { property: \"background-repeat\", value: choice.repeat },\n  ]);\n  return `${size}; ${repeat}`;\n}\n\n/**\n * What the readout says: the choice set here, any other size as Custom with\n * the value written, what reaches it from elsewhere, or that nothing is set.\n */\nfunction sizeReadout(\n  chosen: BackgroundSizeChoice | \"custom\" | undefined,\n  text: string | undefined,\n  inheritedChoice: BackgroundSizeChoice | \"custom\" | undefined,\n  inherited: string | undefined\n): string {\n  if (chosen !== undefined && chosen !== \"custom\") return chosen.label;\n  if (text !== undefined) return `Custom: ${text}`;\n  if (inheritedChoice !== undefined && inheritedChoice !== \"custom\") {\n    return `${inheritedChoice.label}, inherited`;\n  }\n  return inherited === undefined ? \"Not set\" : `Inherited: ${inherited}`;\n}\n","/**\n * What an Image's empty state decides without drawing anything: which\n * canvas boxes are Images waiting for a picture, whether a file is a\n * picture, whether a link is one the page may load and does load, and what\n * a choice writes to the block.\n *\n * Kept apart from the overlay (`image-states.tsx`) so each answer is asked\n * once, by whoever needs it, and tested without a canvas.\n *\n * @module canvas/image-states-model\n */\n\nimport {\n  findNode,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  fetchableUrl,\n  INSTANCE_ATTRIBUTE,\n  NODE_ID_ATTRIBUTE,\n  type RemotePatternInput,\n} from \"@nextlyhq/blocks-react\";\n\nimport {\n  addressChanges,\n  mediaPickChanges,\n  type ImageChanges,\n  type ImageSourceGroup,\n} from \"../inspector/content/image-group\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\n/**\n * The attribute the Image block puts on the box it draws for an author when\n * it has no picture: `empty`, nothing chosen yet, or `missing`, a library\n * file the library no longer has. Spelled here as the block spells it; the\n * overlay's test draws the block itself to find the box, so the two cannot\n * drift apart unseen.\n */\nconst IMAGE_EMPTY_ATTRIBUTE = \"data-nx-image-empty\";\n\n/** The block whose empty state this is. */\nconst IMAGE_BLOCK_TYPE = \"core/image\";\n\n/** Why an Image draws its empty box. */\nexport type ImageEmptyReason = \"empty\" | \"missing\";\n\n/** The words the empty state uses, in one place. */\nexport const IMAGE_STATE_WORDS = {\n  title: \"Add an image\",\n  upload: \"Upload\",\n  library: \"Media library\",\n  link: \"Link\",\n  drop: \"or drop a file here\",\n  notImage: \"That file isn't an image\",\n  badLink: \"This link didn't load an image\",\n  tryAnotherLink: \"Try another link\",\n  missing: \"This image's file is missing\",\n  replace: \"Replace\",\n  linkLabel: \"Image address\",\n  addLink: \"Add\",\n  cancel: \"Cancel\",\n  checking: \"Checking the link\",\n  uploading: \"Uploading\",\n  dropToReplace: \"Drop to replace the image\",\n  uploadFailed: \"The upload didn't finish\",\n  libraryTitle: \"Choose an image\",\n} as const;\n\n/** The two props an Image's picture comes from, as the inspector groups them. */\nconst SOURCE: ImageSourceGroup = {\n  media: \"mediaId\",\n  address: \"src\",\n  drawn: new Set([\"mediaId\", \"src\"]),\n};\n\n/** One Image box on the canvas, waiting for a picture. */\nexport interface EmptyImageBox {\n  readonly nodeId: string;\n  readonly reason: ImageEmptyReason;\n  readonly element: Element;\n}\n\n/**\n * The Image boxes waiting for a picture that this page owns, in document\n * order: each one's node and why it is empty.\n *\n * A box inside a placed component belongs to the component, which its own\n * editor fills; a box for a node the document does not hold belongs to the\n * Layout drawn around the page. Neither is offered here.\n */\nexport function emptyImageBoxes(\n  root: ParentNode,\n  document: BlockDocument\n): EmptyImageBox[] {\n  const found: EmptyImageBox[] = [];\n  root.querySelectorAll(`[${IMAGE_EMPTY_ATTRIBUTE}]`).forEach(element => {\n    if (element.hasAttribute(INSTANCE_ATTRIBUTE)) return;\n    const nodeId = element.getAttribute(NODE_ID_ATTRIBUTE);\n    if (nodeId === null || imageNodeOf(document, nodeId) === undefined) return;\n    const reason =\n      element.getAttribute(IMAGE_EMPTY_ATTRIBUTE) === \"missing\"\n        ? \"missing\"\n        : \"empty\";\n    found.push({ nodeId, reason, element });\n  });\n  return found;\n}\n\n/** The Image node by its id, or `undefined` when it is not one. */\nexport function imageNodeOf(\n  document: BlockDocument,\n  nodeId: string\n): BlockNode | undefined {\n  const node = findNode(document.nodes, nodeId);\n  return node?.type === IMAGE_BLOCK_TYPE ? node : undefined;\n}\n\n/**\n * Whether an Image takes a picture from here: one whose picture is bound,\n * to a media field or to an address field, is filled by its binding instead.\n * Storing a file on it would outrank the binding and stop it following its\n * field.\n */\nexport function takesPicture(node: BlockNode): boolean {\n  return (\n    node.bindings?.mediaId === undefined && node.bindings?.src === undefined\n  );\n}\n\n/** Whether a drag carries files from outside the page. */\nexport function carriesFiles(transfer: DataTransfer | null): boolean {\n  if (transfer === null) return false;\n  return Array.from(transfer.types).includes(\"Files\");\n}\n\n/**\n * The first file a drop or a file chooser handed over, and whether it is a\n * picture, by the type the browser read it as. The library's upload checks\n * the file again, on the server, by its contents.\n */\nexport function chosenFile(\n  files: FileList | readonly File[] | null | undefined\n): { readonly file: File; readonly image: boolean } | undefined {\n  const file = files === null || files === undefined ? undefined : files[0];\n  if (file === undefined) return undefined;\n  return { file, image: file.type.startsWith(\"image/\") };\n}\n\n/**\n * Why an upload did not finish, in the library's own words when it gave any.\n * Shared by every place an author uploads an image, so each says it alike.\n */\nexport function failureWords(error: unknown): string {\n  const reason =\n    error instanceof Error && error.message.trim() !== \"\"\n      ? error.message.trim()\n      : undefined;\n  return reason === undefined\n    ? `${IMAGE_STATE_WORDS.uploadFailed}.`\n    : `${IMAGE_STATE_WORDS.uploadFailed}: ${reason}`;\n}\n\n/**\n * The address a typed link is drawn from, or `undefined` when the page\n * would refuse it: through the same rule the Image block draws by, so a\n * link the canvas accepts is one the page draws.\n */\nexport function linkAddress(\n  typed: string,\n  patterns: readonly RemotePatternInput[] | undefined\n): string | undefined {\n  const trimmed = typed.trim();\n  if (trimmed === \"\") return undefined;\n  return fetchableUrl(trimmed, patterns);\n}\n\n/** How long a link is given to load before it counts as not loading. */\nconst LINK_LOAD_MS = 15_000;\n\n/**\n * Whether an address loads as a picture, asked in the document the page is\n * drawn in, so it is fetched under the same rules the page's own picture\n * will be. A picture that loads with no size is not one.\n */\nexport function loadsAsImage(\n  address: string,\n  where: Document,\n  waitMs: number = LINK_LOAD_MS\n): Promise<boolean> {\n  return new Promise(resolve => {\n    const probe = where.createElement(\"img\");\n    let settled = false;\n    const settle = (loaded: boolean): void => {\n      if (settled) return;\n      settled = true;\n      clearTimeout(timer);\n      probe.onload = null;\n      probe.onerror = null;\n      resolve(loaded);\n    };\n    const timer = setTimeout(() => settle(false), waitMs);\n    probe.onload = () => settle(probe.naturalWidth > 0);\n    probe.onerror = () => settle(false);\n    probe.src = address;\n  });\n}\n\n/**\n * The op that gives an Image its picture: a library file, as the inspector's\n * Library side writes it (an address typed before stays as its fallback), or\n * an address, as its URL side does (dropping the library file). `null` when\n * the node is gone or holds no Image.\n */\nexport function pictureOp(\n  document: BlockDocument,\n  nodeId: string,\n  picture: { readonly mediaId: string } | { readonly address: string }\n): BuilderOp | null {\n  const node = imageNodeOf(document, nodeId);\n  if (node === undefined) return null;\n  const changes: ImageChanges =\n    \"mediaId\" in picture\n      ? mediaPickChanges(SOURCE, picture.mediaId, node.props, [])\n      : addressChanges(SOURCE, picture.address, node.props);\n  const props: Record<string, unknown> = { ...node.props };\n  for (const [name, value] of Object.entries(changes)) {\n    if (value === undefined) delete props[name];\n    else props[name] = value;\n  }\n  return { kind: \"update\", id: nodeId, patch: { props } };\n}\n","/**\n * The Background section's image: chosen from the Media library, uploaded, or\n * given by a link, and shown as a thumbnail with Replace and Remove once set.\n *\n * A background image is stored as its address (`background.url` is a URL the\n * page's CSS reads directly), so a file picked from the library or uploaded\n * is written by its URL. Remove clears only the image; nothing else in the\n * Background section changes.\n *\n * @module background-image-control\n */\nimport {\n  paintsBackgroundImage,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button, Input } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  chosenFile,\n  failureWords,\n  IMAGE_STATE_WORDS,\n} from \"../../canvas/image-states-model\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport {\n  ContentServicesContext,\n  type ContentServices,\n  type PickedMedia,\n} from \"../content/content-services\";\nimport { MediaChoice } from \"../content/media-controls\";\nimport { useFieldDescription } from \"../css-hint\";\n\nimport { refusedBy } from \"./focal-point-field\";\nimport { InheritedValue } from \"./inherited-value\";\nimport { StyleTargetContext } from \"./style-field-surroundings\";\nimport { targetKey } from \"./style-field-target\";\n\ntype CommitOutcome = \"applied\" | \"refused\" | \"unchanged\";\n\n/**\n * What a stored value says about the image: an image, a keyword that paints\n * none (`none`, `inherit`, however escaped), or nothing. Whether it paints is\n * the compiler's own answer, so the field and the page never disagree.\n */\nfunction readStored(\n  stored: StyleValue | undefined\n): { image: string } | { keyword: string } | undefined {\n  if (typeof stored !== \"string\") return undefined;\n  const value = stored.trim();\n  if (value === \"\") return undefined;\n  return paintsBackgroundImage(\"url\", value)\n    ? { image: value }\n    : { keyword: value };\n}\n\n/**\n * A short name for an image's address: its file name, decoded where it can\n * be, else as written (a `%` that starts no escape is a character).\n */\nfunction imageName(address: string): string {\n  const path = address.split(/[?#]/, 1)[0] ?? address;\n  const last = path.split(\"/\").filter(Boolean).pop();\n  if (last === undefined) return address;\n  try {\n    return decodeURIComponent(last);\n  } catch {\n    return last;\n  }\n}\n\n/** The image's writes, and what this field says about them. */\nfunction useImageWrites(\n  services: ContentServices | undefined,\n  onCommit: (value: StyleValue | null) => CommitOutcome\n) {\n  const [issue, setIssue] = React.useState<string | null>(null);\n  const [uploading, setUploading] = React.useState(false);\n  // Counts the writes started here, so an upload that finishes after a later\n  // choice (a pasted link) does not overwrite it.\n  const writes = React.useRef(0);\n  // The newest commit, which writes against the page as it is now: an upload\n  // finishing later must not write through the one it started with, whose\n  // page may since have changed (another style set meanwhile).\n  const commitNow = React.useRef(onCommit);\n  // What the field edits now: the block, or one of its shared styles. An\n  // upload belongs to the one it started on, and is dropped if the author\n  // has since moved to another, rather than written there.\n  const target = targetKey(React.useContext(StyleTargetContext));\n  const targetNow = React.useRef(target);\n  React.useEffect(() => {\n    commitNow.current = onCommit;\n    targetNow.current = target;\n  });\n  // Leaving (another device or state shown remounts the field) ends any\n  // upload still running: its commit would write against the page as it was.\n  React.useEffect(\n    () => () => {\n      writes.current += 1;\n    },\n    []\n  );\n\n  // A picked or uploaded file is written by its address; one without an\n  // address has nothing a page could draw.\n  const writePicked = (media: PickedMedia) => {\n    if (typeof media.url !== \"string\" || media.url === \"\") {\n      setIssue(\"That file has no address to show it from.\");\n      return;\n    }\n    setIssue(null);\n    commitNow.current(media.url);\n  };\n  // The file chosen is checked as the canvas's Image checks it, and its\n  // failure is said in the same words.\n  const upload = async (files: FileList | null) => {\n    const uploadMedia = services?.uploadMedia;\n    const chosen = chosenFile(files);\n    if (uploadMedia === undefined || chosen === undefined) return;\n    if (!chosen.image) {\n      setIssue(`${IMAGE_STATE_WORDS.notImage}.`);\n      return;\n    }\n    const ticket = ++writes.current;\n    const startedOn = targetNow.current;\n    setIssue(null);\n    setUploading(true);\n    try {\n      const media = await uploadMedia(chosen.file);\n      if (ticket !== writes.current) return;\n      if (targetNow.current !== startedOn) {\n        setIssue(\n          \"The upload finished after you switched to another style, so it wasn't used here. Choose it again.\"\n        );\n        return;\n      }\n      writePicked(media);\n    } catch (error) {\n      if (ticket === writes.current) setIssue(failureWords(error));\n    } finally {\n      setUploading(false);\n    }\n  };\n  // A pasted link is written as it is; the field empties once it holds.\n  const commitLink = (input: HTMLInputElement) => {\n    const link = input.value.trim();\n    if (link === \"\") return;\n    writes.current += 1;\n    setIssue(null);\n    if (onCommit(link) === \"applied\") input.value = \"\";\n  };\n  // A newer choice than any upload still running, which it must not undo.\n  const remove = () => {\n    writes.current += 1;\n    setIssue(null);\n    onCommit(null);\n  };\n  return { issue, uploading, writePicked, upload, commitLink, remove };\n}\n\n/**\n * What the field says is set: a keyword set here, the image reaching it\n * from elsewhere while nothing is set here, or the image's thumbnail.\n */\nfunction ImageSummary({\n  read,\n  inherited,\n}: {\n  read: ReturnType<typeof readStored>;\n  inherited: ReturnType<typeof readStored>;\n}): React.JSX.Element | null {\n  if (read !== undefined && \"keyword\" in read) {\n    // `none` clears an earlier image: said, and removable, rather than\n    // looking like nothing is set.\n    return (\n      <p className=\"nx-inspector__note\">No image here ({read.keyword}).</p>\n    );\n  }\n  if (read === undefined) {\n    return inherited !== undefined && \"image\" in inherited ? (\n      <p className=\"nx-inspector__note\" title={inherited.image}>\n        Inherits {imageName(inherited.image)}\n      </p>\n    ) : null;\n  }\n  return (\n    <div className=\"nx-inspector__media-chosen\">\n      <img\n        className=\"nx-inspector__media-thumb\"\n        src={read.image}\n        alt=\"\"\n        aria-hidden=\"true\"\n      />\n      <div className=\"nx-inspector__media-text\">\n        <p className=\"nx-inspector__media-name\" title={read.image}>\n          {imageName(read.image)}\n        </p>\n      </div>\n    </div>\n  );\n}\n\n/** Upload, with the hidden file chooser it opens. */\nfunction UploadButton({\n  uploading,\n  onFiles,\n}: {\n  uploading: boolean;\n  onFiles: (files: FileList | null) => void;\n}): React.JSX.Element {\n  const fileInput = React.useRef<HTMLInputElement>(null);\n  return (\n    <>\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        disabled={uploading}\n        onClick={() => fileInput.current?.click()}\n      >\n        {uploading ? \"Uploading…\" : \"Upload\"}\n      </Button>\n      <input\n        ref={fileInput}\n        type=\"file\"\n        accept=\"image/*\"\n        hidden\n        onChange={event => {\n          onFiles(event.currentTarget.files);\n          event.currentTarget.value = \"\";\n        }}\n      />\n    </>\n  );\n}\n\nexport function BackgroundImageField({\n  id,\n  labelledBy,\n  stored,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  labelledBy: string;\n  stored: StyleValue | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  const services = React.useContext(ContentServicesContext);\n  const described = useFieldDescription(describedBy);\n  const read = readStored(stored);\n  const image = read !== undefined && \"image\" in read ? read.image : undefined;\n  // What reaches the field from elsewhere (an earlier state or a wider\n  // device), said when nothing is set here.\n  const inherited = readStored(React.useContext(InheritedValue));\n  const { issue, uploading, writePicked, upload, commitLink, remove } =\n    useImageWrites(services, onCommit);\n  const Picker = services?.MediaPicker;\n  const canUpload = image === undefined && services?.uploadMedia !== undefined;\n\n  return (\n    <div\n      id={id}\n      role=\"group\"\n      aria-labelledby={labelledBy}\n      className=\"nx-background-image\"\n    >\n      <ImageSummary read={read} inherited={inherited} />\n      <div className=\"nx-background-image__actions\">\n        {Picker === undefined ? null : (\n          <MediaChoice\n            Picker={Picker}\n            label=\"Background image\"\n            // The library is asked for files, not addresses, so nothing is\n            // preselected; the button reads \"Replace\" once an image is set.\n            stored={image ?? null}\n            // An address is no media id: the library opens with nothing\n            // selected, and the button still reads \"Replace\".\n            selected={null}\n            accept=\"image/*\"\n            disabled={uploading}\n            onChoose={writePicked}\n          />\n        )}\n        {canUpload ? (\n          <UploadButton\n            uploading={uploading}\n            onFiles={files => void upload(files)}\n          />\n        ) : null}\n        {read === undefined ? null : (\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"outline\"\n            aria-label=\"Remove background image\"\n            onClick={remove}\n          >\n            Remove\n          </Button>\n        )}\n      </div>\n      {image === undefined ? (\n        <Input\n          type=\"url\"\n          inputMode=\"url\"\n          aria-label=\"Image link\"\n          disabled={uploading}\n          // A refused link (a host the site does not load from) stays in the\n          // field, marked, with the reason read beside it.\n          aria-invalid={refusedBy(describedBy)}\n          aria-describedby={described}\n          placeholder=\"Or paste an image link\"\n          className=\"nx-background-image__link\"\n          onKeyDown={event => {\n            const input = event.currentTarget;\n            // Enter commits as leaving the field does.\n            commitOnEnter(event, () => commitLink(input));\n          }}\n          onBlur={event => commitLink(event.currentTarget)}\n        />\n      ) : null}\n      {issue === null ? null : (\n        <p className=\"nx-inspector__note\" role=\"alert\">\n          {issue}\n        </p>\n      )}\n    </div>\n  );\n}\n","/**\n * A style value chosen from icons: alignment and direction, drawn as the way\n * content flows rather than as CSS words.\n *\n * A radio group, one tab stop on the chosen value (or the first), with the\n * arrow keys moving and choosing, wrapping at the ends, as a radio group\n * does. Each icon is named in words for assistive technology and shows that\n * name in a tooltip on hover and on keyboard focus. Pressing the chosen icon\n * again clears the value, as the panel's other toggles do.\n *\n * The values the icons do not draw sit in a small list beside the group, so\n * every value the catalogue accepts stays reachable, and a stored one shows.\n *\n * @module icon-choice-field\n */\nimport type { StyleValue } from \"@nextlyhq/blocks-engine\";\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n  TooltipProvider,\n} from \"@nextlyhq/ui\";\nimport {\n  AlignCenter,\n  AlignCenterHorizontal,\n  AlignCenterVertical,\n  AlignEndHorizontal,\n  AlignEndVertical,\n  AlignHorizontalDistributeCenter,\n  AlignHorizontalJustifyCenter,\n  AlignHorizontalJustifyEnd,\n  AlignHorizontalJustifyStart,\n  AlignHorizontalSpaceAround,\n  AlignHorizontalSpaceBetween,\n  AlignJustify,\n  AlignLeft,\n  AlignRight,\n  AlignStartHorizontal,\n  AlignStartVertical,\n  AlignVerticalDistributeCenter,\n  AlignVerticalJustifyCenter,\n  AlignVerticalJustifyEnd,\n  AlignVerticalJustifyStart,\n  AlignVerticalSpaceAround,\n  AlignVerticalSpaceBetween,\n  ArrowDown,\n  ArrowLeft,\n  ArrowRight,\n  ArrowRightToLine,\n  ArrowUp,\n  Ban,\n  Baseline,\n  CaseLower,\n  CaseSensitive,\n  CaseUpper,\n  ChevronDown,\n  Circle,\n  Crop,\n  Columns3,\n  EyeOff,\n  Grid2x2,\n  Minus,\n  MoreHorizontal,\n  Play,\n  Plus,\n  RectangleHorizontal,\n  Shrink,\n  StretchHorizontal,\n  StretchVertical,\n  Strikethrough,\n  Underline,\n  WrapText,\n  createLucideIcon,\n  type LucideIcon,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport { useFieldDescription } from \"../css-hint\";\n\nimport { InheritedValue } from \"./inherited-value\";\nimport type { AlignmentGroup, AlignmentOption } from \"./style-alignment-icons\";\nimport {\n  foldKeyword,\n  keywordLabel,\n  menuKeywords,\n} from \"./style-keyword-labels\";\n\n/**\n * A line over an O, as Underline is a U over one: lucide has no overline, and\n * a mark drawn in its own grid sits in the set as one of its own.\n */\nconst Overline = createLucideIcon(\"overline\", [\n  [\"path\", { d: \"M5 3h14\", key: \"line\" }],\n  [\"circle\", { cx: \"12\", cy: \"14\", r: \"6\", key: \"letter\" }],\n]);\n\n/** The icons the mapping names, by their lucide export name. */\nconst ICONS: Readonly<Record<string, LucideIcon>> = {\n  AlignCenter,\n  AlignCenterHorizontal,\n  AlignCenterVertical,\n  AlignEndHorizontal,\n  AlignEndVertical,\n  AlignHorizontalDistributeCenter,\n  AlignHorizontalJustifyCenter,\n  AlignHorizontalJustifyEnd,\n  AlignHorizontalJustifyStart,\n  AlignHorizontalSpaceAround,\n  AlignHorizontalSpaceBetween,\n  AlignJustify,\n  AlignLeft,\n  AlignRight,\n  AlignStartHorizontal,\n  AlignStartVertical,\n  AlignVerticalDistributeCenter,\n  AlignVerticalJustifyCenter,\n  AlignVerticalJustifyEnd,\n  AlignVerticalJustifyStart,\n  AlignVerticalSpaceAround,\n  AlignVerticalSpaceBetween,\n  ArrowDown,\n  ArrowLeft,\n  ArrowRight,\n  ArrowRightToLine,\n  ArrowUp,\n  Ban,\n  Baseline,\n  CaseLower,\n  CaseSensitive,\n  CaseUpper,\n  ChevronDown,\n  Columns3,\n  Crop,\n  EyeOff,\n  Grid2x2,\n  Minus,\n  Play,\n  Plus,\n  RectangleHorizontal,\n  Shrink,\n  StretchHorizontal,\n  StretchVertical,\n  Strikethrough,\n  Underline,\n  Overline,\n  WrapText,\n};\n\n/** How far each key moves the choice. */\nconst STEPS: Readonly<Record<string, number>> = {\n  ArrowRight: 1,\n  ArrowDown: 1,\n  ArrowLeft: -1,\n  ArrowUp: -1,\n};\n\ntype CommitOutcome = \"applied\" | \"refused\" | \"unchanged\";\n\n/**\n * An option's name, and its mark when it is the value inherited from another\n * tier: drawn as a dashed ring and said in its name, since a screen reader\n * otherwise hears every option unchecked and cannot tell which applies.\n */\nfunction inheritedMark(\n  option: AlignmentOption,\n  inherited: string | undefined\n): { \"aria-label\": string; \"data-inherited\"?: \"\" } {\n  return inherited !== undefined && option.value === foldKeyword(inherited)\n    ? { \"aria-label\": `${option.label}, inherited`, \"data-inherited\": \"\" }\n    : { \"aria-label\": option.label };\n}\n\nexport function IconChoiceField({\n  id,\n  labelledBy,\n  group,\n  stored,\n  actionName,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  labelledBy: string;\n  group: AlignmentGroup;\n  stored: StyleValue | undefined;\n  /** The property's name, for naming the list of other values. */\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  const current = typeof stored === \"string\" ? stored : undefined;\n  // The value reaching this block from another tier. Its icon is marked, not\n  // checked, while nothing is set here: the group shows what the canvas draws\n  // without claiming this block chose it.\n  const inherited = React.useContext(InheritedValue);\n  const shownInherited = stored === undefined ? inherited : undefined;\n  const { options } = group;\n  // Matched as CSS reads a keyword, so an imported `FLEX` chooses Flex.\n  const iconFor = (value: string | undefined) =>\n    value === undefined\n      ? -1\n      : options.findIndex(option => option.value === foldKeyword(value));\n  const chosen = iconFor(current);\n  const buttons = React.useRef<(HTMLButtonElement | null)[]>([]);\n\n  // Moves and chooses together, as a radio group's arrow keys do.\n  const choose = (index: number) => {\n    const option = options[index];\n    if (option === undefined) return;\n    onCommit(option.value);\n    buttons.current[index]?.focus();\n  };\n  const onKeyDown = (event: React.KeyboardEvent, index: number) => {\n    const last = options.length - 1;\n    const step = STEPS[event.key];\n    const target =\n      step !== undefined\n        ? (index + step + options.length) % options.length\n        : event.key === \"Home\"\n          ? 0\n          : event.key === \"End\"\n            ? last\n            : undefined;\n    if (target === undefined) return;\n    event.preventDefault();\n    choose(target);\n  };\n\n  // A refused value marks every control, so whichever is focused says so.\n  const invalid = describedBy === undefined ? undefined : true;\n  // A stored spelling the icons do not draw (the engine accepts \"inherit\"\n  // and other spellings): in More, as stored, in the place of a value it\n  // reads the same as or else first, so an active declaration never reads as\n  // unset and is never listed twice.\n  const more = moreValues(group, {\n    current,\n    chosen,\n    inherited: shownInherited,\n    iconFor,\n  });\n  const { help, helpId, describedByAll } = useAppliedHelp(\n    group,\n    current ?? shownInherited,\n    describedBy\n  );\n\n  return (\n    <TooltipProvider delayDuration={300}>\n      <div className=\"nx-icon-choice\">\n        {/* One strip: the icons, then More as its last segment. */}\n        <div className=\"nx-icon-choice__strip\">\n          <div\n            role=\"radiogroup\"\n            aria-labelledby={labelledBy}\n            aria-describedby={describedByAll}\n            className=\"nx-icon-choice__group\"\n          >\n            {options.map((option, index) => {\n              const checked = index === chosen;\n              // The group's one tab stop: the chosen icon, else the first.\n              const stop = index === Math.max(chosen, 0);\n              const Icon = ICONS[option.icon] ?? Circle;\n              return (\n                // Below the icons, over the next row: above, it covered the\n                // value of the row before.\n                <ChromeTooltip key={option.value} content={option.label}>\n                  <button\n                    ref={button => {\n                      buttons.current[index] = button;\n                    }}\n                    type=\"button\"\n                    // The field label's `for` lands here: a label reaches\n                    // only a labelable element, and this is the group's\n                    // way in.\n                    {...(stop ? { id } : {})}\n                    role=\"radio\"\n                    aria-checked={checked}\n                    {...inheritedMark(option, shownInherited)}\n                    aria-invalid={invalid}\n                    tabIndex={stop ? 0 : -1}\n                    data-icon={option.icon}\n                    className=\"nx-icon-choice__option\"\n                    onClick={() => onCommit(checked ? null : option.value)}\n                    onKeyDown={event => onKeyDown(event, index)}\n                  >\n                    <Icon\n                      size={16}\n                      aria-hidden=\"true\"\n                      style={iconStyle(option)}\n                      {...(iconClass(option) === undefined\n                        ? {}\n                        : { className: iconClass(option) })}\n                    />\n                  </button>\n                </ChromeTooltip>\n              );\n            })}\n          </div>\n          {more.length === 0 ? null : (\n            <OtherValues\n              cssProperty={group.cssProperty}\n              values={more}\n              current={current}\n              actionName={actionName}\n              describedBy={describedBy}\n              onCommit={onCommit}\n            />\n          )}\n        </div>\n        {help === undefined ? null : (\n          <p className=\"nx-inspector__note nx-icon-choice__help\" id={helpId}>\n            {help}\n          </p>\n        )}\n      </div>\n    </TooltipProvider>\n  );\n}\n\n/**\n * The values beside the icons: the group's list, with a stored value no icon\n * draws in the place of the one it reads the same as, or else first. So is\n * an inherited value no icon draws, so the field shows what the canvas uses\n * rather than nothing at all.\n */\nfunction moreValues(\n  group: AlignmentGroup,\n  {\n    current,\n    chosen,\n    inherited,\n    iconFor,\n  }: {\n    current: string | undefined;\n    chosen: number;\n    inherited: string | undefined;\n    iconFor: (value: string | undefined) => number;\n  }\n): readonly string[] {\n  const unlisted =\n    current !== undefined\n      ? chosen === -1\n        ? current\n        : \"\"\n      : inherited !== undefined && iconFor(inherited) === -1\n        ? inherited\n        : \"\";\n  return menuKeywords(group.cssProperty, group.rest, unlisted);\n}\n\n/**\n * What the value that applies does, set here or inherited, where the group\n * says it in words (an image's fit), and the ids the group is described by\n * with that line among them.\n */\nfunction useAppliedHelp(\n  group: AlignmentGroup,\n  applies: string | undefined,\n  describedBy: string | undefined\n): {\n  help: string | undefined;\n  helpId: string;\n  describedByAll: string | undefined;\n} {\n  const helpId = React.useId();\n  const help =\n    applies === undefined ? undefined : group.help?.[foldKeyword(applies)];\n  const ids = [describedBy, help === undefined ? undefined : helpId].filter(\n    (id): id is string => id !== undefined\n  );\n  return {\n    help,\n    helpId,\n    describedByAll: ids.length === 0 ? undefined : ids.join(\" \"),\n  };\n}\n\n/** The class an icon is drawn with: turned a quarter, for text down the page. */\nfunction iconClass(\n  option: AlignmentGroup[\"options\"][number]\n): string | undefined {\n  return option.rotated === true ? \"nx-icon-choice__rotated\" : undefined;\n}\n\n/** The transform that maps an icon's own directions onto the container's. */\nfunction iconStyle(\n  option: AlignmentGroup[\"options\"][number]\n): React.CSSProperties | undefined {\n  return option.matrix === undefined\n    ? undefined\n    : { transform: `matrix(${option.matrix.join(\", \")}, 0, 0)` };\n}\n\n/**\n * The values the icons do not draw, as the strip's last segment: \"⋯\" until one\n * of them is the value, then that value's own spelling.\n */\nfunction OtherValues({\n  cssProperty,\n  values,\n  current,\n  actionName,\n  describedBy,\n  onCommit,\n}: {\n  /** The property the values are named for. */\n  cssProperty: string;\n  values: readonly string[];\n  current: string | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const value =\n    current !== undefined && values.includes(current) ? current : \"\";\n  // An inherited value with no icon of its own lives here: More is ringed\n  // as an inherited icon is, and says which value applies.\n  const inherited = React.useContext(InheritedValue);\n  const shows =\n    current === undefined &&\n    inherited !== undefined &&\n    values.includes(inherited)\n      ? inherited\n      : undefined;\n  return (\n    <Select value={value} onValueChange={next => onCommit(next)}>\n      <SelectTrigger\n        className=\"nx-icon-choice__more\"\n        data-inherited={shows === undefined ? undefined : \"\"}\n        title={shows}\n        aria-label={\n          shows === undefined\n            ? `More ${actionName} values`\n            : `More ${actionName} values, showing ${keywordLabel(cssProperty, shows)}`\n        }\n        aria-describedby={described}\n        aria-invalid={describedBy === undefined ? undefined : true}\n      >\n        <SelectValue\n          placeholder={<MoreHorizontal size={16} aria-hidden=\"true\" />}\n        />\n      </SelectTrigger>\n      <SelectContent>\n        {/* In words, the CSS spelling in the tooltip; see style-keyword-labels. */}\n        {values.map(other => (\n          <SelectItem key={other} value={other} title={other}>\n            {keywordLabel(cssProperty, other)}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n","/**\n * Whether the section a style field sits in is held read-only.\n *\n * @module section-held\n */\nimport * as React from \"react\";\n\n/**\n * Whether the section a field sits in is held read-only. Its fieldset holds\n * the form controls; a control that is not one (a slider's thumb), or one\n * drawn outside the fieldset (a popover's, mounted at the page's root), reads\n * this.\n */\nexport const SectionHeld: React.Context<boolean> =\n  React.createContext<boolean>(false);\n","\"use client\";\n\n/**\n * Text decoration as icons (None, Underline, Strikethrough, Overline), with\n * the line's style, thickness and colour in a popover.\n *\n * The catalog stores `text-decoration` as free CSS, so the commonest text\n * option was a text field. This reads the shorthand into its parts and writes\n * it back from them: the line alone where nothing else is set (`underline`),\n * or the line with its style, thickness and colour (`underline wavy 2px\n * red`). A value it cannot read into those parts (two lines at once, a\n * variable that could stand for any of them, a word that is no colour) is left\n * to the text field, and the popover writes one as CSS, so nothing the CSS can\n * say becomes unreachable.\n *\n * @module decoration-field\n */\n\nimport {\n  checkDimensionValue,\n  cssColor,\n  isCssWideKeyword,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { MoreHorizontal } from \"lucide-react\";\nimport * as React from \"react\";\n\n// Enter commits without submitting the entry form the builder sits in.\nimport { useStoredDraft } from \"../../stored-draft\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport { useFieldDescription } from \"../css-hint\";\n\nimport { IconChoiceField } from \"./icon-choice-field\";\nimport { InheritedValue } from \"./inherited-value\";\nimport { commitRawCss } from \"./raw-css\";\nimport { SectionHeld } from \"./section-held\";\nimport type { AlignmentGroup } from \"./style-alignment-icons\";\nimport { keywordLabel } from \"./style-keyword-labels\";\n\ntype CommitOutcome = \"applied\" | \"refused\" | \"unchanged\";\n\n/** A decoration read into the parts its controls edit. */\nexport interface DecorationParts {\n  readonly line: string;\n  readonly style?: string;\n  readonly thickness?: string;\n  readonly color?: string;\n}\n\nconst LINES = [\"none\", \"underline\", \"line-through\", \"overline\"] as const;\nconst STYLES = [\"solid\", \"double\", \"dotted\", \"dashed\", \"wavy\"] as const;\n\n/** A variable may stand for any part of the shorthand, or several. */\nconst VARIABLE = /^(?:var|env)\\(/i;\n\n/**\n * Whether a word is a thickness: `auto`, `from-font`, or a length or\n * percentage as the engine's own length grammar reads one, a computed one\n * included. A CSS-wide keyword stands only alone, so it is none of a\n * shorthand's parts.\n */\nfunction isThickness(token: string): boolean {\n  return (\n    !VARIABLE.test(token) &&\n    !isCssWideKeyword(token) &&\n    checkDimensionValue(token, {\n      keywords: [\"auto\", \"from-font\"],\n      allowPercentage: true,\n    }) === null\n  );\n}\n\n/** Whether a word is a colour the shorthand can hold. */\nfunction isLineColor(token: string): boolean {\n  return !isCssWideKeyword(token) && cssColor(token) !== undefined;\n}\n\n/** The shorthand's parts, split on whitespace outside parentheses. */\nfunction tokensOf(text: string): string[] {\n  const tokens: string[] = [];\n  let depth = 0;\n  let current = \"\";\n  for (const char of text) {\n    if (char === \"(\") depth += 1;\n    if (char === \")\") depth = Math.max(0, depth - 1);\n    if (depth === 0 && /[ \\t\\n\\r\\f]/.test(char)) {\n      if (current !== \"\") tokens.push(current);\n      current = \"\";\n    } else {\n      current += char;\n    }\n  }\n  if (current !== \"\") tokens.push(current);\n  return tokens;\n}\n\n/** Which part of a decoration one of its words is, or why it cannot be read. */\nfunction partOf(token: string): keyof DecorationParts | \"unreadable\" {\n  const word = token.toLowerCase();\n  if ((LINES as readonly string[]).includes(word)) return \"line\";\n  if ((STYLES as readonly string[]).includes(word)) return \"style\";\n  if (isThickness(token)) return \"thickness\";\n  // The colour is one the page's own check reads as a colour. A variable,\n  // which may stand for any part, that check refuses too.\n  return isLineColor(token) ? \"color\" : \"unreadable\";\n}\n\n/**\n * A stored decoration as its parts, in any order the shorthand allows, or\n * `undefined` for one the icons cannot draw: no line, two lines, two of one\n * part, a variable, or a word that is none of the parts.\n */\nexport function parseDecoration(text: string): DecorationParts | undefined {\n  const parts: Record<string, string> = {};\n  const tokens = tokensOf(text);\n  for (const token of tokens) {\n    const part = partOf(token);\n    if (part === \"unreadable\" || parts[part] !== undefined) return undefined;\n    parts[part] = part === \"line\" ? token.toLowerCase() : token;\n  }\n  const { line, style, thickness, color } = parts;\n  if (line === undefined) return undefined;\n  return {\n    line,\n    ...(style === undefined ? {} : { style: style.toLowerCase() }),\n    ...(thickness === undefined ? {} : { thickness }),\n    ...(color === undefined ? {} : { color }),\n  };\n}\n\n/** The shorthand for a decoration's parts, the line first. */\nexport function composeDecoration(parts: DecorationParts): string {\n  return [parts.line, parts.style, parts.thickness, parts.color]\n    .filter((part): part is string => part !== undefined && part !== \"\")\n    .join(\" \");\n}\n\n/** Whether the field can draw a stored value; else the text field keeps it. */\nexport function drawsDecoration(stored: StyleValue | undefined): boolean {\n  return (\n    stored === undefined ||\n    (typeof stored === \"string\" && parseDecoration(stored) !== undefined)\n  );\n}\n\n/** The line as icons: what each shows, in its words. */\nconst LINE_GROUP: AlignmentGroup = {\n  cssProperty: \"text-decoration-line\",\n  options: [\n    { value: \"none\", icon: \"Minus\" },\n    { value: \"underline\", icon: \"Underline\" },\n    { value: \"line-through\", icon: \"Strikethrough\" },\n    { value: \"overline\", icon: \"Overline\" },\n  ].map(option => ({\n    ...option,\n    label: keywordLabel(\"text-decoration-line\", option.value),\n  })),\n  rest: [],\n};\n\nexport function DecorationField({\n  id,\n  labelledBy,\n  stored,\n  actionName,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  labelledBy: string;\n  stored: StyleValue | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  const own = typeof stored === \"string\" ? parseDecoration(stored) : undefined;\n  const inherited = React.useContext(InheritedValue);\n  const inheritedParts =\n    stored === undefined && inherited !== undefined\n      ? parseDecoration(inherited)\n      : undefined;\n  // What a change starts from: the value set here, or else the one inherited,\n  // so a line changed here keeps the style, thickness and colour it showed.\n  const parts = useQueuedParts(\n    typeof stored === \"string\" ? stored : undefined,\n    own ?? inheritedParts,\n    describedBy !== undefined\n  );\n  // A part changed keeps the others: a line changed keeps its style.\n  const write = (next: Partial<DecorationParts>) => parts.write(next, onCommit);\n  // The popover is mounted outside the section's fieldset, so a section held\n  // while it is open reaches its controls through this instead.\n  const held = React.useContext(SectionHeld);\n  return (\n    <div className=\"nx-style-inspector__decoration\">\n      {/* The icons mark the inherited line, not the whole shorthand. */}\n      <InheritedValue.Provider value={inheritedParts?.line ?? inherited}>\n        <IconChoiceField\n          id={id}\n          labelledBy={labelledBy}\n          group={LINE_GROUP}\n          // The line just chosen while its write is on its way, so pressing\n          // it again clears it; otherwise the line set here.\n          stored={parts.pending ? parts.current?.line : own?.line}\n          actionName={actionName}\n          describedBy={describedBy}\n          onCommit={line =>\n            line === null || typeof line !== \"string\"\n              ? onCommit(null)\n              : write({ line })\n          }\n        />\n      </InheritedValue.Provider>\n      <Popover>\n        <PopoverTrigger asChild>\n          <button\n            type=\"button\"\n            className=\"nx-style-inspector__decoration-style\"\n            aria-label={`${actionName} style`}\n            title=\"Style…\"\n          >\n            {/* The strip's last segment, as More is on the other icon\n                choices: its name says what it opens. */}\n            <MoreHorizontal size={16} aria-hidden=\"true\" />\n          </button>\n        </PopoverTrigger>\n        {/* Mounted outside the editor's root: the builder's tokens come\n            with it, and the popover's own rule gives it the inspector's\n            density. Spell-check is off here for the same reason it is off\n            on the Style tab, which this layer is drawn outside of and so\n            does not inherit from: a thickness, a colour code or a line of\n            CSS is not words to correct. */}\n        <PopoverContent\n          className=\"nx-builder-tokens nx-style-inspector__decoration-popover\"\n          spellCheck={false}\n        >\n          <DecorationStyle\n            parts={parts.current}\n            write={write}\n            describedBy={describedBy}\n            held={held}\n          >\n            <DecorationCss\n              stored={typeof stored === \"string\" ? stored : undefined}\n              actionName={actionName}\n              describedBy={describedBy}\n              held={held}\n              onCommit={value => parts.writeCss(value, onCommit)}\n            />\n          </DecorationStyle>\n        </PopoverContent>\n      </Popover>\n    </div>\n  );\n}\n\n/**\n * The parts a change starts from, with the changes written but not yet back\n * in the stored value. A shared style's write lands later than the commit\n * that sent it, so a second part changed meanwhile would otherwise start from\n * the old value and undo the first. The queue follows the stored value: each\n * written value arriving is dropped from it, and any other change (an undo,\n * another author) or a refused write, at once or later, empties it.\n */\nfunction useQueuedParts(\n  stored: string | undefined,\n  base: DecorationParts | undefined,\n  refused: boolean\n): {\n  current: DecorationParts | undefined;\n  /** Whether a written value has yet to come back as the stored one. */\n  pending: boolean;\n  write: (\n    next: Partial<DecorationParts>,\n    onCommit: (value: StyleValue | null) => CommitOutcome\n  ) => CommitOutcome;\n  writeCss: (\n    value: string | null,\n    onCommit: (value: StyleValue | null) => CommitOutcome\n  ) => CommitOutcome;\n} {\n  const queue = React.useRef<{ value: string; parts: DecorationParts }[]>([]);\n  const [, rendered] = React.useReducer((count: number) => count + 1, 0);\n  const seen = React.useRef(stored);\n  if (seen.current !== stored) {\n    seen.current = stored;\n    const arrived = queue.current.findIndex(entry => entry.value === stored);\n    queue.current = arrived === -1 ? [] : queue.current.slice(arrived + 1);\n  }\n  // A refusal that arrives after the write (a shared style's) leaves the\n  // stored value as it was: what was queued will not arrive, so the queue\n  // empties and the controls show what the document holds.\n  if (refused) queue.current = [];\n  const current = queue.current.at(-1)?.parts ?? base;\n  /** Sends a value, queued as its parts when they can be read from it. */\n  const send = (\n    value: string | null,\n    parts: DecorationParts | undefined,\n    onCommit: (value: StyleValue | null) => CommitOutcome\n  ): CommitOutcome => {\n    const outcome = onCommit(value);\n    // A value the parts cannot hold (cleared, two lines) leaves the queue\n    // with nothing to start from, so the next part starts from what is stored.\n    queue.current =\n      outcome === \"applied\" && value !== null && parts !== undefined\n        ? [...queue.current, { value, parts }]\n        : [];\n    // Drawn again, so the controls show the part just written.\n    rendered();\n    return outcome;\n  };\n  const write = (\n    next: Partial<DecorationParts>,\n    onCommit: (value: StyleValue | null) => CommitOutcome\n  ): CommitOutcome => {\n    const parts = { line: current?.line ?? \"underline\", ...current, ...next };\n    return send(composeDecoration(parts), parts, onCommit);\n  };\n  // Written as CSS: queued too, so a part changed next keeps it.\n  const writeCss = (\n    value: string | null,\n    onCommit: (value: StyleValue | null) => CommitOutcome\n  ): CommitOutcome =>\n    send(value, value === null ? undefined : parseDecoration(value), onCommit);\n  return { current, pending: queue.current.length > 0, write, writeCss };\n}\n\n/**\n * A line style's words, each as the keyword it writes. Default writes none,\n * so the line takes CSS's own, solid; a select's item cannot carry an empty\n * value, so it carries this word, which no style is spelled as.\n */\nconst DEFAULT_STYLE = \"default\";\nconst STYLE_LABELS: Readonly<Record<string, string>> = {\n  [DEFAULT_STYLE]: \"Default\",\n  solid: \"Solid\",\n  double: \"Double\",\n  dotted: \"Dotted\",\n  dashed: \"Dashed\",\n  wavy: \"Wavy\",\n};\n\n/**\n * A draft that follows the value it edits: a stored change (an undo, a shared\n * style's update) moves it, so leaving the field never writes back the value\n * that change replaced. The inspector's one draft rule (`useStoredDraft`), so\n * Escape in the field puts an edit back here as in every other field.\n */\nfunction useDraft(value: string | undefined): [string, (next: string) => void] {\n  return useStoredDraft(value ?? \"\");\n}\n\n/**\n * The line's style, thickness and colour, offered once there is a line to\n * style. A thickness is written only once it is one CSS reads, and a colour\n * only as one; leaving either empty removes it.\n */\nfunction DecorationStyle({\n  parts,\n  write,\n  describedBy,\n  held,\n  children,\n}: {\n  parts: DecorationParts | undefined;\n  write: (next: Partial<DecorationParts>) => CommitOutcome;\n  describedBy: string | undefined;\n  /** Whether the section is held read-only. */\n  held: boolean;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const [thickness, setThickness] = useDraft(parts?.thickness);\n  const [color, setColor] = useDraft(parts?.color);\n  const disabled = held || parts === undefined || parts.line === \"none\";\n  const refusal = {\n    \"aria-describedby\": described,\n    \"aria-invalid\": describedBy === undefined ? undefined : true,\n  } as const;\n  const commitThickness = () => {\n    const text = thickness.trim();\n    if (text === (parts?.thickness ?? \"\")) return;\n    if (text !== \"\" && !isThickness(text)) return;\n    write({ thickness: text === \"\" ? undefined : text });\n  };\n  const commitColor = () => {\n    const text = color.trim();\n    if (text === (parts?.color ?? \"\")) return;\n    if (text !== \"\" && !isLineColor(text)) return;\n    write({ color: text === \"\" ? undefined : text });\n  };\n  return (\n    <div className=\"nx-style-inspector__decoration-parts\">\n      <label className=\"nx-style-inspector__decoration-part\">\n        <span>Line style</span>\n        <Select\n          value={parts?.style ?? DEFAULT_STYLE}\n          disabled={disabled}\n          onValueChange={style =>\n            write({ style: style === DEFAULT_STYLE ? undefined : style })\n          }\n        >\n          <SelectTrigger aria-label=\"Line style\" {...refusal}>\n            <SelectValue />\n          </SelectTrigger>\n          <SelectContent>\n            {Object.entries(STYLE_LABELS).map(([value, label]) => (\n              <SelectItem key={value} value={value}>\n                {label}\n              </SelectItem>\n            ))}\n          </SelectContent>\n        </Select>\n      </label>\n      <label className=\"nx-style-inspector__decoration-part\">\n        <span>Thickness</span>\n        <Input\n          aria-label=\"Thickness\"\n          {...refusal}\n          disabled={disabled}\n          placeholder=\"Auto\"\n          value={thickness}\n          onChange={event => setThickness(event.target.value)}\n          onBlur={commitThickness}\n          onKeyDown={event => commitOnEnter(event, commitThickness)}\n        />\n      </label>\n      <label className=\"nx-style-inspector__decoration-part\">\n        <span>Colour</span>\n        <Input\n          aria-label=\"Line colour\"\n          {...refusal}\n          disabled={disabled}\n          placeholder=\"Text colour\"\n          value={color}\n          onChange={event => setColor(event.target.value)}\n          onBlur={commitColor}\n          onKeyDown={event => commitOnEnter(event, commitColor)}\n        />\n      </label>\n      {children}\n    </div>\n  );\n}\n\n/**\n * The decoration as CSS, for what the icons cannot draw: two lines at once,\n * a variable. Written as typed once the author leaves the field; emptied, it\n * removes the decoration set here.\n */\nfunction DecorationCss({\n  stored,\n  actionName,\n  describedBy,\n  held,\n  onCommit,\n}: {\n  stored: string | undefined;\n  actionName: string;\n  describedBy: string | undefined;\n  held: boolean;\n  onCommit: (value: string | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const [text, setText] = useDraft(stored);\n  const commit = () => {\n    commitRawCss(text, stored, onCommit);\n  };\n  return (\n    <label className=\"nx-style-inspector__decoration-part\">\n      <span>Write as CSS</span>\n      <Input\n        aria-label={`${actionName} as CSS`}\n        aria-describedby={described}\n        aria-invalid={describedBy === undefined ? undefined : true}\n        disabled={held}\n        placeholder=\"underline overline\"\n        value={text}\n        onChange={event => setText(event.target.value)}\n        onBlur={commit}\n        onKeyDown={event => commitOnEnter(event, commit)}\n      />\n    </label>\n  );\n}\n","/**\n * Alignment and direction values as icons that follow the way content flows.\n *\n * The inspector sets `justify-content`, `align-items`, `align-content`,\n * `flex-direction`, `flex-wrap` and `text-align` with icon buttons rather than\n * a list of CSS words. An icon is a claim about direction, so it is chosen\n * from the container's flow: the main-axis icons stand upright in a column,\n * start and end change places along a reversed main axis, and a horizontal\n * start sits on the right of a right-to-left element.\n *\n * Only a property's primary values get an icon. The rest of what the\n * catalogue accepts (`safe center`, `flex-start`, `first baseline`, `normal`)\n * is returned as `rest`, for a list beside the icons, so every value stays\n * reachable and a stored rare one still shows.\n *\n * Pure, and it names icons by their lucide export rather than importing\n * them, so the mapping is asserted without a DOM.\n *\n * @module style-alignment-icons\n */\n\nimport {\n  BASE_BREAKPOINT,\n  type NodeStyles,\n  type StyleLeaf,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { SideOrientation } from \"../../styles/side-orientation\";\nimport { readStyleValue } from \"../../styles/style-values\";\n\nimport { keywordLabel } from \"./style-keyword-labels\";\n\n/** How the edited container lays its content out. */\nexport interface Flow {\n  /** The element's `writing-mode`: which way its lines run. */\n  readonly writingMode: string;\n  /** Whether its inline direction is right to left. */\n  readonly rtl: boolean;\n  /** Whether it is a flex container, so `flex-direction` and `flex-wrap` apply. */\n  readonly flex: boolean;\n  /** Its `flex-direction`, `row` when unset. */\n  readonly direction: string;\n}\n\n/** One icon button: the value it stores, its name, and the icon drawn. */\nexport interface AlignmentOption {\n  readonly value: string;\n  readonly label: string;\n  /** A lucide icon's export name. */\n  readonly icon: string;\n  /**\n   * A 2×2 matrix, `[a, b, c, d]` as CSS `matrix(a, b, c, d, 0, 0)` takes it,\n   * that maps the icon's own directions onto the container's. Absent when\n   * they already agree.\n   */\n  readonly matrix?: readonly [number, number, number, number];\n  /** Turned a quarter, for text that runs down the page. */\n  readonly rotated?: true;\n}\n\n/** A property's icon buttons, and the values it accepts that have none. */\nexport interface AlignmentGroup {\n  /** The CSS property, which the values beside the icons are named for. */\n  readonly cssProperty: string;\n  readonly options: readonly AlignmentOption[];\n  readonly rest: readonly string[];\n  /**\n   * What each value does, in a line under the icons, where an icon alone\n   * cannot say it: an image's fit. Absent where the icons are the whole story.\n   */\n  readonly help?: Readonly<Record<string, string>>;\n}\n\ntype Edge = \"left\" | \"right\" | \"top\" | \"bottom\";\n\n/** An axis on the screen: which way it runs, and the edge it starts from. */\ninterface Axis {\n  readonly horizontal: boolean;\n  readonly start: Edge;\n}\n\nconst OPPOSITE: Readonly<Record<Edge, Edge>> = {\n  left: \"right\",\n  right: \"left\",\n  top: \"bottom\",\n  bottom: \"top\",\n};\n\n/** The axis lines run along: across in horizontal writing, down otherwise. */\nfunction inlineAxis(flow: Flow): Axis {\n  if (flow.writingMode.startsWith(\"horizontal\")) {\n    return { horizontal: true, start: flow.rtl ? \"right\" : \"left\" };\n  }\n  const upward = flow.writingMode === \"sideways-lr\";\n  return {\n    horizontal: false,\n    start: upward !== flow.rtl ? \"bottom\" : \"top\",\n  };\n}\n\n/** The axis lines stack along: down the page, or across in vertical writing. */\nfunction blockAxis(flow: Flow): Axis {\n  if (flow.writingMode.startsWith(\"horizontal\")) {\n    return { horizontal: false, start: \"top\" };\n  }\n  return {\n    horizontal: true,\n    start: flow.writingMode.endsWith(\"-lr\") ? \"left\" : \"right\",\n  };\n}\n\n/**\n * The main and cross axes. A flex container's main axis is its inline axis in\n * a row and its block axis in a column; anything else aligns along its inline\n * and block axes, whatever flex values it still stores.\n *\n * Never reversed. CSS Box Alignment ties `start` and `end` to the writing\n * mode's edges, whatever the flex direction or wrap; only `flex-start` and\n * `flex-end` follow a reversed flow, and those are listed, not drawn.\n */\nfunction axesOf(flow: Flow): { main: Axis; cross: Axis; inline: Axis } {\n  const inline = inlineAxis(flow);\n  const block = blockAxis(flow);\n  if (!flow.flex || !flow.direction.startsWith(\"column\")) {\n    return { main: inline, cross: block, inline };\n  }\n  return { main: block, cross: inline, inline };\n}\n\n/** Whether an axis starts at the end its icons draw as start: left or top. */\nfunction natural(axis: Axis): boolean {\n  return axis.start === \"left\" || axis.start === \"top\";\n}\n\nconst ARROWS: Readonly<Record<Edge, string>> = {\n  right: \"ArrowRight\",\n  left: \"ArrowLeft\",\n  bottom: \"ArrowDown\",\n  top: \"ArrowUp\",\n};\n\n/** The icons whose start and end swap, both ways round. */\nconst MIRRORED: Readonly<Record<string, string>> = Object.fromEntries(\n  [\n    [\"AlignHorizontalJustifyStart\", \"AlignHorizontalJustifyEnd\"],\n    [\"AlignVerticalJustifyStart\", \"AlignVerticalJustifyEnd\"],\n    [\"AlignStartHorizontal\", \"AlignEndHorizontal\"],\n    [\"AlignStartVertical\", \"AlignEndVertical\"],\n    [\"AlignLeft\", \"AlignRight\"],\n  ].flatMap(([a, b]) => [\n    [a, b],\n    [b, a],\n  ])\n);\n\n/** An icon choice; its words come from the keyword labels, by its value. */\ninterface Entry {\n  readonly value: string;\n  /** The icon along a horizontal axis, and along a vertical one. */\n  readonly horizontal: string;\n  readonly vertical: string;\n}\n\nfunction entry(value: string, horizontal: string, vertical: string): Entry {\n  return { value, horizontal, vertical };\n}\n\n/** Which axis a property's values point along. */\ntype Along = \"main\" | \"cross\" | \"inline\";\n\nconst GROUPS: Readonly<\n  Record<string, { along: Along; entries: readonly Entry[] }>\n> = {\n  \"justify-content\": {\n    along: \"main\",\n    entries: [\n      entry(\n        \"start\",\n        \"AlignHorizontalJustifyStart\",\n        \"AlignVerticalJustifyStart\"\n      ),\n      entry(\n        \"center\",\n        \"AlignHorizontalJustifyCenter\",\n        \"AlignVerticalJustifyCenter\"\n      ),\n      entry(\"end\", \"AlignHorizontalJustifyEnd\", \"AlignVerticalJustifyEnd\"),\n      entry(\n        \"space-between\",\n        \"AlignHorizontalSpaceBetween\",\n        \"AlignVerticalSpaceBetween\"\n      ),\n    ],\n  },\n  // Items line up against an edge of the cross axis: along a vertical cross\n  // axis that edge is a horizontal line (top, middle, bottom).\n  \"align-items\": {\n    along: \"cross\",\n    entries: [\n      entry(\"start\", \"AlignStartVertical\", \"AlignStartHorizontal\"),\n      entry(\"center\", \"AlignCenterVertical\", \"AlignCenterHorizontal\"),\n      entry(\"end\", \"AlignEndVertical\", \"AlignEndHorizontal\"),\n      entry(\"stretch\", \"StretchHorizontal\", \"StretchVertical\"),\n      entry(\"baseline\", \"Baseline\", \"Baseline\"),\n    ],\n  },\n  \"align-content\": {\n    along: \"cross\",\n    entries: [\n      entry(\n        \"start\",\n        \"AlignHorizontalJustifyStart\",\n        \"AlignVerticalJustifyStart\"\n      ),\n      entry(\n        \"center\",\n        \"AlignHorizontalJustifyCenter\",\n        \"AlignVerticalJustifyCenter\"\n      ),\n      entry(\"end\", \"AlignHorizontalJustifyEnd\", \"AlignVerticalJustifyEnd\"),\n      entry(\n        \"space-between\",\n        \"AlignHorizontalSpaceBetween\",\n        \"AlignVerticalSpaceBetween\"\n      ),\n      entry(\"stretch\", \"StretchHorizontal\", \"StretchVertical\"),\n    ],\n  },\n  \"text-align\": {\n    along: \"inline\",\n    entries: [\n      entry(\"start\", \"AlignLeft\", \"AlignLeft\"),\n      entry(\"center\", \"AlignCenter\", \"AlignCenter\"),\n      entry(\"end\", \"AlignRight\", \"AlignRight\"),\n      entry(\"justify\", \"AlignJustify\", \"AlignJustify\"),\n    ],\n  },\n};\n\n/**\n * Choices whose icons say what a value is rather than which way it points, so\n * they are drawn the same in every flow: Display, text case and an image's\n * fit. `help` says what each value does, where its icon cannot.\n *\n * `more` is what the list beside the icons offers. A value the catalog accepts\n * and neither names, a table or ruby display mode or a two-keyword spelling, is\n * not offered, since the icons and the list cover what a layout reaches for;\n * one already stored still shows, as the field lists any value it does not\n * carry.\n */\nconst FIXED_GROUPS: Readonly<\n  Record<\n    string,\n    {\n      entries: readonly { value: string; icon: string }[];\n      more: readonly string[];\n      help?: Readonly<Record<string, string>>;\n    }\n  >\n> = {\n  display: {\n    entries: [\n      { value: \"block\", icon: \"RectangleHorizontal\" },\n      { value: \"flex\", icon: \"Columns3\" },\n      { value: \"grid\", icon: \"Grid2x2\" },\n      { value: \"none\", icon: \"EyeOff\" },\n    ],\n    more: [\n      \"inline\",\n      \"inline-block\",\n      \"inline-flex\",\n      \"inline-grid\",\n      \"flow-root\",\n      \"list-item\",\n    ],\n  },\n  \"text-transform\": {\n    entries: [\n      { value: \"none\", icon: \"Minus\" },\n      { value: \"uppercase\", icon: \"CaseUpper\" },\n      { value: \"lowercase\", icon: \"CaseLower\" },\n      { value: \"capitalize\", icon: \"CaseSensitive\" },\n    ],\n    more: [\"math-auto\", \"full-width\", \"full-size-kana\"],\n  },\n  // Cover first: the fit most images want. Original size and Shrink to fit\n  // are rarer, and wait under More.\n  \"object-fit\": {\n    entries: [\n      { value: \"cover\", icon: \"Crop\" },\n      { value: \"contain\", icon: \"Shrink\" },\n      { value: \"fill\", icon: \"StretchHorizontal\" },\n    ],\n    more: [\"none\", \"scale-down\"],\n    help: {\n      cover: \"Fills the box; edges may be cut.\",\n      contain: \"Shows all of it inside the box.\",\n      fill: \"Stretches it to the box's shape.\",\n      none: \"Shows it at its own size, cut to the box.\",\n      \"scale-down\": \"Shows all of it, never larger than it is.\",\n    },\n  },\n};\n\n/** A fixed group's icons and list, kept to the values the property accepts. */\nfunction fixedGroup(\n  cssProperty: string,\n  group: (typeof FIXED_GROUPS)[string],\n  values: readonly string[]\n): AlignmentGroup {\n  return {\n    cssProperty,\n    options: group.entries\n      .filter(entry => values.includes(entry.value))\n      .map(entry => ({\n        ...entry,\n        // In the words every keyword is offered in; see style-keyword-labels.\n        label: keywordLabel(cssProperty, entry.value),\n      })),\n    rest: group.more.filter(value => values.includes(value)),\n    ...(group.help === undefined ? {} : { help: group.help }),\n  };\n}\n\n/** The four directions, each an arrow the way it runs on the screen. */\nfunction directionOptions(\n  values: readonly string[],\n  flow: Flow\n): AlignmentOption[] {\n  const inline = inlineAxis(flow);\n  const block = blockAxis(flow);\n  const options: AlignmentOption[] = [\n    { value: \"row\", icon: ARROWS[OPPOSITE[inline.start]] },\n    { value: \"row-reverse\", icon: ARROWS[inline.start] },\n    { value: \"column\", icon: ARROWS[OPPOSITE[block.start]] },\n    { value: \"column-reverse\", icon: ARROWS[block.start] },\n  ].map(option => ({\n    ...option,\n    label: keywordLabel(\"flex-direction\", option.value),\n  }));\n  return options.filter(option => values.includes(option.value));\n}\n\n/** A unit vector on the screen, x to the right and y down, toward an edge. */\nconst TOWARD: Readonly<Record<Edge, readonly [number, number]>> = {\n  right: [1, 0],\n  left: [-1, 0],\n  bottom: [0, 1],\n  top: [0, -1],\n};\n\n/**\n * The wrap icons. Their lines run right and wrap downward, so each carries\n * the matrix mapping those two directions onto the container's: its main\n * direction, reversed by a reversed flex direction, and the way its lines\n * advance, the cross axis's start to end, or the other way for wrap-reverse.\n */\nfunction wrapOptions(values: readonly string[], flow: Flow): AlignmentOption[] {\n  const { main, cross } = axesOf(flow);\n  // Reversed only where the flex direction chose the axes: a block or grid\n  // keeps a stored direction it no longer lays out by.\n  const mainStart =\n    flow.flex && flow.direction.endsWith(\"-reverse\")\n      ? OPPOSITE[main.start]\n      : main.start;\n  const runs = TOWARD[OPPOSITE[mainStart]];\n  const matrixFor = (advanceToward: Edge) => {\n    const advances = TOWARD[advanceToward];\n    const matrix = [runs[0], runs[1], advances[0], advances[1]] as const;\n    return matrix.join(\",\") === \"1,0,0,1\" ? {} : { matrix };\n  };\n  const forward = matrixFor(OPPOSITE[cross.start]);\n  const options: AlignmentOption[] = [\n    { value: \"nowrap\", icon: \"ArrowRightToLine\", ...forward },\n    { value: \"wrap\", icon: \"WrapText\", ...forward },\n    { value: \"wrap-reverse\", icon: \"WrapText\", ...matrixFor(cross.start) },\n  ].map(option => ({\n    ...option,\n    label: keywordLabel(\"flex-wrap\", option.value),\n  }));\n  return options.filter(option => values.includes(option.value));\n}\n\n/** The icon buttons for one aligned property, in this flow. */\nfunction alignedOptions(\n  property: string,\n  group: { along: Along; entries: readonly Entry[] },\n  values: readonly string[],\n  flow: Flow\n): AlignmentOption[] {\n  const axis = axesOf(flow)[group.along];\n  const swap = !natural(axis);\n  // Text running down the page draws the horizontal icons turned a quarter.\n  const rotated = group.along === \"inline\" && !axis.horizontal;\n  return group.entries\n    .filter(candidate => values.includes(candidate.value))\n    .map(candidate => {\n      const drawn =\n        axis.horizontal || rotated ? candidate.horizontal : candidate.vertical;\n      return {\n        value: candidate.value,\n        // In the words every keyword is offered in; see style-keyword-labels.\n        label: keywordLabel(property, candidate.value),\n        icon: swap ? (MIRRORED[drawn] ?? drawn) : drawn,\n        ...(rotated ? { rotated: true as const } : {}),\n      };\n    });\n}\n\n/**\n * The icon buttons for a CSS property's values, in the inspector's order,\n * with the accepted values that have no icon; `undefined` for a property not\n * drawn as icons.\n */\nexport function alignmentGroupFor(\n  cssProperty: string,\n  values: readonly string[],\n  flow: Flow\n): AlignmentGroup | undefined {\n  const fixed = FIXED_GROUPS[cssProperty];\n  if (fixed !== undefined && Object.hasOwn(FIXED_GROUPS, cssProperty)) {\n    return fixedGroup(cssProperty, fixed, values);\n  }\n  let options: AlignmentOption[];\n  if (cssProperty === \"flex-direction\") {\n    options = directionOptions(values, flow);\n  } else if (cssProperty === \"flex-wrap\") {\n    options = wrapOptions(values, flow);\n  } else if (Object.hasOwn(GROUPS, cssProperty)) {\n    const group = GROUPS[cssProperty];\n    if (group === undefined) return undefined;\n    options = alignedOptions(cssProperty, group, values, flow);\n  } else {\n    return undefined;\n  }\n  const iconed = new Set(options.map(option => option.value));\n  return {\n    cssProperty,\n    options,\n    rest: values.filter(value => !iconed.has(value)),\n  };\n}\n\n/**\n * The flow of the container being edited.\n *\n * As the canvas lays it out, when the element was measured: that answers for\n * a class, an intermediate breakpoint and a grid alike, which storage alone\n * cannot. Otherwise from what the node stores where the author is editing\n * (this state, this breakpoint), else the nearest wider place, else CSS's\n * defaults: a row, in no flex container, written left to right.\n *\n * @param styles - the node's stored styles, the fallback\n * @param state - the edited state\n * @param breakpoint - the edited breakpoint\n * @param measured - the element's computed axes and layout, when known\n */\nexport function flowOf(\n  styles: NodeStyles | undefined,\n  state: StyleState,\n  breakpoint: string,\n  measured: SideOrientation | undefined\n): Flow {\n  const at = (property: string) => {\n    const read = (where: StyleState, tier: string) =>\n      readStyleValue(styles, {\n        state: where,\n        breakpoint: tier,\n        property,\n        path: [],\n      });\n    const value =\n      read(state, breakpoint) ??\n      read(\"base\", breakpoint) ??\n      read(state, BASE_BREAKPOINT) ??\n      read(\"base\", BASE_BREAKPOINT);\n    return typeof value === \"string\" ? value : undefined;\n  };\n  const display = measured?.display ?? at(\"display\") ?? \"\";\n  return {\n    writingMode: measured?.writingMode ?? \"horizontal-tb\",\n    rtl: measured?.direction === \"rtl\",\n    flex: display === \"flex\" || display === \"inline-flex\",\n    direction: measured?.flexDirection ?? at(\"flexDirection\") ?? \"row\",\n  };\n}\n\n/**\n * Whether a leaf is drawn as icons in any flow: a keyword of one of the\n * properties above. What a label asks to decide how to point at its control.\n */\nexport function drawsIcons(leaf: StyleLeaf): boolean {\n  if (leaf.kind !== \"keyword\") return false;\n  const property = leaf.cssProperty;\n  return (\n    property === \"flex-direction\" ||\n    property === \"flex-wrap\" ||\n    Object.hasOwn(GROUPS, property) ||\n    Object.hasOwn(FIXED_GROUPS, property)\n  );\n}\n","\"use client\";\n\n/**\n * The value controls a variable's editor draws, one for each kind of value.\n *\n * A size is the block panel's own numeric field, a number beside its unit\n * menu, so a length is edited the same way wherever it is set. A line height\n * is a plain number read as a multiple of the text size, with an offer of\n * pixels when the number is too large to be meant as a multiple. Anything\n * else is a text field. Every field commits on blur or Enter, never per\n * keystroke, because a variable is read by the whole site. Given `onPreview`,\n * what is typed, picked or pointed at meanwhile is offered to be drawn on the\n * canvas, and the end of the edit is said before its one commit.\n *\n * @module variable-value-controls\n */\nimport {\n  emitTokenBlocks,\n  getStyleProperty,\n  resolveTokenPrefix,\n  tokenCustomProperty,\n  tokenIdentity,\n  type SiteToken,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Input,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectSeparator,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { isInput } from \"../../canvas/dom-kind\";\nimport { InheritedValue } from \"../../inspector/style-inspector/inherited-value\";\nimport {\n  TypesLiveContext,\n  type CommitOutcome,\n} from \"../../inspector/style-inspector/style-field-surroundings\";\nimport { NumericField } from \"../../inspector/style-inspector/style-numeric-field\";\nimport {\n  styleControlsFor,\n  type StyleControl,\n} from \"../../styles/style-controls\";\nimport { CSS_NUMBER, lineHeightAsPixels } from \"../../styles/style-numeric\";\n\nimport { FontChoicesContext, FontFamilyField } from \"./font-family-field\";\nimport { NAMED_WEIGHTS, weightName, weightsDrawn } from \"./font-library\";\nimport { typeScaleProperty } from \"./tokens-studio\";\n\n/** What every value field is given. */\nexport interface ValueFieldProps {\n  label: string;\n  value: string;\n  readOnly: boolean;\n  /** The id of the reason, while this field holds a value that was refused. */\n  refusedBy?: string | undefined;\n  onCommit: (value: string) => void;\n  /**\n   * Draws a value on the canvas while it is typed or picked, before the one\n   * write the edit ends with; `null` once the edit ends, said before that\n   * write. Absent, a field only commits.\n   */\n  onPreview?: ((text: string | null) => void) | undefined;\n  /**\n   * The CSS this value writes, shown on hover over a control that writes it\n   * in other words: a number and a unit menu.\n   */\n  css?: string | undefined;\n  /** Which of the variable's values this field edits. */\n  mode?: \"light\" | \"dark\";\n  /** What an empty field shows: what CSS draws with nothing set. */\n  placeholder?: string | undefined;\n}\n\n/**\n * The declaration a variable's value writes into the site's stylesheet: its\n * custom property, under the site's prefix, and the value. Named by the\n * engine's own rules, the ones the stylesheet is written with.\n */\nexport function variableCss(\n  tokens: SiteTokenSet,\n  token: SiteToken,\n  value: string\n): string {\n  const { prefix } = resolveTokenPrefix(tokens.prefix);\n  return `${tokenCustomProperty(tokenIdentity(token), prefix)}: ${value}`;\n}\n\n/**\n * Closes the variable's editor for a control that sends the author elsewhere\n * in the panel, such as a font's \"Manage fonts…\", without handing focus back\n * to the row: the place the author is sent to takes it. Absent outside an\n * editor.\n */\nexport const CloseVariableEditor: React.Context<(() => void) | undefined> =\n  React.createContext<(() => void) | undefined>(undefined);\n\n/**\n * Where a variable's editor hands a value to draw on the canvas before it is\n * written: the whole set with the value in it, or `null` to draw what is\n * stored again. The host draws it without storing it, since a variable is\n * read by the whole site and a write per keystroke would publish half-typed\n * values. Absent, nothing is drawn until the value is written.\n */\nexport const VariablePreview: React.Context<\n  ((tokens: SiteTokenSet | null) => void) | undefined\n> = React.createContext<((tokens: SiteTokenSet | null) => void) | undefined>(\n  undefined\n);\n\n/**\n * What a field shows: the author's typing, until the stored value changes\n * underneath it (a reset, a refused save, an undo), which replaces it.\n *\n * A field keyed by its value would do the second by remounting, and would\n * then also remount after its own commit and drop the focus it had.\n */\nexport function useDraft(value: string): [string, (next: string) => void] {\n  const [draft, setDraft] = React.useState(value);\n  const [shown, setShown] = React.useState(value);\n  if (shown !== value) {\n    setShown(value);\n    setDraft(value);\n  }\n  return [draft, setDraft];\n}\n\n/** A text field that commits when it loses focus or on Enter. */\nfunction TextValue({\n  label,\n  value,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n}: ValueFieldProps): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <label className=\"nx-vars-editor__label\" htmlFor={id}>\n        {label}\n      </label>\n      <CommitInput\n        id={id}\n        value={value}\n        readOnly={readOnly}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n        onPreview={onPreview}\n      />\n    </div>\n  );\n}\n\n/**\n * A value field that commits on blur or Enter, and only a real change: an\n * empty field or the value it already holds writes nothing. While it holds a\n * refused value, the value it held before is committed too, since putting it\n * back is how the author answers the refusal. A text style's letter\n * spacing is typed in one too.\n *\n * Given `onPreview`, each keystroke is offered to be drawn, and the end of\n * the edit is said before its commit, so the host draws what is stored again\n * when the edit writes nothing.\n */\nexport function CommitInput({\n  id,\n  label,\n  value,\n  placeholder,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n}: {\n  id?: string;\n  /** The field's name where no visible label points at it. */\n  label?: string;\n  value: string;\n  placeholder?: string;\n  readOnly: boolean;\n  refusedBy?: string | undefined;\n  onCommit: (value: string) => void;\n  onPreview?: ((text: string | null) => void) | undefined;\n}): React.JSX.Element {\n  const [draft, setDraft] = useDraft(value);\n  const commit = (next: string): void => {\n    onPreview?.(null);\n    if (\n      !readOnly &&\n      next.trim() !== \"\" &&\n      (next.trim() !== value || refusedBy !== undefined)\n    ) {\n      onCommit(next);\n    }\n  };\n  return (\n    <Input\n      id={id}\n      aria-label={label}\n      // A value, not words: no list of earlier entries over the field.\n      autoComplete=\"off\"\n      aria-invalid={refusedBy === undefined ? undefined : true}\n      aria-describedby={refusedBy}\n      className=\"nx-vars-editor__mono\"\n      value={draft}\n      placeholder={placeholder}\n      onChange={event => {\n        setDraft(event.currentTarget.value);\n        if (!readOnly) onPreview?.(event.currentTarget.value);\n      }}\n      readOnly={readOnly}\n      onBlur={event => commit(event.currentTarget.value)}\n      onKeyDown={event => {\n        if (event.key === \"Enter\") commit(event.currentTarget.value);\n      }}\n    />\n  );\n}\n\n/**\n * The control every size is edited with: a padding side's, a length with no\n * keywords that takes every unit a size variable is written in, widened to a\n * negative, which a size variable may hold for a margin or an offset. One\n * leaf for every size, so each one's menu is the same and offers what the\n * block panel offers for a length, and a negative keeps its unit like any\n * other number.\n */\nconst SIZE_CONTROL: StyleControl | undefined = sizeControl();\n\nfunction sizeControl(): StyleControl | undefined {\n  const padding = getStyleProperty(\"padding\");\n  if (padding === undefined) return undefined;\n  const side = styleControlsFor(padding).controls.find(\n    control => control.leaf.kind === \"dimension\"\n  );\n  if (side === undefined || side.leaf.kind !== \"dimension\") return undefined;\n  return { ...side, leaf: { ...side.leaf, allowNegative: true } };\n}\n\n/**\n * The control every number is edited with: a flex grow's, a plain number,\n * widened past its floor of zero, since a number variable may be read by any\n * property that takes one. The block panel draws numbers with the same field.\n */\nconst NUMBER_CONTROL: StyleControl | undefined = numberControl();\n\nfunction numberControl(): StyleControl | undefined {\n  const grow = getStyleProperty(\"flexGrow\");\n  if (grow === undefined) return undefined;\n  const control = styleControlsFor(grow).controls.find(\n    candidate => candidate.leaf.kind === \"number\"\n  );\n  if (control === undefined || control.leaf.kind !== \"number\") return undefined;\n  const leaf = { ...control.leaf };\n  delete leaf.min;\n  return { ...control, leaf };\n}\n\n/**\n * Why a value cannot be written into the site's stylesheet, in the words the\n * stylesheet's own writer uses, or nothing when it can. Asked of the writer\n * itself, with the variable alone, so the field refuses exactly what the\n * site's save would refuse: a value that would load a file, among others.\n */\nexport function unwritableValue(\n  tokens: SiteTokenSet,\n  token: SiteToken,\n  value: string\n): string | undefined {\n  const alone: SiteTokenSet = {\n    tokens: [{ ...token, values: { light: value } }],\n    ...(tokens.prefix === undefined ? {} : { prefix: tokens.prefix }),\n  };\n  const { emitted, issues } = emitTokenBlocks(alone, \":root\");\n  if (emitted.length > 0) return undefined;\n  return (\n    issues.find(issue => issue.severity === \"error\")?.message ??\n    \"This value cannot be used.\"\n  );\n}\n\n/**\n * Whether a field's text is the stored value again, as a field shows a value\n * it cannot split into a number and a unit (`clamp(…)`). The numeric field\n * writes nothing for that, since nothing changed, so a refusal standing over\n * the field is answered here instead.\n */\nfunction restoresStored(text: string, value: string): boolean {\n  return text.trim() === value.trim();\n}\n\n/**\n * What a size field's commit does: a real change is written, and anything\n * else, a cleared field or the value already held, writes nothing. A refused\n * value is written again when it is put back, as a text field does.\n */\nfunction sizeCommit(\n  value: string,\n  refusedBy: string | undefined,\n  onCommit: (value: string) => void\n): (next: unknown) => CommitOutcome {\n  return next => {\n    // A number field commits a number, which a variable stores as text.\n    const text = typeof next === \"number\" ? String(next) : next;\n    if (typeof text !== \"string\" || text.trim() === \"\") return \"unchanged\";\n    const typed = text.trim();\n    if (typed === value && refusedBy === undefined) return \"unchanged\";\n    onCommit(typed);\n    return \"applied\";\n  };\n}\n\n/**\n * A numeric field's typed or dragged value handed to a variable's preview,\n * as text, which judges it as the write would: one it would refuse is not\n * drawn, so the canvas keeps the last valid value. An emptied field draws\n * nothing new; it is a value only once the field is left.\n */\nfunction previewOf(\n  onPreview: (text: string | null) => void\n): (next: unknown) => CommitOutcome {\n  return next => {\n    const text = typeof next === \"number\" ? String(next) : next;\n    if (typeof text !== \"string\" || text.trim() === \"\") return \"unchanged\";\n    onPreview(text.trim());\n    return \"applied\";\n  };\n}\n\n/**\n * A size with its unit menu and no visible label of its own, for a layout\n * that names its columns, such as a type size's pair. Read-only, it is the\n * plain field, which still lets a value be selected and copied.\n */\nexport function SizeInput({\n  label,\n  value,\n  placeholder,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n  css,\n}: Omit<ValueFieldProps, \"label\"> & {\n  label: string;\n  /** What shows in an empty field: the light value, for a dark one. */\n  placeholder?: string;\n}): React.JSX.Element {\n  const id = React.useId();\n  if (readOnly || SIZE_CONTROL === undefined) {\n    return (\n      <CommitInput\n        label={label}\n        value={value}\n        readOnly={readOnly}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n        {...(placeholder === undefined ? {} : { placeholder })}\n      />\n    );\n  }\n  return (\n    <>\n      <label className=\"nx-sr-only\" htmlFor={id}>\n        {label}\n      </label>\n      <SizeField\n        id={id}\n        label={label}\n        value={value}\n        placeholder={placeholder}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n        onPreview={onPreview}\n        control={SIZE_CONTROL}\n        css={css}\n      />\n    </>\n  );\n}\n\n/**\n * A size under its own label, as a variable's Light and Dark are laid out,\n * and as a shadow layer's offsets, blur and spread are.\n */\nexport function SizeValue(props: ValueFieldProps): React.JSX.Element {\n  return <NumericValue {...props} control={SIZE_CONTROL} />;\n}\n\n/** A number under its own label: the numeric field, with no unit to choose. */\nfunction NumberValue(props: ValueFieldProps): React.JSX.Element {\n  return <NumericValue {...props} control={NUMBER_CONTROL} />;\n}\n\n/**\n * The block panel's numeric field under a label, over a variable's value.\n * Read-only, or without a control to draw, the plain field.\n */\nfunction NumericValue({\n  label,\n  value,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n  css,\n  control,\n  placeholder,\n}: ValueFieldProps & { control: StyleControl | undefined }): React.JSX.Element {\n  const id = React.useId();\n  if (readOnly || control === undefined) {\n    return (\n      <TextValue\n        label={label}\n        value={value}\n        readOnly={readOnly}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <label className=\"nx-vars-editor__label\" htmlFor={id}>\n        {label}\n      </label>\n      <SizeField\n        id={id}\n        label={label}\n        value={value}\n        placeholder={placeholder}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n        onPreview={onPreview}\n        control={control}\n        css={css}\n      />\n    </div>\n  );\n}\n\n/** A duration as a number and its unit, `200ms` or `0.2s`. */\nconst DURATION = /^\\s*([+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+))(ms|s)\\s*$/i;\n\n/** The units a duration is offered in. */\nconst DURATION_UNITS = [\"ms\", \"s\"] as const;\n\n/** A typed duration: a bare number takes the unit on screen. */\nfunction durationOf(typed: string, unit: string): string {\n  const text = typed.trim();\n  return CSS_NUMBER.test(text) ? `${text}${unit}` : text;\n}\n\n/**\n * A draft in another unit: a duration typed with its own unit (`200s`) takes\n * the one chosen, as a bare number does. Anything else stays as typed, so a\n * refused draft is still refused.\n */\nfunction durationInUnit(draft: string, unit: string): string {\n  const typed = DURATION.exec(draft);\n  return durationOf(typed?.[1] ?? draft, unit);\n}\n\n/**\n * A duration field's draft: the author's typing, until the stored value\n * changes, number or unit, which replaces it with the stored number. Keyed on\n * the whole value, so `200s` stored over `200ms` resets a draft that still\n * reads `200s`; a refused draft is never stored, so it stays as typed.\n */\nfunction useDurationDraft(\n  value: string,\n  number: string\n): [string, (next: string) => void] {\n  const [draft, setDraft] = React.useState(number);\n  const [shown, setShown] = React.useState(value);\n  if (shown !== value) {\n    setShown(value);\n    setDraft(number);\n  }\n  return [draft, setDraft];\n}\n\n/**\n * A duration: a number with a menu of ms and s. The number box and the menu\n * share one draft, so the menu changes the unit of the number on screen,\n * typed or refused, never of the value stored before it; a refused draft\n * stays refused until it is corrected. A value it cannot split into the two,\n * such as `var(…)`, is edited whole as text, and so is a read-only one.\n */\nfunction DurationValue(props: ValueFieldProps): React.JSX.Element {\n  const { label, value, readOnly, refusedBy, onCommit, onPreview } = props;\n  const id = React.useId();\n  const parts = DURATION.exec(value);\n  const number = parts?.[1] ?? \"\";\n  const unit = (parts?.[2] ?? \"ms\").toLowerCase();\n  const [draft, setDraft] = useDurationDraft(value, number);\n  if (readOnly || parts === null) return <TextValue {...props} />;\n  const commit = (text: string): void => {\n    // The edit is over, written or not.\n    onPreview?.(null);\n    const typed = text.trim();\n    if (typed === \"\" || (typed === number && refusedBy === undefined)) return;\n    onCommit(durationOf(typed, unit));\n  };\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <label className=\"nx-vars-editor__label\" htmlFor={id}>\n        {label}\n      </label>\n      <div className=\"nx-vars-editor__duration\">\n        <Input\n          id={id}\n          autoComplete=\"off\"\n          aria-invalid={refusedBy === undefined ? undefined : true}\n          aria-describedby={refusedBy}\n          className=\"nx-vars-editor__mono\"\n          value={draft}\n          onChange={event => {\n            const typed = event.currentTarget.value;\n            setDraft(typed);\n            // Drawn as it would be written: a bare number in the unit shown.\n            if (typed.trim() !== \"\") onPreview?.(durationOf(typed, unit));\n          }}\n          onBlur={event => commit(event.currentTarget.value)}\n          onKeyDown={event => {\n            if (event.key === \"Enter\") commit(event.currentTarget.value);\n          }}\n        />\n        <Select\n          value={unit}\n          onValueChange={next => {\n            onPreview?.(null);\n            if (next !== unit || draft.trim() !== number) {\n              onCommit(durationInUnit(draft, next));\n            }\n          }}\n        >\n          <SelectTrigger\n            className=\"nx-vars-editor__duration-unit\"\n            aria-label={`Unit for ${label}`}\n          >\n            <SelectValue />\n          </SelectTrigger>\n          <SelectContent>\n            {DURATION_UNITS.map(choice => (\n              <SelectItem key={choice} value={choice}>\n                {choice}\n              </SelectItem>\n            ))}\n          </SelectContent>\n        </Select>\n      </div>\n    </div>\n  );\n}\n\n/**\n * The block panel's numeric field over a variable's value.\n *\n * Given `onPreview`, the field types live as a block's own fields do, but\n * what it types is handed to the preview rather than written: the field's\n * keystrokes and its label's drag (`NumericField`'s `onType`). Every commit\n * says the edit is over first, so the canvas draws what is stored again when\n * the commit writes nothing.\n */\nfunction SizeField({\n  id,\n  label,\n  value,\n  placeholder,\n  refusedBy,\n  onCommit,\n  onPreview,\n  control,\n  css,\n}: {\n  id: string;\n  label: string;\n  value: string;\n  placeholder: string | undefined;\n  refusedBy: string | undefined;\n  onCommit: (value: string) => void;\n  onPreview?: ((text: string | null) => void) | undefined;\n  control: StyleControl;\n  css: string | undefined;\n}): React.JSX.Element {\n  // Putting back what the field stored is how an author answers a refusal.\n  const restore = (event: React.SyntheticEvent): void => {\n    const field = event.target;\n    // Asked by node kind, never `instanceof`: the canvas is a frame, and a\n    // constructor from this window answers false for an element from another.\n    if (refusedBy === undefined || !isInput(field)) return;\n    if (restoresStored(field.value, value)) onCommit(value);\n  };\n  const commit = sizeCommit(value, refusedBy, onCommit);\n  const field = (\n    <NumericField\n      id={id}\n      control={control}\n      stored={value === \"\" ? undefined : value}\n      actionName={label}\n      // No site variables offered: a variable holds a value of its own.\n      tokens={undefined}\n      describedBy={refusedBy}\n      onCommit={\n        onPreview === undefined\n          ? commit\n          : next => {\n              onPreview(null);\n              return commit(next);\n            }\n      }\n      {...(onPreview === undefined ? {} : { onType: previewOf(onPreview) })}\n    />\n  );\n  return (\n    // The light value shows as the empty dark field's hint, as a value\n    // reaching a block's field from elsewhere shows in the block panel.\n    <InheritedValue.Provider value={placeholder}>\n      <div\n        className=\"nx-vars-editor__size\"\n        title={css}\n        onKeyDownCapture={event => {\n          if (event.key === \"Enter\") restore(event);\n        }}\n        onBlurCapture={restore}\n      >\n        {onPreview === undefined ? (\n          field\n        ) : (\n          <TypesLiveContext.Provider value={true}>\n            {field}\n          </TypesLiveContext.Provider>\n        )}\n      </div>\n    </InheritedValue.Provider>\n  );\n}\n\n/**\n * A line height: a plain number, a multiple of the text size, marked \"×\"\n * while it is one. A typed unit is taken as it is.\n */\nexport function LineHeightInput({\n  id,\n  label,\n  value,\n  placeholder,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n}: Omit<ValueFieldProps, \"label\"> & {\n  /** The field's name where no visible label points at it. */\n  label: string | undefined;\n  id?: string;\n  placeholder?: string;\n}): React.JSX.Element {\n  const times = CSS_NUMBER.test((value === \"\" ? placeholder : value) ?? \"\");\n  return (\n    <span className=\"nx-vars-editor__times\">\n      <CommitInput\n        {...(id === undefined ? {} : { id })}\n        {...(label === undefined ? {} : { label })}\n        value={value}\n        readOnly={readOnly}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n        onPreview={onPreview}\n        {...(placeholder === undefined ? {} : { placeholder })}\n      />\n      {times ? (\n        <span\n          className=\"nx-vars-editor__times-mark\"\n          title=\"Times the text size\"\n        >\n          ×\n        </span>\n      ) : null}\n    </span>\n  );\n}\n\n/**\n * The offer under a line height whose number reads as pixels: what it means\n * as it is, and the pixels it was probably meant as, in one press.\n *\n * A dark value takes the kind of its light one, so a dark line height cannot\n * become pixels while the light one is a multiple: there the hint says what\n * to change first rather than offering a press that would be refused.\n */\nexport function LineHeightHint({\n  value,\n  mode,\n  readOnly,\n  onCommit,\n}: {\n  value: string;\n  mode: \"light\" | \"dark\";\n  readOnly: boolean;\n  onCommit: (value: string) => void;\n}): React.JSX.Element | null {\n  const pixels = lineHeightAsPixels(value);\n  if (pixels === undefined) return null;\n  const number = value.trim();\n  if (mode === \"dark\") {\n    return (\n      <div className=\"nx-vars-editor__hint\" role=\"note\">\n        <span>\n          {`${number}× the text size. To use pixels, give the light line height pixels first.`}\n        </span>\n      </div>\n    );\n  }\n  return (\n    <div className=\"nx-vars-editor__hint\" role=\"note\">\n      <span>{`${number}× the text size. Did you mean ${pixels}?`}</span>\n      {readOnly ? null : (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button\"\n          onClick={() => onCommit(pixels)}\n        >\n          {`Use ${pixels}`}\n        </Button>\n      )}\n    </div>\n  );\n}\n\n/**\n * The field a variable's Light and Dark values are edited with, for any\n * kind but a colour, which has its swatch and picker.\n */\nexport function valueFieldFor(\n  token: SiteToken\n): (props: ValueFieldProps) => React.JSX.Element {\n  // A line height before a size: one stored as a length is still a line\n  // height, and a number typed over it means a multiple, never a length.\n  if (typeScaleProperty(token) === \"line-height\") return LineHeightValue;\n  return KIND_FIELDS[token.kind] ?? TextValue;\n}\n\n/** The field each kind with one of its own is edited with. */\nconst KIND_FIELDS: Partial<\n  Record<SiteToken[\"kind\"], (props: ValueFieldProps) => React.JSX.Element>\n> = {\n  dimension: SizeValue,\n  number: NumberValue,\n  duration: DurationValue,\n  fontFamily: FontValue,\n  fontWeight: WeightValue,\n};\n\n/**\n * A font variable: chosen from the families the site has files for and the\n * system's, never typed, ending with the way to the site's fonts. The block\n * panel's own Font control, without its font variables, since a variable\n * holds a family of its own. Read-only, the stored family as text.\n */\nfunction FontValue({\n  label,\n  value,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n}: ValueFieldProps): React.JSX.Element {\n  const fonts = React.useContext(FontChoicesContext);\n  const id = React.useId();\n  const manage = useManageFonts(fonts?.onManageFonts);\n  if (readOnly) {\n    return (\n      <TextValue\n        label={label}\n        value={value}\n        readOnly\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\" id={`${id}-label`}>\n        {label}\n      </span>\n      <FontFamilyField\n        id={id}\n        labelledBy={`${id}-label`}\n        stored={value === \"\" ? undefined : value}\n        tokens={undefined}\n        faces={fonts?.faces}\n        fromCode={fonts?.fromCode ?? []}\n        onCommit={next => {\n          if (typeof next === \"string\" && next !== value) onCommit(next);\n        }}\n        // The family under the keyboard or the pointer is drawn on the\n        // canvas while the list is open; closing it ends that.\n        {...(onPreview === undefined\n          ? {}\n          : {\n              onPreview: (next: unknown) => {\n                if (next === null) onPreview(null);\n                else if (typeof next === \"string\") onPreview(next);\n              },\n            })}\n        {...(manage === undefined ? {} : { onManageFonts: manage })}\n      />\n    </div>\n  );\n}\n\n/**\n * The way to the site's fonts from a font variable: the variable's editor\n * closes first, since it is a dialog over the panel the author is sent to.\n */\nfunction useManageFonts(\n  manage: (() => void) | undefined\n): (() => void) | undefined {\n  const close = React.useContext(CloseVariableEditor);\n  if (manage === undefined) return undefined;\n  return () => {\n    close?.();\n    manage();\n  };\n}\n\n/**\n * The named weights in the order a weight menu lists them: those some face on\n * the site draws, then the rest, each list lightest first. All of them, in\n * order, while the site's fonts are not known.\n */\nfunction weightOrder(drawn: ReadonlySet<number> | undefined): {\n  ours: readonly number[];\n  others: readonly number[];\n} {\n  if (drawn === undefined) return { ours: NAMED_WEIGHTS, others: [] };\n  return {\n    ours: NAMED_WEIGHTS.filter(weight => drawn.has(weight)),\n    others: NAMED_WEIGHTS.filter(weight => !drawn.has(weight)),\n  };\n}\n\n/** A stored weight in words: `Bold 700`, or the value itself when unnamed. */\nfunction shownWeight(value: string): string {\n  const weight = Number(value);\n  return NAMED_WEIGHTS.includes(weight) ? weightName(weight) : value;\n}\n\n/**\n * A weight variable, by name: \"Thin 100\" to \"Black 900\", the weights the\n * site's fonts have first and the others marked, since text set at one of\n * them is drawn by the browser from the nearest weight it has. A stored\n * weight with no name (`450`) still shows, and stays chosen.\n */\nfunction WeightValue({\n  label,\n  value,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n}: ValueFieldProps): React.JSX.Element {\n  const fonts = React.useContext(FontChoicesContext);\n  const id = React.useId();\n  if (readOnly) {\n    return (\n      <TextValue\n        label={label}\n        value={value}\n        readOnly\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  const drawn =\n    fonts?.faces === undefined\n      ? undefined\n      : weightsDrawn([...fonts.faces, ...fonts.fromCode]);\n  const { ours, others } = weightOrder(drawn);\n  const unnamed = value !== \"\" && !NAMED_WEIGHTS.includes(Number(value));\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <label className=\"nx-vars-editor__label\" htmlFor={id}>\n        {label}\n      </label>\n      <Select\n        value={value}\n        onValueChange={next => {\n          onPreview?.(null);\n          if (next !== value) onCommit(next);\n        }}\n        // Closed without a choice, the canvas draws what is stored again.\n        onOpenChange={open => {\n          if (!open) onPreview?.(null);\n        }}\n      >\n        <SelectTrigger\n          id={id}\n          className=\"nx-vars-editor__weight\"\n          aria-describedby={refusedBy}\n          aria-invalid={refusedBy === undefined ? undefined : true}\n        >\n          <SelectValue>{shownWeight(value)}</SelectValue>\n        </SelectTrigger>\n        <SelectContent>\n          {unnamed ? <SelectItem value={value}>{value}</SelectItem> : null}\n          {ours.map(weight => (\n            <SelectItem\n              key={weight}\n              value={String(weight)}\n              // The weight the keyboard or the pointer is on is drawn on\n              // the canvas, as the list moves.\n              onFocus={() => onPreview?.(String(weight))}\n            >\n              {weightName(weight)}\n            </SelectItem>\n          ))}\n          {ours.length > 0 && others.length > 0 ? <SelectSeparator /> : null}\n          {others.map(weight => (\n            <SelectItem\n              key={weight}\n              value={String(weight)}\n              onFocus={() => onPreview?.(String(weight))}\n            >\n              {weightName(weight)}\n              <span className=\"nx-vars-editor__weight-note\">\n                No font on this site has this weight\n              </span>\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    </div>\n  );\n}\n\n/** A line height under its own label, with its hint, outside a type pair. */\nfunction LineHeightValue({\n  label,\n  value,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n  mode = \"light\",\n}: ValueFieldProps): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <label className=\"nx-vars-editor__label\" htmlFor={id}>\n        {label}\n      </label>\n      <LineHeightInput\n        id={id}\n        label={undefined}\n        value={value}\n        readOnly={readOnly}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n        onPreview={onPreview}\n      />\n      <LineHeightHint\n        value={value}\n        mode={mode}\n        readOnly={readOnly}\n        onCommit={onCommit}\n      />\n    </div>\n  );\n}\n","/**\n * A shadow as the shadow fields show it: layers of offsets, blur, spread, a\n * colour and \"Inside\", read from the CSS a shadow is stored as and written\n * back to it.\n *\n * Pure, so what a shadow reads as and what a layer writes are tested apart\n * from the fields. The parts are the engine's reading, the one its shadow\n * check uses, so the fields and the check never disagree about what a part\n * is. What cannot be shown as fields is kept as the CSS it was typed as.\n *\n * @module shadow-css\n */\nimport {\n  resolveTokenPrefix,\n  shadowLayerParts,\n  tokenCustomProperty,\n  type ShadowPart,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { NEW_SHADOW_VALUE } from \"../panels/design/tokens-studio\";\n\nimport { variableFor, variablesFor } from \"./style-colour\";\n\n/**\n * A layer's colour: one of the site's colour variables, by the identity a\n * rename never changes, or a colour written as itself.\n */\nexport type ShadowColour =\n  | { readonly kind: \"variable\"; readonly identity: string }\n  | { readonly kind: \"raw\"; readonly value: string };\n\n/** One shadow layer, as its fields show it. Sizes are CSS lengths. */\nexport interface ShadowLayer {\n  /** \"Inside\": drawn within the box rather than around it. */\n  readonly inset: boolean;\n  readonly x: string;\n  readonly y: string;\n  /** `undefined` where the layer sets none, which draws a sharp edge. */\n  readonly blur: string | undefined;\n  /** `undefined` where the layer sets none, which grows it by nothing. */\n  readonly spread: string | undefined;\n  /** `undefined` where the layer sets none, which takes the text colour. */\n  readonly colour: ShadowColour | undefined;\n}\n\n/** A shadow read as layers, or kept as the CSS it is. */\nexport type ShadowReading =\n  | { readonly kind: \"layers\"; readonly layers: readonly ShadowLayer[] }\n  | { readonly kind: \"css\" };\n\n/**\n * What a colour variable is offered at: a colour with no contrast partner,\n * so every colour variable the site has is listed for a shadow.\n */\nexport const SHADOW_COLOUR_LEAF: Extract<StyleLeaf, { kind: \"color\" }> = {\n  kind: \"color\",\n  cssProperty: \"box-shadow\",\n  tokenKinds: [\"color\"],\n};\n\n/** A reference to one custom property, with no fallback. */\nconst PLAIN_REFERENCE = /^var\\(\\s*(--[A-Za-z0-9_-]+)\\s*\\)$/;\n\n/**\n * The layers a shadow shows as, or `css` where any part cannot be a field:\n * a size through a function, a variable that is no colour of this site's, or\n * anything the engine's reading does not take as a size or a colour.\n */\nexport function readShadow(\n  text: string,\n  tokens: SiteTokenSet | undefined\n): ShadowReading {\n  const trimmed = text.trim();\n  if (trimmed === \"\" || trimmed.toLowerCase() === \"none\") {\n    return { kind: \"layers\", layers: [] };\n  }\n  const layers: ShadowLayer[] = [];\n  for (const parts of shadowLayerParts(trimmed)) {\n    const layer = layerOf(parts, tokens);\n    if (layer === undefined) return { kind: \"css\" };\n    layers.push(layer);\n  }\n  return { kind: \"layers\", layers };\n}\n\n/** One layer as fields, or `undefined` where it cannot be one. */\nfunction layerOf(\n  parts: readonly ShadowPart[],\n  tokens: SiteTokenSet | undefined\n): ShadowLayer | undefined {\n  const sizes = sizesOf(parts);\n  const colour = layerColourOf(parts, tokens);\n  const insets = parts.filter(part => part.kind === \"inset\").length;\n  // At most one \"inset\"; a second is a layer CSS reads differently.\n  if (sizes === undefined || colour === undefined || insets > 1) {\n    return undefined;\n  }\n  return { inset: insets === 1, ...sizes, colour: colour.colour };\n}\n\n/** A layer's sizes: X and Y, then a blur and a spread where it sets them. */\nfunction sizesOf(\n  parts: readonly ShadowPart[]\n): Pick<ShadowLayer, \"x\" | \"y\" | \"blur\" | \"spread\"> | undefined {\n  const [x, y, blur, spread, ...more] = parts\n    .filter(part => part.kind === \"length\")\n    .map(part => part.text);\n  if (x === undefined || y === undefined || more.length > 0) return undefined;\n  return { x, y, blur, spread };\n}\n\n/**\n * A layer's colour, `{ colour: undefined }` where it sets none, or\n * `undefined` where its one remaining part is no colour of the site's, or\n * there are two.\n */\nfunction layerColourOf(\n  parts: readonly ShadowPart[],\n  tokens: SiteTokenSet | undefined\n): { colour: ShadowColour | undefined } | undefined {\n  const rest = parts.filter(\n    part => part.kind !== \"length\" && part.kind !== \"inset\"\n  );\n  const [only, ...more] = rest;\n  if (only === undefined) return { colour: undefined };\n  if (more.length > 0) return undefined;\n  const colour = colourOf(only, tokens);\n  return colour === undefined ? undefined : { colour };\n}\n\n/** A part as a layer's colour, or `undefined` where it is none of the site's. */\nfunction colourOf(\n  part: ShadowPart,\n  tokens: SiteTokenSet | undefined\n): ShadowColour | undefined {\n  if (part.kind === \"colour\") return { kind: \"raw\", value: part.text };\n  if (part.kind !== \"reference\") return undefined;\n  const property = PLAIN_REFERENCE.exec(part.text)?.[1];\n  if (property === undefined) return undefined;\n  const variable = colourVariables(tokens).find(\n    candidate => propertyOf(candidate.identity, tokens) === property\n  );\n  return variable === undefined\n    ? undefined\n    : { kind: \"variable\", identity: variable.identity };\n}\n\n/** The site's colour variables, as a colour field offers them. */\nfunction colourVariables(tokens: SiteTokenSet | undefined) {\n  return variablesFor(SHADOW_COLOUR_LEAF, tokens);\n}\n\n/** The custom property a variable is declared as, under the site's prefix. */\nfunction propertyOf(\n  identity: string,\n  tokens: SiteTokenSet | undefined\n): string {\n  return tokenCustomProperty(\n    identity,\n    resolveTokenPrefix(tokens?.prefix).prefix\n  );\n}\n\n/**\n * The CSS for a shadow's layers, `none` for none. A colour variable is\n * written as the `var()` the site's stylesheet declares it under, so the\n * shadow follows the colour, its dark value included.\n */\nexport function writeShadow(\n  layers: readonly ShadowLayer[],\n  tokens: SiteTokenSet | undefined\n): string {\n  return written(layers, colour =>\n    colour.kind === \"raw\"\n      ? colour.value\n      : `var(${propertyOf(colour.identity, tokens)})`\n  );\n}\n\n/**\n * The CSS for a preview card in one mode: each colour variable painted with\n * its value in that mode, since the panel does not declare the site's\n * custom properties. A variable the site no longer has paints nothing.\n */\nexport function shadowPreview(\n  layers: readonly ShadowLayer[],\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): string {\n  return written(layers, colour =>\n    colour.kind === \"raw\"\n      ? colour.value\n      : (variableFor(colour.identity, tokens, mode)?.swatch ?? \"transparent\")\n  );\n}\n\n/**\n * Whether any colour variable a shadow uses reads differently in dark mode.\n * A variable with no dark value of its own shows its light one there.\n */\nexport function shadowFollowsDark(\n  layers: readonly ShadowLayer[],\n  tokens: SiteTokenSet | undefined\n): boolean {\n  return layers.some(\n    ({ colour }) =>\n      colour?.kind === \"variable\" &&\n      variableFor(colour.identity, tokens, \"dark\")?.value !==\n        variableFor(colour.identity, tokens, \"light\")?.value\n  );\n}\n\n/** Layers as CSS, each colour written by `colourText`. */\nfunction written(\n  layers: readonly ShadowLayer[],\n  colourText: (colour: ShadowColour) => string\n): string {\n  if (layers.length === 0) return \"none\";\n  return layers\n    .map(layer => {\n      // A spread needs a blur before it, so a zero blur is written for one.\n      const blur = layer.blur ?? (layer.spread === undefined ? undefined : \"0\");\n      return [\n        layer.inset ? \"inset\" : undefined,\n        layer.x,\n        layer.y,\n        blur,\n        layer.spread,\n        layer.colour === undefined ? undefined : colourText(layer.colour),\n      ]\n        .filter(part => part !== undefined)\n        .join(\" \");\n    })\n    .join(\", \");\n}\n\n/**\n * The layer \"+ Add layer\" adds: a new shadow variable's one layer, read\n * from its value, so the two cannot differ. Last in the module, so\n * everything reading it uses is defined first.\n */\nexport const NEW_SHADOW_LAYER: ShadowLayer = newShadowLayer();\n\nfunction newShadowLayer(): ShadowLayer {\n  const read = readShadow(NEW_SHADOW_VALUE, undefined);\n  const [layer] = read.kind === \"layers\" ? read.layers : [];\n  if (layer === undefined) throw new Error(\"A new shadow reads as no layer.\");\n  return layer;\n}\n","\"use client\";\n\n/**\n * The shadow control: a shadow built with fields rather than typed as CSS.\n *\n * Each layer has an X offset, a Y offset, a Blur and a Spread, each a size\n * with its unit menu, a Colour (a colour variable or a colour of its own,\n * through the colour picker) and \"Inside\". \"+ Add layer\" adds another, and a\n * layer can be moved and removed. A preview card shows the result in light,\n * and in dark where a colour it uses has a dark value.\n *\n * \"Edit as CSS\" shows the shadow as the CSS it is stored as. Typed CSS is\n * read back into the fields where it can be; where it cannot, it is kept\n * exactly as typed, said to be shown as CSS, and still checked.\n *\n * Given `onPreview`, as a shadow variable is, the whole shadow is offered to\n * be drawn as any of its fields is typed or its colour picked, a shadow CSS\n * would draw nothing for never among them, and every write says the edit is\n * over first.\n *\n * ONE control for every shadow: a shadow variable in Design and a block's\n * shadow in its Style tab both draw it, so the two never offer different\n * ways to build the same thing.\n *\n * @module shadow-control\n */\nimport {\n  checkTokenKind,\n  getStyleProperty,\n  isTokenRef,\n  tokenRef,\n  type SiteTokenSet,\n  type StyleValue,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button, Switch } from \"@nextlyhq/ui\";\nimport { ArrowDown, ArrowUp, Trash2 } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { SizeValue } from \"../../panels/design/variable-value-controls\";\nimport {\n  NEW_SHADOW_LAYER,\n  readShadow,\n  SHADOW_COLOUR_LEAF,\n  shadowFollowsDark,\n  shadowPreview,\n  writeShadow,\n  type ShadowColour,\n  type ShadowLayer,\n} from \"../../styles/shadow-css\";\nimport { variableFor } from \"../../styles/style-colour\";\nimport {\n  styleControlsFor,\n  type StyleControl,\n} from \"../../styles/style-controls\";\nimport { CssHint, CssNamesLine } from \"../css-hint\";\n\nimport { ColourField } from \"./style-colour-field\";\nimport { TypesLiveContext } from \"./style-field-surroundings\";\n\n/** What a shadow control is given by the place that draws it. */\nexport interface ShadowControlProps {\n  /** What it is called: \"Light\", \"Dark\", or the field's own name. */\n  readonly label: string;\n  /** The stored CSS; empty where nothing is set. */\n  readonly value: string;\n  readonly tokens: SiteTokenSet | undefined;\n  readonly readOnly: boolean;\n  /**\n   * The declaration a value writes, shown on hover over each field. Absent\n   * where the field around the control already says it, as a block's does.\n   */\n  readonly writesOf?: ((css: string) => string) | undefined;\n  /** The CSS names printed inline while \"Show CSS names\" is on. */\n  readonly names?: readonly string[] | undefined;\n  /** The id of a reason the host shows, while it refuses the value. */\n  readonly refusedBy?: string | undefined;\n  /** Writes the new CSS: `none` once the last layer is removed. */\n  readonly onCommit: (css: string) => void;\n  /**\n   * Draws the shadow as it is being edited, before it is written; `null` once\n   * the edit ends, said before the write. Absent, a field writes when it is\n   * left.\n   */\n  readonly onPreview?: ((css: string | null) => void) | undefined;\n}\n\n/**\n * A field's preview of the layer it is part of: the layer with that field's\n * value in it, or `null` once the field's edit ends.\n */\ntype LayerPreview = (layer: ShadowLayer | null) => void;\n\n/** What the CSS view says where the CSS can't be fields. */\nconst KEPT_AS_CSS = \"Shown as CSS because it can't be shown as fields\";\n\n/**\n * The colour picker a layer's Colour is chosen with: a block panel colour\n * control, offering every colour variable the site has, with no contrast\n * partner, since a shadow sits behind no text of its own.\n */\nconst SHADOW_COLOUR_CONTROL = shadowColourControl();\n\nfunction shadowColourControl():\n  | (StyleControl & { leaf: typeof SHADOW_COLOUR_LEAF })\n  | undefined {\n  const outline = getStyleProperty(\"outline\");\n  if (outline === undefined) return undefined;\n  const control = styleControlsFor(outline).controls.find(\n    candidate => candidate.leaf.kind === \"color\"\n  );\n  return control === undefined\n    ? undefined\n    : { ...control, leaf: SHADOW_COLOUR_LEAF };\n}\n\n/** Why a shadow can't be written, in a sentence, or nothing. */\nfunction shadowRefusal(css: string): string | undefined {\n  const mismatch = checkTokenKind(\"shadow\", css);\n  return mismatch === undefined ? undefined : `This shadow ${mismatch}.`;\n}\n\nexport function ShadowControl(props: ShadowControlProps): React.JSX.Element {\n  const { label, value, tokens, readOnly, names } = props;\n  const id = React.useId();\n  const reading = readShadow(value, tokens);\n  const [asCss, setAsCss] = React.useState(false);\n  const [refusal, setRefusal] = React.useState<string | undefined>();\n  // Every write is checked first: a field can make a shadow CSS draws\n  // nothing for, a negative blur among them, and typed CSS can be anything.\n  const write = (css: string): boolean => {\n    // The edit is over, written or not.\n    props.onPreview?.(null);\n    const refused = shadowRefusal(css);\n    setRefusal(refused);\n    if (refused !== undefined) return false;\n    if (css !== value) props.onCommit(css);\n    return true;\n  };\n  // A shadow being edited, drawn where it is one CSS would draw; the canvas\n  // keeps the last that was.\n  const preview =\n    props.onPreview === undefined\n      ? undefined\n      : (css: string | null): void => {\n          if (css === null) props.onPreview?.(null);\n          else if (shadowRefusal(css) === undefined) props.onPreview?.(css);\n        };\n  const showsCss = asCss || reading.kind === \"css\";\n  return (\n    <div className=\"nx-shadow\" role=\"group\" aria-label={label}>\n      <ShadowPreviews\n        layers={reading.kind === \"layers\" ? reading.layers : undefined}\n        value={value}\n        tokens={tokens}\n      />\n      {showsCss ? (\n        <CssView\n          id={id}\n          label={label}\n          value={value}\n          readOnly={readOnly}\n          kept={reading.kind === \"css\"}\n          refusal={refusal}\n          refusedBy={props.refusedBy}\n          onPreview={preview}\n          onCommit={typed => {\n            // Read back into the fields where it can be; kept as CSS where not.\n            if (write(typed) && readShadow(typed, tokens).kind === \"layers\") {\n              setAsCss(false);\n            }\n          }}\n        />\n      ) : (\n        <LayerList\n          layers={reading.kind === \"layers\" ? reading.layers : []}\n          tokens={tokens}\n          readOnly={readOnly}\n          writesOf={props.writesOf}\n          refusal={refusal}\n          refusalId={`${id}-said`}\n          onLayers={layers => write(writeShadow(layers, tokens))}\n          onPreview={\n            preview === undefined\n              ? undefined\n              : layers =>\n                  preview(layers === null ? null : writeShadow(layers, tokens))\n          }\n          onEditAsCss={() => setAsCss(true)}\n        />\n      )}\n      {names === undefined ? null : (\n        <CssNamesLine id={`${id}-css`} names={names} />\n      )}\n    </div>\n  );\n}\n\n/**\n * The preview cards: the shadow in light, and in dark where a colour it uses\n * has a dark value, each on the site's own background for that mode.\n */\nfunction ShadowPreviews({\n  layers,\n  value,\n  tokens,\n}: {\n  layers: readonly ShadowLayer[] | undefined;\n  value: string;\n  tokens: SiteTokenSet | undefined;\n}): React.JSX.Element {\n  const modes: TokenMode[] =\n    layers !== undefined && shadowFollowsDark(layers, tokens)\n      ? [\"light\", \"dark\"]\n      : [\"light\"];\n  return (\n    <div className=\"nx-shadow__previews\" aria-hidden=\"true\">\n      {modes.map(mode => (\n        <span key={mode} className=\"nx-shadow__preview\">\n          <span\n            className=\"nx-shadow__card\"\n            data-mode={mode}\n            style={{\n              // CSS the fields can't show is drawn as it is.\n              boxShadow:\n                layers === undefined\n                  ? value\n                  : shadowPreview(layers, tokens, mode),\n              background: variableFor(\"color.background\", tokens, mode)?.swatch,\n            }}\n          />\n          <span className=\"nx-shadow__mode\">\n            {mode === \"light\" ? \"Light\" : \"Dark\"}\n          </span>\n        </span>\n      ))}\n    </div>\n  );\n}\n\n/** The shadow as the CSS it is stored as, in one field. */\nfunction CssView({\n  id,\n  label,\n  value,\n  readOnly,\n  kept,\n  refusal,\n  refusedBy,\n  onPreview,\n  onCommit,\n}: {\n  id: string;\n  label: string;\n  value: string;\n  readOnly: boolean;\n  /** Whether it is CSS because the fields can't show it. */\n  kept: boolean;\n  refusal: string | undefined;\n  refusedBy: string | undefined;\n  onPreview: ((css: string | null) => void) | undefined;\n  onCommit: (typed: string) => void;\n}): React.JSX.Element {\n  const [draft, setDraft] = React.useState(value);\n  const [shown, setShown] = React.useState(value);\n  if (shown !== value) {\n    setShown(value);\n    setDraft(value);\n  }\n  const saidId = `${id}-said`;\n  const commit = (text: string): void => {\n    const typed = text.trim();\n    if (!readOnly && typed !== \"\") onCommit(typed);\n    // Nothing to write: the edit is over all the same.\n    else onPreview?.(null);\n  };\n  return (\n    <div className=\"nx-shadow__css\">\n      <textarea\n        className=\"nx-shadow__css-field nx-vars-editor__mono\"\n        aria-label={`${label} as CSS`}\n        rows={3}\n        spellCheck={false}\n        readOnly={readOnly}\n        value={draft}\n        aria-invalid={\n          refusal === undefined && refusedBy === undefined ? undefined : true\n        }\n        aria-describedby={refusal === undefined ? refusedBy : saidId}\n        onChange={event => {\n          const typed = event.currentTarget.value;\n          setDraft(typed);\n          if (!readOnly && typed.trim() !== \"\") onPreview?.(typed.trim());\n        }}\n        onBlur={event => commit(event.currentTarget.value)}\n        onKeyDown={event => {\n          // Enter commits; Shift+Enter is a new line, for a long shadow.\n          if (event.key === \"Enter\" && !event.shiftKey) {\n            event.preventDefault();\n            commit(event.currentTarget.value);\n          }\n        }}\n      />\n      {kept ? <p className=\"nx-shadow__note\">{KEPT_AS_CSS}</p> : null}\n      {refusal === undefined ? null : (\n        <p className=\"nx-shadow__refusal\" id={saidId} role=\"alert\">\n          {refusal}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/** Every layer's fields, then \"+ Add layer\" and \"Edit as CSS\". */\nfunction LayerList({\n  layers,\n  tokens,\n  readOnly,\n  writesOf,\n  refusal,\n  refusalId,\n  onLayers,\n  onPreview,\n  onEditAsCss,\n}: {\n  layers: readonly ShadowLayer[];\n  tokens: SiteTokenSet | undefined;\n  readOnly: boolean;\n  writesOf: ((css: string) => string) | undefined;\n  refusal: string | undefined;\n  refusalId: string;\n  onLayers: (layers: readonly ShadowLayer[]) => void;\n  /** Draws the layers as one is edited; `null` ends it. */\n  onPreview: ((layers: readonly ShadowLayer[] | null) => void) | undefined;\n  onEditAsCss: () => void;\n}): React.JSX.Element {\n  const writes = writesOf?.(writeShadow(layers, tokens));\n  const change = (at: number, layer: ShadowLayer): void =>\n    onLayers(layers.map((each, index) => (index === at ? layer : each)));\n  const move = (at: number, by: -1 | 1): void => {\n    const next = [...layers];\n    const [moved] = next.splice(at, 1);\n    if (moved !== undefined) next.splice(at + by, 0, moved);\n    onLayers(next);\n  };\n  return (\n    <>\n      {layers.map((layer, index) => (\n        <LayerFields\n          // Layers have no identity of their own; their place is it.\n          key={index}\n          index={index}\n          count={layers.length}\n          layer={layer}\n          tokens={tokens}\n          readOnly={readOnly}\n          writes={writes}\n          onChange={next => change(index, next)}\n          onPreview={\n            onPreview === undefined\n              ? undefined\n              : next =>\n                  onPreview(\n                    next === null\n                      ? null\n                      : layers.map((each, at) => (at === index ? next : each))\n                  )\n          }\n          onMove={by => move(index, by)}\n          onRemove={() => onLayers(layers.filter((_, at) => at !== index))}\n        />\n      ))}\n      {refusal === undefined ? null : (\n        <p className=\"nx-shadow__refusal\" id={refusalId} role=\"alert\">\n          {refusal}\n        </p>\n      )}\n      {readOnly ? null : (\n        <div className=\"nx-shadow__actions\">\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"outline\"\n            className=\"nx-vars-editor__button\"\n            onClick={() => onLayers([...layers, NEW_SHADOW_LAYER])}\n          >\n            + Add layer\n          </Button>\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"ghost\"\n            className=\"nx-vars-editor__button\"\n            onClick={onEditAsCss}\n          >\n            Edit as CSS\n          </Button>\n        </div>\n      )}\n    </>\n  );\n}\n\n/** The sizes a layer has, each with its field's label. */\nconst SIZES = [\n  [\"x\", \"X offset\"],\n  [\"y\", \"Y offset\"],\n  [\"blur\", \"Blur\"],\n  [\"spread\", \"Spread\"],\n] as const;\n\n/** One layer: its four sizes, its Colour and Inside, and its actions. */\nfunction LayerFields({\n  index,\n  count,\n  layer,\n  tokens,\n  readOnly,\n  writes,\n  onChange,\n  onPreview,\n  onMove,\n  onRemove,\n}: {\n  index: number;\n  count: number;\n  layer: ShadowLayer;\n  tokens: SiteTokenSet | undefined;\n  readOnly: boolean;\n  writes: string | undefined;\n  onChange: (layer: ShadowLayer) => void;\n  /** Draws the layer as one of its fields is edited; `null` ends it. */\n  onPreview: LayerPreview | undefined;\n  onMove: (by: -1 | 1) => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  const name = `Layer ${String(index + 1)}`;\n  return (\n    <div className=\"nx-shadow__layer\" role=\"group\" aria-label={name}>\n      <div className=\"nx-shadow__layer-head\">\n        <span className=\"nx-shadow__layer-name\">{name}</span>\n        {readOnly ? null : (\n          <LayerActions\n            name={name.toLowerCase()}\n            first={index === 0}\n            last={index === count - 1}\n            onMove={onMove}\n            onRemove={onRemove}\n          />\n        )}\n      </div>\n      <div className=\"nx-shadow__sizes\">\n        {SIZES.map(([part, label]) => (\n          <Hinted key={part} writes={writes}>\n            <SizeValue\n              label={label}\n              value={layer[part] ?? \"\"}\n              // An unset blur or spread draws as 0.\n              placeholder=\"0\"\n              readOnly={readOnly}\n              onCommit={typed => onChange({ ...layer, [part]: typed })}\n              {...(onPreview === undefined\n                ? {}\n                : {\n                    onPreview: (typed: string | null) =>\n                      onPreview(\n                        typed === null ? null : { ...layer, [part]: typed }\n                      ),\n                  })}\n            />\n          </Hinted>\n        ))}\n      </div>\n      <Hinted writes={writes}>\n        <LayerColour\n          layer={name.toLowerCase()}\n          colour={layer.colour}\n          tokens={tokens}\n          readOnly={readOnly}\n          onColour={colour => onChange({ ...layer, colour })}\n          {...(onPreview === undefined\n            ? {}\n            : {\n                onPreviewColour: (colour: ShadowColour | undefined) =>\n                  onPreview({ ...layer, colour }),\n              })}\n        />\n      </Hinted>\n      <Hinted writes={writes}>\n        <label className=\"nx-shadow__inside\">\n          <Switch\n            aria-label=\"Inside\"\n            checked={layer.inset}\n            disabled={readOnly}\n            onCheckedChange={inset => onChange({ ...layer, inset })}\n          />\n          <span aria-hidden=\"true\">Inside</span>\n        </label>\n      </Hinted>\n    </div>\n  );\n}\n\n/** A field with the declaration it writes on hover, where one is said. */\nfunction Hinted({\n  writes,\n  children,\n}: {\n  writes: string | undefined;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <CssHint writes={writes}>\n      <div className=\"nx-shadow__field\">{children}</div>\n    </CssHint>\n  );\n}\n\n/** Move up, Move down and Remove, named for the layer. */\nfunction LayerActions({\n  name,\n  first,\n  last,\n  onMove,\n  onRemove,\n}: {\n  name: string;\n  first: boolean;\n  last: boolean;\n  onMove: (by: -1 | 1) => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-shadow__layer-actions\">\n      <Button\n        type=\"button\"\n        size=\"icon-sm\"\n        variant=\"ghost\"\n        disabled={first}\n        aria-label={`Move ${name} up`}\n        onClick={() => onMove(-1)}\n      >\n        <ArrowUp aria-hidden=\"true\" />\n      </Button>\n      <Button\n        type=\"button\"\n        size=\"icon-sm\"\n        variant=\"ghost\"\n        disabled={last}\n        aria-label={`Move ${name} down`}\n        onClick={() => onMove(1)}\n      >\n        <ArrowDown aria-hidden=\"true\" />\n      </Button>\n      <Button\n        type=\"button\"\n        size=\"icon-sm\"\n        variant=\"ghost\"\n        aria-label={`Remove ${name}`}\n        onClick={onRemove}\n      >\n        <Trash2 aria-hidden=\"true\" />\n      </Button>\n    </span>\n  );\n}\n\n/**\n * A layer's Colour, through the block panel's own colour picker: the site's\n * colour variables first, then a colour of its own.\n */\nfunction LayerColour({\n  layer,\n  colour,\n  tokens,\n  readOnly,\n  onColour,\n  onPreviewColour,\n}: {\n  /** The layer's name, which the picker's controls are named for. */\n  layer: string;\n  colour: ShadowColour | undefined;\n  tokens: SiteTokenSet | undefined;\n  readOnly: boolean;\n  onColour: (colour: ShadowColour | undefined) => void;\n  /**\n   * Draws a colour typed or picked before it is written. Given, the field\n   * types live into it, and its commit still writes once.\n   */\n  onPreviewColour?: (colour: ShadowColour | undefined) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  const stored = storedColour(colour);\n  return (\n    <div className=\"nx-shadow__colour\">\n      <label className=\"nx-vars-editor__label\" id={`${id}-label`} htmlFor={id}>\n        Colour\n      </label>\n      {readOnly || SHADOW_COLOUR_CONTROL === undefined ? (\n        <input\n          id={id}\n          className=\"nx-vars-editor__mono\"\n          readOnly\n          value={typeof stored === \"string\" ? stored : \"\"}\n        />\n      ) : (\n        <TypesLive on={onPreviewColour !== undefined}>\n          <ColourField\n            id={id}\n            labelledBy={`${id}-label`}\n            control={SHADOW_COLOUR_CONTROL}\n            stored={stored}\n            actionName={layer}\n            tokens={tokens}\n            prefersDark={false}\n            pairedColour={undefined}\n            obscuredBy={undefined}\n            describedBy={undefined}\n            onCommit={next => {\n              onColour(colourOf(next));\n              return \"applied\";\n            }}\n            {...(onPreviewColour === undefined\n              ? {}\n              : {\n                  onType: (next: StyleValue | null) => {\n                    onPreviewColour(colourOf(next));\n                    return \"applied\" as const;\n                  },\n                })}\n          />\n        </TypesLive>\n      )}\n    </div>\n  );\n}\n\n/**\n * Fields drawn as typing live where `on`, as a previewed shadow's are, and as\n * the panel around them says otherwise.\n */\nfunction TypesLive({\n  on,\n  children,\n}: {\n  on: boolean;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return on ? (\n    <TypesLiveContext.Provider value={true}>\n      {children}\n    </TypesLiveContext.Provider>\n  ) : (\n    <>{children}</>\n  );\n}\n\n/** A layer's colour as the colour picker stores one. */\nfunction storedColour(\n  colour: ShadowColour | undefined\n): StyleValue | undefined {\n  if (colour === undefined) return undefined;\n  return colour.kind === \"variable\" ? tokenRef(colour.identity) : colour.value;\n}\n\n/** What the colour picker chose, as a layer's colour. */\nfunction colourOf(value: StyleValue | null): ShadowColour | undefined {\n  if (isTokenRef(value)) return { kind: \"variable\", identity: value.$token };\n  return typeof value === \"string\" && value.trim() !== \"\"\n    ? { kind: \"raw\", value: value.trim() }\n    : undefined;\n}\n","\"use client\";\n\n/**\n * A block's shadow in its Style tab: the shadow control a shadow variable is\n * built with in Design, and a menu at its end to use one of the site's shadow\n * variables instead.\n *\n * @module style-shadow-field\n */\nimport type { SiteTokenSet, StyleValue } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { VariableChoice } from \"../../panels/design/variable-choice\";\nimport type { StyleControl } from \"../../styles/style-controls\";\n\nimport { ShadowControl } from \"./shadow-control\";\nimport type { CommitOutcome } from \"./style-field-surroundings\";\n\n/** The CSS property the shadow control draws in the Style tab. */\nexport const BOX_SHADOW = \"box-shadow\";\n\n/**\n * Whether the shadow control draws a box shadow's stored value: one written\n * as CSS, or none yet. A held variable keeps its chip.\n */\nexport function drawsShadow(stored: StyleValue | undefined): boolean {\n  return stored === undefined || typeof stored === \"string\";\n}\n\nexport function ShadowField({\n  id,\n  control,\n  stored,\n  actionName,\n  tokens,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  /** The field label's id; the control is a group named by its own label. */\n  labelledBy: string;\n  control: StyleControl;\n  stored: StyleValue | undefined;\n  actionName: string;\n  tokens: SiteTokenSet | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-shadow-field\" id={id}>\n      <ShadowControl\n        label={actionName}\n        value={typeof stored === \"string\" ? stored : \"\"}\n        tokens={tokens}\n        readOnly={false}\n        refusedBy={describedBy}\n        // What it writes is said by the field around it, on hover and inline.\n        onCommit={css => {\n          onCommit(css);\n        }}\n      />\n      <VariableChoice\n        leaf={control.leaf}\n        tokens={tokens}\n        current={undefined}\n        label={actionName}\n        onPick={identity => onCommit({ $token: identity })}\n      />\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The value fields a control draws by kind: select, folded, length or\n * number, percent and toggle, and the value field that picks between them.\n *\n * @module style-value-fields\n */\nimport {\n  APPEAR_DELAY_PROPERTY,\n  APPEAR_DURATION_PROPERTY,\n  isStyleLeaf,\n  isTokenRef,\n  OVERLAY_STRENGTH,\n  STYLE_CATALOG,\n  trimCssWhitespace,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n  Slider,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport { typedStyleText } from \"../../live-draft\";\nimport { useLiveGesture } from \"../../live-gesture\";\nimport {\n  focusVariableAfterPick,\n  pickedVariable,\n  useOfferedVariables,\n  VariableChoice,\n  VariableSelectItems,\n} from \"../../panels/design/variable-choice\";\nimport { foldedLeaf, type SiteVariable } from \"../../styles/style-colour\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport {\n  fontWeightOptions,\n  lineHeightFromText,\n  lineHeightLeafFor,\n  lineHeightScrubOrigin,\n  storedKey,\n  type FoldedControl,\n  type FoldedOption,\n} from \"../../styles/style-folded\";\nimport {\n  scrubbedValue,\n  steppedValue,\n  toggleOptionsFor,\n  toggleShows,\n} from \"../../styles/style-numeric\";\nimport { tokenForTypedName } from \"../../styles/style-variables\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport { CssHint, OptionWrites, useFieldDescription } from \"../css-hint\";\n\nimport { AspectRatioField, drawsAspectRatio } from \"./aspect-ratio-field\";\nimport {\n  BackgroundPositionField,\n  BackgroundSizeField,\n} from \"./background-fields\";\nimport { BackgroundImageField } from \"./background-image-control\";\nimport { DecorationField, drawsDecoration } from \"./decoration-field\";\nimport { FocalPointField } from \"./focal-point-field\";\nimport { IconChoiceField } from \"./icon-choice-field\";\nimport { InheritedValue, useUnsetHint } from \"./inherited-value\";\nimport { useLabelScrub } from \"./label-scrub\";\nimport { SectionHeld } from \"./section-held\";\nimport {\n  alignmentGroupFor,\n  drawsIcons,\n  type Flow,\n} from \"./style-alignment-icons\";\nimport type { CommitOutcome } from \"./style-field-surroundings\";\nimport { keywordLabel, menuKeywords } from \"./style-keyword-labels\";\nimport { textNumber, UnitWords, NumericField } from \"./style-numeric-field\";\nimport { BOX_SHADOW, drawsShadow, ShadowField } from \"./style-shadow-field\";\nimport {\n  useDraft,\n  arrowStep,\n  storedText,\n  useTypesLive,\n} from \"./style-text-field\";\n\n/**\n * The leaf a catalog property's variables are offered for, outside the style\n * panel: its own leaf, or, for a union such as line height or weight, the one\n * folded leaf over its forms the panel's field uses. `undefined` for a\n * property the catalog does not list, or one with no form a variable fits.\n */\nexport function propertyVariableLeaf(property: string): StyleLeaf | undefined {\n  const shape = STYLE_CATALOG.find(entry => entry.property === property)?.shape;\n  if (shape === undefined) return undefined;\n  if (isStyleLeaf(shape)) return shape;\n  if (shape.kind !== \"union\") return undefined;\n  const first = shape.of.find(isStyleLeaf);\n  return first === undefined ? undefined : foldedLeafFor(property, first);\n}\n\n/**\n * The leaf a field's variables are offered for: the control's own, or, for a\n * folded union drawn as one field, one leaf over all its forms, which takes\n * every kind any form takes and judges each variable by the form its kind is\n * written in (see `foldedLeaf`).\n */\nexport function variableLeafOf(\n  leaf: StyleLeaf,\n  fold: Fold | undefined\n): StyleLeaf {\n  return fold === undefined ? leaf : foldedLeafFor(fold.property, leaf);\n}\n\n/**\n * The folded leaf for one catalog property, made once: its forms are the\n * catalog's, which do not change, and one leaf object keeps the forms it\n * carries attached. The control's own leaf stands in if the catalog has no\n * union there.\n */\nfunction foldedLeafFor(property: string, fallback: StyleLeaf): StyleLeaf {\n  const made = FOLDED_LEAVES.get(property);\n  if (made !== undefined) return made;\n  const shape = STYLE_CATALOG.find(entry => entry.property === property)?.shape;\n  const arms =\n    shape?.kind === \"union\" ? shape.of.filter(isStyleLeaf) : [fallback];\n  // With its union, so each variable is judged by the arm the engine picks\n  // for its value.\n  const leaf =\n    shape?.kind === \"union\" && arms.length > 0\n      ? foldedLeaf(arms, shape)\n      : foldedLeaf(arms.length > 0 ? arms : [fallback]);\n  FOLDED_LEAVES.set(property, leaf);\n  return leaf;\n}\n\nconst FOLDED_LEAVES = new Map<string, StyleLeaf>();\n\n/**\n * A closed vocabulary of more than two keywords, as a menu.\n *\n * Its own component rather than a branch inside the router, so that deciding\n * WHICH surface a leaf gets and drawing one are separate readings: the router\n * is then short enough to see all three choices at once, which is the thing a\n * reader comes to it for.\n */\nfunction SelectField({\n  id,\n  control,\n  stored,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  control: StyleControl & { leaf: Extract<StyleLeaf, { kind: \"keyword\" }> };\n  stored: StyleValue | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const current = typeof stored === \"string\" ? stored : \"\";\n  const hint = useUnsetHint(\"Not set\");\n  // The validator accepts a keyword case-insensitively, with surrounding CSS\n  // whitespace and escapes, and accepts the CSS-wide keywords everywhere — so\n  // a stored `Bold` or `inherit` is live and compiles while matching no item\n  // here, and the select would render empty over a value that is doing\n  // something. Offered VERBATIM rather than normalised, in the place of the\n  // item it reads the same as, so the stored string needs no rule of its own.\n  const offered = menuKeywords(\n    control.leaf.cssProperty,\n    control.leaf.values,\n    current\n  );\n  return (\n    <div className=\"nx-style-inspector__select\">\n      <Select value={current} onValueChange={value => onCommit(value)}>\n        <SelectTrigger\n          id={id}\n          aria-describedby={described}\n          aria-invalid={describedBy === undefined ? undefined : true}\n        >\n          <SelectValue placeholder={hint} />\n        </SelectTrigger>\n        <SelectContent>\n          {/* In words, the CSS spelling in the tooltip; see style-keyword-labels. */}\n          {offered.map(option => (\n            <SelectItem key={option} value={option} title={option}>\n              {keywordLabel(control.leaf.cssProperty, option)}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    </div>\n  );\n}\n\n/**\n * What this control's clear action removes, named for the author.\n *\n * The property alone where a property draws one control, and the property plus\n * the position where it draws several: `padding` and `margin` both have a block\n * start, so two buttons called \"Clear block start\" name the same thing twice\n * and a screen-reader user cannot tell which style each removes.\n */\n/** A folded union's control, and the property it edits. */\ninterface Fold {\n  readonly kind: FoldedControl;\n  readonly property: string;\n}\n\n/** The folded control the property being drawn takes, if it is folded. */\nexport const FoldedUnion: React.Context<Fold | undefined> = React.createContext<\n  Fold | undefined\n>(undefined);\n\n/**\n * One control for a union the author picks without naming its form: a list\n * holding both forms' values, or a field that infers the form from the text.\n */\nfunction FoldedField({\n  id,\n  fold,\n  leaf,\n  stored,\n  actionName,\n  tokens,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  fold: Fold;\n  /** The leaf the field's variables are offered for; see `variableLeafOf`. */\n  leaf: StyleLeaf;\n  stored: StyleValue | undefined;\n  actionName: string;\n  tokens: SiteTokenSet | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The site's variables for this property: first in the list a weight is\n  // chosen from, and behind a menu of its own at a typed field's end, which\n  // has no unit menu to hold them.\n  const offered = useOfferedVariables(leaf, tokens);\n  const pick = (identity: string): void => {\n    onCommit({ $token: identity });\n  };\n  if (fold.kind === \"number-or-length\") {\n    return (\n      <div className=\"nx-style-inspector__numeric\">\n        <LengthOrNumberField\n          id={id}\n          leaf={leaf}\n          stored={stored}\n          tokens={tokens}\n          describedBy={describedBy}\n          onCommit={onCommit}\n        />\n        <VariableChoice\n          leaf={leaf}\n          tokens={tokens}\n          current={undefined}\n          label={actionName}\n          onPick={pick}\n        />\n      </div>\n    );\n  }\n  return (\n    <OptionSelect\n      id={id}\n      options={fontWeightOptions(stored)}\n      stored={stored}\n      describedBy={describedBy}\n      onCommit={onCommit}\n      variables={offered}\n      onPickVariable={pick}\n    />\n  );\n}\n\n/**\n * An inherited value by the name its option carries — `700` as \"Bold 700\" —\n * found by the key it would be stored under, so the list and the hint name a\n * weight the same way. As written when no option holds it.\n */\nfunction optionNamed(\n  options: readonly FoldedOption[],\n  written: string\n): string {\n  const number = trimCssWhitespace(written) === \"\" ? NaN : Number(written);\n  const key = storedKey(Number.isFinite(number) ? number : written);\n  return options.find(option => option.key === key)?.label ?? written;\n}\n\n/** A select over named options, each committing its own stored value. */\nfunction OptionSelect({\n  id,\n  options,\n  stored,\n  describedBy,\n  onCommit,\n  variables,\n  onPickVariable,\n}: {\n  id: string;\n  options: readonly FoldedOption[];\n  stored: StyleValue | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n  /** The site's variables the property takes, listed before the options. */\n  variables: readonly SiteVariable[];\n  onPickVariable: (identity: string) => void;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const current = storedKey(stored) ?? \"\";\n  const inherited = React.useContext(InheritedValue);\n  const hint =\n    inherited === undefined ? \"Not set\" : optionNamed(options, inherited);\n  return (\n    <div className=\"nx-style-inspector__select\">\n      <Select\n        value={current}\n        onValueChange={key => {\n          const identity = pickedVariable(key);\n          if (identity !== undefined) {\n            // The list becomes the variable's chip; focus follows to it.\n            focusVariableAfterPick(document.getElementById(id));\n            onPickVariable(identity);\n            return;\n          }\n          const chosen = options.find(option => option.key === key);\n          if (chosen !== undefined) onCommit(chosen.value);\n        }}\n      >\n        <SelectTrigger\n          id={id}\n          aria-describedby={described}\n          aria-invalid={describedBy === undefined ? undefined : true}\n        >\n          <SelectValue placeholder={hint} />\n        </SelectTrigger>\n        <SelectContent>\n          <VariableSelectItems offered={variables} before />\n          {options.map(option => (\n            <SelectItem key={option.key} value={option.key}>\n              {option.label}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    </div>\n  );\n}\n\n/**\n * A field taking a number or a length as typed: \"1.5\" is stored as a number,\n * \"24px\" or \"150%\" as written. Written as it is typed, as every text field in\n * the panel is, and the stretch of typing is one undo step, ended on blur and\n * on Enter. A shared style is written only when the edit ends.\n */\nfunction LengthOrNumberField({\n  id,\n  leaf,\n  stored,\n  tokens,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  /** The leaf the field's variables are offered for, both arms' kinds. */\n  leaf: StyleLeaf;\n  stored: StyleValue | undefined;\n  tokens: SiteTokenSet | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const { draft, setDraft, live } = useDraft(stored);\n  const typedLive = useTypesLive();\n  const mode = useCanvasTokenMode();\n  const hint = useUnsetHint(\"1.5, 24px or 150%\");\n  // A variable's name typed here is that variable, asked before the text is\n  // read as a number or a length, as every text field asks it.\n  const valueOf = (text: string): StyleValue | null => {\n    const named = tokenForTypedName(leaf, tokens, text, mode);\n    return named === undefined ? lineHeightFromText(text) : { $token: named };\n  };\n  const commit = () => {\n    live.join(() => {\n      if (draft === storedText(stored) || live.written(draft)) return;\n      if (onCommit(valueOf(draft)) === \"unchanged\") {\n        setDraft(storedText(stored));\n      }\n    });\n    live.end();\n  };\n  // A keystroke writes nothing while emptied or refused, so the canvas keeps\n  // the last valid value. Nor while it names a variable: a whole name can be\n  // on its way to a longer one, and storing it would swap the field for the\n  // variable mid-word. The name is matched when the field is left.\n  const write = (text: string): boolean => {\n    if (typedStyleText(text) === undefined) return false;\n    const value = valueOf(text);\n    return !isTokenRef(value) && onCommit(value) === \"applied\";\n  };\n  const owning = useLineHeightLabelScrub({ draft, setDraft, stored, onCommit });\n  return (\n    <Input\n      id={id}\n      value={draft}\n      placeholder={hint}\n      // A value, not words: no list of earlier entries over the field.\n      autoComplete=\"off\"\n      aria-describedby={described}\n      aria-invalid={describedBy === undefined ? undefined : true}\n      onChange={event => {\n        if (typedLive) live.type(event.target.value, write);\n        else setDraft(event.target.value);\n      }}\n      // Nothing of its own is written while a drag on the label owns it.\n      onBlur={() => owning() || commit()}\n      onKeyDown={event => {\n        if (commitOnEnter(event, commit)) return;\n        // An arrow steps the value as its kind steps, a number or a length,\n        // through the same rule as every numeric field.\n        const delta = arrowStep(event);\n        const leaf = delta === null ? undefined : lineHeightLeafFor(draft);\n        if (delta === null || leaf === undefined) return;\n        const next = steppedValue(\n          leaf,\n          lineHeightFromText(draft) ?? undefined,\n          delta\n        );\n        if (next === undefined) return;\n        event.preventDefault();\n        if (onCommit(next) !== \"refused\") setDraft(String(next));\n      }}\n    />\n  );\n}\n\n/**\n * A line height offered to its row's label to drag, as its kind steps: a\n * number or a length. Written as it moves where the panel writes as it is\n * typed, and on release, as a typed value is: the drag is one undo step.\n *\n * @returns whether a drag owns the value now, so the field writes nothing of\n *   its own meanwhile\n */\nfunction useLineHeightLabelScrub({\n  draft,\n  setDraft,\n  stored,\n  onCommit,\n}: {\n  draft: string;\n  setDraft: (value: string) => void;\n  stored: StyleValue | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): () => boolean {\n  const inherited = React.useContext(InheritedValue);\n  const typesLive = useTypesLive();\n  return useLabelScrub({\n    origin: lineHeightScrubOrigin(draft, inherited),\n    at: (from, delta) => {\n      const leaf = lineHeightLeafFor(String(from));\n      return leaf === undefined ? undefined : scrubbedValue(leaf, from, delta);\n    },\n    draft,\n    show: setDraft,\n    reset: () => setDraft(storedText(stored)),\n    commit: value => {\n      if (onCommit(value) === \"unchanged\") setDraft(storedText(stored));\n    },\n    ...(typesLive\n      ? { preview: (value: string | number) => onCommit(value) }\n      : {}),\n  });\n}\n\n/**\n * Properties whose free CSS has a field of its own, by CSS property: an aspect\n * ratio's menu and text decoration's icons, each with what it can draw.\n */\nconst OWN_FIELDS: Readonly<\n  Record<\n    string,\n    {\n      draws: (stored: StyleValue | undefined) => boolean;\n      /** Given the control and the site's variables too, for a field that offers them. */\n      Field: (\n        props: Parameters<typeof AspectRatioField>[0] & {\n          control: StyleControl;\n          tokens: SiteTokenSet | undefined;\n        }\n      ) => React.JSX.Element;\n      /** Whether its tab stop is a button a label's `for` would click. */\n      buttons: boolean;\n      /**\n       * The kind of value it draws, where one CSS property is written by\n       * several: `background-image` is both an image's address and a\n       * gradient, and only the address is a file to choose.\n       */\n      leaf?: StyleControl[\"leaf\"][\"kind\"];\n    }\n  >\n> = {\n  \"aspect-ratio\": {\n    draws: drawsAspectRatio,\n    Field: AspectRatioField,\n    buttons: false,\n  },\n  \"text-decoration\": {\n    draws: drawsDecoration,\n    Field: DecorationField,\n    buttons: true,\n  },\n  // A shadow is built with the shadow control, as a shadow variable is; a\n  // held shadow variable keeps its chip.\n  [BOX_SHADOW]: {\n    draws: drawsShadow,\n    Field: ShadowField,\n    buttons: false,\n  },\n  // Any position: the nine points, or one written as CSS beside them.\n  \"object-position\": {\n    draws: stored => stored === undefined || typeof stored === \"string\",\n    Field: FocalPointField,\n    buttons: true,\n  },\n  // The background's image: the Media library, an upload or a link, rather\n  // than an address typed as CSS.\n  \"background-image\": {\n    draws: stored => stored === undefined || typeof stored === \"string\",\n    Field: BackgroundImageField,\n    buttons: false,\n    leaf: \"url\",\n  },\n  // Where the background image sits, as the object position does.\n  \"background-position\": {\n    draws: stored => stored === undefined || typeof stored === \"string\",\n    Field: BackgroundPositionField,\n    buttons: true,\n  },\n  // How it is sized: Cover, Fit or Tile, each with the repeat it needs, or\n  // any other size written as CSS.\n  \"background-size\": {\n    draws: stored => stored === undefined || typeof stored === \"string\",\n    Field: BackgroundSizeField,\n    buttons: true,\n  },\n};\n\n/**\n * The field of its own a control is drawn with, if any: found by the CSS\n * property it writes, and by the kind of value where an entry names one.\n */\nfunction ownFieldFor(\n  leaf: StyleControl[\"leaf\"]\n): (typeof OWN_FIELDS)[string] | undefined {\n  const own = OWN_FIELDS[leaf.cssProperty];\n  return own === undefined || (own.leaf !== undefined && own.leaf !== leaf.kind)\n    ? undefined\n    : own;\n}\n\n/**\n * Whether a field's label only moves focus: where the control drawn is a\n * group of buttons, whose tab stop a label's `for` would click. Read from the\n * same decision that picks the control, so the two never disagree.\n */\nexport function labelFocusOnly(\n  leaf: StyleControl[\"leaf\"],\n  stored: StyleValue | undefined\n): boolean {\n  if (drawsIcons(leaf)) return true;\n  const own = ownFieldFor(leaf);\n  return own !== undefined && own.buttons && own.draws(stored);\n}\n\n/** The edited container's flow; CSS's defaults until it is measured or read. */\nexport const AlignmentFlow: React.Context<Flow> = React.createContext<Flow>({\n  writingMode: \"horizontal-tb\",\n  rtl: false,\n  flex: false,\n  direction: \"row\",\n});\n\n/**\n * The icon buttons a keyword control draws, when its property is one drawn as\n * icons, in the flow of the container being edited.\n */\nfunction useAlignmentGroup(control: StyleControl) {\n  const flow = React.useContext(AlignmentFlow);\n  return control.leaf.kind === \"keyword\"\n    ? alignmentGroupFor(control.leaf.cssProperty, control.leaf.values, flow)\n    : undefined;\n}\n\n/**\n * The control a leaf's kind resolves to.\n *\n * A keyword leaf carries a closed vocabulary: two values get a toggle and more\n * than two get a select over them. Every other kind is drawn as a text field\n * that accepts whatever the catalog judges — `length`, `number`, `color`, `css`\n * and `url` all store a scalar — with the numeric affordances layered on top\n * where the stored value is a single measurement.\n *\n * Layered rather than substituted, which is the decision worth keeping. A field\n * that MODELLED a length as a number and a unit could not hold `auto`,\n * `clamp(...)`, a two-part shorthand or a token, and would write each of them\n * away on the first edit. So the text field remains the control and the stepper\n * and unit menu are affordances it grows when the value is simple enough to\n * carry them; `style-numeric.ts` decides when that is, and answers `undefined`\n * rather than guessing.\n */\nexport function ValueField({\n  id,\n  labelledBy,\n  control,\n  stored,\n  actionName,\n  tokens,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  /** The field label's id, so a group of buttons can be named by it. */\n  labelledBy: string;\n  control: StyleControl;\n  stored: StyleValue | undefined;\n  /** What this control's clear action removes, named for the property. */\n  actionName: string;\n  /** The site's variables, which a field offers where its property takes one. */\n  tokens: SiteTokenSet | undefined;\n  /**\n   * The id of the message explaining why this control's last value was refused,\n   * or `undefined` when nothing was. Also what marks the control invalid: the\n   * two travel together because a control described by an error message and not\n   * marked invalid reads as one carrying a hint.\n   */\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // Decided BEFORE the menu, because every keyword leaf resolves to the\n  // `select` control kind — so a branch on that kind placed first would return\n  // for all of them and the toggle could never be reached.\n  // Both read before any branch, as hooks must be.\n  const fold = React.useContext(FoldedUnion);\n  // Alignment and direction as icons that follow the container's flow.\n  const alignment = useAlignmentGroup(control);\n  if (fold !== undefined) {\n    return (\n      <FoldedField\n        id={id}\n        fold={fold}\n        leaf={variableLeafOf(control.leaf, fold)}\n        stored={stored}\n        actionName={actionName}\n        tokens={tokens}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  if (alignment !== undefined) {\n    return (\n      <IconChoiceField\n        id={id}\n        labelledBy={labelledBy}\n        group={alignment}\n        stored={stored}\n        actionName={actionName}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  // A property with a field of its own, where the stored value is one that\n  // field can draw; any other spelling keeps the text field.\n  const own = ownFieldFor(control.leaf);\n  if (own !== undefined && own.draws(stored)) {\n    return (\n      <own.Field\n        id={id}\n        labelledBy={labelledBy}\n        control={control}\n        stored={stored}\n        actionName={actionName}\n        tokens={tokens}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  const toggle = toggleOptionsFor(control.leaf);\n  if (toggle !== undefined && toggleShows(toggle, stored)) {\n    return (\n      <ToggleField\n        id={id}\n        labelledBy={labelledBy}\n        options={toggle}\n        cssProperty={control.leaf.cssProperty}\n        stored={stored}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n\n  // A keyword vocabulary too wide for a toggle is a menu. Narrowed here rather\n  // than inside the component so the leaf carries its own kind through.\n  if (control.kind === \"select\" && control.leaf.kind === \"keyword\") {\n    return (\n      <SelectField\n        id={id}\n        control={{ ...control, leaf: control.leaf }}\n        stored={stored}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  if (MILLISECOND_PROPERTIES.has(control.leaf.cssProperty)) {\n    return (\n      <MillisecondsField\n        id={id}\n        control={control}\n        stored={stored}\n        actionName={actionName}\n        tokens={tokens}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  const scale = PERCENT_SCALES[control.leaf.cssProperty];\n  if (scale !== undefined) {\n    return (\n      <PercentField\n        scale={scale}\n        id={id}\n        control={control}\n        stored={stored}\n        actionName={actionName}\n        tokens={tokens}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  return (\n    <NumericField\n      id={id}\n      control={control}\n      stored={stored}\n      actionName={actionName}\n      tokens={tokens}\n      describedBy={describedBy}\n      onCommit={onCommit}\n    />\n  );\n}\n\n/**\n * A fraction as a percent, and back: multiplied or divided by 100 and no\n * more, to twelve significant figures, which drops the binary noise of the\n * division (`12.345 / 100` is `0.12345000000000001`) without rounding a\n * value an author typed.\n */\nfunction percentOf(fraction: number): number {\n  return Number((fraction * 100).toPrecision(12));\n}\n\nfunction fractionOf(percent: number): number {\n  return Number((percent / 100).toPrecision(12));\n}\n\n/**\n * How a value an author reads in percent is stored: opacity as the fraction\n * CSS takes, an overlay's strength as the percent itself; and where the\n * slider rests while nothing is set.\n */\ninterface PercentScale {\n  readonly fraction: boolean;\n  readonly unset: number;\n}\n\n/** The values drawn in percent, by CSS property. */\nconst PERCENT_SCALES: Readonly<Record<string, PercentScale>> = {\n  opacity: { fraction: true, unset: 100 },\n  [OVERLAY_STRENGTH]: { fraction: false, unset: 50 },\n};\n\n/** A stored value as the percent the field shows; anything else as stored. */\nfunction toPercent(\n  value: StyleValue | undefined,\n  scale: PercentScale\n): StyleValue | undefined {\n  return typeof value === \"number\" && scale.fraction ? percentOf(value) : value;\n}\n\n/**\n * What the percent field commits, as the fraction CSS takes. A number, or a\n * number typed as text, is divided by 100; a CSS-wide keyword is a whole\n * value and passes through unscaled.\n */\nfunction fromPercent(\n  value: StyleValue | null,\n  scale: PercentScale\n): StyleValue | null {\n  const number =\n    typeof value === \"number\"\n      ? value\n      : typeof value === \"string\"\n        ? textNumber(value)\n        : undefined;\n  if (number === undefined) return value;\n  return scale.fraction ? fractionOf(number) : number;\n}\n\n/** The values stored as whole milliseconds, by CSS property. */\nconst MILLISECOND_PROPERTIES: ReadonlySet<string> = new Set([\n  APPEAR_DURATION_PROPERTY,\n  APPEAR_DELAY_PROPERTY,\n]);\n\n/**\n * A time stored as a number of milliseconds: the ordinary number field, with\n * its unit beside it, since the number alone does not say what it counts.\n */\nfunction MillisecondsField(\n  props: React.ComponentProps<typeof NumericField>\n): React.JSX.Element {\n  const unitId = React.useId();\n  return (\n    <div className=\"nx-style-inspector__unit-field\">\n      <UnitWords.Provider value={unitId}>\n        <NumericField {...props} />\n      </UnitWords.Provider>\n      <span className=\"nx-style-inspector__unit\" aria-hidden=\"true\">\n        ms\n      </span>\n      {/* The sign is not read; these words are, as the field's description. */}\n      <span id={unitId} className=\"sr-only\">\n        milliseconds\n      </span>\n    </div>\n  );\n}\n\n/**\n * Opacity, which an author thinks of in percent: a slider for \"more or\n * less\" and the number field beside it for an exact value, both 0 to 100.\n *\n * The number field is the ordinary one, handed the value and its range in\n * percent and converting what it commits back, so every behaviour it has (a\n * draft held while its menu opens, a refused value said beside it, a keyword\n * passed through, the variables at its end) is the same here. The inherited\n * value it shows as a hint is converted the same way.\n */\nfunction PercentField({\n  scale,\n  ...props\n}: React.ComponentProps<typeof NumericField> & {\n  scale: PercentScale;\n}): React.JSX.Element {\n  const { control, stored, actionName, describedBy, onCommit } = props;\n  const unitId = React.useId();\n  const { shown, inheritedShown, resting } = percentReading(\n    stored,\n    React.useContext(InheritedValue),\n    scale\n  );\n  const leaf = control.leaf;\n  const percentControl =\n    leaf.kind === \"number\"\n      ? { ...control, leaf: { ...leaf, min: 0, max: 100 } }\n      : control;\n  return (\n    <div className=\"nx-style-inspector__opacity\">\n      {resting === undefined ? null : (\n        <PercentSlider\n          resting={resting}\n          actionName={actionName}\n          describedBy={describedBy}\n          onCommit={next => onCommit(fromPercent(next, scale))}\n        />\n      )}\n      <InheritedValue.Provider value={inheritedShown}>\n        <UnitWords.Provider value={unitId}>\n          <NumericField\n            {...props}\n            control={percentControl}\n            stored={shown}\n            onCommit={value => onCommit(fromPercent(value, scale))}\n          />\n        </UnitWords.Provider>\n      </InheritedValue.Provider>\n      <span className=\"nx-style-inspector__percent\" aria-hidden=\"true\">\n        %\n      </span>\n      {/* The sign is not read; these words are, as the field's description. */}\n      <span id={unitId} className=\"sr-only\">\n        percent\n      </span>\n    </div>\n  );\n}\n\n/**\n * An opacity as the field shows it: the stored value in percent, the\n * inherited one in percent as its hint, and where the slider's thumb rests.\n *\n * The thumb rests on the value set here, else the one inherited, else the\n * 100% of an unset opacity. A keyword (`inherit`) is none of these, so it has\n * no resting place and no slider: no position stands for it, and a nudge\n * would replace it with a number built from a position it never had.\n */\nfunction percentReading(\n  stored: StyleValue | undefined,\n  inherited: string | undefined,\n  scale: PercentScale\n): {\n  shown: StyleValue | undefined;\n  inheritedShown: string | undefined;\n  resting: number | undefined;\n} {\n  const shown = toPercent(stored, scale);\n  const inheritedNumber =\n    inherited === undefined ? undefined : textNumber(inherited);\n  const inheritedPercent =\n    inheritedNumber === undefined\n      ? undefined\n      : scale.fraction\n        ? percentOf(inheritedNumber)\n        : inheritedNumber;\n  const unsetResting =\n    inheritedPercent ?? (inherited === undefined ? scale.unset : undefined);\n  return {\n    shown,\n    inheritedShown:\n      inheritedPercent === undefined ? inherited : String(inheritedPercent),\n    resting:\n      typeof shown === \"number\"\n        ? shown\n        : shown === undefined\n          ? unsetResting\n          : undefined,\n  };\n}\n\n/**\n * A percent's slider, 0 to 100: the thumb follows a drag, and so does the\n * canvas where the panel writes as it is typed, at most once a frame; the\n * value it settles on is written in the same run, so the drag is one undo\n * step. Elsewhere the value is written once it settles.\n */\nfunction PercentSlider({\n  resting,\n  actionName,\n  describedBy,\n  onCommit,\n}: {\n  resting: number;\n  actionName: string;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  const [preview, setPreview] = React.useState<number | undefined>(undefined);\n  // Held with its section, as the fieldset holds the form controls; a\n  // slider's thumb is not one, so it is told.\n  const held = React.useContext(SectionHeld);\n  const typesLive = useTypesLive();\n  const gesture = useLiveGesture();\n  const at = preview ?? resting;\n  return (\n    <Slider\n      value={[at]}\n      min={0}\n      max={100}\n      step={1}\n      disabled={held}\n      onValueChange={([next]) => {\n        setPreview(next);\n        if (typesLive && next !== undefined) gesture.move(() => onCommit(next));\n      }}\n      onValueCommit={([next]) => {\n        setPreview(undefined);\n        if (next === undefined) gesture.end();\n        else if (typesLive) gesture.end(() => onCommit(next));\n        else onCommit(next);\n      }}\n      thumbs={[\n        {\n          \"aria-label\": `${actionName} slider`,\n          \"aria-valuetext\": `${at} percent`,\n          // A refusal said for the field is said for the slider too, which\n          // may hold the focus when it arrives.\n          ...(describedBy === undefined\n            ? {}\n            : { \"aria-describedby\": described }),\n        },\n      ]}\n    />\n  );\n}\n\n/**\n * Two keywords as two buttons, with the current one pressed.\n *\n * `aria-pressed` rather than a radio group: these are two states of one\n * property rather than a choice among options that includes \"neither\", and the\n * clear affordance beside them is what expresses unset. Labelled by the field's\n * own label, so a screen reader reads the property name before the state.\n */\nfunction ToggleField({\n  id,\n  labelledBy,\n  options,\n  cssProperty,\n  stored,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  labelledBy: string;\n  options: readonly string[];\n  /** The property the options are keywords of, for their words. */\n  cssProperty: string;\n  stored: StyleValue | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // The refusal, and the CSS names while they are shown.\n  const described = useFieldDescription(describedBy);\n  // What each option writes, from the field it is drawn in.\n  const optionWrites = React.useContext(OptionWrites);\n  return (\n    <div\n      // The field's id sits on the GROUP rather than on any one button. The\n      // field label carries `htmlFor`, and a label pointing at a button\n      // forwards a click to it — so naming the first option that way would make\n      // clicking the property label press it, or clear it when already pressed,\n      // and write an edit the author never asked for. A `div` is not labelable,\n      // so the association is inert and the group is named by `aria-labelledby`\n      // instead, which is what a screen reader reads either way.\n      id={id}\n      className=\"nx-style-inspector__toggle\"\n      role=\"group\"\n      aria-labelledby={labelledBy}\n      aria-describedby={described}\n    >\n      {options.map(option => {\n        const pressed = stored === option;\n        return (\n          // What this option writes, on hover or keyboard focus.\n          <CssHint\n            key={option}\n            writes={optionWrites?.(option) ?? `${cssProperty}: ${option}`}\n          >\n            <button\n              type=\"button\"\n              aria-pressed={pressed}\n              // Marked on the BUTTONS rather than on the group, which carries the\n              // description. `aria-invalid` is not a state `role=\"group\"`\n              // supports, so setting it there would be an attribute a screen\n              // reader is entitled to ignore — and the file's own rule is that a\n              // control described by a refusal must also read as invalid, or it\n              // announces the message as a hint rather than as a failure.\n              aria-invalid={describedBy === undefined ? undefined : true}\n              // Pressing the pressed option CLEARS rather than re-writing it,\n              // which is the only way a group of options can reach unset without\n              // spending a button on \"neither\".\n              onClick={() => onCommit(pressed ? null : option)}\n            >\n              {keywordLabel(cssProperty, option)}\n            </button>\n          </CssHint>\n        );\n      })}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * Which control a style property draws: the font control or the value\n * control, a held variable, a retained value the control cannot show, and\n * the field drawn for a value no control supports.\n *\n * @module style-control-value\n */\nimport {\n  isTokenRef,\n  type FontFaceDef,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type StyleValue,\n  tokenRef,\n} from \"@nextlyhq/blocks-engine\";\nimport { Label } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  FontChoicesContext,\n  FontFamilyField,\n  fontFamilyShowable,\n  type FontChoices,\n} from \"../../panels/design/font-family-field\";\nimport {\n  focusAfterUnlink,\n  VariableChip,\n} from \"../../panels/design/variable-choice\";\nimport { BASELINE_WITHHELD_HINT } from \"../../styles/style-baseline\";\nimport { colourShowable } from \"../../styles/style-colour\";\nimport type { StyleControl } from \"../../styles/style-controls\";\n\nimport { ColourField } from \"./style-colour-field\";\nimport type { CommitOutcome } from \"./style-field-surroundings\";\nimport { displayText, editableText } from \"./style-text-field\";\nimport { variableLeafOf, FoldedUnion, ValueField } from \"./style-value-fields\";\n\n/** No faces, as one value, so the Font control's list is not rebuilt each render. */\nconst NO_FACES: readonly FontFaceDef[] = Object.freeze([]);\n\n/**\n * The Font control where the leaf is `font-family`, chosen from what the site\n * can draw before any other surface (a stored variable shows as the choice it\n * is); every other value as {@link ControlValue} draws it. A value that can\n * only be cleared stays that way.\n */\nexport function ControlOrFont(\n  props: Parameters<typeof ControlValue>[0]\n): React.JSX.Element {\n  const fonts = React.useContext(FontChoicesContext);\n  const font = props.clearOnly ? null : fontControl({ ...props, fonts });\n  return font ?? <ControlValue {...props} />;\n}\n\n/**\n * The Font control, for the `font-family` leaf: CHOSEN from what the site can\n * draw rather than typed, since a typed family the site has no file for\n * renders in whatever the reader's device has. `null` for any other leaf, or\n * a stored value the picker cannot show.\n */\nfunction fontControl({\n  id,\n  labelledBy,\n  control,\n  stored,\n  tokens,\n  fonts,\n  onCommit,\n}: {\n  id: string;\n  labelledBy: string;\n  control: Parameters<typeof ControlValue>[0][\"control\"];\n  stored: Parameters<typeof ControlValue>[0][\"stored\"];\n  tokens: Parameters<typeof ControlValue>[0][\"tokens\"];\n  fonts: FontChoices | undefined;\n  onCommit: Parameters<typeof ControlValue>[0][\"onCommit\"];\n}): React.JSX.Element | null {\n  const isFontFamily =\n    control.leaf.kind === \"cssValue\" &&\n    control.leaf.cssProperty === \"font-family\";\n  if (!isFontFamily || !fontFamilyShowable(stored)) return null;\n  const manage = fonts?.onManageFonts;\n  return (\n    <FontFamilyField\n      id={id}\n      labelledBy={labelledBy}\n      stored={stored}\n      tokens={tokens}\n      faces={fonts?.faces}\n      fromCode={fonts?.fromCode ?? NO_FACES}\n      onCommit={onCommit}\n      {...(manage === undefined ? {} : { onManageFonts: manage })}\n    />\n  );\n}\n\n/**\n * The surface one value is shown through: read-only, a token, or editable.\n *\n * Its own component rather than a chain of conditionals inside the field,\n * because the three are genuinely different surfaces — one of them cannot be\n * typed into at all — and reading them as early returns says that, where a\n * nested ternary reads as one control with two exceptions.\n */\nfunction ControlValue({\n  id,\n  labelledBy,\n  control,\n  stored,\n  actionName,\n  clearOnly,\n  tokens,\n  prefersDark,\n  pairedColour,\n  obscuredBy,\n  describedBy,\n  onCommit,\n}: {\n  id: string;\n  labelledBy: string;\n  control: StyleControl;\n  stored: StyleValue | undefined;\n  actionName: string;\n  clearOnly: boolean;\n  tokens: SiteTokenSet | undefined;\n  /** Whether the viewer's system asks for dark, for a site on the media strategy. */\n  prefersDark: boolean;\n  /** The other half of this control's contrast pair, when its leaf has one. */\n  pairedColour: StyleValue | undefined;\n  /**\n   * A property on this node that puts something between the pair, or\n   * `undefined` when none does. A verdict is withheld while one is set.\n   */\n  obscuredBy: string | undefined;\n  describedBy: string | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // Read before any branch, as hooks must be: a folded union offers the\n  // variables either of its arms takes.\n  const fold = React.useContext(FoldedUnion);\n  if (clearOnly) {\n    return (\n      <RetainedValue\n        labelledBy={labelledBy}\n        label={actionName}\n        stored={stored}\n        // A value the Baseline gate no longer offers says why it is clear-only.\n        note={control.withheld ? BASELINE_WITHHELD_HINT : undefined}\n        onClear={() => onCommit(null)}\n      />\n    );\n  }\n  /*\n   * A colour draws its own surface, INCLUDING for a stored token reference.\n   *\n   * Placed before the token branch below rather than after it, because that one\n   * returns for every reference and a colour control would never see one. It\n   * exists for controls that cannot offer a token picker, and says so: choosing\n   * a token was \"the token picker's job and it does not exist yet\". For a\n   * colour it now does, so a reference here is editable rather than read-only.\n   *\n   * Narrowed on the LEAF rather than on `control.kind`, because the leaf is what\n   * carries `tokenKinds` and `cssProperty` — the two facts the colour surface\n   * asks the catalog for — so passing it narrowed means neither is re-derived.\n   *\n   * Guarded by {@link colourShowable}, so a value NO colour control can\n   * represent — an object at a scalar position from an import or the API — does\n   * not take this branch and skip the read-only surface below. Without it the\n   * field projects that object to an empty draft and reads as unset while the\n   * value goes on compiling, which is the failure the surface below exists to\n   * prevent.\n   */\n  if (control.leaf.kind === \"color\" && colourShowable(stored)) {\n    return (\n      <ColourField\n        id={id}\n        labelledBy={labelledBy}\n        control={{ ...control, leaf: control.leaf }}\n        stored={stored}\n        actionName={actionName}\n        tokens={tokens}\n        prefersDark={prefersDark}\n        pairedColour={pairedColour}\n        obscuredBy={obscuredBy}\n        describedBy={describedBy}\n        onCommit={onCommit}\n      />\n    );\n  }\n  /*\n   * A held variable, by name in place of the typed value, the name the way to\n   * choose another. Every reference reaches this, including one at a leaf\n   * that takes no variable or to a variable the site no longer has: the chip\n   * still names it, the name opens a list only where a choice exists, and the\n   * row's Reset removes it.\n   * Typing over a reference is not offered, because the text would store the\n   * variable's NAME as a literal, which compiles to nothing.\n   */\n  if (isTokenRef(stored)) {\n    return (\n      <HeldVariable\n        id={id}\n        labelledBy={labelledBy}\n        leaf={variableLeafOf(control.leaf, fold)}\n        identity={stored.$token}\n        times={stored.times}\n        actionName={actionName}\n        tokens={tokens}\n        onCommit={onCommit}\n      />\n    );\n  }\n  // A value the editing surface below cannot represent. Drawing it anyway is\n  // the worst of the three outcomes: the control reads as unset, the value goes\n  // on compiling, and the keystroke that would clear it is the one the field\n  // refuses. Shown and removable instead, which is what the other two branches\n  // already do for the other two kinds of unteachable value.\n  if (editableText(control, stored) === undefined) {\n    return (\n      <RetainedValue\n        labelledBy={labelledBy}\n        label={actionName}\n        stored={stored}\n        note=\"No control here can edit this value. It is still on the page and can be cleared.\"\n        onClear={() => onCommit(null)}\n      />\n    );\n  }\n  return (\n    <ValueField\n      id={id}\n      labelledBy={labelledBy}\n      control={control}\n      stored={stored}\n      actionName={actionName}\n      tokens={tokens}\n      describedBy={describedBy}\n      onCommit={onCommit}\n    />\n  );\n}\n\n/**\n * The reference a chip commits when another variable replaces its own: the\n * new variable at the held one's scale, which is the size it was set to (a\n * Small button's padding), not a property of the variable.\n */\nexport function pickedReference(\n  picked: string,\n  times: number | undefined\n): { $token: string; times?: number } {\n  // Built by the engine's one constructor, which a reader of stored text\n  // derives the reference's spelling from.\n  return tokenRef(picked, times);\n}\n\n/**\n * A field holding a variable: the green chip naming it, its name the way to\n * choose another, and its Unlink, which puts the typed field back holding the\n * variable's value.\n */\nfunction HeldVariable({\n  id,\n  labelledBy,\n  leaf,\n  identity,\n  times,\n  actionName,\n  tokens,\n  onCommit,\n}: {\n  /** The id the typed field takes again once the variable is cleared. */\n  id: string;\n  labelledBy: string;\n  /** The leaf the field's variables are offered for; see `variableLeafOf`. */\n  leaf: StyleLeaf;\n  identity: string;\n  /** The factor the variable is scaled by, if it is. */\n  times?: number | undefined;\n  actionName: string;\n  tokens: SiteTokenSet | undefined;\n  onCommit: (value: StyleValue | null) => CommitOutcome;\n}): React.JSX.Element {\n  // A scaled variable stays scaled when another replaces it: the factor is\n  // the size it was set to (a Small button's padding), not the variable's.\n  const pick = (picked: string): CommitOutcome =>\n    onCommit(pickedReference(picked, times));\n  const unlink = (value: StyleValue): void => {\n    // Unlinking puts the typed field back in the chip's place, holding the\n    // value, and the Unlink that held focus is gone: focus goes to that field\n    // once it is drawn, rather than falling to the page. One commit, so one\n    // undo puts the variable back.\n    if (onCommit(value) === \"refused\") return;\n    focusAfterUnlink(() => document.getElementById(id));\n  };\n  return (\n    <div className=\"nx-style-inspector__numeric\">\n      <VariableChip\n        leaf={leaf}\n        tokens={tokens}\n        identity={identity}\n        times={times}\n        label={actionName}\n        labelledBy={labelledBy}\n        onPick={pick}\n        onUnlink={unlink}\n      />\n    </div>\n  );\n}\n\n/**\n * A value that is live on the page and cannot be edited here: shown, and\n * removable.\n *\n * Three different reasons reach this one surface — the block's `supports` no\n * longer declares the property, no control in this build can draw the leaf's\n * kind, or the stored value has a shape the control cannot represent — and they\n * share it because the author's position is identical in all three: the styling\n * is on the page, nothing here can change it, and the panel owes them the\n * action that removes it. `note` is what tells them WHICH of the three, since\n * only the first has a notice of its own beside the property.\n *\n * Named for the property for the same reason the variable chip is — several of\n * these on one panel would otherwise be a column of identical \"Clear\" buttons.\n */\nfunction RetainedValue({\n  labelledBy,\n  label,\n  stored,\n  note,\n  onClear,\n}: {\n  /** The id of the label element that names this value. */\n  labelledBy: string;\n  label: string;\n  stored: StyleValue | undefined;\n  /** Why this value cannot be edited, where the property does not already say. */\n  note?: string;\n  onClear: () => void;\n}): React.JSX.Element {\n  const noteId = React.useId();\n  return (\n    <>\n      {/*\n        `group` for the reason the variable chip carries one: the ARIA\n        `paragraph` role a bare paragraph maps to prohibits an accessible name.\n\n        The note is pointed AT rather than left beside: it is the only thing\n        saying why this value cannot be edited, and a group announced with its\n        name and its Clear button but not its reason tells a screen-reader user\n        that a field is read-only without ever saying what made it so.\n      */}\n      <p\n        className=\"nx-style-inspector__token\"\n        role=\"group\"\n        aria-labelledby={labelledBy}\n        aria-describedby={note === undefined ? undefined : noteId}\n        tabIndex={-1}\n      >\n        {/*\n          `displayText` rather than the text-field projection, which answers\n          `\"\"` for a shape it cannot type — and an empty span beside a Clear\n          button asks an author to remove something they cannot see.\n        */}\n        <span>{displayText(stored)}</span>\n        <button type=\"button\" onClick={onClear} aria-label={`Clear ${label}`}>\n          Clear\n        </button>\n      </p>\n      {note === undefined ? null : (\n        <p className=\"nx-inspector__note\" id={noteId}>\n          {note}\n        </p>\n      )}\n    </>\n  );\n}\n\n/**\n * Whether this position renders no element a label can be attached to.\n *\n * HTML's `for` only associates a label with a LABELABLE element — input,\n * select, textarea, button, output, meter, progress. Pointing it at the\n * paragraph the read-only surfaces render drops the association SILENTLY, so\n * the label carries an id of its own and the value points back at it instead.\n *\n * `control.supported` is not a term here: the caller returns before this is\n * read, so including it would be a condition that can never be true where it\n * is used.\n */\nexport function showsNoField(\n  control: StyleControl,\n  stored: StyleValue | undefined,\n  clearOnly: boolean\n): boolean {\n  if (clearOnly) return true;\n  // Every reference, whatever the control. The colour surface reaches this the\n  // same way the others do: it draws a name and a button for a reference and a\n  // text field only for a literal, so a reference has no field there either.\n  if (isTokenRef(stored)) return true;\n  return editableText(control, stored) === undefined;\n}\n\n/**\n * A position this build has no control for: shown by value, and removable.\n *\n * Its own component because it is a different SURFACE rather than a variation\n * of one — nothing here is editable, so no labelable element exists and the\n * label has to name the value by id instead of pointing at a field.\n *\n * UNTESTED as a CATALOG case, and stated rather than left to be assumed: every\n * leaf kind the engine ships resolves to a control, so only a catalog written\n * by a newer engine reaches this — and the catalog is compiled in rather than\n * registered, so no fixture can hand this panel an unknown kind. What IS\n * reachable and IS covered is the value: a node can store one at such a leaf,\n * and it compiles.\n */\nexport function UnsupportedField({\n  labelId,\n  label,\n  summary,\n  actionName,\n  leafKind,\n  stored,\n  onClear,\n}: {\n  labelId: string;\n  label: string;\n  summary: string | undefined;\n  actionName: string;\n  leafKind: StyleLeaf[\"kind\"];\n  stored: StyleValue | undefined;\n  onClear: () => void;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-inspector__field\" data-unsupported={leafKind}>\n      {/* No `htmlFor`: this branch renders no labelable element. */}\n      <Label id={labelId} title={summary}>\n        {label}\n      </Label>\n      <RetainedValue\n        labelledBy={labelId}\n        label={actionName}\n        stored={stored}\n        note={`This build has no control for ${leafKind} values.`}\n        onClear={onClear}\n      />\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * Where a control's value came from, told to the author: the shared value\n * line, the provenance dot and its description, and the breakpoint label\n * both use.\n *\n * @module style-provenance-indicators\n */\nimport type {\n  BreakpointId,\n  BreakpointSet,\n  NodeStyles,\n  StyleOrigin,\n  StyleTraceEntry,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  DEFAULT_TOKEN_PREFIX,\n  SITE_TEXT_LABELS,\n  siteTextRoleOf,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { SharedStyleRow } from \"../../styles/shared-style-library\";\nimport {\n  breakpointSource,\n  propertiesWriting,\n  type StyleProvenance,\n} from \"../../styles/style-provenance\";\nimport { readStyleValue, type StyleAddress } from \"../../styles/style-values\";\nimport { fieldLabel } from \"../inspector\";\n\nimport { siteDefaultSource } from \"./site-default-source\";\nimport { stateLabel } from \"./state-switcher\";\nimport {\n  TokenPrefixContext,\n  type ProvenanceAnswer,\n  type EditedAddress,\n} from \"./style-field-surroundings\";\nimport type { StyleTarget } from \"./style-target\";\n\n/**\n * Where a value stands between the block and its shared style, in words.\n *\n * Editing the block, a value the block sets over its style reads \"Set on this\n * block · overrides Card\", with Reset, which shows the style's value again.\n * Editing the style, a value the block sets over it reads \"Set on this block\n * · Move to Card\", which moves it into the style. Nothing otherwise.\n */\nexport function SharedValueLine({\n  target,\n  answer,\n  nodeStyles,\n  address,\n  actionName,\n  onResetBlock,\n  onMoveTo,\n}: {\n  target: StyleTarget;\n  answer: ProvenanceAnswer | undefined;\n  nodeStyles: NodeStyles | undefined;\n  address: StyleAddress;\n  actionName: string;\n  onResetBlock: () => void;\n  onMoveTo: (target: Extract<StyleTarget, { kind: \"shared\" }>) => void;\n}): React.JSX.Element | null {\n  if (readStyleValue(nodeStyles, address) === undefined) return null;\n  if (target.kind === \"shared\") {\n    return (\n      <div className=\"nx-style-inspector__shared-line\" data-shared-line=\"move\">\n        <span data-shared-line-text=\"\">Set on this block</span>\n        {/* The action on a line of its own, so no separator can end a line. */}\n        <button\n          type=\"button\"\n          className=\"nx-style-inspector__breakpoint-action\"\n          aria-label={`Move ${actionName} to ${target.style.name}`}\n          disabled={target.readOnly !== undefined}\n          onClick={() => onMoveTo(target)}\n        >\n          Move to {target.style.name}\n        </button>\n      </div>\n    );\n  }\n  const under = styleBeneath(target.worn, answer, address);\n  if (under === undefined) return null;\n  // A text style is the block's own typographic choice, so a value over it\n  // reads as a change from it: \"Changed from Eyebrow\".\n  const words =\n    under.text === true\n      ? `Changed from\\u00a0${under.name}`\n      : `Set on this block\\u00a0·\\u00a0overrides\\u00a0${under.name}`;\n  return (\n    <div\n      className=\"nx-style-inspector__shared-line\"\n      data-shared-line=\"override\"\n    >\n      {/*\n       * The separator is held to the words on either side by no-break spaces,\n       * so a wrap falls between other words and never leaves it ending a line.\n       */}\n      <span data-shared-line-text=\"\">{words}</span>\n      <button\n        type=\"button\"\n        className=\"nx-style-inspector__breakpoint-action\"\n        aria-label={`Reset ${actionName} on this block, showing ${under.name}'s value`}\n        onClick={onResetBlock}\n      >\n        Reset\n      </button>\n    </div>\n  );\n}\n\n/**\n * The worn style that would show at this control without the block's own\n * value, or `undefined` when none would: the block's own value at a wider\n * tier, or nothing at all.\n *\n * Read from the cascade's answer where the host supplies one, so a value the\n * block sets at a narrow breakpoint or in a state over the style's wider or\n * base-state value is named, and a block value between the two is not. With\n * no cascade, or a declaration the trace cannot tie to one control, the\n * style's own value at this exact address, the last in library order as the\n * cascade applies them: true where it answers, silent elsewhere.\n */\nfunction styleBeneath(\n  worn: readonly SharedStyleRow[],\n  answer: ProvenanceAnswer | undefined,\n  address: StyleAddress\n): SharedStyleRow | undefined {\n  const beneath = answer?.beneath;\n  if (beneath === undefined || beneath.kind === \"ambiguous\") {\n    return [...worn]\n      .reverse()\n      .find(row => readStyleValue(row.styles, address) !== undefined);\n  }\n  if (beneath.kind !== \"inherited\") return undefined;\n  const from = beneath.from;\n  return from.kind === \"class\"\n    ? worn.find(row => row.id === from.id)\n    : undefined;\n}\n\n/**\n * Where a control's value came from, as a dot beside its label.\n *\n * Three visible states, following the affordance `style-provenance.ts` already\n * says it follows: nothing set draws no dot at all, a value authored here is\n * accented, and one arriving from anywhere else is warned. An author scanning a\n * section sees at a glance which fields are theirs and which they would be\n * taking over by typing.\n *\n * **A dot rather than a written badge**, because a section holds eight or more\n * controls and a label naming the source would have to name its AXIS too once\n * breakpoints are in play — which does not fit beside a numeric input without\n * widening the panel or wrapping every row.\n *\n * **The source is named in the accessible label, not only in the tooltip.** A\n * `title` reaches a mouse and nothing else, so a dot carrying its meaning only\n * there is decoration to a screen-reader user and to anyone navigating by\n * keyboard. The text is the same in both.\n *\n * **`ambiguous` deliberately draws NOTHING.** One CSS property can be written by\n * two catalog controls — `background-image` comes from both `background.url`\n * and `backgroundGradient` — and with one of the pair stored, the trace cannot\n * say which control wrote it. A dot claiming a value this control does not hold\n * is worse than no dot, which is the same judgement `StyleProvenance` makes by\n * reporting the case rather than guessing.\n */\nexport function ProvenanceDot({\n  answer,\n  editing,\n  descendant,\n}: {\n  answer: ProvenanceAnswer | undefined;\n  editing: EditedAddress;\n  /** The control's own descendant selector, to tell its rules from a sibling's. */\n  descendant: string | undefined;\n}): React.JSX.Element | null {\n  const tokenPrefix = React.useContext(TokenPrefixContext);\n  const described = describeProvenance(\n    answer?.provenance,\n    editing,\n    descendant,\n    tokenPrefix\n  );\n  if (described === null) return null;\n  return (\n    <>\n      <span\n        className=\"nx-style-inspector__provenance\"\n        data-provenance={described.kind}\n        title={described.text}\n        /*\n         * A role, because the element is empty: the dot is drawn by the\n         * stylesheet, so without one the label is the only content and assistive\n         * technology has nothing to attach the description to.\n         */\n        role=\"img\"\n        aria-label={described.text}\n      />\n      {/*\n       * The same sentence, for a sighted keyboard user.\n       *\n       * `title` reaches a POINTER and nothing else, and `aria-label` reaches\n       * assistive technology and nothing else. Between them sits the person who\n       * tabs to a control and can see the screen: they got a coloured dot with\n       * no way to learn what it means, which is the one group the first two\n       * accommodations do not cover.\n       *\n       * Revealed on `:focus-within` of the field rather than made focusable\n       * itself. A focusable dot would put a second tab stop in front of every\n       * control in a panel that already has eight or more per section, so\n       * reaching the last field would cost twice the presses — fixing the\n       * explanation by damaging the navigation it explains.\n       *\n       * `aria-hidden` because the dot beside it already carries this text: two\n       * copies in the accessibility tree is the same sentence announced twice,\n       * which reads as a stutter rather than as emphasis.\n       */}\n      {described.kind === \"inherited\" && answer?.jump === undefined ? (\n        /*\n         * An inherited value's source stays in sight, under the label: the\n         * value shown greyed in the control is only half an answer without\n         * where it came from. In brief, with the whole sentence on hover for\n         * a caption the row cuts short, and in text on focus below. Not where\n         * the row offers a jump to its source: the jump names it, and goes\n         * there.\n         */\n        <span\n          className=\"nx-style-inspector__provenance-source\"\n          title={described.text}\n          aria-hidden=\"true\"\n        >\n          {described.source}\n        </span>\n      ) : null}\n      <span className=\"nx-style-inspector__provenance-text\" aria-hidden=\"true\">\n        {described.text}\n      </span>\n    </>\n  );\n}\n\n/**\n * The dot's state and the sentence that names it, or `null` to draw nothing.\n *\n * Separated from the component so the wording is testable without rendering,\n * and so the two cannot drift: the tooltip and the accessible label are the same\n * string by construction rather than by two call sites agreeing.\n */\nexport function describeProvenance(\n  provenance: StyleProvenance | undefined,\n  editing: EditedAddress,\n  controlDescendant?: string,\n  /** The prefix the compile wrote variables under, to name a site default. */\n  tokenPrefix: string = DEFAULT_TOKEN_PREFIX\n):\n  | { kind: \"authored\"; text: string }\n  | { kind: \"inherited\"; text: string; source: string }\n  | null {\n  if (provenance === undefined) return null;\n  if (provenance.kind === \"authored\") {\n    return { kind: \"authored\", text: \"Set here\" };\n  }\n  if (provenance.kind !== \"inherited\") return null;\n  const { from, entry } = provenance;\n  // A Site text row is named as the row: \"From Site text: Heading 2\", in the\n  // sentence and the caption alike, since the row is where it is changed.\n  const row = siteTextRowOf(from, entry);\n  if (row !== undefined) {\n    const words = `From Site text: ${row}`;\n    return { kind: \"inherited\", text: words, source: words };\n  }\n  // A block default reading a site setting is named as the setting: \"Site\n  // default: Section spacing\", and \"Site default\" in brief.\n  const siteDefault = siteDefaultSource(from, entry, tokenPrefix);\n  if (siteDefault !== undefined) {\n    return { kind: \"inherited\", text: siteDefault, source: \"Site default\" };\n  }\n  // A shared style is named as the source the author chose for the block,\n  // \"From Card\"; every other tier is inherited.\n  const lead = from.kind === \"class\" ? \"From\" : \"Inherited from\";\n  return {\n    kind: \"inherited\",\n    text: `${lead} ${originName(from, entry, editing, controlDescendant)}`,\n    source: `From ${originBrief(from, entry, editing, controlDescendant)}`,\n  };\n}\n\n/**\n * The Site text row a declaration came from, by its label (\"Heading 2\"), or\n * `undefined` for any other: the element tier writes a row's values and its\n * own defaults (a margin, a heading's weight), and only the first are a row's.\n */\nfunction siteTextRowOf(\n  origin: StyleOrigin,\n  entry: StyleTraceEntry\n): string | undefined {\n  if (origin.kind !== \"element\") return undefined;\n  const role = siteTextRoleOf(origin.tag, entry.property);\n  return role === undefined ? undefined : SITE_TEXT_LABELS[role];\n}\n\n/**\n * The same place in brief, for the caption drawn beside an inherited value:\n * the tier, then each axis that differs, named as the panel names them.\n *\n * Built from the same reading as {@link originName}: the control a rule came\n * through and the axes that differ are asked of the same helpers, so the\n * caption and the sentence cannot name two different places. Shorter where\n * the sentence spends words on what the author already knows, the block they\n * selected, and on qualifiers a caption of one row has no room for.\n */\nfunction originBrief(\n  origin: StyleOrigin,\n  entry: StyleTraceEntry,\n  editing: EditedAddress,\n  controlDescendant: string | undefined\n): string {\n  const control = sourceControl(entry, controlDescendant);\n  const ownBlock = origin.kind === \"node\" && origin.id === editing.nodeId;\n  const parts = [ownBlock ? control : briefSubject(origin, editing)];\n  // Defaults are no breakpoint's to edit, so naming one after them would send\n  // an author to a tier where the value is not.\n  const defaults = origin.kind === \"element\" || origin.kind === \"blockType\";\n  if (!defaults && entry.breakpoint !== editing.breakpoint) {\n    parts.push(editing.labelOf(entry.breakpoint));\n  }\n  if (entry.state !== editing.state) parts.push(stateLabel(entry.state));\n  const named = parts.filter(part => part !== undefined);\n  return named.length === 0 ? \"this block\" : named.join(\" · \");\n}\n\n/** {@link originSubject}'s tiers, in the words a one-row caption can hold. */\nfunction briefSubject(origin: StyleOrigin, editing: EditedAddress): string {\n  switch (origin.kind) {\n    case \"class\":\n      return className(origin, editing);\n    case \"blockType\":\n      return origin.type === editing.blockType\n        ? \"block defaults\"\n        : \"enclosing block defaults\";\n    case \"page\":\n      return \"the page\";\n    // The tag as the HTML tag control shows it, which is where an author\n    // meets it.\n    case \"element\":\n      return `${origin.tag.toUpperCase()} defaults`;\n    case \"node\":\n      return enclosingName(editing, origin.id);\n  }\n}\n\n/**\n * A class as the author knows it: a shared style by its name (\"Card\"), a\n * text style said to be one (\"text style: Eyebrow\"), each by its class name\n * where the panel does not know its name.\n */\nfunction className(\n  origin: Extract<StyleOrigin, { kind: \"class\" }>,\n  editing: EditedAddress\n): string {\n  const name = editing.sharedStyleName?.(origin.slug) ?? `.${origin.slug}`;\n  return origin.role === \"text\" ? `text style: ${name}` : name;\n}\n\n/** An enclosing block as the Layers panel names it, or in general words. */\nfunction enclosingName(editing: EditedAddress, nodeId: string): string {\n  return editing.nameOf?.(nodeId) ?? \"an enclosing block\";\n}\n\n/**\n * Which block, class or tier a value came from — the SUBJECT of the phrase.\n *\n * Split from {@link originName} because the address that qualifies it is the\n * same for every tier while the subject is different for each, and composing\n * both in one function made the tier answers hard to read past the qualifiers.\n *\n * A same-node origin resolves to the CONTROL where one differs, because there\n * the control is what the author must open: a rule reaches a control whose\n * descendant selector is more specific than its own — `linkColorHover` displays\n * the plain `a` declaration when no hover value exists — and told \"this block\",\n * the author cannot find the field that holds it.\n */\nfunction originSubject(\n  origin: StyleOrigin,\n  editing: EditedAddress,\n  control: string | undefined\n): string {\n  switch (origin.kind) {\n    case \"class\":\n      return className(origin, editing);\n    case \"blockType\":\n      /*\n       * The same problem the `node` case has, and it arrives by the same route:\n       * `reachesThroughAncestor` asks `reachesNode` about each ancestor, and\n       * that matches a `blockType` origin against the ANCESTOR's type. So a\n       * descendant rule from an enclosing block's defaults reaches this control\n       * carrying that block's type, not this one's.\n       */\n      return origin.type === editing.blockType\n        ? \"this block's defaults\"\n        : \"an enclosing block's defaults\";\n    case \"page\":\n      return \"the page\";\n    // Named for what an author can act on. \"the `h1` baseline\" rather than the\n    // tier's internal name, because the next thing they do is either override\n    // it on this block or replace the baseline for the whole site, and both\n    // start from knowing which element it keys on.\n    case \"element\":\n      return `the ${origin.tag} typography baseline`;\n    case \"node\":\n      if (origin.id !== editing.nodeId)\n        return enclosingName(editing, origin.id);\n      return control ?? \"this block\";\n  }\n}\n\n/**\n * The label of the control a declaration came from, when it was not this one.\n *\n * `undefined` when the declaration belongs to this control's own address.\n *\n * The catalog is asked rather than the selector rendered: ` a` is not a name an\n * author has seen anywhere, while the property that writes it is the field they\n * are looking at.\n *\n * The multiple-writers guard is NOT currently reachable, and that is recorded\n * rather than left for someone to rediscover. Measured over the whole catalog,\n * exactly one `(cssProperty, descendant)` pair has two writers —\n * `background-image` with no descendant, from `background` and\n * `backgroundGradient` — and nothing writes `background-image` at a descendant\n * at all. So a differing descendant always resolves to one property today.\n *\n * It is kept because it is not redundant: nothing else stops this naming one of\n * two writers arbitrarily, and a control labelled with a field the author did\n * not touch is the failure this whole indicator exists to avoid. A catalog leaf\n * added at a descendant would reach it on the day it lands.\n */\nfunction sourceControl(\n  entry: StyleTraceEntry,\n  controlDescendant: string | undefined\n): string | undefined {\n  const mine = (controlDescendant ?? \"\").trim();\n  const theirs = (entry.descendant ?? \"\").trim();\n  if (mine === theirs) return undefined;\n  const writers = propertiesWriting(entry.property, entry.descendant);\n  if (writers.length !== 1) return undefined;\n  return fieldLabel(writers[0] ?? \"\");\n}\n\n/**\n * A breakpoint's author-facing name, or its id when the site defines no such\n * breakpoint.\n *\n * Resolved through `breakpointContexts` — the engine's own normalisation — and\n * not by searching the stored axes. The two disagree, and the disagreement is\n * exactly the case a label matters in. `breakpointContexts` sorts each axis\n * WIDEST-FIRST and then claims each id once, so of two rows storing the same id\n * the wider one survives and emits the rule; a raw search returns whichever was\n * stored first. With a narrow `dup` above a wider `dup`, the value on screen\n * comes from the wide row while the tooltip names the narrow one — an author\n * sent to a definition that did not produce the value.\n *\n * The surviving DEFINITION is then matched by axis and bound rather than by id\n * alone, because id alone is what is ambiguous here. Two rows sharing an id and\n * a bound differ only in their label, and the compiler's sort is stable, so the\n * first of those is the one it kept.\n *\n * Falling back to the id rather than to a placeholder: a value keyed to a\n * breakpoint the settings no longer define is exactly the case an author needs\n * to recognise, and \"unknown\" tells them nothing they can act on.\n */\nexport function breakpointLabel(\n  breakpoints: BreakpointSet | undefined,\n  id: BreakpointId\n): string {\n  // One matcher, in `style-provenance`. The survivor is found by BOUND as well\n  // as id — among definitions sharing an id the compiler keeps one — and a\n  // second lookup here would be a second place to lose that.\n  return breakpointSource(id, breakpoints)?.label ?? id;\n}\n\n/**\n * What to call the place a value came from, as ONE address.\n *\n * Every axis that differs from what the panel is editing is named, not just the\n * first. Naming a subset is not a vaguer answer, it is a WRONG one: editing\n * hover at Tablet, a value arriving from base at Mobile labelled \"this block at\n * Mobile\" sends the author to a real address that does not hold the value, and\n * finding nothing there they conclude the indicator is broken.\n *\n * The qualifiers apply to EVERY tier, not only to a node. A class carries\n * responsive and interaction-state values of its own, so `.card` alone leaves an\n * author who opens the class editor at base looking at the wrong row — the same\n * misdirection, one tier over.\n *\n * The control is the SUBJECT for a same-node origin and a `via` clause for every\n * other tier, because that is what it means in each: on this block it is the\n * field to open, while on a class or an enclosing block it says which field's\n * rule reached here, and the place to go is still the class or the block.\n */\nfunction originName(\n  origin: StyleOrigin,\n  entry: StyleTraceEntry,\n  editing: EditedAddress,\n  controlDescendant: string | undefined\n): string {\n  const label = sourceControl(entry, controlDescendant);\n  const control = label === undefined ? undefined : `the ${label} control`;\n  const ownControl = origin.kind === \"node\" && origin.id === editing.nodeId;\n  const parts = [originSubject(origin, editing, control)];\n  if (!ownControl && control !== undefined) parts.push(`via ${control}`);\n  if (entry.breakpoint !== editing.breakpoint) {\n    parts.push(`at ${editing.labelOf(entry.breakpoint)}`);\n  }\n  if (entry.state !== editing.state) {\n    parts.push(`in its ${entry.state} state`);\n  }\n  return parts.join(\" \");\n}\n","\"use client\";\n\n/**\n * A type size picked in a block's font size field carries its line height.\n *\n * A type size is a pair of variables joined by name (`font-size.h2` and\n * `line-height.h2`). Picked for a block that has no line height of its own,\n * the same edit writes the line height's variable too, so the block reads\n * \"From H2 type size\" there, with \"Detach\" to give it a value of its own.\n * Where the block already has its own line height, the pick keeps it and\n * the field offers \"Use H2's line height\". The pairing is read through the\n * Type tab's own list of type sizes (`typeSizeChoices`), so the two never\n * disagree about which line height goes with a size.\n *\n * @module type-size-pair\n */\nimport {\n  isTokenRef,\n  tokenRef,\n  type NodeStyles,\n  type SiteTokenSet,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport { pickedTypeSize } from \"../../panels/design/site-text-rows\";\nimport { unlinkedValue } from \"../../panels/design/variable-choice\";\nimport { variableFor } from \"../../styles/style-colour\";\nimport { readStyleValue, type StyleAddress } from \"../../styles/style-values\";\n\n/** The line height's address beside a font size's. */\nfunction lineHeightAt(address: StyleAddress): StyleAddress {\n  return { ...address, property: \"lineHeight\", path: [] };\n}\n\n/**\n * What a field at `address` writes with a font size pick: the paired line\n * height, for the field's write to make in the same edit.\n */\nexport function lineHeightPairFor(\n  address: StyleAddress,\n  tokens: SiteTokenSet | undefined\n): (\n  value: StyleValue,\n  styles: NodeStyles | undefined\n) => { address: StyleAddress; value: StyleValue } | undefined {\n  return (value, styles) => pairedLineHeight(address, value, styles, tokens);\n}\n\n/**\n * The line height a font size pick writes with it, or `undefined` for none:\n * only a type size with a line height of its own, picked for a block that has\n * no line height at the same state and breakpoint.\n */\nfunction pairedLineHeight(\n  address: StyleAddress,\n  value: StyleValue,\n  styles: NodeStyles | undefined,\n  tokens: SiteTokenSet | undefined\n): { address: StyleAddress; value: StyleValue } | undefined {\n  if (address.property !== \"fontSize\" || address.path.length > 0) {\n    return undefined;\n  }\n  const choice = pickedTypeSize(tokens, value);\n  if (choice?.lineHeight === undefined) return undefined;\n  const at = lineHeightAt(address);\n  if (readStyleValue(styles, at) !== undefined) return undefined;\n  return { address: at, value: tokenRef(choice.lineHeight) };\n}\n\n/**\n * Under a block's line height field: \"From H2 type size\" with \"Detach\"\n * while the line height follows the type size the block's font size points\n * at, or \"Use H2's line height\" while the block has its own.\n */\nexport function TypeSizeLineHint({\n  address,\n  styles,\n  tokens,\n  onBlock,\n  readOnly,\n  onCommit,\n}: {\n  /** The line height field's address. */\n  address: StyleAddress;\n  styles: NodeStyles | undefined;\n  tokens: SiteTokenSet | undefined;\n  /** Whether the field edits a block, not a shared style: only then shown. */\n  onBlock: boolean;\n  readOnly: boolean;\n  onCommit: (value: StyleValue) => unknown;\n}): React.JSX.Element | null {\n  // The mode the canvas draws, so Detach keeps the value it shows.\n  const mode = useCanvasTokenMode();\n  const hint = lineHintOf(address, styles, onBlock ? tokens : undefined);\n  if (hint === undefined) return null;\n  if (hint.follows) {\n    // Resolved as the field's own Unlink resolves a variable: the value the\n    // canvas shows, as the number a line height stores.\n    const variable = variableFor(hint.partner, tokens, mode);\n    return (\n      <FollowsLine\n        name={hint.name}\n        own={\n          readOnly || variable === undefined ? null : unlinkedValue(variable)\n        }\n        onCommit={onCommit}\n      />\n    );\n  }\n  return hint.own && !readOnly ? (\n    <UseTypeSizeLine\n      name={hint.name}\n      onUse={() => onCommit(tokenRef(hint.partner))}\n    />\n  ) : null;\n}\n\n/**\n * What the hint under a line height field says, or nothing: the type size\n * the block's font size points at, its line height, and whether the block's\n * line height follows it or is its own. Nothing without the site's\n * variables, or for any other field.\n */\nfunction lineHintOf(\n  address: StyleAddress,\n  styles: NodeStyles | undefined,\n  tokens: SiteTokenSet | undefined\n):\n  | { name: string; partner: string; follows: boolean; own: boolean }\n  | undefined {\n  if (address.property !== \"lineHeight\" || tokens === undefined) {\n    return undefined;\n  }\n  const size = readStyleValue(styles, { ...address, property: \"fontSize\" });\n  const choice = pickedTypeSize(tokens, size);\n  const partner = choice?.lineHeight;\n  if (choice === undefined || partner === undefined) return undefined;\n  const line = readStyleValue(styles, address);\n  return {\n    name: choice.name,\n    partner,\n    follows: isTokenRef(line) && line.$token === partner,\n    own: line !== undefined,\n  };\n}\n\n/** \"From H2 type size\", with \"Detach\" where the block may take its own. */\nfunction FollowsLine({\n  name,\n  own,\n  onCommit,\n}: {\n  name: string;\n  own: StyleValue | null;\n  onCommit: (value: StyleValue) => unknown;\n}): React.JSX.Element {\n  return (\n    <p className=\"nx-type-pair\">\n      <span>{`From ${name} type size`}</span>\n      {own === null ? null : (\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          className=\"nx-type-pair__action\"\n          onClick={() => onCommit(own)}\n        >\n          Detach\n        </Button>\n      )}\n    </p>\n  );\n}\n\n/** \"Use H2's line height\", under a block's own line height. */\nfunction UseTypeSizeLine({\n  name,\n  onUse,\n}: {\n  name: string;\n  onUse: () => void;\n}): React.JSX.Element {\n  return (\n    <p className=\"nx-type-pair\">\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"sm\"\n        className=\"nx-type-pair__action\"\n        onClick={onUse}\n      >\n        {`Use ${name}'s line height`}\n      </Button>\n    </p>\n  );\n}\n","\"use client\";\n\n/**\n * The shell around every Style tab control: its label, the control field\n * itself, the issue line under it, and the breakpoint actions beside it\n * (reset at the tier being edited, and jump to the tier a value came from).\n *\n * @module style-field-shell\n */\nimport {\n  isTokenRef,\n  type BreakpointId,\n  type SiteTokenSet,\n  type StyleState,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport { Label, TooltipProvider } from \"@nextlyhq/ui\";\nimport { RotateCcw } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport type { EditorState } from \"../../editor-state\";\nimport {\n  contrastObscuredAbove,\n  contrastObscuredIn,\n} from \"../../styles/style-colour\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport type {\n  BreakpointBadge,\n  BreakpointSource,\n} from \"../../styles/style-provenance\";\nimport type { StyleAddress, StylePolicy } from \"../../styles/style-values\";\nimport { controlWrites } from \"../code-hints\";\nimport { CssHint, CssNamesLine, OptionWrites, FieldNamesId } from \"../css-hint\";\n\nimport { FieldPathWrites } from \"./field-path-writes\";\nimport { InheritedValue } from \"./inherited-value\";\nimport { LabelScrubRow, useLabelScrubProps } from \"./label-scrub\";\nimport {\n  RENDERED_TEXT_SIZES,\n  RenderedLengths,\n  type RenderedLengthsValue,\n} from \"./rendered-lengths\";\nimport { CompactSides, fieldDescribedBy, sideKeysFor } from \"./spacing-box\";\nimport { SpacingSide } from \"./spacing-side\";\nimport { commitsFor, partnerColour } from \"./style-colour-field\";\nimport {\n  ControlOrFont,\n  showsNoField,\n  UnsupportedField,\n} from \"./style-control-value\";\nimport {\n  type ProvenanceAnswer,\n  type ProvenanceOf,\n  NamedAbove,\n  TokenPrefixContext,\n  type EditedAddress,\n} from \"./style-field-surroundings\";\nimport { targetKey, useFieldTarget } from \"./style-field-target\";\nimport { SharedValueLine, ProvenanceDot } from \"./style-provenance-indicators\";\nimport { editableText } from \"./style-text-field\";\nimport { labelFocusOnly } from \"./style-value-fields\";\nimport { lineHeightPairFor, TypeSizeLineHint } from \"./type-size-pair\";\n\n/** One editable position, drawn as the control its leaf kind resolves to. */\n/**\n * A style field's label: its words, and the dot saying where the value came from.\n *\n * Its own component because the two parts are hidden INDEPENDENTLY. Inside a\n * box of logical sides the words are noise — position is saying which edge this\n * is — while the provenance dot says whether the side is authored or inherited,\n * which position cannot tell anyone. So the words are wrapped in an element the\n * stylesheet can clip on its own; clipping the label would take the dot and its\n * focus-revealed explanation with it.\n *\n * @param props - the label's identity, its words, and the provenance to show\n * @returns the label element\n */\nfunction StyleFieldLabel({\n  id,\n  htmlFor,\n  readOnly,\n  focusOnly,\n  title,\n  label,\n  answer,\n  editing,\n  descendant,\n}: {\n  id: string;\n  htmlFor: string;\n  /**\n   * Whether the control cannot be edited, in which case the label names NOTHING.\n   *\n   * A label pointing at a read-only field would move focus into a control an\n   * author cannot use. Decided here rather than by the caller so the field is\n   * left saying what it wants drawn rather than how to draw it.\n   */\n  readOnly: boolean;\n  /**\n   * Whether the control is a group of buttons. A label's `for` would CLICK\n   * a button, choosing or clearing a value; this label only moves focus to\n   * the element the id names, the group's tab stop.\n   */\n  focusOnly: boolean;\n  title: string | undefined;\n  label: string;\n  answer: ProvenanceAnswer | undefined;\n  editing: EditedAddress;\n  descendant: string | undefined;\n}): React.JSX.Element {\n  const namedAbove = React.useContext(NamedAbove);\n  // Dragging the label to change a number field's value, while it can.\n  const scrub = useLabelScrubProps();\n  return (\n    <Label\n      id={id}\n      htmlFor={readOnly || focusOnly ? undefined : htmlFor}\n      title={title}\n      data-named-above={namedAbove ? \"\" : undefined}\n      // A read-only field's label names nothing, so it drags nothing either.\n      {...(readOnly ? {} : scrub)}\n      {...(focusOnly && !readOnly\n        ? {\n            onClick: (event: React.MouseEvent<HTMLLabelElement>) =>\n              tabStopOf(\n                event.currentTarget.ownerDocument.getElementById(htmlFor)\n              )?.focus(),\n          }\n        : {})}\n    >\n      <span className=\"nx-style-inspector__field-label-text\">{label}</span>\n      <ProvenanceDot\n        answer={answer}\n        editing={editing}\n        descendant={descendant}\n      />\n    </Label>\n  );\n}\n\n/**\n * Where a label that only moves focus sends it: the control itself when it\n * takes focus, else the tab stop inside it. A group of buttons is named by\n * its container, which takes no focus, so focusing the container would do\n * nothing; its tab stop is the button in force, or the first.\n */\nfunction tabStopOf(control: HTMLElement | null): HTMLElement | null {\n  if (control === null) return null;\n  if (control.tabIndex >= 0 && control.matches(FOCUSABLE)) return control;\n  return control.querySelector<HTMLElement>(\n    '[tabindex=\"0\"], button:not([tabindex=\"-1\"]), input, select, textarea'\n  );\n}\n\n/** What takes focus by itself, as a label's target. */\nconst FOCUSABLE = \"button, input, select, textarea, [tabindex]\";\n\n/** Whether a written value reads a CSS variable: `var(--site-font-size-h2)`. */\nfunction readsVariable(value: string): boolean {\n  return /\\bvar\\(\\s*--/.test(value);\n}\n\n/**\n * What reaches a control from another tier, shown in it while nothing is set\n * here. Read from the same answer as the dot, so the two never disagree.\n *\n * A text size that reads a variable (Site text's heading sizes) is shown as\n * the size the canvas draws it at, at the device being edited, and not at\n * all where the canvas hasn't measured it: an author never sees the CSS. The\n * dot beside the label says where it comes from (\"From Site text: Heading\n * 2\"). Other values pass as they are: a spacing side names the variable it\n * reads from the value itself.\n */\nfunction inheritedShown(\n  stored: StyleValue | undefined,\n  answer: ProvenanceAnswer | undefined,\n  leaf: StyleControl[\"leaf\"],\n  rendered: RenderedLengthsValue\n): string | undefined {\n  if (stored !== undefined || answer?.provenance.kind !== \"inherited\") {\n    return undefined;\n  }\n  const value = answer.provenance.entry.value;\n  const read = Object.hasOwn(RENDERED_TEXT_SIZES, leaf.cssProperty);\n  if (!read || !readsVariable(value)) return value;\n  return rendered[leaf.cssProperty];\n}\n\nexport function StyleControlField({\n  control,\n  side,\n  label,\n  summary,\n  propertyLabel,\n  clearOnly,\n  nodeId,\n  state,\n  breakpoint,\n  editor,\n  policy,\n  tokens,\n  prefersDark,\n  provenanceOf,\n  editing,\n}: {\n  control: StyleControl;\n  /**\n   * Which side of a box this field draws, when the property is drawn as one.\n   *\n   * Present only where the panel decided a box is justified, and read by the\n   * stylesheet to PLACE the field. Placement by identity rather than by the\n   * field's position among its siblings, because that list varies: the property\n   * heading, a form selector and the notice for a withdrawn property are all\n   * siblings, so a rule counting elements moves every side the moment one of\n   * them appears.\n   */\n  side?: string;\n  label: string;\n  summary: string | undefined;\n  /**\n   * The whole property's name, for naming an ACTION rather than a field.\n   *\n   * A field is labelled by its position — \"Block start\" — which is enough\n   * beside its own property's heading and not enough on a button: `padding` and\n   * `margin` both have a block start, so two buttons called \"Clear block start\"\n   * name the same thing twice and a screen-reader user cannot tell which style\n   * each removes.\n   */\n  propertyLabel: string;\n  /**\n   * Whether this value may only be REMOVED, not changed.\n   *\n   * True for a property the block's `supports` no longer declares. The value is\n   * still emitted — nothing in validation or compilation reads `supports` — so\n   * withholding the control entirely would leave styling on the page that the\n   * author can see and cannot remove. Letting them go on EDITING it is the\n   * other error: it writes new values through a capability the block has\n   * withdrawn, which is the definition the panel is supposed to be reading.\n   */\n  clearOnly: boolean;\n  nodeId: string;\n  state: StyleState;\n  breakpoint: BreakpointId;\n  editor: EditorState;\n  policy: StylePolicy | undefined;\n  tokens: SiteTokenSet | undefined;\n  prefersDark: boolean;\n  provenanceOf: ProvenanceOf;\n  editing: EditedAddress;\n}): React.JSX.Element {\n  const id = React.useId();\n  // The message's own id, so the control can point at it. A `role=\"alert\"`\n  // announces once and then it is gone: a screen-reader user who returns to the\n  // field, or meets several rejected controls, has no way to tell which message\n  // belongs to which without the relationship being stated.\n  const errorId = `${id}-error`;\n  const address: StyleAddress = {\n    state,\n    breakpoint,\n    property: control.property,\n    path: control.path,\n  };\n  const writes = useFieldTarget({\n    editor,\n    nodeId,\n    address,\n    policy,\n    // A type size picked here brings its line height where the block has none.\n    pairFor: lineHeightPairFor(address, tokens),\n  });\n  const { target, nodeStyles, styles, stored, issue } = writes;\n  const pairedColour = partnerColour(control.leaf, styles, address);\n  // This node's own styles first, then every ancestor's. An ancestor's\n  // `opacity`, `filter` or `mixBlendMode` composites this node along with the\n  // rest of the subtree, so both colours reach the eye altered and the ratio\n  // between the two stored values describes a rendering that does not happen.\n  const obscuredBy =\n    contrastObscuredIn(styles) ??\n    contrastObscuredAbove(editor.document.nodes, nodeId);\n  const actionName = actionNameFor(propertyLabel, label);\n\n  const commit = writes.commit;\n  /*\n   * The provenance and its breakpoint reading, from ONE ranking of the trace.\n   * The dot and the action are two readings of one answer, not two answers.\n   */\n  const answer = provenanceOf(control.leaf);\n  // The sizes the canvas drew the block at, for an inherited variable.\n  const rendered = React.useContext(RenderedLengths);\n  const inherited = inheritedShown(stored, answer, control.leaf, rendered);\n\n  // A spacing-box side resets by key: see `sideKeysFor`.\n  const inBox = React.useContext(CompactSides);\n  const { asSide, readOnly } = fieldSurface(\n    inBox && side !== undefined,\n    control,\n    stored,\n    clearOnly\n  );\n  const sideKeys = sideKeysFor(side, inBox, stored, readOnly, id, commit);\n  const labelId = `${id}-label`;\n  // Computed once and used by both the control and its message: two spellings\n  // of \"is there an error\" is the shape that drifts into a control described by\n  // a message it is not marked invalid for.\n  const namesId = `${id}-css`;\n  // The refusal alone: whether the control is invalid is read from it. The\n  // CSS names join the description through `FieldNamesId` below.\n  const describedBy = issueId(issue, errorId);\n  const tokenPrefix = React.useContext(TokenPrefixContext);\n\n  if (!control.supported) {\n    return (\n      <UnsupportedField\n        labelId={labelId}\n        label={label}\n        summary={summary}\n        actionName={actionName}\n        leafKind={control.leaf.kind}\n        stored={stored}\n        onClear={() => commit(null)}\n      />\n    );\n  }\n\n  return (\n    // What it writes, on hover or keyboard focus anywhere in the field.\n    // What each of its options writes, for an option's own tooltip.\n    <OptionWrites.Provider\n      value={option => controlWrites(control, option, tokenPrefix)}\n    >\n      <FieldNamesId.Provider value={namesId}>\n        <CssHint\n          summary={summary}\n          writes={controlWrites(control, stored, tokenPrefix)}\n        >\n          <div\n            className=\"nx-inspector__field\"\n            data-control={control.kind}\n            // Absent when this is not a side: React omits an `undefined` attribute, so\n            // the value says whether the field is in a box without a branch here.\n            data-side={side}\n            onKeyDown={sideKeys.onKeyDown}\n            {...writes.caption}\n          >\n            {/* The label drags the value the number field below offers it. */}\n            <LabelScrubRow subject={`${nodeId} ${targetKey(writes.target)}`}>\n              <StyleFieldLabel\n                id={labelId}\n                htmlFor={id}\n                readOnly={readOnly}\n                focusOnly={labelFocusOnly(control.leaf, stored)}\n                title={undefined}\n                label={label}\n                answer={answer}\n                editing={editing}\n                descendant={control.leaf.descendant}\n              />\n              <InheritedValue.Provider value={inherited}>\n                {/* Several paths in one edit, for a control that sets more than its own. */}\n                <FieldPathWrites.Provider value={writes.commitPaths}>\n                  <FieldValue\n                    asSide={asSide}\n                    id={id}\n                    labelledBy={labelId}\n                    control={control}\n                    stored={stored}\n                    inherited={inherited}\n                    actionName={actionName}\n                    clearOnly={clearOnly}\n                    tokens={tokens}\n                    prefersDark={prefersDark}\n                    pairedColour={pairedColour}\n                    obscuredBy={obscuredBy}\n                    describedBy={describedBy}\n                    onCommit={commit}\n                    onCommitSides={writes.commitSides}\n                    refusal={issue}\n                  />\n                </FieldPathWrites.Provider>\n              </InheritedValue.Provider>\n            </LabelScrubRow>\n            <CssNamesLine id={namesId} names={[control.leaf.cssProperty]} />\n            <TypeSizeLineHint\n              address={address}\n              styles={nodeStyles}\n              tokens={tokens}\n              // A shared style's line height is the style's own: the hint\n              // speaks of a block's.\n              onBlock={target.kind !== \"shared\"}\n              // A held variable draws no typed field, so the field's own\n              // read-only answer is not this one: only a withdrawn property\n              // is, and a lock refuses the write itself.\n              readOnly={clearOnly}\n              onCommit={commit}\n            />\n            <BreakpointAction\n              answer={answer}\n              label={actionName}\n              editing={editing}\n              fieldId={id}\n              onReset={() => commit(null)}\n              stored={stored}\n              readOnly={clearsItself(readOnly, stored)}\n              resetByKey={sideKeys.resetByKey}\n            />\n            {sideKeys.hint}\n            <SharedValueLine\n              target={target}\n              answer={answer}\n              nodeStyles={nodeStyles}\n              address={address}\n              actionName={actionName}\n              onResetBlock={writes.resetBlock}\n              onMoveTo={writes.moveTo}\n            />\n            <FieldIssue id={errorId} issue={issue} />\n          </div>\n        </CssHint>\n      </FieldNamesId.Provider>\n    </OptionWrites.Provider>\n  );\n}\n\n/**\n * A field's value: a spacing-box side's button, or the control its leaf\n * resolves to.\n */\nfunction FieldValue({\n  asSide,\n  inherited,\n  refusal,\n  onCommitSides,\n  ...control\n}: Parameters<typeof ControlOrFont>[0] & {\n  refusal: string | null;\n  /** Drawn as a side of the spacing box: see {@link drawnAsSide}. */\n  asSide: boolean;\n  inherited: string | undefined;\n  onCommitSides: React.ComponentProps<typeof SpacingSide>[\"onCommitSides\"];\n}): React.JSX.Element {\n  if (!asSide) return <ControlOrFont {...control} />;\n  return (\n    <SpacingSide\n      id={control.id}\n      labelledBy={control.labelledBy}\n      name={control.actionName}\n      control={control.control}\n      stored={control.stored}\n      inherited={inherited}\n      tokens={control.tokens}\n      describedBy={fieldDescribedBy(control.describedBy, true, control.id)}\n      onCommit={control.onCommit}\n      onCommitSides={onCommitSides}\n      refusal={refusal}\n    />\n  );\n}\n\n/**\n * How a field is drawn: in the spacing box, a side whose value it can show is\n * a button that opens the side's popover, which edits a variable it holds as\n * readily as a number; otherwise read-only where no field can show its value.\n */\nfunction fieldSurface(\n  inSpacingBox: boolean,\n  control: StyleControl,\n  stored: StyleValue | undefined,\n  clearOnly: boolean\n): { asSide: boolean; readOnly: boolean } {\n  if (inSpacingBox && drawnAsSide(control, stored, clearOnly)) {\n    return { asSide: true, readOnly: false };\n  }\n  return { asSide: false, readOnly: showsNoField(control, stored, clearOnly) };\n}\n\n/**\n * Whether a spacing-box side is drawn as its button: a length it can show,\n * a number or a variable. A value it can only remove keeps its own surface.\n */\nfunction drawnAsSide(\n  control: StyleControl,\n  stored: StyleValue | undefined,\n  clearOnly: boolean\n): boolean {\n  if (clearOnly || control.leaf.kind !== \"dimension\") return false;\n  return isTokenRef(stored) || editableText(control, stored) !== undefined;\n}\n\n/**\n * Whether a field's own surface removes its value, so its row offers no Reset\n * as well: a value shown only to be cleared, with a Clear of its own. A held\n * variable's chip has none, its Unlink keeping the value instead, so its row\n * offers Reset as any set row does.\n */\nfunction clearsItself(\n  readOnly: boolean,\n  stored: StyleValue | undefined\n): boolean {\n  return readOnly && !isTokenRef(stored);\n}\n\n/** The id a field's refusal is said under, or none while nothing is refused. */\nfunction issueId(issue: unknown, errorId: string): string | undefined {\n  return issue === null ? undefined : errorId;\n}\n\n/** A field's refusal, which the control points at by its id; nothing without one. */\nfunction FieldIssue({\n  id,\n  issue,\n}: {\n  id: string;\n  issue: string | null;\n}): React.JSX.Element | null {\n  if (issue === null) return null;\n  return (\n    <p className=\"nx-inspector__error\" id={id} role=\"alert\">\n      {issue}\n    </p>\n  );\n}\n\n/**\n * The action a control's breakpoint provenance earns, or nothing.\n *\n * Rendered ONLY where it means something: a Reset for a value authored at the\n * tier being edited, a Jump for a value that arrived from another tier, and\n * nothing at all for the unset controls that are the large majority of a panel.\n *\n * That bound is the whole design. {@link ProvenanceDot} refuses to be focusable\n * because a stop per control would double the presses to cross a section of\n * eight or more — and the same objection would apply here if every control\n * carried a button. Tying the affordance to the state that makes it meaningful\n * puts the cost only on controls the author has actually touched.\n *\n * AFTER the input in DOM order, so a keyboard user reaches the value first and\n * the action second. Before it, every control would answer its own question in\n * the wrong order: what to do about a value, then the value.\n *\n * Jump is withheld when no handler is supplied rather than rendered inert. A\n * host that cannot move the canvas — one with no width to move — would\n * otherwise offer a button that does nothing, which is worse than a missing\n * affordance because it reads as a broken one.\n */\nfunction BreakpointAction({\n  answer,\n  label,\n  editing,\n  fieldId,\n  onReset,\n  stored,\n  readOnly,\n  resetByKey = false,\n}: {\n  answer: ProvenanceAnswer | undefined;\n  /**\n   * The control's ACTION NAME — the containing property and the leaf together.\n   *\n   * The leaf label alone is not unique: `margin` and `padding` both have a\n   * block start, so two controls would offer buttons called \"Reset Block start\"\n   * and a screen-reader user could not tell which style each removes. The panel\n   * already computes this for exactly that reason, and `Clear` on a token value\n   * uses it.\n   */\n  label: string;\n  editing: EditedAddress;\n  /** The field this control's actions write, passed on to {@link ResetAction}. */\n  fieldId: string;\n  onReset: () => void;\n  /** What this address stores: with no cascade, reset while it holds anything. */\n  stored: StyleValue | undefined;\n  /** A field drawn as a retained value, whose own Clear already resets it. */\n  readOnly: boolean;\n  /** A field that resets by a key of its own: its reset leaves the Tab order. */\n  resetByKey?: boolean;\n}): React.JSX.Element | null {\n  /*\n   * The row's one way back, so a list or an icon group needs no Clear of its\n   * own. With a cascade it follows the cascade's answer: a value authored at\n   * this tier is reset, revealing whatever shows through, and one arriving\n   * from another tier is a jump there.\n   *\n   * Where the cascade gives no answer for this row — none was supplied, or\n   * the tier being edited is one the canvas is not showing, so its values\n   * read as unset — a value stored at this address is still reset, unless the\n   * field is a retained value with a Clear of its own. What it reveals is not\n   * known there, so the reset does not claim it.\n   */\n  const badge = answer?.badge;\n  if (badge === undefined || badge.kind === \"none\") {\n    if (stored === undefined || readOnly) return null;\n    return (\n      <ResetAction\n        revealed=\"unknown\"\n        label={label}\n        editing={editing}\n        fieldId={fieldId}\n        onReset={onReset}\n        outOfTabOrder={resetByKey}\n      />\n    );\n  }\n  if (badge.kind === \"authored\") {\n    return (\n      <ResetAction\n        revealed={revealedBy(badge)}\n        label={label}\n        editing={editing}\n        fieldId={fieldId}\n        onReset={onReset}\n        outOfTabOrder={resetByKey}\n      />\n    );\n  }\n  /*\n   * The value showing came from another tier. A value stored HERE as well is\n   * shadowed by it, and is still this row's to remove: the reset stays beside\n   * the jump, naming nothing it reveals, since what shows here once it is\n   * gone is the winning tier's business.\n   */\n  const reset =\n    stored === undefined || readOnly ? null : (\n      <ResetAction\n        revealed=\"unknown\"\n        label={label}\n        editing={editing}\n        fieldId={fieldId}\n        onReset={onReset}\n        outOfTabOrder={resetByKey}\n      />\n    );\n  if (answer?.jump === undefined) return reset;\n  return (\n    <>\n      {reset}\n      <JumpAction source={badge.source} label={label} onJump={answer.jump} />\n    </>\n  );\n}\n\n/**\n * What to call a breakpoint source in front of an author.\n *\n * ONE naming for both actions. `BreakpointSource` carries the axis precisely\n * because a site defining both makes a bare tier name ambiguous — and a\n * container tier may share its label with a viewport one — so a reset saying\n * \"showing the value from Tablet\" while a jump says \"Tablet (container)\" leaves\n * the author to work out that the two Tablets are different tiers.\n */\nfunction sourceLabel(source: BreakpointSource): string {\n  return source.axis === \"container\"\n    ? `${source.label} (container)`\n    : source.label;\n}\n\n/**\n * What a reset reveals, from an authored badge: another tier, nothing, or a\n * value passed down from an enclosing block or the page, which no tier names.\n */\nfunction revealedBy(\n  badge: Extract<BreakpointBadge, { kind: \"authored\" }>\n): BreakpointSource | \"unset\" | \"unknown\" {\n  if (badge.revealed !== undefined) return badge.revealed;\n  return badge.passedDown === true ? \"unknown\" : \"unset\";\n}\n\n/**\n * Clear this control at the tier being edited, saying what will show through.\n *\n * \"Reset\" alone asks an author to guess whether the control becomes unset or\n * falls back to a wider tier's value. In a desktop-first cascade it is usually\n * the second, and not always base — so the fallback is named, in the accessible\n * name AND in visible text, because computing it exists to remove that guess\n * for everybody rather than for screen-reader users alone.\n */\nfunction ResetAction({\n  revealed,\n  label,\n  editing,\n  fieldId,\n  onReset,\n  outOfTabOrder = false,\n}: {\n  /** Out of the Tab order (still clickable): its field resets by key. */\n  outOfTabOrder?: boolean;\n  /**\n   * What shows once this value is gone: another tier's value, nothing, or\n   * `\"unknown\"` where no ranking of the cascade covers this tier, which the\n   * names then leave unsaid rather than guess.\n   */\n  revealed: BreakpointSource | \"unset\" | \"unknown\";\n  label: string;\n  editing: EditedAddress;\n  /** The field whose value this press writes. See {@link commitsFor}. */\n  fieldId: string;\n  onReset: () => void;\n}): React.JSX.Element {\n  const at = `Reset ${label} at ${editing.labelOf(editing.breakpoint)}`;\n  const named =\n    revealed === \"unknown\"\n      ? at\n      : revealed === \"unset\"\n        ? `${at}, leaving it unset`\n        : `${at}, showing the value from ${sourceLabel(revealed)}`;\n  const tip =\n    revealed === \"unknown\"\n      ? \"Reset\"\n      : revealed === \"unset\"\n        ? \"Reset to unset\"\n        : `Reset to ${sourceLabel(revealed)}`;\n  return (\n    <TooltipProvider delayDuration={300}>\n      <ChromeTooltip content={tip}>\n        <button\n          type=\"button\"\n          className=\"nx-style-inspector__breakpoint-action\"\n          data-action=\"reset\"\n          {...commitsFor(fieldId)}\n          onClick={onReset}\n          tabIndex={outOfTabOrder ? -1 : undefined}\n          aria-label={named}\n        >\n          {/* An icon at the row's end, where a \"Reset to unset\" line under\n                every set control made each one two rows. The words are its\n                tooltip and, in full, its name. */}\n          <RotateCcw size={14} aria-hidden=\"true\" />\n        </button>\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/**\n * Take the canvas to the tier this control's value was authored at.\n *\n * The AXIS is named beside the tier, since a site defining both makes a bare\n * tier name ambiguous and the container axis is the one an author is least\n * likely to be holding in mind.\n */\nfunction JumpAction({\n  source,\n  label,\n  onJump,\n}: {\n  source: BreakpointSource;\n  label: string;\n  onJump: () => void;\n}): React.JSX.Element {\n  const where = sourceLabel(source);\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-style-inspector__breakpoint-action\"\n      data-action=\"jump\"\n      onClick={onJump}\n      aria-label={`Edit ${label} at ${where}, where its value was set`}\n    >\n      {/* The source, as the caption beside an inherited value says it, and\n          the way there: one line rather than a caption and a \"Go to\". */}\n      From {where}\n    </button>\n  );\n}\n\nfunction actionNameFor(propertyLabel: string, label: string): string {\n  return propertyLabel === label\n    ? propertyLabel\n    : `${propertyLabel} ${label.toLowerCase()}`;\n}\n","\"use client\";\n\n/**\n * The spacing box as the Style tab draws it: margin the outer ring and\n * padding the inner, around the element, with each side's field in a frame.\n * Which properties form the box, and its keyboard order, live in\n * `spacing-box.tsx`.\n *\n * @module spacing-box-fields\n */\nimport { isTokenRef } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport {\n  physicalSideName,\n  sideBoxFor,\n  sideOf,\n  type SideBox,\n} from \"../../styles/style-sides\";\nimport { readStyleValue } from \"../../styles/style-values\";\nimport { fieldLabel } from \"../inspector\";\n\nimport { siteDefaultSource } from \"./site-default-source\";\nimport { CompactSides } from \"./spacing-box\";\nimport { SpacingRingContext } from \"./spacing-side\";\nimport { StyleControlField } from \"./style-field-shell\";\nimport {\n  StyleTargetContext,\n  TokenPrefixContext,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\nimport { fieldStyles } from \"./style-field-target\";\nimport type { InspectedStyleProperty } from \"./style-inspector\";\n\n/**\n * The element that carries the box arrangement, wrapping ONLY the four sides.\n *\n * Its own element rather than the property container, and that is the whole\n * point of it. The container also holds the property's heading, the form\n * selectors and the notice for a withdrawn property, and those must go on\n * reading in the PANEL's axes. Putting the edited element's `writing-mode` on\n * the container rotated everything inside it: in a vertical writing mode the\n * row reserved above the diagram becomes a physical column beside it, so the\n * heading ends up next to the box rather than over it, and the narrow fallback\n * — which stacks the sides with `flex-direction: column` — runs sideways.\n *\n * Scoped here, the axes reach exactly what they are about: the grid whose\n * columns and rows ARE the inline and block axes of the element being edited.\n *\n * A plain wrapper when there is no box, so the fields stay direct children of\n * the property in the ordinary case and nothing about the row layout changes.\n *\n * @param props - the settled box decision and the fields to place\n * @returns the sides, framed if they are a box\n */\nexport function SideBoxFrame({\n  box,\n  ring,\n  children,\n}: {\n  box: SideBox;\n  /** Which ring of the spacing box this is, when it is one. */\n  ring?: \"margin\" | \"padding\";\n  children: React.ReactNode;\n}): React.JSX.Element {\n  if (!box.boxed || box.axes === undefined) return <>{children}</>;\n  return (\n    <div\n      className=\"nx-style-inspector__side-box\"\n      // Read by the stylesheet, which owns the arrangement.\n      data-sides=\"logical\"\n      data-ring={ring}\n      /*\n       * The EDITED ELEMENT's axes, so this grid's own placement resolves in\n       * them: columns run along the inline axis and rows along the block axis,\n       * so column one is the inline start in either direction and a vertical\n       * mode transposes the pair — with no table of physical edges written here\n       * to keep in step with CSS.\n       *\n       * Passed as custom PROPERTIES rather than applied as `writing-mode` and\n       * `direction` directly. An inline declaration outranks every selector, so\n       * the stylesheet could then only take the axes back by shouting; handed\n       * over as values, the property that uses them is set by a rule, and the\n       * narrow fallback overrides it by ordinary cascade order.\n       */\n      style={\n        {\n          \"--nx-side-writing-mode\": box.axes.writingMode,\n          \"--nx-side-direction\": box.axes.direction,\n        } as React.CSSProperties\n      }\n    >\n      {children}\n    </div>\n  );\n}\n\n/**\n * The spacing section as the design draws it: one box, margin the outer ring\n * and padding the inner, around the element.\n *\n * Each side keeps its own field, so it commits on its own, undoes on its own,\n * and shows where its value comes from, exactly as a side drawn in a row does.\n * The box is the drawing alone.\n */\nexport function SpacingBox({\n  margin,\n  padding,\n  surroundings,\n}: {\n  margin: InspectedStyleProperty | undefined;\n  padding: InspectedStyleProperty;\n  surroundings: StyleFieldSurroundings;\n}): React.JSX.Element {\n  const inner = (\n    <SpacingRing\n      property={padding}\n      ring=\"padding\"\n      surroundings={surroundings}\n    />\n  );\n  const bound = useAnySideBound([margin, padding], surroundings);\n  const siteDefault = useSiteDefaultSource(padding, surroundings);\n  return (\n    <div className=\"nx-spacing-box\">\n      <CompactSides.Provider value={true}>\n        {margin === undefined ? (\n          inner\n        ) : (\n          <SpacingRing\n            property={margin}\n            ring=\"margin\"\n            surroundings={surroundings}\n          >\n            <div className=\"nx-spacing-box__centre\">{inner}</div>\n          </SpacingRing>\n        )}\n      </CompactSides.Provider>\n      {siteDefault === undefined ? null : (\n        <p className=\"nx-spacing-box__note\" data-site-default=\"\">\n          {siteDefault}\n        </p>\n      )}\n      {bound ? (\n        <p className=\"nx-spacing-box__note\">\n          Green values come from your spacing variables.\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * The site setting the padding comes from, once, under the box: \"Site\n * default: Section spacing\" on a new Section, whose padding reads the site's\n * section spacing variables. `undefined` when no side takes its value from a\n * site setting, or the sides take it from two.\n */\nfunction useSiteDefaultSource(\n  padding: InspectedStyleProperty,\n  surroundings: StyleFieldSurroundings\n): string | undefined {\n  const tokenPrefix = React.useContext(TokenPrefixContext);\n  const sources = new Set<string>();\n  for (const control of padding.controls) {\n    const provenance = surroundings.provenanceOf(control.leaf)?.provenance;\n    if (provenance?.kind !== \"inherited\") continue;\n    const source = siteDefaultSource(\n      provenance.from,\n      provenance.entry,\n      tokenPrefix\n    );\n    if (source !== undefined) sources.add(source);\n  }\n  return sources.size === 1 ? [...sources][0] : undefined;\n}\n\n/** Whether any side of the box holds a variable, at the tier being edited. */\nfunction useAnySideBound(\n  properties: readonly (InspectedStyleProperty | undefined)[],\n  surroundings: StyleFieldSurroundings\n): boolean {\n  const target = React.useContext(StyleTargetContext);\n  const { styles } = fieldStyles(\n    target,\n    surroundings.editor,\n    surroundings.nodeId\n  );\n  const { state, breakpoint } = surroundings;\n  return properties.some(property =>\n    (property?.controls ?? []).some(control =>\n      isTokenRef(\n        readStyleValue(styles, {\n          state,\n          breakpoint,\n          property: control.property,\n          path: control.path,\n        })\n      )\n    )\n  );\n}\n\n/** One ring of the spacing box: a property's four sides, and what it holds. */\nfunction SpacingRing({\n  property,\n  ring,\n  surroundings,\n  children,\n}: {\n  property: InspectedStyleProperty;\n  ring: \"margin\" | \"padding\";\n  surroundings: StyleFieldSurroundings;\n  children?: React.ReactNode;\n}): React.JSX.Element {\n  const { orientation, state, breakpoint } = surroundings;\n  const box = sideBoxFor(property.controls, orientation);\n  return (\n    <div\n      className=\"nx-style-inspector__property\"\n      data-property={property.property}\n    >\n      <SpacingRingContext.Provider value={box}>\n        <SideBoxFrame box={box} ring={ring}>\n          {/* Seen, not heard: every side's own name already says it. */}\n          <span className=\"nx-spacing-box__caption\" aria-hidden=\"true\">\n            {property.label}\n          </span>\n          {box.controls.map(control => {\n            const name = spacingSideName(property, box, control);\n            return (\n              <StyleControlField\n                key={[\n                  state,\n                  breakpoint,\n                  property.property,\n                  ...control.path,\n                ].join(\".\")}\n                control={control}\n                side={sideOf(box, control)}\n                label={name}\n                summary={undefined}\n                // The side's whole name, so its actions say \"Reset Margin top\"\n                // rather than naming the property twice.\n                propertyLabel={name}\n                clearOnly={control.withheld}\n                nodeId={surroundings.nodeId}\n                state={state}\n                breakpoint={breakpoint}\n                editor={surroundings.editor}\n                policy={surroundings.policy}\n                tokens={surroundings.tokens}\n                prefersDark={surroundings.prefersDark}\n                provenanceOf={surroundings.provenanceOf}\n                editing={surroundings.editing}\n              />\n            );\n          })}\n          {children}\n        </SideBoxFrame>\n      </SpacingRingContext.Provider>\n    </div>\n  );\n}\n\n/**\n * \"Margin top\": the property and the side in plain words, where the element's\n * axes give the side a physical name, and the logical one where they do not.\n */\nfunction spacingSideName(\n  property: InspectedStyleProperty,\n  box: SideBox,\n  control: StyleControl\n): string {\n  const side = sideOf(box, control);\n  const physical =\n    side === undefined || box.axes === undefined\n      ? undefined\n      : physicalSideName(side, box.axes);\n  const sideName =\n    physical ?? fieldLabel(control.path[control.path.length - 1] ?? \"\");\n  return `${property.label} ${sideName.toLowerCase()}`;\n}\n","\"use client\";\n\n/**\n * The fields of a section's style properties: one control per property, the\n * choices a placement offers, and the toggle between a property's forms.\n *\n * @module style-property-fields\n */\nimport {\n  findNode,\n  type BreakpointId,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport { radioGroupStep } from \"../../roving-radios\";\nimport { batchStyleClearOps } from \"../../styles/batch-style\";\nimport type { SideOrientation } from \"../../styles/side-orientation\";\nimport {\n  formNamesOf,\n  type StyleControl,\n  type StyleControlVariants,\n} from \"../../styles/style-controls\";\nimport { foldedControlFor } from \"../../styles/style-folded\";\nimport {\n  isLogicalSide,\n  physicalCornerName,\n  physicalSideName,\n  sideBoxFor,\n  sideOf,\n} from \"../../styles/style-sides\";\nimport {\n  readStyleValue,\n  type StyleAddress,\n  type StylePolicy,\n} from \"../../styles/style-values\";\nimport { CssHint } from \"../css-hint\";\nimport { fieldLabel } from \"../inspector\";\n\nimport { APPEAR_PROPERTY, AppearPlay } from \"./appear-play\";\nimport { propertyWordsFor, wordedProperty } from \"./block-style-words\";\nimport { SideBoxFrame } from \"./spacing-box-fields\";\nimport { flowOf } from \"./style-alignment-icons\";\nimport { StyleControlField } from \"./style-field-shell\";\nimport {\n  type StyleFieldSurroundings,\n  NamedAbove,\n  type ChooseForm,\n} from \"./style-field-surroundings\";\nimport type { InspectedStyleProperty } from \"./style-inspector\";\nimport { FoldedUnion, AlignmentFlow } from \"./style-value-fields\";\n\n/**\n * One catalog property, which is one control or several.\n *\n * `margin` is four logical sides and `position` is a scheme, four offsets and a\n * stacking order, so a property is a GROUP of controls rather than a field. The\n * heading is drawn only when there is more than one, because a lone control\n * already carries the property's name, and not when the section is titled\n * with it.\n */\nexport function StylePropertyFields({\n  property: catalogProperty,\n  orientation,\n  nodeId,\n  state,\n  breakpoint,\n  editor,\n  policy,\n  tokens,\n  prefersDark,\n  provenanceOf,\n  editing,\n  onChooseForm,\n  namesSection,\n}: {\n  property: InspectedStyleProperty;\n  /**\n   * Whether the property shares its section's name, as `border` does in the\n   * Border section: its heading would say the section's title again.\n   */\n  namesSection: boolean;\n} & StyleFieldSurroundings): React.JSX.Element {\n  // The block's own words for this property, where it has them: the fields\n  // it draws, what each is called, and a line saying what it is here.\n  const words = propertyWordsFor(\n    findNode(editor.document.nodes, nodeId)?.type,\n    catalogProperty.property\n  );\n  const property = wordedProperty(catalogProperty, words);\n  const many = property.controls.length > 1;\n  const fold = property.offered\n    ? foldedControlFor(property.property)\n    : undefined;\n  const choices = (property.offered ? property.variants : [])\n    // A folded property's root form follows from its value; see\n    // `style-folded.ts`. Its other choices, if any, stay.\n    .filter(\n      variant =>\n        variant.count > 1 && (fold === undefined || variant.path.length > 0)\n    );\n  // A toggle at the root is drawn on a row named for the property, so the\n  // property needs no heading over it as well.\n  const headed =\n    many && !namesSection && !choices.some(choice => choice.path.length === 0);\n  /*\n   * Whether this property is drawn as a box, and in what order — one decision,\n   * settled outside the component. Each side still keeps its own control, so it\n   * commits on its own and undo stays per side; the grouping is for the DRAWING\n   * only.\n   */\n  const box = sideBoxFor(property.controls, orientation);\n  const { above, before, toggled } = placeChoices(choices, box.boxed);\n  const toggle = (variant: StyleControlVariants) => (\n    <FormChoice\n      key={variant.path.join(\".\")}\n      property={property}\n      variant={variant}\n      nodeId={nodeId}\n      state={state}\n      breakpoint={breakpoint}\n      editor={editor}\n      policy={policy}\n      onChooseForm={onChooseForm}\n    />\n  );\n  return (\n    <div\n      className=\"nx-style-inspector__property\"\n      data-property={property.property}\n    >\n      <PropertyHeading\n        property={property}\n        headed={headed}\n        nodeId={nodeId}\n        state={state}\n        breakpoint={breakpoint}\n        editor={editor}\n      />\n      {/*\n        The forms the catalog offers at each union position, so every one is\n        reachable. Without this an unset `borderRadius` could only ever be\n        authored as a single radius and `position.zIndex` only as a number: the\n        engine answers with the catalog's first arm when nothing is stored, and\n        that answer is right precisely because the author has not spoken yet.\n\n        Withheld for a property the block no longer offers. `FormChoice`\n        REMOVES what is stored at the union's position — `styleClearOp`, so the\n        new form starts empty — which is right while a property is still\n        editable and wrong once it is not: a selector left enabled beside the\n        notice below reads as \"switch this to corners\" and instead deletes the\n        value, through a capability the block has withdrawn. The Clear action on\n        the value itself is the honest way to remove it, and it is already\n        there.\n      */}\n      {words?.hint === undefined ? null : (\n        <p className=\"nx-inspector__note\">{words.hint}</p>\n      )}\n      {above.map(toggle)}\n      {property.offered ? null : (\n        <p className=\"nx-inspector__note\" data-not-offered={property.property}>\n          {/* Not \"no longer\": a value written through the API is stored on\n              blocks that never offered the property. Said plainly so the\n              author knows clearing it changes the page. */}\n          This block doesn&apos;t offer {property.label}. The value set here\n          still applies; clearing it removes it.\n        </p>\n      )}\n      {/* The container's flow, which alignment icons are drawn in. */}\n      <AlignmentFlow.Provider\n        value={flowOf(\n          findNode(editor.document.nodes, nodeId)?.styles,\n          state,\n          breakpoint,\n          orientation\n        )}\n      >\n        {/* A folded union's one control, read where the value field is drawn;\n          see `style-folded.ts`. Its controls sit at the root, so the whole\n          property is the fold's. */}\n        <FoldedUnion.Provider\n          value={\n            fold === undefined\n              ? undefined\n              : { kind: fold, property: property.property }\n          }\n        >\n          <SideBoxFrame box={box}>\n            {box.controls.map(control => (\n              <React.Fragment\n                // The ADDRESS, not just the position: a host switching state or\n                // breakpoint leaves this field mounted, and where the old and new\n                // addresses hold the same value — both unset, most often — the\n                // synchronisation effect does not run either. An unfinished draft\n                // from the base breakpoint would then commit into the hover state.\n                key={[\n                  state,\n                  breakpoint,\n                  property.property,\n                  ...control.path,\n                ].join(\".\")}\n              >\n                {before(control.path).map(toggle)}\n                <NamedAbove.Provider\n                  value={toggled.includes(control.path.join(\".\"))}\n                >\n                  <StyleControlField\n                    control={control}\n                    side={sideOf(box, control)}\n                    label={\n                      words?.labels[control.path.join(\".\")] ??\n                      (many\n                        ? positionLabel(control, orientation)\n                        : property.label)\n                    }\n                    summary={many ? undefined : property.summary}\n                    propertyLabel={property.label}\n                    clearOnly={!property.offered || control.withheld}\n                    nodeId={nodeId}\n                    state={state}\n                    breakpoint={breakpoint}\n                    editor={editor}\n                    policy={policy}\n                    tokens={tokens}\n                    prefersDark={prefersDark}\n                    provenanceOf={provenanceOf}\n                    editing={editing}\n                  />\n                </NamedAbove.Provider>\n              </React.Fragment>\n            ))}\n          </SideBoxFrame>\n        </FoldedUnion.Provider>\n      </AlignmentFlow.Provider>\n    </div>\n  );\n}\n\n/**\n * A property's heading, when it has one, and the action drawn beside it: Play\n * beside \"Animation when it appears\", the one property that has one.\n */\nfunction PropertyHeading({\n  property,\n  headed,\n  nodeId,\n  state,\n  breakpoint,\n  editor,\n}: {\n  property: InspectedStyleProperty;\n  headed: boolean;\n  nodeId: string;\n  state: StyleState;\n  breakpoint: BreakpointId;\n  editor: EditorState;\n}): React.JSX.Element | null {\n  const label = headed ? (\n    // What the property does, then the CSS its fields write, on hover.\n    <CssHint\n      summary={property.summary}\n      writes={writtenProperties(property.controls)}\n    >\n      <p className=\"nx-style-inspector__property-label\">{property.label}</p>\n    </CssHint>\n  ) : null;\n  if (property.property !== APPEAR_PROPERTY) return label;\n  return (\n    <div className=\"nx-style-inspector__property-head\">\n      {label}\n      <AppearPlay\n        nodeId={nodeId}\n        state={state}\n        breakpoint={breakpoint}\n        editor={editor}\n      />\n    </div>\n  );\n}\n\n/**\n * Where each form toggle is drawn. A nested form's toggle sits just above its\n * own control where the controls are a list; a box places its sides itself,\n * so its toggles stay above it. Only a control with its toggle just above\n * drops its own visible name (`toggled`, by path).\n */\nfunction placeChoices(\n  choices: readonly StyleControlVariants[],\n  boxed: boolean\n): {\n  above: readonly StyleControlVariants[];\n  before: (path: readonly string[]) => readonly StyleControlVariants[];\n  toggled: readonly string[];\n} {\n  const inline = boxed ? [] : choices.filter(c => c.path.length > 0);\n  const above = choices.filter(choice => !inline.includes(choice));\n  const toggled = [\n    ...above.filter(choice => choice.path.length === 0),\n    ...inline,\n  ].map(choice => choice.path.join(\".\"));\n  return {\n    above,\n    before: path =>\n      inline.filter(choice => choice.path.join(\".\") === path.join(\".\")),\n    toggled,\n  };\n}\n\n/**\n * Rows whose stored key reads wrong as a word, by the kind of value and the\n * CSS property they set: the background's `url` is the image an author\n * chooses, not an address (a gradient writes the same property, as itself).\n */\nconst ROW_LABELS: Readonly<Record<string, string>> = {\n  \"url:background-image\": \"Image\",\n};\n\n/**\n * A control's name within its property: a side or a corner in plain words\n * (\"Top\", \"Bottom left\"), as the element's measured axes place it, rather\n * than CSS's logical words (\"Block start\", \"End start\"); any other position\n * by its key. Logical until the canvas has said which way the element runs:\n * on a right-to-left or vertical page a guessed \"Left\" would be wrong, and\n * the logical word is true either way.\n */\nfunction positionLabel(\n  control: StyleControl,\n  orientation: SideOrientation | undefined\n): string {\n  const named = ROW_LABELS[`${control.leaf.kind}:${control.leaf.cssProperty}`];\n  if (named !== undefined) return named;\n  const key = control.path[control.path.length - 1] ?? \"\";\n  if (orientation === undefined) return fieldLabel(key);\n  const plain =\n    (isLogicalSide(key) ? physicalSideName(key, orientation) : undefined) ??\n    physicalCornerName(key, orientation);\n  return plain === undefined\n    ? fieldLabel(key)\n    : plain.charAt(0).toUpperCase() + plain.slice(1);\n}\n\n/**\n * The choice of form at one union position: a toggle of its forms, named in\n * plain words (\"All | Corners\", \"Number | Auto\"), on a row named for the\n * property, where a menu labelled \"Border radius form\" put an internal word in\n * front of authors.\n *\n * Choosing a form while a value is stored CLEARS it. The two forms hold\n * different things — one radius is not four corners — so there is nothing to\n * carry across, and leaving the value in place would be worse than clearing:\n * the stored value decides its own arm, so the panel would snap straight back\n * to the form the author just moved away from.\n */\nfunction FormChoice({\n  property,\n  variant,\n  nodeId,\n  state,\n  breakpoint,\n  editor,\n  policy,\n  onChooseForm,\n}: {\n  property: InspectedStyleProperty;\n  variant: StyleControlVariants;\n  nodeId: string;\n  state: StyleState;\n  breakpoint: BreakpointId;\n  editor: EditorState;\n  policy: StylePolicy | undefined;\n  onChooseForm: ChooseForm;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  const radios = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const choose = (arm: number) => {\n    if (arm === variant.active) return;\n    onChooseForm(property.property, variant.path, arm);\n    const current = findNode(editor.document.nodes, nodeId);\n    if (current === undefined) return;\n    // The union's OWN position, not the property's root. A union can sit below\n    // it — `position` holds a type, an inset and a zIndex, and only the last is\n    // a union — so clearing the root to change the zIndex form would delete the\n    // author's positioning scheme and offsets along with it.\n    const address: StyleAddress = {\n      state,\n      breakpoint,\n      property: property.property,\n      path: variant.path,\n    };\n    // Read at this position for the same reason: `property.set` answers for the\n    // whole property, which is true whenever any sibling holds a value.\n    if (readStyleValue(current.styles, address) === undefined) return;\n    // Through the batch layer as a group of ONE, like every other style write\n    // in this panel. A refusal or an already-absent value both come back as no\n    // ops, which is what the two conditions here used to say separately.\n    const cleared = batchStyleClearOps([current], address, policy);\n    if (cleared.ops.length > 0) editor.applyAll(cleared.ops);\n  };\n  // As a radio group's arrow keys do: move and choose together, wrapping.\n  const step = (event: React.KeyboardEvent) => {\n    const delta = radioGroupStep(event.key);\n    if (delta === null) return;\n    event.preventDefault();\n    const next = (variant.active + delta + variant.count) % variant.count;\n    choose(next);\n    radios.current[next]?.focus();\n  };\n\n  return (\n    <div className=\"nx-inspector__field\" data-form-choice={property.property}>\n      {/*\n        The PROPERTY's name at the root, and the position's below it, where the\n        heading names the property: a toggle called \"Form\" would tell a\n        screen-reader user nothing about which property it changes. Plain text\n        rather than a label, which would forward a click to a radio.\n      */}\n      <p className=\"nx-inspector__field-name\" id={labelId}>\n        {variant.path.length === 0\n          ? property.label\n          : fieldLabel(variant.path[variant.path.length - 1] ?? \"\")}\n      </p>\n      <div\n        className=\"nx-style-inspector__toggle\"\n        role=\"radiogroup\"\n        aria-labelledby={labelId}\n      >\n        {formNamesOf(variant).map((name, index) => {\n          const checked = index === variant.active;\n          return (\n            <button\n              key={`${index}:${name}`}\n              ref={button => {\n                radios.current[index] = button;\n              }}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={checked}\n              // The group's one tab stop is the chosen form.\n              tabIndex={checked ? 0 : -1}\n              onClick={() => choose(index)}\n              onKeyDown={step}\n            >\n              {name}\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\n/** The CSS properties a property's fields write, each once, in their order. */\nfunction writtenProperties(\n  controls: readonly { readonly leaf: { readonly cssProperty: string } }[]\n): string | undefined {\n  const names = [...new Set(controls.map(control => control.leaf.cssProperty))];\n  return names.length === 0 ? undefined : names.join(\"; \");\n}\n","\"use client\";\n\n/**\n * A container's Arrange in Style › Layout: Stack, Row or Grid in plain words,\n * the CSS each writes shown small under it, and the rows each offers.\n *\n * Read back and written through `plain-layout`, by the arrangement in force\n * at the device being edited, at the edited target and state, through the\n * same write path as every Style control: one undoable step per change.\n *\n * @module plain-layout-controls\n */\nimport {\n  BASE_BREAKPOINT,\n  breakpointContexts,\n  findNode,\n  type BreakpointSet,\n  type NodeStyles,\n  type StyleState,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport { Input, Switch } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { offeredTiers } from \"../../canvas/canvas-width\";\nimport { chainedStyleOp, COLUMNS_ROW } from \"../../canvas/columns-layout\";\nimport type { EditorState } from \"../../editor-state\";\nimport {\n  LAYOUT_CSS_NAMES,\n  LAYOUT_PROPERTIES,\n  normalBeneath,\n  ownCascade,\n  planAlign,\n  planArrange,\n  planColumns,\n  planPlain,\n  planReverse,\n  planRows,\n  planSpread,\n  planStackOn,\n  planWrap,\n  readArrange,\n  readSpace,\n  spreadAxis,\n  unusedSettings,\n  type AlignPoint,\n  type AlignX,\n  type AlignY,\n  type LayoutProperty,\n  type LayoutTiers,\n  type LayoutValues,\n  type GridColumns,\n  type LayoutWrite,\n  type PlainFlow,\n  type PlainArrange,\n  type Spread,\n} from \"../../styles/plain-layout\";\nimport {\n  sharedStyleChange,\n  type SharedStyleChange,\n} from \"../../styles/shared-style-target\";\nimport type { SideOrientation } from \"../../styles/side-orientation\";\nimport { readStyleValue, type StyleAddress } from \"../../styles/style-values\";\nimport { layoutWritesText } from \"../code-hints\";\nimport { CssHint } from \"../css-hint\";\nimport { SegmentChoices } from \"../segment-choices\";\n\nimport {\n  AppliedAtTier,\n  BeneathAtTier,\n  StyleTargetContext,\n  TypesLiveContext,\n  type CascadeAt,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\nimport type { InspectedStyleProperty } from \"./style-inspector\";\nimport { StylePropertyFields } from \"./style-property-fields\";\nimport type { StyleTarget } from \"./style-target\";\n\n/**\n * The devices the switcher offers, widest (the base) first: of two at one\n * width the one the browser lets win, so a write lands where it applies.\n */\nfunction deviceOrder(breakpoints: BreakpointSet | undefined): string[] {\n  return [BASE_BREAKPOINT, ...offeredTiers(breakpoints).map(tier => tier.id)];\n}\n\n/**\n * Every viewport tier the page's styles are written for, in their order, as\n * the engine answers it: a target's own values are read through all of them,\n * though the switcher offers one tier of each width.\n */\nfunction compiledOrder(breakpoints: BreakpointSet | undefined): string[] {\n  return breakpointContexts(breakpoints)\n    .filter(context => context.axis === \"viewport\")\n    .map(context => context.id);\n}\n\n/** The edited target's styles: the block's, or the shared style's. */\nfunction stylesOf(\n  target: StyleTarget,\n  surroundings: StyleFieldSurroundings\n): NodeStyles | undefined {\n  if (target.kind === \"shared\") return target.style.styles;\n  return findNode(surroundings.editor.document.nodes, surroundings.nodeId)\n    ?.styles;\n}\n\n/** What the target stores at one device, as text. */\nfunction ownAt(\n  styles: NodeStyles | undefined,\n  state: StyleState,\n  device: string\n): LayoutValues {\n  const values: Partial<Record<LayoutProperty, string>> = {};\n  for (const property of LAYOUT_PROPERTIES) {\n    const value = readStyleValue(styles, {\n      state,\n      breakpoint: device,\n      property,\n      path: [],\n    });\n    if (typeof value === \"string\") values[property] = value;\n    // A variable or token set here is a value too: kept as written, so a\n    // control knows the property holds one.\n    else if (value !== undefined) values[property] = JSON.stringify(value);\n  }\n  return values;\n}\n\n/** What the cascade applies to the block at a device, property by property. */\nfunction appliedInForce(applied: CascadeAt): (device: string) => LayoutValues {\n  return device => {\n    const values: Partial<Record<LayoutProperty, string>> = {};\n    for (const property of LAYOUT_PROPERTIES) {\n      const answer = applied(device, LAYOUT_CSS_NAMES[property] ?? property);\n      if (answer !== undefined) values[property] = answer.value;\n    }\n    return values;\n  };\n}\n\n/**\n * What is in force and stored at each device. A block reads what the cascade\n * applies to it there (its own values over a shared style it wears and its\n * block's defaults); a shared style reads its own values, which are what its\n * Arrange writes.\n */\nfunction layoutTiers(\n  surroundings: StyleFieldSurroundings,\n  target: StyleTarget,\n  cascade: { applied: CascadeAt | undefined; beneath: CascadeAt | undefined }\n): LayoutTiers {\n  const order = deviceOrder(surroundings.breakpoints);\n  const styles = stylesOf(target, surroundings);\n  const own = (device: string) => ownAt(styles, surroundings.state, device);\n  const normal = (device: string) => ownAt(styles, \"base\", device);\n  const block = target.kind === \"block\";\n  const inForce =\n    block && cascade.applied !== undefined\n      ? appliedInForce(cascade.applied)\n      : ownCascade(compiledOrder(surroundings.breakpoints), own, normal);\n  const beneath = beneathOf({\n    order: compiledOrder(surroundings.breakpoints),\n    normal,\n    atState: surroundings.state !== \"base\",\n    cascade: block ? cascade.beneath : undefined,\n  });\n  return {\n    order,\n    cascadeOrder: compiledOrder(surroundings.breakpoints),\n    own,\n    inForce,\n    ...(beneath === undefined ? {} : { beneath }),\n    flow: flowOf(surroundings.orientation),\n  };\n}\n\n/**\n * What lies beneath the target's own values at a device: for a block, what\n * the cascade applies without its declarations; at an interaction state, the\n * target's own Normal values too, which a value cleared at the state leaves.\n */\nfunction beneathOf({\n  order,\n  normal,\n  atState,\n  cascade,\n}: {\n  order: readonly string[];\n  normal: (device: string) => LayoutValues;\n  atState: boolean;\n  cascade: CascadeAt | undefined;\n}): ((device: string) => LayoutValues) | undefined {\n  const others = cascade === undefined ? undefined : appliedInForce(cascade);\n  const ownNormal = atState ? normalBeneath(order, normal) : undefined;\n  if (others === undefined) return ownNormal;\n  if (ownNormal === undefined) return others;\n  return device => ({ ...others(device), ...ownNormal(device) });\n}\n\n/** The container's flow, as the canvas measured it; left to right if not. */\nfunction flowOf(orientation: SideOrientation | undefined): PlainFlow {\n  return {\n    writingMode: orientation?.writingMode ?? \"horizontal-tb\",\n    rtl: orientation?.direction === \"rtl\",\n  };\n}\n\n/** The properties each arrangement draws in plain words. */\nconst DRAWN_BY: Readonly<\n  Record<\"stack\" | \"row\" | \"grid\", ReadonlySet<string>>\n> = {\n  stack: new Set([\n    \"display\",\n    \"flexDirection\",\n    \"justifyContent\",\n    \"alignItems\",\n    \"gap\",\n    \"rowGap\",\n    \"columnGap\",\n  ]),\n  row: new Set([\n    \"display\",\n    \"flexDirection\",\n    \"flexWrap\",\n    \"justifyContent\",\n    \"alignItems\",\n    \"gap\",\n    \"rowGap\",\n    \"columnGap\",\n  ]),\n  grid: new Set([\n    \"display\",\n    \"gridTemplateColumns\",\n    \"gridTemplateRows\",\n    \"justifyItems\",\n    \"alignItems\",\n    \"gap\",\n    \"rowGap\",\n    \"columnGap\",\n  ]),\n};\n\n/**\n * Whether a layout property's raw row is left out under the arrangement in\n * force: drawn there in plain words, or holding nothing. One it doesn't draw\n * that holds a value still in effect (a Grid's `justify-content`) stays a raw\n * row, so no value in force is out of reach; one that no longer applies is\n * said in the \"aren't used\" line instead.\n */\nexport function arrangedAway(\n  property: {\n    readonly property: string;\n    readonly set: boolean;\n    readonly applies: boolean;\n  },\n  mode: \"stack\" | \"row\" | \"grid\"\n): boolean {\n  if (!ARRANGED_PROPERTIES.has(property.property)) return false;\n  if (DRAWN_BY[mode].has(property.property)) return true;\n  return !(property.set && property.applies);\n}\n\n/** The properties Arrange draws in plain words, out of the raw rows. */\nconst ARRANGED_PROPERTIES: ReadonlySet<string> = new Set([\n  \"display\",\n  \"flexDirection\",\n  \"flexWrap\",\n  \"justifyContent\",\n  \"alignItems\",\n  \"justifyItems\",\n  \"gap\",\n  \"rowGap\",\n  \"columnGap\",\n  \"gridTemplateColumns\",\n  \"gridTemplateRows\",\n]);\n\n/** Whether a block's Layout is drawn by Arrange: a container, not Columns. */\nexport function arrangesLayout(blockType: string | undefined): boolean {\n  return blockType !== COLUMNS_ROW;\n}\n\n/**\n * The writes made, as one step: an op through the block's write path, or\n * one change to the shared style being edited.\n */\n/** The layout properties the catalog stores as numbers: a flex share. */\nconst NUMBER_PROPERTIES: ReadonlySet<string> = new Set([\n  \"flexGrow\",\n  \"flexShrink\",\n]);\n\n/** A planned value as the catalog stores it: a number where it is one. */\nfunction storedForm(\n  property: string,\n  value: string | null\n): string | number | null {\n  if (value === null || !NUMBER_PROPERTIES.has(property)) return value;\n  const number = Number(value);\n  return Number.isFinite(number) ? number : value;\n}\n\nexport function useApply(\n  surroundings: StyleFieldSurroundings,\n  target: StyleTarget\n): (writes: readonly LayoutWrite[]) => void {\n  const { editor, nodeId, state, policy } = surroundings;\n  return writes => {\n    if (writes.length === 0) return;\n    const steps = writes.map(write => ({\n      address: {\n        state,\n        breakpoint: write.device,\n        property: write.property,\n        path: [] as string[],\n      },\n      value: storedForm(write.property, write.value),\n    }));\n    if (target.kind === \"shared\") {\n      if (target.readOnly !== undefined) return;\n      void target.write(\n        combined(\n          steps.map(step => sharedStyleChange(step.address, step.value, policy))\n        )\n      );\n      return;\n    }\n    const node = findNode(editor.document.nodes, nodeId);\n    if (node === undefined) return;\n    const op = chainedStyleOp(node, steps);\n    if (op !== null) editor.apply(op);\n  };\n}\n\n/** Several changes to a shared style as one, undone as one. */\nfunction combined(changes: readonly SharedStyleChange[]): SharedStyleChange {\n  return Object.assign(\n    (styles: NodeStyles) => {\n      let current = styles;\n      let wrote = false;\n      for (const change of changes) {\n        const write = change(current);\n        if (write.kind === \"refused\") return write;\n        if (write.kind === \"write\") {\n          current = write.styles;\n          wrote = true;\n        }\n      }\n      return wrote\n        ? { kind: \"write\" as const, styles: current }\n        : { kind: \"unchanged\" as const };\n    },\n    {\n      invert: (before: NodeStyles) => {\n        // Each change undone in reverse, each from the styles it was applied to.\n        const states: NodeStyles[] = [];\n        let current = before;\n        for (const change of changes) {\n          states.push(current);\n          const write = change(current);\n          if (write.kind === \"write\") current = write.styles;\n        }\n        return combined(\n          changes\n            .map((change, index) => change.invert(states[index] ?? before))\n            .reverse()\n        );\n      },\n    }\n  );\n}\n\nconst MODES = [\"stack\", \"row\", \"grid\"] as const;\n\n/** What each mode writes at the edited device, from the writes it plans. */\nfunction modeWrites(\n  tiers: LayoutTiers,\n  editing: string\n): Record<(typeof MODES)[number], string> {\n  return {\n    stack: layoutWritesText(planArrange(tiers, editing, \"stack\")),\n    row: layoutWritesText(planArrange(tiers, editing, \"row\")),\n    grid: layoutWritesText(planArrange(tiers, editing, \"grid\")),\n  };\n}\nconst MODE_LABELS = { stack: \"Stack\", row: \"Row\", grid: \"Grid\" } as const;\n\n/** What a mode writes, small, as a developer reads it. */\nfunction modeLine(arrange: PlainArrange): string {\n  if (arrange.mode === \"grid\") return \"display: grid\";\n  if (arrange.mode === \"custom\") return \"Set in CSS: the rows below hold it.\";\n  if (arrange.mode === \"stack\" && !arrange.flex) return \"display: block\";\n  const column = arrange.mode === \"stack\" || arrange.stacked;\n  const direction = column ? \"column\" : \"row\";\n  return `display: flex · flex-direction: ${direction}${arrange.reverse ? \"-reverse\" : \"\"}`;\n}\n\n/** What Arrange reads at the edited device, shared by its rows and the section. */\nexport interface ArrangeReading {\n  readonly tiers: LayoutTiers;\n  readonly editing: string;\n  readonly arrange: PlainArrange;\n}\n\n/**\n * Arrange's reading for a Layout section, or `undefined` where Arrange isn't\n * drawn: a block with no layout (its section offers no Display) and Columns,\n * whose tiles are its own.\n */\n/**\n * What is in force and stored at each device for the edited target, read\n * through the cascade the panel lends: Arrange's reading, and the one\n * \"Inside its parent\" sizes the block by.\n */\nexport function useLayoutTiers(\n  surroundings: StyleFieldSurroundings\n): LayoutTiers {\n  const target = React.useContext(StyleTargetContext);\n  const applied = React.useContext(AppliedAtTier);\n  const beneath = React.useContext(BeneathAtTier);\n  return layoutTiers(surroundings, target, { applied, beneath });\n}\n\nexport function useArrangeReading(\n  surroundings: StyleFieldSurroundings,\n  offersDisplay: boolean\n): ArrangeReading | undefined {\n  const target = React.useContext(StyleTargetContext);\n  const applied = React.useContext(AppliedAtTier);\n  const beneath = React.useContext(BeneathAtTier);\n  if (!offersDisplay || !arrangesLayout(surroundings.editing.blockType)) {\n    return undefined;\n  }\n  const tiers = layoutTiers(surroundings, target, { applied, beneath });\n  const editing = surroundings.breakpoint;\n  return { tiers, editing, arrange: readArrange(tiers, editing) };\n}\n\n/**\n * Arrange and its rows, at the top of a container's Layout section, from the\n * section's reading. `spacing` is the section's own Space between fields,\n * drawn in the mode's order.\n */\nexport function ArrangeFields({\n  surroundings,\n  reading,\n  spacing,\n}: {\n  surroundings: StyleFieldSurroundings;\n  reading: ArrangeReading;\n  spacing: readonly InspectedStyleProperty[];\n}): React.JSX.Element {\n  const target = React.useContext(StyleTargetContext);\n  const labelId = React.useId();\n  const apply = useApply(surroundings, target);\n  const { tiers, editing, arrange } = reading;\n  const unused = unusedSettings(tiers, editing);\n  const space = (\n    <SpaceBetween\n      surroundings={surroundings}\n      reading={reading}\n      properties={spacing}\n      apartOffered={arrange.mode === \"grid\"}\n    />\n  );\n  return (\n    <div className=\"nx-arrange\" data-control=\"arrange\">\n      <div className=\"nx-inspector__field\">\n        <span className=\"nx-inspector__field-name\" id={labelId}>\n          Arrange\n        </span>\n        <SegmentChoices\n          options={MODES}\n          on={arrange.mode === \"custom\" ? undefined : arrange.mode}\n          labels={MODE_LABELS}\n          labelId={labelId}\n          writes={modeWrites(tiers, editing)}\n          onChoose={mode => apply(planArrange(tiers, editing, mode))}\n        />\n      </div>\n      <p className=\"nx-arrange__css\">{modeLine(arrange)}</p>\n      {arrange.mode === \"custom\" ? (\n        <p className=\"nx-arrange__custom\">\n          Arrange: Custom{\" · \"}\n          <button\n            type=\"button\"\n            className=\"nx-arrange__link\"\n            onClick={() => apply(planPlain(tiers, editing))}\n          >\n            Use plain controls\n          </button>\n        </p>\n      ) : null}\n      <ModeRows\n        arrange={arrange}\n        tiers={tiers}\n        editing={editing}\n        breakpoints={surroundings.breakpoints}\n        apply={apply}\n        space={space}\n      />\n      {unused.length === 0 ? null : (\n        <UnusedLine\n          unused={unused}\n          onClear={() =>\n            apply(\n              unused.map(property => ({\n                device: editing,\n                property,\n                value: null,\n              }))\n            )\n          }\n        />\n      )}\n    </div>\n  );\n}\n\n/** The rows the arrangement in force offers. */\nfunction ModeRows({\n  arrange,\n  tiers,\n  editing,\n  breakpoints,\n  apply,\n  space,\n}: {\n  arrange: PlainArrange;\n  tiers: LayoutTiers;\n  editing: string;\n  breakpoints: BreakpointSet | undefined;\n  apply: (writes: readonly LayoutWrite[]) => void;\n  /** Space between, drawn in the mode's order. */\n  space: React.JSX.Element;\n}): React.JSX.Element | null {\n  if (arrange.mode === \"custom\") return null;\n  const align = (\n    <AlignGrid\n      point={arrange.align}\n      onChoose={point => apply(planAlign(tiers, editing, point))}\n      held={\n        arrange.mode === \"row\" && arrange.spread !== \"packed\"\n          ? spreadAxis(arrange.stacked, tiers.flow)\n          : undefined\n      }\n    />\n  );\n  if (arrange.mode === \"stack\") {\n    return (\n      <>\n        {align}\n        {space}\n        <SwitchRow\n          label=\"Reverse order\"\n          on={arrange.reverse}\n          onChange={on => apply(planReverse(tiers, editing, on))}\n        />\n      </>\n    );\n  }\n  if (arrange.mode === \"grid\") {\n    return (\n      <GridRows\n        arrange={arrange}\n        tiers={tiers}\n        editing={editing}\n        apply={apply}\n        align={align}\n        space={space}\n      />\n    );\n  }\n  return (\n    <>\n      <StackOnRow\n        tiers={tiers}\n        stackOn={arrange.stackOn}\n        breakpoints={breakpoints}\n        onChoose={device => apply(planStackOn(tiers, device))}\n      />\n      {align}\n      <SpreadRow\n        spread={arrange.spread}\n        writes={\n          Object.fromEntries(\n            SPREADS.map(each => [\n              each,\n              spreadWritesText(planSpread(tiers, editing, each)),\n            ])\n          ) as Record<Spread, string>\n        }\n        onChoose={spread => apply(planSpread(tiers, editing, spread))}\n      />\n      {space}\n      {arrange.stacked ? null : (\n        <SwitchRow\n          label=\"Wrap onto new lines\"\n          on={arrange.wrap}\n          writes=\"flex-wrap: wrap\"\n          onChange={on => apply(planWrap(tiers, editing, on))}\n        />\n      )}\n      <SwitchRow\n        label=\"Reverse order\"\n        on={arrange.reverse}\n        onChange={on => apply(planReverse(tiers, editing, on))}\n      />\n    </>\n  );\n}\n\nconst X_POINTS = [\"left\", \"center\", \"right\"] as const;\nconst Y_POINTS = [\"top\", \"middle\", \"bottom\"] as const;\nconst POINT_NAMES: Readonly<Record<AlignY, Readonly<Record<AlignX, string>>>> =\n  {\n    top: { left: \"Top left\", center: \"Top centre\", right: \"Top right\" },\n    middle: { left: \"Middle left\", center: \"Centre\", right: \"Middle right\" },\n    bottom: {\n      left: \"Bottom left\",\n      center: \"Bottom centre\",\n      right: \"Bottom right\",\n    },\n  };\n\n/** A point's name: \"Top left\", \"Centre\", \"Bottom right\". */\nfunction pointName(point: AlignPoint): string {\n  return POINT_NAMES[point.y][point.x];\n}\n\n/**\n * The 3×3 Align: a radio group moved with the arrows in two dimensions, each\n * point named. No point chosen is the default stretch, said under it. While\n * Spread is on, the axis it takes is held.\n */\nfunction AlignGrid({\n  point,\n  onChoose,\n  held,\n}: {\n  point: AlignPoint | undefined;\n  onChoose: (point: AlignPoint | null) => void;\n  /** The axis Spread holds, while it is on. */\n  held: \"x\" | \"y\" | undefined;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  const points = Y_POINTS.flatMap(y => X_POINTS.map(x => ({ x, y })));\n  const index =\n    point === undefined\n      ? -1\n      : points.findIndex(each => each.x === point.x && each.y === point.y);\n  const stop = index === -1 ? 0 : index;\n  const choose = (next: number) => {\n    const to = points[next];\n    if (to !== undefined) onChoose(to);\n  };\n  const onKey = (event: React.KeyboardEvent<HTMLButtonElement>, at: number) => {\n    const moves: Record<string, number> = {\n      ArrowLeft: -1,\n      ArrowRight: 1,\n      ArrowUp: -3,\n      ArrowDown: 3,\n    };\n    const step = moves[event.key];\n    if (step === undefined) return;\n    event.preventDefault();\n    const next = Math.min(8, Math.max(0, at + step));\n    choose(next);\n    event.currentTarget.parentElement\n      ?.querySelectorAll<HTMLElement>('[role=\"radio\"]')\n      [next]?.focus();\n  };\n  return (\n    <div className=\"nx-inspector__field\">\n      <span className=\"nx-inspector__field-name\" id={labelId}>\n        Align\n      </span>\n      <div className=\"nx-align-grid__wrap\">\n        <div\n          role=\"radiogroup\"\n          aria-labelledby={labelId}\n          className=\"nx-align-grid\"\n        >\n          {points.map((each, at) => (\n            <button\n              key={`${each.y}-${each.x}`}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={at === index}\n              aria-label={pointName(each)}\n              tabIndex={at === stop ? 0 : -1}\n              className=\"nx-align-grid__point\"\n              onKeyDown={event => onKey(event, at)}\n              onClick={() => onChoose(at === index ? null : each)}\n            />\n          ))}\n        </div>\n        <p className=\"nx-inspector__note\">\n          {held !== undefined\n            ? \"Spread is on: it places blocks along the row.\"\n            : point === undefined\n              ? \"Fills the width.\"\n              : pointName(point)}\n        </p>\n      </div>\n    </div>\n  );\n}\n\nconst SPREADS = [\"packed\", \"between\", \"around\", \"even\"] as const;\n\n/** Packed writes no spread: the main axis is left to Align. */\nfunction spreadWritesText(writes: readonly LayoutWrite[]): string {\n  return writes.some(write => write.value !== null)\n    ? layoutWritesText(writes)\n    : \"justify-content (from Align)\";\n}\nconst SPREAD_LABELS = {\n  packed: \"Packed\",\n  between: \"Space between\",\n  around: \"Space around\",\n  even: \"Even\",\n} as const;\n\n/** A Row's Spread along its main axis, each choice hinted by what it writes. */\nfunction SpreadRow({\n  spread,\n  writes,\n  onChoose,\n}: {\n  spread: Spread;\n  writes: Readonly<Record<Spread, string>>;\n  onChoose: (spread: Spread) => void;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  return (\n    <div className=\"nx-inspector__field\">\n      <span className=\"nx-inspector__field-name\" id={labelId}>\n        Spread\n      </span>\n      <SegmentChoices\n        options={SPREADS}\n        on={spread}\n        labels={SPREAD_LABELS}\n        labelId={labelId}\n        writes={writes}\n        onChoose={onChoose}\n      />\n    </div>\n  );\n}\n\n/** A plain on and off row, with what it writes on hover. */\nfunction SwitchRow({\n  label,\n  on,\n  writes,\n  onChange,\n}: {\n  label: string;\n  on: boolean;\n  writes?: string;\n  onChange: (on: boolean) => void;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-inspector__field\" data-display=\"switch\">\n      <span className=\"nx-inspector__field-name\">{label}</span>\n      <CssHint writes={writes}>\n        <Switch aria-label={label} checked={on} onCheckedChange={onChange} />\n      </CssHint>\n    </div>\n  );\n}\n\n/** Whether a device's name reads well as \"and smaller\". */\nfunction deviceLabel(\n  breakpoints: BreakpointSet | undefined,\n  device: string\n): string {\n  return (\n    breakpoints?.viewport.find(each => each.id === device)?.label ?? device\n  );\n}\n\n/** A Row's Stack on: Never, or a device and the smaller ones. */\nfunction StackOnRow({\n  tiers,\n  stackOn,\n  breakpoints,\n  onChoose,\n}: {\n  tiers: LayoutTiers;\n  stackOn: string | undefined;\n  breakpoints: BreakpointSet | undefined;\n  onChoose: (device: string | null) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  const devices = tiers.order.slice(1);\n  return (\n    <div className=\"nx-inspector__field\">\n      <label className=\"nx-inspector__field-name\" htmlFor={id}>\n        Stack on\n      </label>\n      <CssHint writes=\"flex-direction: column\">\n        <select\n          id={id}\n          className=\"nx-arrange__select\"\n          value={stackOn ?? \"\"}\n          onChange={event =>\n            onChoose(event.target.value === \"\" ? null : event.target.value)\n          }\n        >\n          <option value=\"\">Never</option>\n          {devices.map((device, index) => (\n            <option key={device} value={device}>\n              {index === devices.length - 1\n                ? deviceLabel(breakpoints, device)\n                : `${deviceLabel(breakpoints, device)} and smaller`}\n            </option>\n          ))}\n        </select>\n      </CssHint>\n    </div>\n  );\n}\n\n/** A Grid's columns, rows and Align. */\nfunction GridRows({\n  arrange,\n  tiers,\n  editing,\n  apply,\n  align,\n  space,\n}: {\n  arrange: Extract<PlainArrange, { mode: \"grid\" }>;\n  tiers: LayoutTiers;\n  editing: string;\n  apply: (writes: readonly LayoutWrite[]) => void;\n  align: React.JSX.Element;\n  space: React.JSX.Element;\n}): React.JSX.Element {\n  const columnsId = React.useId();\n  const fit = arrange.columns?.kind === \"fit\";\n  const labelId = React.useId();\n  return (\n    <>\n      <div className=\"nx-inspector__field\">\n        <span className=\"nx-inspector__field-name\" id={labelId}>\n          Columns\n        </span>\n        <SegmentChoices\n          options={[\"count\", \"fit\"] as const}\n          on={fit ? \"fit\" : \"count\"}\n          labels={{ count: \"Number\", fit: \"As many as fit\" }}\n          labelId={labelId}\n          writes={{\n            count: \"grid-template-columns: repeat(N, minmax(0, 1fr))\",\n            fit: \"grid-template-columns: repeat(auto-fill, minmax(W, 1fr))\",\n          }}\n          onChoose={kind =>\n            apply(\n              planColumns(\n                tiers,\n                editing,\n                kind === \"fit\"\n                  ? { kind: \"fit\", min: \"12rem\" }\n                  : { kind: \"count\", count: 2 }\n              )\n            )\n          }\n        />\n      </div>\n      <div className=\"nx-inspector__field\">\n        <label className=\"nx-inspector__field-name\" htmlFor={columnsId}>\n          {fit ? \"Minimum width\" : \"How many\"}\n        </label>\n        <DraftInput\n          id={columnsId}\n          value={\n            arrange.columns === undefined\n              ? \"\"\n              : arrange.columns.kind === \"fit\"\n                ? arrange.columns.min\n                : String(arrange.columns.count)\n          }\n          placeholder={fit ? \"12rem\" : \"Auto\"}\n          onCommit={text => {\n            const columns = columnsTyped(text, fit);\n            if (columns !== \"refused\") {\n              apply(planColumns(tiers, editing, columns));\n            }\n          }}\n        />\n      </div>\n      <GridRowsCount\n        rows={arrange.rows}\n        onCommit={rows => apply(planRows(tiers, editing, rows))}\n      />\n      {align}\n      {space}\n    </>\n  );\n}\n\n/**\n * The columns a typed value asks for: a minimum width or a count, nothing\n * (Auto) when emptied, or `\"refused\"` for a count that isn't a whole number.\n */\nfunction columnsTyped(\n  text: string,\n  fit: boolean\n): GridColumns | undefined | \"refused\" {\n  const typed = text.trim();\n  if (typed === \"\") return undefined;\n  if (fit) return { kind: \"fit\", min: typed };\n  const count = Number.parseInt(typed, 10);\n  return Number.isInteger(count) && count > 0\n    ? { kind: \"count\", count }\n    : \"refused\";\n}\n\n/** A Grid's rows: a number, or empty for Auto. */\nfunction GridRowsCount({\n  rows,\n  onCommit,\n}: {\n  rows: number | undefined;\n  onCommit: (rows: number | undefined) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <div className=\"nx-inspector__field\">\n      <label className=\"nx-inspector__field-name\" htmlFor={id}>\n        Rows\n      </label>\n      <DraftInput\n        id={id}\n        value={rows === undefined ? \"\" : String(rows)}\n        placeholder=\"Auto\"\n        onCommit={text => {\n          if (text.trim() === \"\") return onCommit(undefined);\n          const count = Number.parseInt(text, 10);\n          if (Number.isInteger(count) && count > 0) onCommit(count);\n        }}\n      />\n    </div>\n  );\n}\n\n/** A text field committed on blur and on Enter, as every field here is. */\nexport function DraftInput({\n  id,\n  value,\n  placeholder,\n  onCommit,\n}: {\n  id: string;\n  value: string;\n  placeholder: string;\n  onCommit: (text: string) => void;\n}): React.JSX.Element {\n  const [draft, setDraft] = React.useState(value);\n  React.useEffect(() => setDraft(value), [value]);\n  const commit = () => {\n    if (draft !== value) onCommit(draft);\n  };\n  return (\n    <Input\n      id={id}\n      value={draft}\n      placeholder={placeholder}\n      autoComplete=\"off\"\n      onChange={event => setDraft(event.target.value)}\n      onBlur={commit}\n      onKeyDown={event => {\n        if (event.key !== \"Enter\") return;\n        event.preventDefault();\n        commit();\n      }}\n    />\n  );\n}\n\n/** Which choice a set of unused values came from, for the line. */\nfunction unusedFrom(unused: readonly LayoutProperty[]): string {\n  const grid = unused.some(\n    property => property.startsWith(\"grid\") || property === \"justifyItems\"\n  );\n  const flex = unused.some(property => property.startsWith(\"flex\"));\n  if (grid && flex) return \"Row and Grid\";\n  // What's left without a grid property (alignment, space) is a Row's or a\n  // flex Stack's, and only a Row writes it outside a flex column.\n  return grid ? \"Grid\" : \"Row\";\n}\n\n/** \"2 settings from Row aren't used · Clear\". */\nfunction UnusedLine({\n  unused,\n  onClear,\n}: {\n  unused: readonly LayoutProperty[];\n  onClear: () => void;\n}): React.JSX.Element {\n  const count = unused.length;\n  return (\n    <p className=\"nx-arrange__unused\" role=\"status\">\n      {count === 1\n        ? `1 setting from ${unusedFrom(unused)} isn't used`\n        : `${String(count)} settings from ${unusedFrom(unused)} aren't used`}\n      {\" · \"}\n      <button type=\"button\" className=\"nx-arrange__clear\" onClick={onClear}>\n        Clear\n      </button>\n    </p>\n  );\n}\n\n/** The space properties, in the order the rows draw them. */\nconst SPACE_ORDER = [\"gap\", \"rowGap\", \"columnGap\"] as const;\n\n/** The properties Space between draws, out of the section's own fields. */\nexport const SPACE_PROPERTIES: ReadonlySet<string> = new Set(SPACE_ORDER);\n\n/** Whether styles set any space at the edited address. */\nfunction setsSpace(\n  styles: NodeStyles | undefined,\n  state: StyleState,\n  breakpoint: string\n): boolean {\n  return SPACE_ORDER.some(\n    property =>\n      readStyleValue(styles, { state, breakpoint, property, path: [] }) !==\n      undefined\n  );\n}\n\n/** The flex column a Stack in block flow becomes to space its blocks. */\nfunction columnSteps(\n  state: StyleState,\n  breakpoint: string\n): { address: StyleAddress; value: StyleValue }[] {\n  return [\n    {\n      address: { state, breakpoint, property: \"display\", path: [] },\n      value: \"flex\",\n    },\n    {\n      address: { state, breakpoint, property: \"flexDirection\", path: [] },\n      value: \"column\",\n    },\n  ];\n}\n\n/**\n * The editor a Stack in block flow writes its space through: a space set\n * there also writes the flex column, in the same op, so it applies and one\n * undo takes both back. A style op holds the node's whole styles, so the\n * last one for the node is extended.\n */\nfunction columnOnSpace(\n  editor: EditorState,\n  nodeId: string,\n  state: StyleState,\n  breakpoint: string\n): EditorState {\n  return {\n    ...editor,\n    applyAll: ops => {\n      const node = findNode(editor.document.nodes, nodeId);\n      const at = ops.findLastIndex(\n        op =>\n          op.kind === \"update\" &&\n          op.id === nodeId &&\n          op.patch?.styles !== undefined\n      );\n      const last = at === -1 ? undefined : ops[at];\n      const styles =\n        last?.kind === \"update\"\n          ? (last.patch?.styles as NodeStyles)\n          : undefined;\n      if (\n        node === undefined ||\n        last === undefined ||\n        !setsSpace(styles, state, breakpoint)\n      ) {\n        return editor.applyAll(ops);\n      }\n      const flexed = chainedStyleOp(\n        { ...node, styles },\n        columnSteps(state, breakpoint)\n      );\n      return editor.applyAll(\n        ops.map((op, index) => (index === at ? (flexed ?? op) : op))\n      );\n    },\n  };\n}\n\n/** The shared style a Stack in block flow writes its space through, likewise. */\nfunction sharedColumnOnSpace(\n  target: Extract<StyleTarget, { kind: \"shared\" }>,\n  state: StyleState,\n  breakpoint: string,\n  policy: StyleFieldSurroundings[\"policy\"]\n): StyleTarget {\n  return {\n    ...target,\n    write: change => {\n      const write = change(target.style.styles);\n      if (\n        write.kind !== \"write\" ||\n        !setsSpace(write.styles, state, breakpoint)\n      ) {\n        return target.write(change);\n      }\n      return target.write(\n        combined([\n          change,\n          ...columnSteps(state, breakpoint).map(step =>\n            sharedStyleChange(step.address, step.value, policy)\n          ),\n        ])\n      );\n    },\n  };\n}\n\n/**\n * The editor and target Space between writes through: in a Stack in block\n * flow, ones that also write its flex column; elsewhere the panel's own.\n */\nfunction spaceWriters(\n  surroundings: StyleFieldSurroundings,\n  reading: ArrangeReading,\n  target: StyleTarget\n): { editor: EditorState; written: StyleTarget } {\n  const { arrange } = reading;\n  if (arrange.mode !== \"stack\" || arrange.flex) {\n    return { editor: surroundings.editor, written: target };\n  }\n  const { state, breakpoint, nodeId, policy } = surroundings;\n  return {\n    editor: columnOnSpace(surroundings.editor, nodeId, state, breakpoint),\n    written:\n      target.kind === \"shared\"\n        ? sharedColumnOnSpace(target, state, breakpoint, policy)\n        : target,\n  };\n}\n\n/**\n * Space between: the section's own gap field, so a variable or a token works\n * as on any spacing field, named in plain words. A Grid can set rows and\n * columns apart, which writes `row-gap` and `column-gap`.\n */\nfunction SpaceBetween({\n  surroundings,\n  reading,\n  properties,\n  apartOffered,\n}: {\n  surroundings: StyleFieldSurroundings;\n  reading: ArrangeReading;\n  properties: readonly InspectedStyleProperty[];\n  apartOffered: boolean;\n}): React.JSX.Element | null {\n  const target = React.useContext(StyleTargetContext);\n  const space = readSpace(reading.tiers, reading.editing);\n  const setApart = space.rowGap !== undefined || space.columnGap !== undefined;\n  const [apartAsked, setApartAsked] = React.useState(false);\n  // Rows and columns set apart stay drawn wherever they apply, a Row's\n  // included; only a Grid offers to set them apart.\n  const apart = setApart || (apartOffered && apartAsked);\n  const { editor, written } = spaceWriters(surroundings, reading, target);\n  const drawn = properties.filter(property =>\n    apart ? property.property !== \"gap\" : property.property === \"gap\"\n  );\n  if (drawn.length === 0) return null;\n  return (\n    <StyleTargetContext.Provider value={written}>\n      {/* A block's own fields: the canvas follows what is typed in them. */}\n      <TypesLiveContext.Provider value={true}>\n        {drawn.map(property => (\n          <StylePropertyFields\n            key={property.property}\n            property={property}\n            namesSection={false}\n            {...surroundings}\n            editor={editor}\n          />\n        ))}\n        {apartOffered && !apart ? (\n          <button\n            type=\"button\"\n            className=\"nx-arrange__link\"\n            onClick={() => setApartAsked(true)}\n          >\n            Set rows and columns apart\n          </button>\n        ) : null}\n      </TypesLiveContext.Provider>\n    </StyleTargetContext.Provider>\n  );\n}\n","\"use client\";\n\n/**\n * \"Inside its parent\": how a block takes its place in its parent, in plain\n * words. Width: Fill, Fit or Fixed, and Height the same under a Row or a\n * Grid, each with the line that says what it does and the CSS it writes on\n * hover.\n *\n * Read and written through `plain-layout` by the parent's arrangement at the\n * device being edited: a Row stacked here is a column, and offers no Height.\n *\n * @module plain-parent-controls\n */\nimport * as React from \"react\";\n\nimport {\n  childAxisRows,\n  offersChildAxis,\n  planChildSize,\n  readChildSize,\n  type ChildAxis,\n  type ChildFit,\n  type ChildSize,\n  type LayoutTiers,\n  type LayoutWrite,\n  type ParentArrangement,\n  type ParentItems,\n} from \"../../styles/plain-layout\";\nimport { layoutWritesText } from \"../code-hints\";\nimport { SegmentChoices } from \"../segment-choices\";\nimport { SettingSlot } from \"../settings-filter\";\n\nimport { DraftInput, useApply, useLayoutTiers } from \"./plain-layout-controls\";\nimport {\n  StyleTargetContext,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\nimport type { ParentLayout } from \"./style-inspector\";\n\n/** How the selected block's parent lays it out, lent by the Style panel. */\nexport const ParentArrangementContext: React.Context<ParentLayout | undefined> =\n  React.createContext<ParentLayout | undefined>(undefined);\n\n/** What sizing a block in its parent reads by, where it is offered. */\ninterface ParentSizing {\n  readonly parent: ParentArrangement;\n  readonly tiers: LayoutTiers;\n  readonly items: ParentItems;\n}\n\n/**\n * The parent's arrangement, the block's values, and the alignment the parent\n * gives its items. The flow is the canvas's measured one: a writing mode\n * isn't a style a block stores, so a block's runs as its parent's does.\n * None where the parent isn't known or a shared style is edited.\n */\nfunction useParentSizing(\n  surroundings: StyleFieldSurroundings\n): ParentSizing | undefined {\n  const layout = React.useContext(ParentArrangementContext);\n  const target = React.useContext(StyleTargetContext);\n  const tiers = useLayoutTiers(surroundings);\n  if (layout === undefined || target.kind === \"shared\") return undefined;\n  return {\n    parent: layout.arrangement,\n    tiers,\n    items: { alignItems: layout.alignItems, justifyItems: layout.justifyItems },\n  };\n}\n\n/** The ids the settings search knows Width and Height by. */\nexport const CHILD_SIZE_IDS = {\n  width: \"child:width\",\n  height: \"child:height\",\n} as const;\n\nconst CHOICES = [\"fill\", \"fit\", \"fixed\"] as const;\nconst CHOICE_LABELS = { fill: \"Fill\", fit: \"Fit\", fixed: \"Fixed\" } as const;\n\n/** What each Width choice does, in a line under the row. */\nconst WIDTH_LINES: Readonly<Record<ChildFit | \"custom\", string>> = {\n  fill: \"Takes the space it's given.\",\n  fit: \"As wide as its content.\",\n  fixed: \"A width you set.\",\n  custom: \"Custom: set another way, in the rows below.\",\n};\n\n/** What each Height choice does. */\nconst HEIGHT_LINES: Readonly<Record<ChildFit | \"custom\", string>> = {\n  fill: \"Takes the height it's given.\",\n  fit: \"As tall as its content.\",\n  fixed: \"A height you set.\",\n  custom: \"Custom: set another way, in Size.\",\n};\n\n/** The size a Fixed choice starts from where none is set yet. */\nconst STARTING_SIZE = { width: \"320px\", height: \"200px\" } as const;\n\n/** What one axis offers: its choices' writes, and how a choice is planned. */\ninterface Axis {\n  readonly name: \"Width\" | \"Height\";\n  readonly lines: Readonly<Record<ChildFit | \"custom\", string>>;\n  readonly size: ChildSize;\n  readonly start: string;\n  readonly plan: (choice: ChildFit, size?: string) => LayoutWrite[];\n}\n\n/**\n * Width, and Height under a Row or a Grid, at the top of \"Inside its\n * parent\". Nothing where the parent isn't known (a shared style is worn\n * wherever its blocks sit): the section's rows say what is set.\n */\nexport function InsideParentFields({\n  surroundings,\n}: {\n  surroundings: StyleFieldSurroundings;\n}): React.JSX.Element | null {\n  const sizing = useParentSizing(surroundings);\n  const target = React.useContext(StyleTargetContext);\n  const apply = useApply(surroundings, target);\n  if (sizing === undefined) return null;\n  const { parent, tiers, items } = sizing;\n  const editing = surroundings.breakpoint;\n  const width = axisOf(tiers, editing, parent, \"width\", items);\n  // A Row or a Grid sizes its blocks across too; a column's height is its\n  // blocks' own, set in Size.\n  const height = offersChildAxis(parent, \"height\", tiers.flow)\n    ? axisOf(tiers, editing, parent, \"height\", items)\n    : undefined;\n  return (\n    <div className=\"nx-inside-parent\" data-control=\"inside-parent\">\n      <SettingSlot tab=\"style\" ids={[CHILD_SIZE_IDS.width]}>\n        <AxisRow axis={width} apply={apply} />\n      </SettingSlot>\n      {height === undefined ? null : (\n        <SettingSlot tab=\"style\" ids={[CHILD_SIZE_IDS.height]}>\n          <AxisRow axis={height} apply={apply} />\n        </SettingSlot>\n      )}\n    </div>\n  );\n}\n\n/** One size's axis, by the role it plays in the parent here. */\nfunction axisOf(\n  tiers: LayoutTiers,\n  editing: string,\n  parent: ParentArrangement,\n  axis: ChildAxis,\n  items: ParentItems\n): Axis {\n  const width = axis === \"width\";\n  return {\n    name: width ? \"Width\" : \"Height\",\n    lines: width ? WIDTH_LINES : HEIGHT_LINES,\n    size: readChildSize(tiers, editing, parent, axis, items),\n    start: width ? STARTING_SIZE.width : STARTING_SIZE.height,\n    plan: (choice, size) =>\n      planChildSize(tiers, editing, parent, axis, choice, size),\n  };\n}\n\n/** One axis: its three choices, the line under them, and Fixed's size. */\nfunction AxisRow({\n  axis,\n  apply,\n}: {\n  axis: Axis;\n  apply: (writes: readonly LayoutWrite[]) => void;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  const sizeId = React.useId();\n  const { size } = axis;\n  const fixed = size.choice === \"fixed\" ? size.size : undefined;\n  const writes = {\n    fill: layoutWritesText(axis.plan(\"fill\")),\n    fit: layoutWritesText(axis.plan(\"fit\")),\n    fixed: layoutWritesText(axis.plan(\"fixed\", fixed ?? axis.start)),\n  };\n  return (\n    <div className=\"nx-inside-parent__axis\">\n      <div className=\"nx-inspector__field\">\n        <span className=\"nx-inspector__field-name\" id={labelId}>\n          {axis.name}\n        </span>\n        <SegmentChoices\n          options={CHOICES}\n          on={size.choice === \"custom\" ? undefined : size.choice}\n          labels={CHOICE_LABELS}\n          labelId={labelId}\n          writes={writes}\n          onChoose={choice =>\n            apply(\n              axis.plan(\n                choice,\n                choice === \"fixed\" ? (fixed ?? axis.start) : undefined\n              )\n            )\n          }\n        />\n      </div>\n      <p className=\"nx-inspector__note\">{axis.lines[size.choice]}</p>\n      {fixed === undefined ? null : (\n        <div className=\"nx-inspector__field\">\n          <label className=\"nx-inspector__field-name\" htmlFor={sizeId}>\n            {`${axis.name} set`}\n          </label>\n          <DraftInput\n            id={sizeId}\n            value={fixed}\n            placeholder={axis.start}\n            onCommit={text => {\n              const typed = text.trim();\n              if (typed !== \"\") apply(axis.plan(\"fixed\", typed));\n            }}\n          />\n        </div>\n      )}\n    </div>\n  );\n}\n\n/**\n * The rows of \"Inside its parent\" that Width and Height draw in plain words\n * while each reads as a choice: they leave the raw rows, as Arrange's do,\n * and come back while that axis reads Custom. None where neither is drawn.\n */\nexport function useDrawnChildRows(\n  surroundings: StyleFieldSurroundings\n): ReadonlySet<string> {\n  const sizing = useParentSizing(surroundings);\n  if (sizing === undefined) return NONE;\n  const { parent, tiers, items } = sizing;\n  const editing = surroundings.breakpoint;\n  const drawn = new Set<string>();\n  for (const axis of [\"width\", \"height\"] as const) {\n    if (!offersChildAxis(parent, axis, tiers.flow)) continue;\n    if (\n      readChildSize(tiers, editing, parent, axis, items).choice === \"custom\"\n    ) {\n      continue;\n    }\n    for (const row of childAxisRows(parent, axis, tiers.flow)) drawn.add(row);\n  }\n  return drawn;\n}\n\nconst NONE: ReadonlySet<string> = new Set();\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 * The Style tab's \"CSS properties\": which of a block's properties its sections\n * draw unasked, which the author has added (or that hold a value) and so sit\n * in \"CSS properties\" with a Remove each, and which \"Add CSS property\" offers.\n *\n * Pure, and read by the panel and the settings index alike, so the rows an\n * author sees, the picker's list and what \"Find a setting\" offers to add are\n * one answer. Built from the inspection (`inspectStyle`), never from a list of\n * its own: the catalog decides what exists, the engine's `applies` what has\n * an effect, and the placement table (`inspector-sections`) what shows\n * unasked.\n *\n * - **Shown unasked** stays in its section: a property whose tier shows it\n *   here, as before.\n * - **Added or holding a value**, for one whose tier doesn't show it, is a row\n *   of \"CSS properties\". A set value is never hidden, and is removed from the\n *   same row it is shown in.\n * - **Addable** is the rest that applies to the block now and the block\n *   offers: only catalog properties, so the list is never a free CSS box.\n *\n * @module css-properties\n */\nimport { SECTION_BLOCK } from \"../../styles/block-shortcuts\";\nimport {\n  OWN_ROW_FIELDS,\n  type InspectorSectionKey,\n} from \"../inspector-sections\";\n\nimport { arrangesLayout, SPACE_PROPERTIES } from \"./plain-layout-controls\";\nimport type { InspectedStyleProperty, StyleSection } from \"./style-inspector\";\n\n/** The section's key and words. */\nexport const CSS_PROPERTIES_SECTION: {\n  readonly key: InspectorSectionKey;\n  readonly label: string;\n} = { key: \"css-properties\", label: \"CSS properties\" };\n\n/** One property \"CSS properties\" can hold, or \"Add CSS property\" offer. */\nexport interface CssPropertyRow {\n  /** The catalog key, or `key.field` for a field drawn on its own. */\n  readonly id: string;\n  /**\n   * What its fields draw: the property, or the one field of it, labelled with\n   * its CSS name, which is the label a developer searches for here.\n   */\n  readonly row: InspectedStyleProperty;\n  /** Where in the property's value it is stored: the root, or the field. */\n  readonly path: readonly string[];\n  /** Its CSS name: \"z-index\", \"mix-blend-mode\". */\n  readonly cssName: string;\n  /** Its plain name: \"Layer order\", \"Mix blend mode\". */\n  readonly plainName: string;\n  /** The section it belongs to, which the picker names beside it. */\n  readonly section: { readonly key: string; readonly label: string };\n}\n\n/** A block's Style sections as the tab draws them, and its own CSS rows. */\nexport interface ArrangedStyle {\n  /** The sections, holding only what their tier shows unasked. */\n  readonly sections: readonly StyleSection[];\n  /** Every property whose tier doesn't show it, in the sections' order. */\n  readonly extras: readonly CssPropertyRow[];\n}\n\n/** The CSS properties a property's controls write, each once, in order. */\nexport function writtenCss(property: InspectedStyleProperty): string[] {\n  const names = new Set<string>();\n  for (const control of property.controls) {\n    if (\"cssProperty\" in control.leaf) names.add(control.leaf.cssProperty);\n  }\n  return [...names];\n}\n\n/**\n * The one CSS name a property is known by: what all its fields write, or the\n * name they share (\"outline\" for its width, style, colour and offset). A\n * property whose fields share none is named by its key, hyphenated.\n */\nfunction cssNameOf(property: InspectedStyleProperty): string {\n  const names = writtenCss(property);\n  const [first] = names;\n  if (first === undefined) return hyphenated(property.property);\n  if (names.length === 1) return first;\n  let shared = first.split(\"-\");\n  for (const name of names.slice(1)) {\n    const words = name.split(\"-\");\n    let same = 0;\n    while (same < shared.length && shared[same] === words[same]) same += 1;\n    shared = shared.slice(0, same);\n  }\n  return shared.length === 0 ? hyphenated(property.property) : shared.join(\"-\");\n}\n\n/** A catalog key as CSS spells such names: `mixBlendMode` to `mix-blend-mode`. */\nfunction hyphenated(key: string): string {\n  return key.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);\n}\n\n/** Whether a value is an object of fields. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Whether a value stores any field of its object other than these. */\nfunction storesOtherThan(value: unknown, fields: ReadonlySet<string>): boolean {\n  if (!isRecord(value)) return value !== undefined;\n  return Object.keys(value).some(field => !fields.has(field));\n}\n\n/** A property's controls and form choices at, or away from, some fields. */\nfunction narrowed(\n  property: InspectedStyleProperty,\n  keep: (field: string) => boolean\n): Pick<InspectedStyleProperty, \"controls\" | \"variants\"> {\n  return {\n    controls: property.controls.filter(control => keep(control.path[0] ?? \"\")),\n    variants: property.variants.filter(variant => keep(variant.path[0] ?? \"\")),\n  };\n}\n\n/** One field of a property, drawn as a property of its own. */\ninterface FieldRow {\n  readonly field: string;\n  readonly row: InspectedStyleProperty;\n}\n\n/**\n * A property split into the part its section draws and the fields \"CSS\n * properties\" draws on their own (`position` and its z-index).\n */\nfunction splitFields(property: InspectedStyleProperty): {\n  readonly home: InspectedStyleProperty;\n  readonly fields: readonly FieldRow[];\n} {\n  const own = OWN_ROW_FIELDS.filter(\n    entry => entry.property === property.property\n  );\n  if (own.length === 0) return { home: property, fields: [] };\n  const apart = new Set(own.map(entry => entry.field));\n  const set = storesOtherThan(property.value, apart);\n  const home: InspectedStyleProperty = {\n    ...property,\n    ...narrowed(property, field => !apart.has(field)),\n    set,\n    common: set || (property.applies && property.tierShows),\n  };\n  const fields = own.map(({ field, label }): FieldRow => {\n    const stored =\n      isRecord(property.value) && Object.hasOwn(property.value, field);\n    return {\n      field,\n      row: {\n        ...property,\n        ...narrowed(property, each => each === field),\n        label,\n        set: stored,\n        applies: property.fieldApplies?.[field] ?? property.applies,\n        tierShows: false,\n        common: stored,\n      },\n    };\n  });\n  return { home, fields };\n}\n\n/** A property as a row of \"CSS properties\", named by its CSS name. */\nfunction cssRow(\n  id: string,\n  property: InspectedStyleProperty,\n  path: readonly string[],\n  section: StyleSection\n): CssPropertyRow {\n  const cssName = cssNameOf(property);\n  return {\n    id,\n    // Labelled by its CSS name, with the plain name leading its tooltip.\n    row: {\n      ...property,\n      label: cssName,\n      summary: `${property.label}: ${property.summary}`,\n    },\n    path,\n    cssName,\n    plainName: property.label,\n    section: { key: section.key, label: section.label },\n  };\n}\n\n/**\n * Whether a Layout section draws Arrange: where the block offers a display,\n * not only keeps a stored one (a block that no longer has layout keeps it\n * clear-only, as a raw row).\n */\nexport function offersArrange(section: StyleSection): boolean {\n  return (\n    section.key === \"layout\" &&\n    section.properties.some(\n      property => property.property === \"display\" && property.offered\n    )\n  );\n}\n\n/** What the block's plain controls draw, which decides what stays home. */\nexport interface PlainControls {\n  /**\n   * The block's type where the block itself is edited, `undefined` for a\n   * shared style: a Section's Height presets are the block's own.\n   */\n  readonly blockType: string | undefined;\n  /**\n   * Whether Arrange draws the Layout and reads it in plain words (not\n   * Custom), so its Space between draws the space properties. Where the\n   * reading isn't known (the Style tab isn't drawn), taken from whether the\n   * block's Layout is Arrange's at all.\n   */\n  readonly arranges?: boolean | undefined;\n}\n\n/**\n * The properties a section's own plain controls draw, which stay in it\n * whatever their tier: Arrange's space between (rows and columns set apart\n * included) while Arrange reads the Layout in plain words, and the min height\n * a Section's Height presets stand over. Under Arrange: Custom the raw rows\n * hold the layout and its space rows are added like any other.\n */\nfunction drawnByPlainControls(\n  section: StyleSection,\n  plain: PlainControls\n): ReadonlySet<string> {\n  if (offersArrange(section)) {\n    const arranges = plain.arranges ?? arrangesLayout(plain.blockType);\n    return arranges ? SPACE_PROPERTIES : NONE;\n  }\n  if (section.key === \"size\" && plain.blockType === SECTION_BLOCK) {\n    return MIN_HEIGHT;\n  }\n  return NONE;\n}\n\nconst MIN_HEIGHT: ReadonlySet<string> = new Set([\"minHeight\"]);\nconst NONE: ReadonlySet<string> = new Set();\n\n/**\n * A block's sections as the Style tab draws them: each keeps what its tier\n * shows unasked and what its plain controls draw, and every other property\n * becomes a row \"CSS properties\" can hold. A section left with nothing is not\n * drawn.\n */\nexport function arrangeCssProperties(\n  sections: readonly StyleSection[],\n  plain: PlainControls\n): ArrangedStyle {\n  const drawn: StyleSection[] = [];\n  const extras: CssPropertyRow[] = [];\n  for (const section of sections) {\n    const kept: InspectedStyleProperty[] = [];\n    const drawnHere = drawnByPlainControls(section, plain);\n    for (const property of section.properties) {\n      const { home, fields } = splitFields(property);\n      if (home.tierShows || drawnHere.has(home.property)) kept.push(home);\n      else extras.push(cssRow(home.property, home, [], section));\n      for (const { field, row } of fields) {\n        extras.push(cssRow(`${row.property}.${field}`, row, [field], section));\n      }\n    }\n    if (kept.length > 0) drawn.push({ ...section, properties: kept });\n  }\n  return { sections: drawn, extras };\n}\n\n/** The rows \"CSS properties\" draws: those holding a value, and those added. */\nexport function cssPropertyRows(\n  extras: readonly CssPropertyRow[],\n  added: ReadonlySet<string>\n): CssPropertyRow[] {\n  return extras.filter(each => each.row.set || added.has(each.id));\n}\n\n/**\n * What \"Add CSS property\" offers: each row not drawn yet that the block\n * offers and that has an effect on it now.\n */\nexport function addableRows(\n  extras: readonly CssPropertyRow[],\n  added: ReadonlySet<string>\n): CssPropertyRow[] {\n  return extras.filter(\n    each =>\n      !each.row.set &&\n      !added.has(each.id) &&\n      each.row.offered &&\n      each.row.applies\n  );\n}\n","\"use client\";\n\n/**\n * The Style tab's last section, \"CSS properties\": the properties the author\n * added, each with its value and a Remove, and \"+ Add CSS property\", which\n * opens a searchable list of the catalog properties that work on this block\n * now. While \"Find a setting\" is searching, the properties it finds that the\n * block can use but hasn't added are listed here with an \"Add\" each.\n *\n * What is drawn, offered and found is `css-properties`'s answer; this file\n * draws it. Only catalog properties are ever offered: the list is not a free\n * CSS box.\n *\n * @module add-css-property\n */\nimport { AccordionContent, AccordionItem } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { SectionHeading } from \"../panel-section\";\nimport {\n  SettingSlot,\n  sectionShown,\n  useSettingsMatch,\n} from \"../settings-filter\";\nimport { entryMatches } from \"../settings-index\";\n\nimport {\n  addableRows,\n  CSS_PROPERTIES_SECTION,\n  cssPropertyRows,\n  type CssPropertyRow,\n} from \"./css-properties\";\nimport { SectionHeld } from \"./section-held\";\nimport type { StyleFieldSurroundings } from \"./style-field-surroundings\";\nimport { useFieldTarget } from \"./style-field-target\";\nimport { StylePropertyFields } from \"./style-property-fields\";\n\n/**\n * The properties the author added to one block, while it stays selected.\n * Panel state, like a section's folds: what the author chose to look at, not\n * anything the page stores. A property holding a value is drawn whatever this\n * says, so it hides nothing set; it starts empty for the next block.\n *\n * `used` says the author has added or removed a property on this block, so\n * the section they are working in stays open, as a section holding a value\n * opens, even once its last value is removed.\n */\nexport function useAddedProperties(nodeId: string): {\n  readonly added: ReadonlySet<string>;\n  readonly used: boolean;\n  readonly add: (id: string) => void;\n  readonly remove: (id: string) => void;\n} {\n  const [held, setHeld] = React.useState<{\n    readonly nodeId: string;\n    readonly ids: ReadonlySet<string>;\n  }>(() => ({ nodeId, ids: EMPTY }));\n  const mine = held.nodeId === nodeId;\n  const change = (next: (ids: Set<string>) => void) =>\n    setHeld(current => {\n      const ids = new Set(current.nodeId === nodeId ? current.ids : EMPTY);\n      next(ids);\n      return { nodeId, ids };\n    });\n  return {\n    added: mine ? held.ids : EMPTY,\n    // A change made here for this block, which only an add or a remove makes.\n    used: mine && held.ids !== EMPTY,\n    add: id => change(ids => ids.add(id)),\n    remove: id => change(ids => ids.delete(id)),\n  };\n}\n\nconst EMPTY: ReadonlySet<string> = new Set();\n\n/** The props the section is drawn from. */\ninterface CssPropertiesSectionProps {\n  /** Every property the block's sections don't show unasked. */\n  readonly extras: readonly CssPropertyRow[];\n  /** What the author added to this block, and how to change it. */\n  readonly added: ReturnType<typeof useAddedProperties>;\n  /** Why every control is read-only, which also withholds adding. */\n  readonly readOnlyReason: string | undefined;\n  readonly surroundings: StyleFieldSurroundings;\n}\n\n/** \"CSS properties\", the Style tab's last section. */\nexport function CssPropertiesSection({\n  extras,\n  added,\n  readOnlyReason,\n  surroundings,\n}: CssPropertiesSectionProps): React.JSX.Element {\n  const match = useSettingsMatch();\n  const { key, label } = CSS_PROPERTIES_SECTION;\n  return (\n    <AccordionItem\n      value={key}\n      data-section={key}\n      hidden={!sectionShown(match, \"style\", key)}\n    >\n      <SectionHeading\n        label={label}\n        holdsValues={extras.some(each => each.row.set)}\n      />\n      <AccordionContent>\n        <CssPropertiesBody\n          // Keyed by node: the list's search and where focus goes start\n          // afresh for the next block.\n          key={surroundings.nodeId}\n          extras={extras}\n          added={added}\n          readOnlyReason={readOnlyReason}\n          surroundings={surroundings}\n        />\n      </AccordionContent>\n    </AccordionItem>\n  );\n}\n\n/** Where focus goes once the rows are drawn again. */\ntype FocusNext = { readonly row: string } | \"add\" | undefined;\n\n/** The section's rows, what search found to add, and the picker. */\nfunction CssPropertiesBody({\n  extras,\n  added,\n  readOnlyReason,\n  surroundings,\n}: CssPropertiesSectionProps): React.JSX.Element {\n  const readOnly = readOnlyReason !== undefined;\n  const rows = cssPropertyRows(extras, added.added);\n  const addable = addableRows(extras, added.added);\n  const body = React.useRef<HTMLFieldSetElement | null>(null);\n  const addButton = React.useRef<HTMLButtonElement | null>(null);\n  const [focusNext, setFocusNext] = React.useState<FocusNext>(undefined);\n  React.useEffect(() => {\n    if (focusNext === undefined) return;\n    setFocusNext(undefined);\n    if (focusNext === \"add\") {\n      addButton.current?.focus();\n      return;\n    }\n    focusValueOf(body.current, focusNext.row);\n  }, [focusNext]);\n  const add = (id: string) => {\n    added.add(id);\n    setFocusNext({ row: id });\n  };\n  const removed = (id: string) => {\n    // To the row after it, or the one before where it was last, or to \"+ Add\n    // CSS property\" where it was the only one.\n    const index = rows.findIndex(each => each.id === id);\n    const next = rows[index + 1] ?? rows[index - 1];\n    added.remove(id);\n    setFocusNext(next === undefined ? \"add\" : { row: next.id });\n  };\n  return (\n    <fieldset className=\"nx-inspector__fields\" disabled={readOnly} ref={body}>\n      <SectionHeld.Provider value={readOnly}>\n        {rows.map(each => (\n          <SettingSlot\n            key={`${surroundings.nodeId}:${each.id}`}\n            tab=\"style\"\n            ids={[each.id]}\n          >\n            <CssPropertyLine\n              entry={each}\n              surroundings={surroundings}\n              onRemoved={() => removed(each.id)}\n            />\n          </SettingSlot>\n        ))}\n        <FoundToAdd addable={addable} onAdd={add} />\n        {readOnly ? null : (\n          <AddCssProperty addable={addable} onAdd={add} button={addButton} />\n        )}\n      </SectionHeld.Provider>\n    </fieldset>\n  );\n}\n\n/**\n * Focus a row's value: its first text field or menu, else its first control\n * that is not its Remove. Never a control kept out of reach, such as the\n * native select a menu keeps hidden for forms.\n */\nfunction focusValueOf(within: HTMLElement | null, id: string): void {\n  const row = [\n    ...(within?.querySelectorAll<HTMLElement>(\"[data-css-property]\") ?? []),\n  ].find(each => each.dataset.cssProperty === id);\n  if (row === undefined) return;\n  const reachable = (selector: string) =>\n    [...row.querySelectorAll<HTMLElement>(selector)].find(\n      each =>\n        each.closest('[aria-hidden=\"true\"]') === null && each.tabIndex >= 0\n    );\n  const value =\n    reachable(\"input, textarea, [role='combobox']\") ??\n    reachable(\"button:not([data-remove])\");\n  value?.focus();\n}\n\n/** One added property: its fields, and its Remove. */\nfunction CssPropertyLine({\n  entry,\n  surroundings,\n  onRemoved,\n}: {\n  entry: CssPropertyRow;\n  surroundings: StyleFieldSurroundings;\n  onRemoved: () => void;\n}): React.JSX.Element {\n  const field = useFieldTarget({\n    editor: surroundings.editor,\n    nodeId: surroundings.nodeId,\n    address: {\n      state: surroundings.state,\n      breakpoint: surroundings.breakpoint,\n      property: entry.row.property,\n      path: entry.path,\n    },\n    policy: surroundings.policy,\n  });\n  const remove = () => {\n    // The value and the row go together: clearing is one edit, so one undo\n    // brings both back. A refused clear keeps the row, saying why.\n    if (field.stored !== undefined && field.commit(null) === \"refused\") return;\n    onRemoved();\n  };\n  return (\n    <div className=\"nx-css-property\" data-css-property={entry.id}>\n      <div className=\"nx-css-property__fields\">\n        <StylePropertyFields\n          property={entry.row}\n          namesSection={false}\n          {...surroundings}\n        />\n      </div>\n      <button\n        type=\"button\"\n        className=\"nx-css-property__remove\"\n        data-remove=\"\"\n        aria-label={`Remove ${entry.cssName}`}\n        onClick={remove}\n      >\n        <span aria-hidden=\"true\">✕</span>\n      </button>\n      {field.issue === null ? null : (\n        <p className=\"nx-inspector__note\" role=\"alert\">\n          {field.issue}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/** A property's CSS name, plain name and section, as the lists draw them. */\nfunction PropertyNames({\n  entry,\n}: {\n  entry: CssPropertyRow;\n}): React.JSX.Element {\n  return (\n    // Spaced, so each is read as its own word.\n    <>\n      <span className=\"nx-css-picker__css\">{entry.cssName}</span>{\" \"}\n      <span className=\"nx-css-picker__plain\">{entry.plainName}</span>{\" \"}\n      <span className=\"nx-css-picker__section\">{entry.section.label}</span>\n    </>\n  );\n}\n\n/**\n * While \"Find a setting\" is searching, the properties it found that the block\n * can use but hasn't added, each with \"Add\": listed while the design is held\n * too, as the tab's count says, with Add held by the section's fieldset.\n */\nfunction FoundToAdd({\n  addable,\n  onAdd,\n}: {\n  addable: readonly CssPropertyRow[];\n  onAdd: (id: string) => void;\n}): React.JSX.Element | null {\n  const match = useSettingsMatch();\n  if (!match.active) return null;\n  const kept = match.kept.get(\"style\");\n  const found = addable.filter(each => kept?.has(each.id) === true);\n  if (found.length === 0) return null;\n  return (\n    <ul className=\"nx-css-found\" aria-label=\"CSS properties you can add\">\n      {found.map(each => (\n        <li key={each.id} className=\"nx-css-found__item\">\n          <span className=\"nx-css-found__names\">\n            <PropertyNames entry={each} />\n          </span>\n          <button\n            type=\"button\"\n            className=\"nx-css-found__add\"\n            aria-label={`Add ${each.cssName}`}\n            onClick={() => onAdd(each.id)}\n          >\n            Add\n          </button>\n        </li>\n      ))}\n    </ul>\n  );\n}\n\n/** Whether a picker entry answers what was typed, as \"Find a setting\" reads. */\nfunction pickerMatches(entry: CssPropertyRow, query: string): boolean {\n  return entryMatches(\n    {\n      tab: \"style\",\n      section: entry.section.key,\n      sectionLabel: entry.section.label,\n      id: entry.id,\n      label: entry.plainName,\n      options: [],\n      css: [entry.cssName],\n      set: false,\n    },\n    query\n  );\n}\n\n/**\n * \"+ Add CSS property\" and the list it opens: a search field over the\n * properties that work on this block now and aren't drawn yet, each named by\n * its CSS name, its plain name and its section. Inline under the button, so\n * it stays inside the panel at any width.\n */\nfunction AddCssProperty({\n  addable,\n  onAdd,\n  button,\n}: {\n  addable: readonly CssPropertyRow[];\n  onAdd: (id: string) => void;\n  button: React.RefObject<HTMLButtonElement | null>;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const pickerId = React.useId();\n  return (\n    <div className=\"nx-css-properties__add-wrap\">\n      <button\n        ref={button}\n        type=\"button\"\n        className=\"nx-css-properties__add\"\n        aria-expanded={open}\n        aria-controls={open ? pickerId : undefined}\n        onClick={() => setOpen(!open)}\n      >\n        + Add CSS property\n      </button>\n      {open ? (\n        <CssPropertyPicker\n          id={pickerId}\n          addable={addable}\n          onPick={id => {\n            setOpen(false);\n            onAdd(id);\n          }}\n          onClose={() => {\n            setOpen(false);\n            button.current?.focus();\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/** The picker's search field and the list it narrows. */\nfunction CssPropertyPicker({\n  id,\n  addable,\n  onPick,\n  onClose,\n}: {\n  id: string;\n  addable: readonly CssPropertyRow[];\n  onPick: (id: string) => void;\n  onClose: () => void;\n}): React.JSX.Element {\n  const [query, setQuery] = React.useState(\"\");\n  const [active, setActive] = React.useState(0);\n  const listId = `${id}-list`;\n  const search = React.useRef<HTMLInputElement | null>(null);\n  // Into the search as the list opens, so the author types at once.\n  React.useEffect(() => search.current?.focus(), []);\n  const listed = addable.filter(entry => pickerMatches(entry, query));\n  const current = listed[Math.min(active, listed.length - 1)];\n  const list = React.useRef<HTMLUListElement | null>(null);\n  // The chosen option kept in view: focus stays in the search field, so\n  // moving the choice from the keyboard doesn't scroll the list by itself.\n  const currentId = current?.id;\n  React.useEffect(() => {\n    if (currentId === undefined) return;\n    const option = [\n      ...(list.current?.querySelectorAll<HTMLElement>(\"[data-css-id]\") ?? []),\n    ].find(each => each.dataset.cssId === currentId);\n    option?.scrollIntoView({ block: \"nearest\" });\n  }, [currentId]);\n  const optionId = (entry: CssPropertyRow) => `${id}-${entry.id}`;\n  const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {\n    const step = { ArrowDown: 1, ArrowUp: -1 }[event.key];\n    if (step !== undefined && listed.length > 0) {\n      event.preventDefault();\n      setActive((Math.max(active, 0) + step + listed.length) % listed.length);\n    } else if (event.key === \"Enter\" && current !== undefined) {\n      event.preventDefault();\n      onPick(current.id);\n    } else if (event.key === \"Escape\") {\n      // Closed here, and kept from the canvas, which would take Escape as\n      // leaving the block.\n      event.preventDefault();\n      event.stopPropagation();\n      onClose();\n    }\n  };\n  return (\n    <div className=\"nx-css-picker\" id={id}>\n      <input\n        ref={search}\n        type=\"search\"\n        className=\"nx-css-picker__search\"\n        role=\"combobox\"\n        aria-label=\"Search CSS properties\"\n        aria-expanded=\"true\"\n        aria-controls={listId}\n        aria-autocomplete=\"list\"\n        aria-activedescendant={\n          current === undefined ? undefined : optionId(current)\n        }\n        placeholder=\"Search properties\"\n        autoComplete=\"off\"\n        spellCheck={false}\n        value={query}\n        onChange={event => {\n          setQuery(event.target.value);\n          setActive(0);\n        }}\n        onKeyDown={onKeyDown}\n      />\n      <ul\n        ref={list}\n        className=\"nx-css-picker__list\"\n        id={listId}\n        role=\"listbox\"\n        aria-label=\"CSS properties\"\n      >\n        {listed.map(entry => (\n          <li\n            key={entry.id}\n            id={optionId(entry)}\n            role=\"option\"\n            aria-selected={entry === current}\n            data-css-id={entry.id}\n            className=\"nx-css-picker__option\"\n            // Kept from taking focus, so the search field keeps it.\n            onMouseDown={event => event.preventDefault()}\n            onClick={() => onPick(entry.id)}\n          >\n            <PropertyNames entry={entry} />\n          </li>\n        ))}\n      </ul>\n      {listed.length > 0 ? null : (\n        <p className=\"nx-css-picker__empty\">\n          {addable.length === 0\n            ? \"Nothing left that applies here.\"\n            : \"No property matches.\"}\n        </p>\n      )}\n      <p className=\"nx-css-picker__note\">\n        Only properties that work on this block are listed.\n      </p>\n    </div>\n  );\n}\n","/**\n * The Section and Button shortcuts, drawn at the top of the Size section: a\n * Section's Height, a Button's Size and Full width, and an Icon's Size. Each writes the Style\n * value beneath it at the device being edited, which stays editable as itself.\n *\n * @module block-shortcuts-field\n */\nimport {\n  findNode,\n  type BlockNode,\n  type BreakpointId,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport { Switch } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport {\n  BUTTON_BLOCK,\n  FULL_SCREEN,\n  fullWidthOf,\n  heightOf,\n  ICON_BLOCK,\n  ICON_SIZES,\n  iconSizeOf,\n  planFullWidth,\n  planHeight,\n  planIconSize,\n  planSize,\n  SECTION_BLOCK,\n  SIZES,\n  sizeOf,\n  sizesOffered,\n  type HeightChoice,\n  type Reaching,\n  type ShortcutAt,\n  type SizeChoice,\n} from \"../../styles/block-shortcuts\";\nimport {\n  FULL_WIDTH_WRITES,\n  heightShortcutWrites,\n  iconSizeShortcutWrites,\n  sizeShortcutWrites,\n} from \"../code-hints\";\nimport { CssHint } from \"../css-hint\";\nimport { SegmentChoices } from \"../segment-choices\";\nimport { SettingSlot } from \"../settings-filter\";\n\n/** The ids the settings search knows each shortcut by. */\nexport const SHORTCUT_IDS = {\n  height: \"shortcut:height\",\n  size: \"shortcut:size\",\n  fullWidth: \"shortcut:fullWidth\",\n} as const;\n\n/** A Section's height, in the words of what it does: fit, or fill the screen. */\nexport const HEIGHT_LABELS: Readonly<Record<HeightChoice, string>> = {\n  auto: \"Fit content\",\n  screen: \"Full screen\",\n};\n\n/** What each Height choice writes. */\nconst HEIGHT_WRITES = heightShortcutWrites(FULL_SCREEN);\n\n/** What each Size choice writes. */\nconst SIZE_WRITES = sizeShortcutWrites(SIZES);\n\n/** What each of an Icon's Size choices writes. */\nconst ICON_SIZE_WRITES = iconSizeShortcutWrites(ICON_SIZES);\n\nexport const SIZE_LABELS: Readonly<Record<SizeChoice, string>> = {\n  small: \"Small\",\n  medium: \"Medium\",\n  large: \"Large\",\n};\n\n/**\n * A labelled row of choices, with the line that says what they do. Unlabelled\n * on screen where it stands over the field it presets, which carries the\n * label; its name is still read.\n */\nfunction ChoiceRow<T extends string>({\n  label,\n  shownLabel = true,\n  options,\n  on,\n  labels,\n  hint,\n  onChoose,\n  writes,\n}: {\n  label: string;\n  shownLabel?: boolean;\n  options: readonly T[];\n  on: T | undefined;\n  labels: Readonly<Record<T, string>>;\n  /** What each choice writes, for its tooltip. */\n  writes?: Readonly<Record<T, string>> | undefined;\n  /** What the choices do, or none where the field beneath already says. */\n  hint?: string | undefined;\n  onChoose: (choice: T) => void;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  return (\n    <>\n      <div className=\"nx-inspector__field\">\n        <span className=\"nx-inspector__field-name\" id={labelId}>\n          {shownLabel ? label : <span className=\"sr-only\">{label}</span>}\n        </span>\n        <SegmentChoices\n          options={options}\n          on={on}\n          labels={labels}\n          labelId={labelId}\n          onChoose={onChoose}\n          writes={writes}\n        />\n      </div>\n      {hint === undefined ? null : <p className=\"nx-inspector__note\">{hint}</p>}\n    </>\n  );\n}\n\n/** Where a shortcut control writes, and from what. */\ninterface ShortcutProps {\n  editor: EditorState;\n  nodeId: string;\n  state: StyleState;\n  breakpoint: BreakpointId;\n  /** What reaches the edited address from elsewhere, as the cascade says. */\n  reaching?: Reaching | undefined;\n  /** The prefix the site's tokens are written under, as the cascade's are. */\n  tokenPrefix?: string | undefined;\n}\n\n/**\n * The Section whose presets held focus when a choice moved them, if any.\n * Choosing Full screen draws the Min height field and the presets move over\n * it, and Fit content moves them back: two places in the panel, so the\n * focused radio is unmounted with the old row. The row drawn in the new\n * place takes the focus back, read once by whichever row draws next and\n * cleared.\n */\nlet focusMovesWith: string | undefined;\n\n/** The radio a moved row's focus lands on: the chosen one, else the first. */\nfunction takeMovedFocus(group: HTMLElement | null, nodeId: string): void {\n  if (focusMovesWith !== nodeId) return;\n  focusMovesWith = undefined;\n  const radio =\n    group?.querySelector<HTMLElement>('[role=\"radio\"][aria-checked=\"true\"]') ??\n    group?.querySelector<HTMLElement>('[role=\"radio\"]');\n  radio?.focus();\n}\n\n/**\n * A Section's Height, Fit content and Full screen, which presets its min\n * height: a row over the Min height input where that field is drawn\n * (`over`), named for screen readers only, else a row of its own, named\n * Height, until a value draws the field.\n */\nexport function MinHeightPresets({\n  editor,\n  nodeId,\n  state,\n  breakpoint,\n  reaching,\n  tokenPrefix,\n  over,\n}: ShortcutProps & { over: boolean }): React.JSX.Element | null {\n  const row = React.useRef<HTMLDivElement>(null);\n  // After every draw: a row that moved takes back the focus its old place had.\n  React.useLayoutEffect(() => takeMovedFocus(row.current, nodeId));\n  const node = findNode(editor.document.nodes, nodeId);\n  if (node?.type !== SECTION_BLOCK) return null;\n  const at: ShortcutAt = {\n    state,\n    breakpoint,\n    ...(tokenPrefix === undefined ? {} : { tokenPrefix }),\n  };\n  return (\n    <div ref={row} className=\"nx-block-shortcuts\" data-control=\"section-height\">\n      <SettingSlot tab=\"style\" ids={[SHORTCUT_IDS.height]}>\n        <ChoiceRow\n          label=\"Height\"\n          shownLabel={!over}\n          options={[\"auto\", \"screen\"] as const}\n          on={heightOf(node, at, reaching)}\n          labels={HEIGHT_LABELS}\n          writes={HEIGHT_WRITES}\n          // Over the field, the value beneath says what Full screen wrote, and a\n          // line between them would part the presets from the field they set.\n          hint={\n            over\n              ? undefined\n              : \"Full screen: at least the screen's height, growing with its content.\"\n          }\n          onChoose={choice => {\n            const op = planHeight(node, choice, at, reaching);\n            if (op === null) return;\n            // Marked before the write, which may move this row elsewhere.\n            if (row.current?.contains(document.activeElement) === true) {\n              focusMovesWith = nodeId;\n              // Only for the draw this write makes, committed within the event:\n              // a write that draws nothing (refused) leaves no mark to steal\n              // focus from a field typed in later.\n              setTimeout(() => {\n                if (focusMovesWith === nodeId) focusMovesWith = undefined;\n              }, 0);\n            }\n            editor.apply(op);\n          }}\n        />\n      </SettingSlot>\n    </div>\n  );\n}\n\n/** A Button's Size and Full width, at the top of its Size section. */\nexport function BlockShortcutsControl({\n  editor,\n  nodeId,\n  state,\n  breakpoint,\n  reaching,\n  tokenPrefix,\n}: ShortcutProps): React.JSX.Element | null {\n  const node = findNode(editor.document.nodes, nodeId);\n  if (node === undefined) return null;\n  const at: ShortcutAt = {\n    state,\n    breakpoint,\n    ...(tokenPrefix === undefined ? {} : { tokenPrefix }),\n  };\n  const apply = (op: BuilderOp | null) => {\n    if (op !== null) editor.apply(op);\n  };\n  if (node.type === ICON_BLOCK) {\n    return (\n      <IconSizeRow node={node} at={at} reaching={reaching} apply={apply} />\n    );\n  }\n  if (node.type !== BUTTON_BLOCK) return null;\n  const size = sizeOf(node, at, reaching);\n  return (\n    <div className=\"nx-block-shortcuts\" data-control=\"button-size\">\n      {sizesOffered(node) ? (\n        <SettingSlot tab=\"style\" ids={[SHORTCUT_IDS.size]}>\n          <ChoiceRow\n            label=\"Size\"\n            options={[\"small\", \"medium\", \"large\"] as const}\n            on={size}\n            labels={SIZE_LABELS}\n            writes={SIZE_WRITES}\n            hint={\n              size === undefined\n                ? \"Custom: the padding or text size below is set another way.\"\n                : \"Sets the padding and text size together.\"\n            }\n            onChoose={choice => apply(planSize(node, choice, at, reaching))}\n          />\n        </SettingSlot>\n      ) : null}\n      <SettingSlot tab=\"style\" ids={[SHORTCUT_IDS.fullWidth]}>\n        <div className=\"nx-inspector__field\">\n          <span className=\"nx-inspector__field-name\">Full width</span>\n          <CssHint writes={FULL_WIDTH_WRITES}>\n            <Switch\n              aria-label=\"Full width\"\n              checked={fullWidthOf(node, at, reaching)}\n              onCheckedChange={on =>\n                apply(planFullWidth(node, on, at, reaching))\n              }\n            />\n          </CssHint>\n        </div>\n        <p className=\"nx-inspector__note\">\n          As wide as its container, here and below.\n        </p>\n      </SettingSlot>\n    </div>\n  );\n}\n\n/** An Icon's Size, at the top of its Size section: the font size its glyph is drawn at. */\nfunction IconSizeRow({\n  node,\n  at,\n  reaching,\n  apply,\n}: {\n  node: BlockNode;\n  at: ShortcutAt;\n  reaching: Reaching | undefined;\n  apply: (op: BuilderOp | null) => void;\n}): React.JSX.Element {\n  const iconSize = iconSizeOf(node, at, reaching);\n  return (\n    <div className=\"nx-block-shortcuts\" data-control=\"icon-size\">\n      <SettingSlot tab=\"style\" ids={[SHORTCUT_IDS.size]}>\n        <ChoiceRow\n          label=\"Size\"\n          options={[\"small\", \"medium\", \"large\"] as const}\n          on={iconSize}\n          labels={SIZE_LABELS}\n          writes={ICON_SIZE_WRITES}\n          hint={\n            iconSize === undefined\n              ? \"Custom: the font size below is set another way.\"\n              : \"Sets the icon's font size, which its glyph is drawn at.\"\n          }\n          onChoose={choice => apply(planIconSize(node, choice, at, reaching))}\n        />\n      </SettingSlot>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * A container's Content width, in Style › Layout: Boxed or Full width as two\n * picture buttons, and the line under them that says the width in force and\n * where it comes from, with the way to give this container its own.\n *\n * Both are the block's own settings (`contained` and `contentWidth`), not\n * styles: one value on every device, written to the block whatever the Style\n * target says. So the control is held while a shared style or a state other\n * than Normal is being edited, and says why.\n *\n * @module content-width-control\n */\nimport {\n  checkDimensionValue,\n  CONTENT_WIDTH_CLASS,\n  CONTENT_WIDTH_PROP,\n  CONTENT_WIDTH_PROPERTY,\n  isTokenRef,\n  STYLE_CATALOG,\n  isStyleLeaf,\n  trimCssWhitespace,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type TokenRef,\n} from \"@nextlyhq/blocks-engine\";\nimport { Input } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  focusAfterUnlink,\n  VariableChip,\n  VariableChoice,\n} from \"../../panels/design/variable-choice\";\nimport { variablesFor, type SiteVariable } from \"../../styles/style-colour\";\nimport { variableValueText } from \"../../styles/style-variables\";\nimport { commitOnEnter } from \"../commit-on-enter\";\nimport { CssHint } from \"../css-hint\";\nimport { arrowTo } from \"../segment-choices\";\n\n/** The site token that holds the site's content width. */\nconst SITE_WIDTH_TOKEN = \"content.width\";\n\n/** Why the control is held while a shared style or a state is edited. */\nexport const CONTENT_WIDTH_HELD = \"Part of this block, not of its style\";\n\n/**\n * The leaf a width is offered variables for: a maximum width's, which takes\n * every length the site names.\n */\nconst WIDTH_LEAF: StyleLeaf = (() => {\n  const shape = STYLE_CATALOG.find(\n    entry => entry.property === \"maxWidth\"\n  )?.shape;\n  return shape !== undefined && isStyleLeaf(shape)\n    ? shape\n    : { kind: \"dimension\", tokenKinds: [\"dimension\"] };\n})() as StyleLeaf;\n\n/** A width as stored: a length, a percentage, or a site variable. */\nexport type StoredWidth = string | TokenRef;\n\n/** Whether a stored value is a width this control can show. */\nexport function storedWidthOf(value: unknown): StoredWidth | undefined {\n  if (isTokenRef(value)) return value;\n  if (typeof value === \"string\" && trimCssWhitespace(value) !== \"\") {\n    return value;\n  }\n  return undefined;\n}\n\n/**\n * A typed width as it is stored, or `undefined` when it is no width: a length\n * or a percentage, the forms the page compile writes. A bare number is read\n * as pixels, as every length field here reads one.\n */\nexport function typedWidth(text: string): string | undefined {\n  const value = trimCssWhitespace(text);\n  if (value === \"\") return undefined;\n  const withUnit = /^\\d+(?:\\.\\d+)?$/.test(value) ? `${value}px` : value;\n  return checkDimensionValue(withUnit, {\n    allowPercentage: true,\n    functions: [\"calc\", \"min\", \"max\", \"clamp\"],\n  }) === null\n    ? withUnit\n    : undefined;\n}\n\n/** What a width reads as in the line: its value, or its variable's. */\nfunction widthWords(\n  width: StoredWidth,\n  variables: readonly SiteVariable[]\n): string {\n  if (!isTokenRef(width)) return trimCssWhitespace(width);\n  const variable = variables.find(each => each.identity === width.$token);\n  return variable === undefined ? width.$token : variableValueText(variable);\n}\n\n/** The site's content width in force, as the line says it. */\nfunction siteWidthWords(variables: readonly SiteVariable[]): string {\n  const site = variables.find(each => each.identity === SITE_WIDTH_TOKEN);\n  return site === undefined\n    ? \"the site's content width\"\n    : variableValueText(site);\n}\n\n/** What {@link ContentWidthControl} is given. */\nexport interface ContentWidthControlProps {\n  /** Whether the container is Boxed. */\n  readonly contained: boolean;\n  /** The width it states for itself, if it states one. */\n  readonly width: StoredWidth | undefined;\n  readonly tokens: SiteTokenSet | undefined;\n  /** The site's width variables, in the mode the canvas shows. */\n  readonly variables: readonly SiteVariable[];\n  /** Why it can't be changed here, when it can't. */\n  readonly held: string | undefined;\n  readonly onContained: (contained: boolean) => void;\n  /** A width of its own, or `undefined` to use the site's. */\n  readonly onWidth: (width: StoredWidth | undefined) => void;\n}\n\n/** Content width's two choices, by the words drawn on them. */\nexport const CONTENT_WIDTH_CHOICES = [\n  { contained: true, label: \"Boxed\" },\n  { contained: false, label: \"Full width\" },\n] as const;\n\nconst CHOICES = CONTENT_WIDTH_CHOICES;\n\n/** Boxed and Full width, as a radio group of picture buttons. */\nfunction WidthChoices({\n  contained,\n  labelId,\n  held,\n  onContained,\n}: {\n  contained: boolean;\n  labelId: string;\n  held: boolean;\n  onContained: (contained: boolean) => void;\n}): React.JSX.Element {\n  const allowed = CHOICES.map(() => !held);\n  return (\n    <div\n      role=\"radiogroup\"\n      aria-labelledby={labelId}\n      className=\"nx-content-width__choices\"\n    >\n      {CHOICES.map((choice, index) => (\n        // What a choice writes: Boxed puts the content-width class on the\n        // root; Full width writes nothing.\n        <CssHint\n          key={choice.label}\n          writes={\n            choice.contained ? `class=\"${CONTENT_WIDTH_CLASS}\"` : undefined\n          }\n        >\n          <button\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={choice.contained === contained}\n            tabIndex={choice.contained === contained ? 0 : -1}\n            disabled={held}\n            className=\"nx-content-width__choice\"\n            onKeyDown={event =>\n              arrowTo(event, index, allowed, next => {\n                const to = CHOICES[next];\n                if (to !== undefined) onContained(to.contained);\n              })\n            }\n            onClick={() => onContained(choice.contained)}\n          >\n            {/* The result in small: the content held in, or edge to edge. */}\n            <span\n              aria-hidden=\"true\"\n              className=\"nx-content-width__picture\"\n              data-shape={choice.contained ? \"boxed\" : \"full\"}\n            >\n              <i />\n            </span>\n            <span>{choice.label}</span>\n          </button>\n        </CssHint>\n      ))}\n    </div>\n  );\n}\n\n/** What the width field writes: its typed width, or the site's while empty. */\nfunction ownWidthWrites(draft: string, siteWords: string): string {\n  return `${CONTENT_WIDTH_PROPERTY}: ${draft === \"\" ? siteWords : draft}`;\n}\n\n/** The field a width of the container's own is typed or picked in. */\nfunction OwnWidthField({\n  width,\n  siteWords,\n  tokens,\n  variables,\n  held,\n  autoFocus,\n  onWidth,\n}: {\n  width: StoredWidth | undefined;\n  siteWords: string;\n  tokens: SiteTokenSet | undefined;\n  variables: readonly SiteVariable[];\n  held: boolean;\n  autoFocus: boolean;\n  onWidth: (width: StoredWidth | undefined) => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  const errorId = React.useId();\n  const typed = width !== undefined && !isTokenRef(width) ? width : \"\";\n  const [draft, setDraft] = React.useState(typed);\n  const [refused, setRefused] = React.useState(false);\n  React.useEffect(() => setDraft(typed), [typed]);\n  const commit = () => {\n    if (trimCssWhitespace(draft) === trimCssWhitespace(typed)) return;\n    if (trimCssWhitespace(draft) === \"\") {\n      setRefused(false);\n      onWidth(undefined);\n      return;\n    }\n    const next = typedWidth(draft);\n    setRefused(next === undefined);\n    if (next !== undefined) onWidth(next);\n  };\n  const pick = (identity: string) => onWidth({ $token: identity });\n  return (\n    <div className=\"nx-inspector__field nx-content-width__own\">\n      <label className=\"nx-inspector__field-name\" htmlFor={id}>\n        Width\n      </label>\n      {isTokenRef(width) ? (\n        <VariableChip\n          leaf={WIDTH_LEAF}\n          tokens={tokens}\n          identity={width.$token}\n          label=\"Width\"\n          onPick={pick}\n          // The width the variable gives now, kept as the container's own\n          // through the rule a typed width meets; \"Use site default\" above is\n          // what removes it.\n          onUnlink={value => {\n            const kept =\n              typeof value === \"string\" ? typedWidth(value) : undefined;\n            if (kept === undefined) return;\n            onWidth(kept);\n            // The typed field takes the chip's place, holding the width.\n            focusAfterUnlink(() => document.getElementById(id));\n          }}\n        />\n      ) : (\n        <span className=\"nx-content-width__entry\">\n          {/* What it writes: the container's own content width. */}\n          <CssHint writes={ownWidthWrites(draft, siteWords)}>\n            <Input\n              id={id}\n              value={draft}\n              placeholder={siteWords}\n              autoComplete=\"off\"\n              autoFocus={autoFocus}\n              disabled={held}\n              aria-invalid={refused ? true : undefined}\n              aria-describedby={refused ? errorId : undefined}\n              onChange={event => setDraft(event.target.value)}\n              onBlur={commit}\n              onKeyDown={event => commitOnEnter(event, commit)}\n            />\n          </CssHint>\n          {variables.length === 0 || held ? null : (\n            <VariableChoice\n              leaf={WIDTH_LEAF}\n              tokens={tokens}\n              current={undefined}\n              label=\"Width\"\n              onPick={pick}\n            />\n          )}\n        </span>\n      )}\n      {refused ? (\n        <p id={errorId} className=\"nx-inspector__note\" role=\"alert\">\n          Use a width such as 1400px or 90%.\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * Content width: Boxed or Full width, what is in force, and a width of the\n * container's own.\n */\nexport function ContentWidthControl({\n  contained,\n  width,\n  tokens,\n  variables,\n  held,\n  onContained,\n  onWidth,\n}: ContentWidthControlProps): React.JSX.Element {\n  const labelId = React.useId();\n  // Whether the author asked to give this container its own width, which\n  // shows the field before anything is stored in it.\n  const [changing, setChanging] = React.useState(false);\n  const siteWords = siteWidthWords(variables);\n  const own = width !== undefined;\n  const isHeld = held !== undefined;\n  return (\n    // A fieldset, so a hold disables every control inside it at once: the\n    // buttons, the field, and a held variable's chip and its list.\n    <fieldset\n      className=\"nx-content-width\"\n      data-control=\"content-width\"\n      disabled={isHeld}\n    >\n      <div className=\"nx-inspector__field\">\n        <span className=\"nx-inspector__field-name\" id={labelId}>\n          Content width\n        </span>\n        <WidthChoices\n          contained={contained}\n          labelId={labelId}\n          held={isHeld}\n          onContained={onContained}\n        />\n      </div>\n      <p className=\"nx-content-width__line\" aria-live=\"polite\">\n        {!contained ? (\n          \"Content runs edge to edge.\"\n        ) : (\n          <>\n            Boxed to <b>{own ? widthWords(width, variables) : siteWords}</b>\n            {own ? \" · this section · \" : \" · site default · \"}\n            <button\n              type=\"button\"\n              className=\"nx-content-width__action\"\n              disabled={isHeld}\n              onClick={() => {\n                if (own) {\n                  setChanging(false);\n                  onWidth(undefined);\n                } else {\n                  setChanging(true);\n                }\n              }}\n            >\n              {own ? \"Use site default\" : \"Change for this section\"}\n            </button>\n          </>\n        )}\n      </p>\n      {contained && (own || changing) ? (\n        <OwnWidthField\n          width={width}\n          siteWords={siteWords}\n          tokens={tokens}\n          variables={variables}\n          held={isHeld}\n          autoFocus={changing && !own}\n          onWidth={onWidth}\n        />\n      ) : null}\n      <p className=\"nx-inspector__note\">{held ?? \"Same on every device\"}</p>\n    </fieldset>\n  );\n}\n\n/** The site's width variables, for a container's own width. */\nexport function widthVariables(\n  tokens: SiteTokenSet | undefined,\n  mode: Parameters<typeof variablesFor>[2]\n): readonly SiteVariable[] {\n  return variablesFor(WIDTH_LEAF, tokens, mode);\n}\n\n/** The prop a container's own width is stored under. */\nexport const OWN_WIDTH_PROP: string = CONTENT_WIDTH_PROP;\n","\"use client\";\n\n/**\n * Content width as the Style tab's Layout section draws it, for a container\n * that declares it: read from the block's own settings and written to them.\n *\n * @module content-width-fields\n */\nimport { findNode, type BlockNode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport type { EditorState } from \"../../editor-state\";\nimport {\n  inspectSelection,\n  lockViewOf,\n  propIsWritable,\n  propPatch,\n  type EditableProp,\n} from \"../inspector\";\n\nimport {\n  CONTENT_WIDTH_HELD,\n  ContentWidthControl,\n  OWN_WIDTH_PROP,\n  storedWidthOf,\n  widthVariables,\n} from \"./content-width-control\";\nimport {\n  StyleTargetContext,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\n\n/** The prop that says whether a container is Boxed. */\nconst CONTAINED_PROP = \"contained\";\n\n/** The block's own settings a Style section draws, by the section's key. */\nfunction styleRowsOf(\n  editor: EditorState,\n  nodeId: string,\n  sectionKey: string\n): readonly EditableProp[] {\n  const inspection = inspectSelection(\n    editor.document,\n    nodeId,\n    lockViewOf(editor)\n  );\n  return (\n    inspection?.sections.styleProps.find(section => section.key === sectionKey)\n      ?.rows ?? []\n  );\n}\n\n/** Set one of the block's settings, as the Content tab sets one. */\nfunction commitSetting(\n  editor: EditorState,\n  nodeId: string,\n  name: string,\n  value: unknown\n): void {\n  const document = editor.document;\n  if (!propIsWritable(document, nodeId, name, lockViewOf(editor))) return;\n  const node: BlockNode | undefined = findNode(document.nodes, nodeId);\n  if (node === undefined) return;\n  editor.apply({\n    kind: \"update\",\n    id: nodeId,\n    patch: propPatch(node, name, value),\n  });\n}\n\n/**\n * Why the block's own settings can't be changed where the panel is: they\n * belong to the block, so not while a shared style is edited, and they are one\n * value whatever the state, so not while a state other than Normal is.\n */\nfunction contentWidthHeld(\n  target: { readonly kind: string },\n  state: string\n): string | undefined {\n  return target.kind !== \"block\" || state !== \"base\"\n    ? CONTENT_WIDTH_HELD\n    : undefined;\n}\n\n/**\n * Content width at the top of a container's Layout section, or nothing for a\n * block that does not declare it.\n */\nexport function ContentWidthFields({\n  surroundings,\n}: {\n  surroundings: StyleFieldSurroundings;\n}): React.JSX.Element | null {\n  const target = React.useContext(StyleTargetContext);\n  const mode = useCanvasTokenMode();\n  const { editor, nodeId, state, tokens } = surroundings;\n  const rows = styleRowsOf(editor, nodeId, \"layout\");\n  const contained = rows.find(row => row.name === CONTAINED_PROP);\n  if (contained === undefined) return null;\n  const own = rows.find(row => row.name === OWN_WIDTH_PROP);\n  const boxed = (contained.value ?? contained.defaultValue) === true;\n  const locked = contained.readOnly ? \"Held by a lock on this area\" : undefined;\n  const held = locked ?? contentWidthHeld(target, state);\n  // Refused here as well as disabled there: a control that reaches a write\n  // while held must still not change the block.\n  const write = (name: string, value: unknown) => {\n    if (held === undefined) commitSetting(editor, nodeId, name, value);\n  };\n  return (\n    <ContentWidthControl\n      contained={boxed}\n      width={storedWidthOf(own?.value)}\n      tokens={tokens}\n      variables={widthVariables(tokens, mode)}\n      held={held}\n      onContained={next => write(CONTAINED_PROP, next)}\n      onWidth={next => write(OWN_WIDTH_PROP, next)}\n    />\n  );\n}\n","/**\n * A Section's Padding as Compact, Normal or Roomy: what it reads as, and the\n * one op a choice makes.\n *\n * The preset is one of the block's own settings (`paddingPreset`), and\n * Normal is the setting left out, so a Section that never picks one stores\n * nothing new. \"Custom\" is never stored: it is read back while any side of\n * the block's padding holds a value of its own, on any device or state,\n * since that value is what the browser shows there. Choosing a preset clears\n * those values in the same op that sets it, so one undo brings both back.\n *\n * @module section-padding\n */\nimport {\n  PADDING_PRESET_PROP,\n  type BlockNode,\n  type NodeStyles,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../../op-vocabulary\";\n\n/** The choices, in the order they are drawn. */\nexport const PADDING_CHOICES = [\"compact\", \"normal\", \"roomy\"] as const;\n\n/** One of {@link PADDING_CHOICES}. */\nexport type PaddingChoice = (typeof PADDING_CHOICES)[number];\n\n/** Each choice in the words drawn on it. */\nexport const PADDING_LABELS: Readonly<Record<PaddingChoice, string>> = {\n  compact: \"Compact\",\n  normal: \"Normal\",\n  roomy: \"Roomy\",\n};\n\n/** A record a walk may read keys from. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Whether any device of any state of these styles holds its own padding. */\nfunction holdsOwnPadding(styles: NodeStyles | undefined): boolean {\n  if (!isRecord(styles)) return false;\n  return Object.values(styles).some(\n    byBreakpoint =>\n      isRecord(byBreakpoint) &&\n      Object.values(byBreakpoint).some(\n        values => isRecord(values) && Object.hasOwn(values, \"padding\")\n      )\n  );\n}\n\n/** The preset a node stores, read as a choice: Normal for none. */\nfunction storedChoice(node: BlockNode): PaddingChoice {\n  const stored = node.props[PADDING_PRESET_PROP];\n  return stored === \"compact\" || stored === \"roomy\" ? stored : \"normal\";\n}\n\n/** What a Section's Padding reads as: a choice, or `\"custom\"`. */\nexport function paddingReading(node: BlockNode): PaddingChoice | \"custom\" {\n  return holdsOwnPadding(node.styles) ? \"custom\" : storedChoice(node);\n}\n\n/** The styles with every padding taken out, pruning what empties. */\nfunction withoutPadding(styles: NodeStyles): NodeStyles {\n  const states: Record<string, unknown> = {};\n  for (const [state, byBreakpoint] of Object.entries(styles)) {\n    if (!isRecord(byBreakpoint)) {\n      states[state] = byBreakpoint;\n      continue;\n    }\n    const kept: Record<string, unknown> = {};\n    for (const [breakpoint, values] of Object.entries(byBreakpoint)) {\n      if (!isRecord(values)) {\n        kept[breakpoint] = values;\n        continue;\n      }\n      const { padding: _padding, ...rest } = values;\n      if (Object.keys(rest).length > 0) kept[breakpoint] = rest;\n    }\n    if (Object.keys(kept).length > 0) states[state] = kept;\n  }\n  return states;\n}\n\n/** The props with the preset set, or taken out for Normal. */\nfunction propsFor(\n  node: BlockNode,\n  choice: PaddingChoice\n): Record<string, unknown> {\n  const { [PADDING_PRESET_PROP]: _old, ...rest } = node.props;\n  return choice === \"normal\"\n    ? rest\n    : { ...rest, [PADDING_PRESET_PROP]: choice };\n}\n\n/**\n * The one op choosing a preset makes: the preset set (or, for Normal, taken\n * out) and every padding of the block's own cleared, or `null` when the block\n * already reads as that choice.\n */\nexport function planPadding(\n  node: BlockNode,\n  choice: PaddingChoice\n): BuilderOp | null {\n  if (paddingReading(node) === choice) return null;\n  const props = propsFor(node, choice);\n  if (!holdsOwnPadding(node.styles)) {\n    return { kind: \"update\", id: node.id, patch: { props } };\n  }\n  const styles = withoutPadding(node.styles as NodeStyles);\n  return Object.keys(styles).length > 0\n    ? { kind: \"update\", id: node.id, patch: { props, styles } }\n    : { kind: \"update\", id: node.id, patch: { props }, unset: [\"styles\"] };\n}\n","\"use client\";\n\n/**\n * A Section's Padding, drawn above the spacing box in Style › Spacing:\n * Compact, Normal or Roomy, each sized by the site's spacing variables, and\n * \"Custom\" while a side of the box holds a value of its own.\n *\n * The preset is one of the block's own settings, not a style: one value on\n * every device, written to the block whatever the Style target says. So it\n * is held, as Content width is, while a shared style or a state other than\n * Normal is being edited.\n *\n * @module section-padding-fields\n */\nimport {\n  findNode,\n  PADDING_PRESET_PROP,\n  type PropSchema,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { inspectSelection, lockViewOf } from \"../inspector\";\nimport { withSectionFold } from \"../panel-folds\";\nimport { usePanelFolds } from \"../panel-folds-context\";\nimport { SegmentChoices } from \"../segment-choices\";\n\nimport { CONTENT_WIDTH_HELD } from \"./content-width-control\";\nimport { SectionHeld } from \"./section-held\";\nimport {\n  PADDING_CHOICES,\n  PADDING_LABELS,\n  paddingReading,\n  planPadding,\n  type PaddingChoice,\n} from \"./section-padding\";\nimport {\n  StyleTargetContext,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\n\n/** What the choices do, under them. */\nconst PADDING_HINT = \"Space inside the section, from the site's settings\";\n\n/** What \"Custom\" says, in place of the hint, while a side has its own value. */\nconst CUSTOM_HINT =\n  \"Custom: a side below has its own value. Choosing one clears it.\";\n\n/**\n * The Style section the control is drawn in, by the label its fold is kept\n * under.\n */\nconst SPACING_SECTION = \"Spacing\";\n\n/** What each choice writes, from the setting's own `code`, for its tooltip. */\nfunction writesOf(\n  schema: PropSchema\n): Readonly<Record<PaddingChoice, string>> | undefined {\n  const code = schema.code;\n  if (code === undefined || typeof code === \"string\") return undefined;\n  return Object.fromEntries(\n    PADDING_CHOICES.map(choice => [choice, code[choice] ?? \"\"])\n  ) as Record<PaddingChoice, string>;\n}\n\n/**\n * Padding at the top of a Section's Spacing section, or nothing for a block\n * that does not declare it.\n */\nexport function SectionPaddingFields({\n  surroundings,\n}: {\n  surroundings: StyleFieldSurroundings;\n}): React.JSX.Element | null {\n  const labelId = React.useId();\n  const target = React.useContext(StyleTargetContext);\n  const sectionHeld = React.useContext(SectionHeld);\n  const { change } = usePanelFolds();\n  const { editor, nodeId, state } = surroundings;\n  const row = inspectSelection(editor.document, nodeId, lockViewOf(editor))\n    ?.sections.styleProps.find(section => section.key === \"spacing\")\n    ?.rows.find(each => each.name === PADDING_PRESET_PROP);\n  const node = findNode(editor.document.nodes, nodeId);\n  if (row === undefined || node === undefined) return null;\n  const held =\n    sectionHeld || row.readOnly || target.kind !== \"block\" || state !== \"base\";\n  const reading = paddingReading(node);\n  const choose = (choice: PaddingChoice) => {\n    // Refused here as well as disabled there: a control reaching a write\n    // while held must still not change the block.\n    if (held) return;\n    const op = planPadding(node, choice);\n    if (op === null) return;\n    // Kept open as the author's own fold: clearing the last own padding\n    // would otherwise close the section opened for holding it, under the\n    // control being used.\n    change(folds => withSectionFold(folds, \"style\", SPACING_SECTION, true));\n    editor.apply(op);\n  };\n  const ownHeld =\n    !sectionHeld && !row.readOnly && held ? CONTENT_WIDTH_HELD : undefined;\n  return (\n    <fieldset\n      className=\"nx-section-padding\"\n      data-control=\"section-padding\"\n      disabled={held}\n    >\n      <div className=\"nx-inspector__field\">\n        <span className=\"nx-inspector__field-name\" id={labelId}>\n          Padding\n        </span>\n        <SegmentChoices\n          options={PADDING_CHOICES}\n          on={reading === \"custom\" ? undefined : reading}\n          labels={PADDING_LABELS}\n          labelId={labelId}\n          onChoose={choose}\n          writes={writesOf(row.schema)}\n        />\n      </div>\n      <p className=\"nx-inspector__note\">\n        {ownHeld ?? (reading === \"custom\" ? CUSTOM_HINT : PADDING_HINT)}\n      </p>\n    </fieldset>\n  );\n}\n","\"use client\";\n\n/**\n * The fields a block adds to its own Style sections: its shortcuts, and the\n * presets drawn over a section.\n *\n * @module style-block-shortcuts\n */\nimport { findNode, type StyleValue } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenMode } from \"../../canvas/prefers-dark\";\nimport {\n  planSpacerHeight,\n  reachingBeneath,\n  SPACER_BLOCK,\n} from \"../../styles/block-shortcuts\";\nimport type { StyleControl } from \"../../styles/style-controls\";\nimport { SegmentChoices } from \"../segment-choices\";\n\nimport {\n  BlockShortcutsControl,\n  MinHeightPresets,\n} from \"./block-shortcuts-field\";\nimport {\n  identityOfKey,\n  NONE,\n  offeredPreset,\n  presetKey,\n  presetLabels,\n  spacingPresets,\n} from \"./spacing-presets\";\nimport {\n  StyleTargetContext,\n  TokenPrefixContext,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\n\n/**\n * A Section's Height and a Button's Size and Full width, at the top of its\n * Size section. Only for the block itself: a shared style's values are not\n * the block's to size.\n */\nexport function BlockShortcutsFields({\n  surroundings,\n  minHeightDrawn,\n}: {\n  surroundings: StyleFieldSurroundings;\n  /** Whether the Min height field is drawn, which then carries its presets. */\n  minHeightDrawn: boolean;\n}): React.JSX.Element | null {\n  const target = React.useContext(StyleTargetContext);\n  const tokenPrefix = React.useContext(TokenPrefixContext);\n  if (target.kind !== \"block\") return null;\n  const where = shortcutWhere(surroundings, tokenPrefix);\n  return (\n    <>\n      <BlockShortcutsControl {...where} />\n      {minHeightDrawn ? null : <MinHeightPresets {...where} over={false} />}\n    </>\n  );\n}\n\n/** A Section's Min height presets, over the Min height field it presets. */\nexport function BlockPresetsOver({\n  surroundings,\n}: {\n  surroundings: StyleFieldSurroundings;\n}): React.JSX.Element | null {\n  const target = React.useContext(StyleTargetContext);\n  const tokenPrefix = React.useContext(TokenPrefixContext);\n  if (target.kind !== \"block\") return null;\n  return (\n    <MinHeightPresets {...shortcutWhere(surroundings, tokenPrefix)} over />\n  );\n}\n\n/**\n * Where a shortcut writes, and what reaches it from elsewhere: the value the\n * panel's own provenance reports as inherited, the one ranking of the trace.\n */\nfunction shortcutWhere(\n  surroundings: StyleFieldSurroundings,\n  tokenPrefix: string\n) {\n  return {\n    editor: surroundings.editor,\n    nodeId: surroundings.nodeId,\n    state: surroundings.state,\n    breakpoint: surroundings.breakpoint,\n    tokenPrefix,\n    reaching: reachingBeneath(cssProperty =>\n      surroundings.provenanceOf({\n        kind: \"cssValue\",\n        cssProperty,\n        tokenKinds: [],\n      })\n    ),\n  };\n}\n\n/**\n * A Spacer's Height presets, over its Height field: the site's spacing\n * variables, smallest first, as a spacing side's popover offers them, so a\n * space between blocks is chosen from the same scale as a padding or a gap.\n * Only for the block itself. Held, as the section's other fields are, by the\n * fieldset a locked block's section is drawn in.\n */\nexport function SpacerHeightPresets({\n  surroundings,\n  control,\n  stored,\n}: {\n  surroundings: StyleFieldSurroundings;\n  /** The Height field's control, whose variables the presets are. */\n  control: StyleControl | undefined;\n  /** The height stored at the edited state and device. */\n  stored: StyleValue | undefined;\n}): React.JSX.Element | null {\n  const target = React.useContext(StyleTargetContext);\n  const mode = useCanvasTokenMode();\n  const id = React.useId();\n  const { editor, nodeId, state, breakpoint, tokens } = surroundings;\n  const node = findNode(editor.document.nodes, nodeId);\n  if (target.kind !== \"block\" || node?.type !== SPACER_BLOCK) return null;\n  if (control === undefined) return null;\n  const presets = spacingPresets(control, tokens, mode);\n  if (presets.length === 0) return null;\n  const at = { state, breakpoint };\n  const held = offeredPreset(stored, presets);\n  return (\n    <div\n      className=\"nx-block-shortcuts nx-spacer-presets\"\n      data-control=\"spacer-height\"\n    >\n      <span id={`${id}-presets`} className=\"nx-inspector__field-name\">\n        Presets\n      </span>\n      <SegmentChoices\n        options={presets.map(preset => presetKey(preset.identity))}\n        // A zero height is no preset here (there is no None to mark), so\n        // it marks none and the first preset keeps the group's Tab stop.\n        on={held === NONE ? undefined : held}\n        labels={presetLabels(presets)}\n        labelId={`${id}-presets`}\n        onChoose={choice => {\n          const identity = identityOfKey(choice);\n          if (identity === undefined) return;\n          const op = planSpacerHeight(node, identity, at);\n          if (op !== null) editor.apply(op);\n        }}\n      />\n    </div>\n  );\n}\n","/**\n * What the Style tab's \"Text style\" picker reads and writes.\n *\n * A text style is a named class with the text role (`textStylesOf`), worn\n * from a block's class list beside its block style and shared style. A block\n * wears one at most: picking one writes or replaces that one entry and\n * leaves the block's other classes where they were, so the document's shape\n * is the one it already had.\n *\n * Pure, so the rules are testable without a DOM; `text-style-picker.tsx`\n * draws them.\n *\n * @module text-style-choice\n */\nimport {\n  BASE_BREAKPOINT,\n  findNode,\n  isTextStyle,\n  textStylesOf,\n  type BlockDocument,\n  type NamedClass,\n  type NodeStyles,\n  type SiteTokenSet,\n  type StyleValue,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { designReadOnlyReason, type LockView } from \"../../inspector/inspector\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { nodeHasRoom } from \"../../styles/class-library\";\nimport { lengthInPx } from \"../../styles/fluid-size\";\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\n\nimport { pairWords, valueText } from \"./site-text-rows\";\n\n/** One text style as the picker lists it. */\nexport interface TextStyleOption {\n  readonly id: string;\n  /** Its name, as the author gave it. */\n  readonly name: string;\n  /** Its size and line height (\"12 / 1.4\"), its variables read. */\n  readonly pair: string;\n  /** What its sample text is drawn with. */\n  readonly preview: TextStylePreview;\n}\n\n/** The inline style a sample is drawn with: only what could be read. */\nexport interface TextStylePreview {\n  fontFamily?: string;\n  fontSize?: string;\n  fontWeight?: string;\n  letterSpacing?: string;\n  textTransform?: string;\n}\n\n/** The sizes a preview is drawn between, in px, so every row fits its line. */\nconst PREVIEW_PX = { min: 11, max: 20 } as const;\n\n/** A style's values at the widest device, which the preview shows. */\nfunction baseValues(styles: NodeStyles): Readonly<Record<string, StyleValue>> {\n  const values: unknown = styles.base?.[BASE_BREAKPOINT];\n  return typeof values === \"object\" && values !== null\n    ? (values as Record<string, StyleValue>)\n    : {};\n}\n\n/**\n * The site's text styles, in the order they override one another, each with\n * its name, pair and preview. Empty while the library is unread, or for a\n * site with none.\n */\nexport function textStyleOptions(\n  library: readonly NamedClass[] | undefined,\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode\n): TextStyleOption[] {\n  if (library === undefined) return [];\n  const set = tokens ?? { tokens: [] };\n  return textStylesOf(library).map(style => {\n    const values = baseValues(style.styles);\n    return {\n      id: style.id,\n      name: sharedStyleName(style),\n      pair: pairWords(\n        valueText(values.fontSize, set, mode),\n        valueText(values.lineHeight, set, mode)\n      ),\n      preview: textStylePreview(style.styles, set, mode),\n    };\n  });\n}\n\n/**\n * The inline style a text style's sample is drawn with, at the widest\n * device: its font, weight, letter spacing and case as they are, and its\n * size scaled into a row's bounds so a display size still fits. A value that\n * reads no variable the site has is left out rather than guessed.\n */\nexport function textStylePreview(\n  styles: NodeStyles,\n  tokens: SiteTokenSet,\n  mode: TokenMode\n): TextStylePreview {\n  const values = baseValues(styles);\n  const read = (property: string): string | undefined =>\n    valueText(values[property], tokens, mode);\n  const preview: TextStylePreview = {};\n  const family = read(\"fontFamily\");\n  if (family !== undefined) preview.fontFamily = family;\n  const weight = read(\"fontWeight\");\n  if (weight !== undefined) preview.fontWeight = weight;\n  const spacing = read(\"letterSpacing\");\n  if (spacing !== undefined) preview.letterSpacing = spacing;\n  const transform = read(\"textTransform\");\n  if (transform !== undefined) preview.textTransform = transform;\n  const size = read(\"fontSize\");\n  const px = size === undefined ? undefined : lengthInPx(size);\n  if (px !== undefined) {\n    const scaled = Math.min(\n      PREVIEW_PX.max,\n      Math.max(PREVIEW_PX.min, px * 0.55)\n    );\n    preview.fontSize = `${String(Math.round(scaled * 10) / 10)}px`;\n  }\n  return preview;\n}\n\n/**\n * The text style a block wears: the first of its classes that is one of the\n * site's usable text styles, or `undefined`.\n */\nexport function wornTextStyle(\n  library: readonly NamedClass[] | undefined,\n  classIds: readonly string[]\n): NamedClass | undefined {\n  if (library === undefined) return undefined;\n  const styles = textStylesOf(library);\n  for (const id of classIds) {\n    const found = styles.find(style => style.id === id);\n    if (found !== undefined) return found;\n  }\n  return undefined;\n}\n\n/** A plan for the picker's write: the ops, or why there are none. */\nexport type TextStylePlan =\n  | { readonly ok: true; readonly ops: BuilderOp[] }\n  | { readonly ok: false; readonly reason: string };\n\n/**\n * The class list a pick leaves on a block: `id` in the place of the text\n * style it wore (or after its classes, where it wore none), and with `null`\n * no text style at all. Every class the library marks as a text style is\n * taken off, an unusable one too, so a block never ends wearing two.\n *\n * Refused for a block whose design is held, for an id that is not one of\n * the site's text styles, and where the block has no room for another class.\n */\nexport function planTextStyle(\n  document: BlockDocument,\n  nodeId: string,\n  library: readonly NamedClass[],\n  id: string | null,\n  view?: LockView\n): TextStylePlan {\n  const held = designReadOnlyReason(document, nodeId, view);\n  const node = findNode(document.nodes, nodeId);\n  if (held !== undefined || node === undefined) {\n    return {\n      ok: false,\n      reason: held ?? \"This block is no longer on the page.\",\n    };\n  }\n  if (id !== null && !textStylesOf(library).some(style => style.id === id)) {\n    return { ok: false, reason: \"That text style is no longer on this site.\" };\n  }\n  const classes = node.classes ?? [];\n  const isText = (classId: string): boolean =>\n    library.some(entry => entry.id === classId && isTextStyle(entry));\n  const at = classes.findIndex(isText);\n  const kept = classes.filter(classId => !isText(classId));\n  // The first text style worn is the place the pick takes: every class\n  // before it is kept, so its index in `kept` is the same.\n  const next =\n    id === null\n      ? kept\n      : at === -1\n        ? [...kept, id]\n        : [...kept.slice(0, at), id, ...kept.slice(at)];\n  if (sameIds(next, classes)) return { ok: true, ops: [] };\n  if (at === -1 && id !== null && !nodeHasRoom(classes)) {\n    return {\n      ok: false,\n      reason: \"This block already lists as many styles as the page applies.\",\n    };\n  }\n  return {\n    ok: true,\n    ops: [\n      next.length > 0\n        ? { kind: \"update\", id: nodeId, patch: { classes: next } }\n        : { kind: \"update\", id: nodeId, patch: {}, unset: [\"classes\"] },\n    ],\n  };\n}\n\n/** Two id lists by value. */\nfunction sameIds(a: readonly string[], b: readonly string[]): boolean {\n  return a.length === b.length && a.every((each, index) => each === b[index]);\n}\n","\"use client\";\n\n/**\n * \"Text style\", at the top of the Style tab's Text section: the site's text\n * styles, each previewed in its own look, and None. Picking one gives the\n * block its whole look (font, size per device, line height, weight, letter\n * spacing and case) by writing or replacing the one text-style entry in the\n * block's class list (`text-style-choice`), so a heading can look like\n * \"Display\" and a paragraph like \"Eyebrow\".\n *\n * A page edit, as applying a shared style is: an author who may not change\n * the site's design may still choose one, and a block whose design is held\n * may not. Not drawn while a shared style is the target, since a shared\n * style wears no text style.\n *\n * @module text-style-picker\n */\nimport { findNode, type NamedClass } from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { ChevronDown } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { EDITOR_WORDS } from \"../../editor-words\";\nimport {\n  planTextStyle,\n  textStyleOptions,\n  wornTextStyle,\n  type TextStyleOption,\n} from \"../../panels/design/text-style-choice\";\nimport { lockViewOf } from \"../inspector\";\n\nimport { SectionHeld } from \"./section-held\";\nimport {\n  StyleTargetContext,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\n\n/**\n * The site's class library, lent to the picker by the Style tab: the text\n * styles are read from it. `undefined` while it is unread, or for a host\n * that lends none, and then no picker is drawn.\n */\nexport const TextStyleLibrary: React.Context<\n  readonly NamedClass[] | undefined\n> = React.createContext<readonly NamedClass[] | undefined>(undefined);\n\n/** The sample every text style is previewed with, as Site text's rows are. */\nconst SAMPLE = \"The quick survey\";\n\n/** The value the menu gives None, which no class id can be. */\nconst NONE = \"\";\n\n/** The picker's label. */\nconst LABEL = \"Text style\";\n\n/** Where text styles are made, said while the site has none. */\nconst NONE_YET = `No text styles yet. Make one in ${EDITOR_WORDS.design} › ${EDITOR_WORDS.type} › ${EDITOR_WORDS.textStyles}.`;\n\n/** What the picker says while a state other than Normal is edited. */\nconst STATE_HELD = \"A text style is the same in every state.\";\n\n/** The picker, or a note where the site has no text styles yet. */\nexport function TextStylePicker({\n  surroundings,\n}: {\n  surroundings: StyleFieldSurroundings;\n}): React.JSX.Element | null {\n  const library = React.useContext(TextStyleLibrary);\n  const target = React.useContext(StyleTargetContext);\n  // The section's hold (a locked block, or one inside held content), which\n  // the write is refused by as well.\n  const sectionHeld = React.useContext(SectionHeld);\n  const labelId = React.useId();\n  const [refusal, setRefusal] = React.useState<{\n    nodeId: string;\n    reason: string;\n  } | null>(null);\n  const { editor, nodeId, state, tokens, prefersDark } = surroundings;\n  if (library === undefined || target.kind !== \"block\") return null;\n  const options = textStyleOptions(\n    library,\n    tokens,\n    prefersDark ? \"dark\" : \"light\"\n  );\n  if (options.length === 0) {\n    return (\n      <p className=\"nx-inspector__note\" data-control=\"text-style\">\n        {NONE_YET}\n      </p>\n    );\n  }\n  const worn = wornTextStyle(\n    library,\n    findNode(editor.document.nodes, nodeId)?.classes ?? []\n  );\n  const inState = state !== \"base\";\n  const held = inState || sectionHeld;\n  const choose = (id: string): void => {\n    if (held) return;\n    const plan = planTextStyle(\n      editor.document,\n      nodeId,\n      library,\n      id === NONE ? null : id,\n      lockViewOf(editor)\n    );\n    if (!plan.ok) {\n      setRefusal({ nodeId, reason: plan.reason });\n      return;\n    }\n    setRefusal(null);\n    if (plan.ops.length === 0) return;\n    if (editor.applyAll(plan.ops) === null) {\n      setRefusal({\n        nodeId,\n        reason: \"This change could not be applied to the page.\",\n      });\n    }\n  };\n  const shown = worn === undefined ? \"None\" : (worn.label ?? worn.slug);\n  const said = refusal?.nodeId === nodeId ? refusal.reason : undefined;\n  return (\n    <fieldset\n      className=\"nx-text-style-picker\"\n      data-control=\"text-style\"\n      disabled={held}\n    >\n      <div className=\"nx-inspector__field\">\n        <span className=\"nx-inspector__field-name\" id={labelId}>\n          {LABEL}\n        </span>\n        <DropdownMenu modal={false}>\n          <DropdownMenuTrigger asChild>\n            <button\n              type=\"button\"\n              className=\"nx-fonts__choice nx-text-style-picker__button\"\n              aria-label={`${LABEL}, ${shown}`}\n              title={shown}\n            >\n              <span className=\"nx-fonts__choice-value\">{shown}</span>\n              <ChevronDown aria-hidden=\"true\" size={14} />\n            </button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent\n            align=\"end\"\n            collisionPadding={8}\n            className=\"nx-vars__menu nx-text-style-picker__menu\"\n          >\n            <DropdownMenuRadioGroup\n              value={worn?.id ?? NONE}\n              onValueChange={choose}\n            >\n              <DropdownMenuRadioItem value={NONE} data-text-style={NONE}>\n                <span className=\"nx-vars__name\">None</span>\n              </DropdownMenuRadioItem>\n              {options.map(option => (\n                <TextStyleItem key={option.id} option={option} />\n              ))}\n            </DropdownMenuRadioGroup>\n          </DropdownMenuContent>\n        </DropdownMenu>\n      </div>\n      {inState ? <p className=\"nx-inspector__note\">{STATE_HELD}</p> : null}\n      {said === undefined ? null : (\n        <p className=\"nx-inspector__note\" role=\"alert\">\n          {said}\n        </p>\n      )}\n    </fieldset>\n  );\n}\n\n/** One text style in the list: its name, its sample in its look, its pair. */\nfunction TextStyleItem({\n  option,\n}: {\n  option: TextStyleOption;\n}): React.JSX.Element {\n  return (\n    <DropdownMenuRadioItem\n      value={option.id}\n      data-text-style={option.id}\n      className=\"nx-text-style-picker__item\"\n      // Named by the style and its pair; the sample is decoration.\n      aria-label={\n        option.pair === \"\" ? option.name : `${option.name}, ${option.pair}`\n      }\n    >\n      <span\n        className=\"nx-vars__name nx-text-style-picker__name\"\n        title={option.name}\n      >\n        {option.name}\n      </span>\n      <span\n        className=\"nx-site-text__preview\"\n        aria-hidden=\"true\"\n        style={option.preview}\n      >\n        {SAMPLE}\n      </span>\n      {option.pair === \"\" ? null : (\n        <span className=\"nx-text-style-picker__pair\" aria-hidden=\"true\">\n          {option.pair}\n        </span>\n      )}\n    </DropdownMenuRadioItem>\n  );\n}\n","\"use client\";\n\n/**\n * The Style tab's sections: the accordion of sections a block offers, each\n * section's heading and fields, the background's overlay fields offered only\n * over an image, and \"CSS properties\" last.\n *\n * @module style-panel-sections\n */\nimport {\n  findNode,\n  PADDING_PRESET_PROP,\n  paintsBackgroundImage,\n  type NodeStyles,\n  type StyleValues,\n  type StyleLeaf,\n} from \"@nextlyhq/blocks-engine\";\nimport { Accordion, AccordionContent, AccordionItem } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { ParentArrangement } from \"../../styles/plain-layout\";\nimport type { StyleProvenance } from \"../../styles/style-provenance\";\nimport type { InspectorSectionKey } from \"../inspector-sections\";\nimport { useTabFolds } from \"../panel-folds-context\";\nimport { SectionHeading } from \"../panel-section\";\nimport {\n  SettingSlot,\n  sectionShown,\n  useReportStyle,\n  useSettingsMatch,\n} from \"../settings-filter\";\n\nimport { CssPropertiesSection, useAddedProperties } from \"./add-css-property\";\nimport { SHORTCUT_IDS } from \"./block-shortcuts-field\";\nimport { ContentWidthFields } from \"./content-width-fields\";\nimport {\n  arrangeCssProperties,\n  CSS_PROPERTIES_SECTION,\n  offersArrange,\n} from \"./css-properties\";\nimport { FocalFrame } from \"./focal-frame\";\nimport {\n  ArrangeFields,\n  arrangedAway,\n  SPACE_PROPERTIES,\n  useArrangeReading,\n  type ArrangeReading,\n} from \"./plain-layout-controls\";\nimport { InsideParentFields, useDrawnChildRows } from \"./plain-parent-controls\";\nimport { SectionHeld } from \"./section-held\";\nimport { SectionPaddingFields } from \"./section-padding-fields\";\nimport { spacingRings } from \"./spacing-box\";\nimport { SpacingBox } from \"./spacing-box-fields\";\nimport {\n  BlockShortcutsFields,\n  BlockPresetsOver,\n  SpacerHeightPresets,\n} from \"./style-block-shortcuts\";\nimport {\n  StyleTargetContext,\n  type StyleFieldSurroundings,\n} from \"./style-field-surroundings\";\nimport { fieldStyles } from \"./style-field-target\";\nimport type { InspectedStyleProperty, StyleSection } from \"./style-inspector\";\nimport { StylePropertyFields } from \"./style-property-fields\";\nimport type { StyleTarget } from \"./style-target\";\nimport { TextStylePicker } from \"./text-style-picker\";\n\n/**\n * The panel's sections, each folding on its own and remembered as the author\n * left it (`panel-folds`), with the block's picture and fit for the focal\n * point drawn over it, and \"CSS properties\" last: what each section's tier\n * doesn't show unasked is added there (`css-properties`).\n */\nexport function StyleSections({\n  sections,\n  readOnlyReason,\n  surroundings,\n  fit,\n  report,\n}: {\n  sections: readonly StyleSection[];\n  readOnlyReason: React.ComponentProps<\n    typeof StyleSectionItem\n  >[\"readOnlyReason\"];\n  surroundings: StyleFieldSurroundings;\n  fit: string | undefined;\n  /** What the panel's filter is told beside the sections drawn here. */\n  report: {\n    readonly shared: boolean;\n    readonly styles: unknown;\n    readonly parent: ParentArrangement | undefined;\n  };\n}): React.JSX.Element {\n  // The picture lent from above, with the fit in force here.\n  const { picture, position } = React.useContext(FocalFrame);\n  const match = useSettingsMatch();\n  const target = React.useContext(StyleTargetContext);\n  const layout = sections.find(offersArrange);\n  // Read here as Layout reads it, so what Arrange draws stays out of CSS\n  // properties only while Arrange draws it.\n  const reading = useArrangeReading(surroundings, layout !== undefined);\n  // No reading is no Arrange (Columns draws its own layout), so nothing of\n  // Layout is Arrange's to keep.\n  const arranges = reading !== undefined && reading.arrange.mode !== \"custom\";\n  const arranged = arrangeCssProperties(sections, {\n    blockType:\n      target.kind === \"block\"\n        ? findNode(surroundings.editor.document.nodes, surroundings.nodeId)\n            ?.type\n        : undefined,\n    arranges,\n  });\n  // What the panel's filter keeps in Style: what these controls draw.\n  useReportStyle(\n    surroundings.nodeId,\n    sections,\n    report.shared,\n    report.styles,\n    report.parent,\n    arranges\n  );\n  const added = useAddedProperties(surroundings.nodeId);\n  // Drawn wherever the block has any Style section, so the tab always ends\n  // the same way.\n  const css = sections.length === 0 ? undefined : arranged.extras;\n  const { open, onOpenChange } = useTabFolds(\"style\", [\n    ...arranged.sections.map(section => ({\n      key: section.key,\n      label: section.label,\n      holdsValue: holdsValues(section),\n    })),\n    ...(css === undefined\n      ? []\n      : [\n          {\n            ...CSS_PROPERTIES_SECTION,\n            // Kept open once the author works in it, so removing its last\n            // value doesn't close the section they are using.\n            holdsValue: added.used || css.some(each => each.row.set),\n          },\n        ]),\n  ]);\n  return (\n    <FocalFrame.Provider value={{ picture, position, fit }}>\n      <Accordion type=\"multiple\" value={open} onValueChange={onOpenChange}>\n        {arranged.sections.map(section => (\n          <StyleSectionItem\n            // Keyed by group alone, so a closed section whose heading reads\n            // the same is kept as it is for the next block. What a field\n            // holds is keyed by node inside it (`SectionBody`).\n            key={section.key}\n            section={section}\n            open={open.includes(section.key)}\n            hidden={!sectionShown(match, \"style\", section.key)}\n            readOnlyReason={readOnlyReason}\n            {...surroundings}\n          />\n        ))}\n        {css === undefined ? null : (\n          <CssPropertiesSection\n            extras={css}\n            added={added}\n            readOnlyReason={readOnlyReason}\n            surroundings={surroundings}\n          />\n        )}\n      </Accordion>\n    </FocalFrame.Provider>\n  );\n}\n\n/**\n * The elements whose content is an external resource the box fits, which is\n * where the media fit properties show without being asked for. Not\n * `<picture>`: it only chooses a source, and the `<img>` inside it is the\n * element `object-fit` applies to.\n */\nconst REPLACED_ELEMENTS: ReadonlySet<string> = new Set([\n  \"img\",\n  \"video\",\n  \"iframe\",\n  \"embed\",\n  \"object\",\n  \"canvas\",\n]);\n\n/** Whether the block renders as one of {@link REPLACED_ELEMENTS}. */\nexport function rendersMedia(\n  renderedTag: string | undefined,\n  renderedPicture?: string\n): boolean {\n  // A replaced element, or a picture of the block's own inside a link or a\n  // figure: a captioned or linked image's root is not the image.\n  if (renderedPicture !== undefined) return true;\n  return renderedTag !== undefined && REPLACED_ELEMENTS.has(renderedTag);\n}\n\n/** The props one section is drawn from. */\ntype StyleSectionItemProps = {\n  section: StyleSection;\n  /** Whether it is the section open, whose fields are drawn. */\n  open: boolean;\n  /** Whether the panel's filter keeps nothing in it, so it is not drawn. */\n  hidden: boolean;\n  /** Why every control is read-only. */\n  readOnlyReason: string | undefined;\n} & StyleFieldSurroundings;\n\n/** Whether any of a section's properties holds a value. */\nfunction holdsValues(section: StyleSection): boolean {\n  return section.properties.some(property => property.set);\n}\n\n/**\n * Whether a section draws nothing new: closed both times, it draws only its\n * heading, so it is drawn again only when what the heading says changes. An\n * open section draws its fields, which read everything, and is always drawn.\n */\nfunction sameClosedSection(\n  before: StyleSectionItemProps,\n  after: StyleSectionItemProps\n): boolean {\n  if (before.open || after.open) return false;\n  return (\n    before.hidden === after.hidden &&\n    before.section.key === after.section.key &&\n    before.section.label === after.section.label &&\n    holdsValues(before.section) === holdsValues(after.section)\n  );\n}\n\n/**\n * One section: its heading, and while it is open, its fields.\n *\n * **The header marks a section that holds values** with a dot and the words\n * \"has values\" for a screen reader, so an author can see which sections they\n * have touched without opening each one, and the dot is never colour alone.\n *\n * Kept as it is while it stays closed and its heading reads the same, so a\n * selection rebuilds only the sections that change: the open one, and any\n * whose dot comes or goes.\n */\nconst StyleSectionItem: React.NamedExoticComponent<StyleSectionItemProps> =\n  React.memo(function StyleSectionItem({\n    section,\n    open: _open,\n    hidden,\n    readOnlyReason,\n    ...surroundings\n  }: StyleSectionItemProps): React.JSX.Element {\n    return (\n      <AccordionItem\n        value={section.key}\n        data-section={section.key}\n        hidden={hidden}\n      >\n        <SectionHeading\n          label={section.label}\n          holdsValues={holdsValues(section)}\n        />\n        <AccordionContent>\n          <SectionBody\n            // Keyed by node: what a field holds stays with the block it was\n            // for, and the next block's fields start from its own values.\n            key={surroundings.nodeId}\n            section={section}\n            readOnlyReason={readOnlyReason}\n            {...surroundings}\n          />\n        </AccordionContent>\n      </AccordionItem>\n    );\n  }, sameClosedSection);\n\n/** The spacing box's properties, which the filter keeps it by. */\nconst SPACING_IDS: readonly string[] = [\"margin\", \"padding\"];\n\n/** The block's settings Content width draws, which the filter keeps it by. */\nconst CONTENT_WIDTH_IDS: readonly string[] = [\"contained\", \"contentWidth\"];\n\n/** A Section's Padding, which the filter keeps it by. */\nconst PADDING_PRESET_IDS: readonly string[] = [PADDING_PRESET_PROP];\n\n/** The Size shortcuts, which the filter keeps them by. */\nconst SHORTCUTS: readonly string[] = Object.values(SHORTCUT_IDS);\n\n/**\n * A section's properties drawn: those that show unasked and apply, and those\n * holding a value. While the panel is filtered the same rows stay mounted,\n * hidden where the filter keeps nothing of them, so an unsaved or refused\n * value outlives the search. The rest are added in \"CSS properties\".\n */\nfunction shownProperties(\n  properties: readonly InspectedStyleProperty[]\n): readonly InspectedStyleProperty[] {\n  return properties.filter(property => property.common);\n}\n\n/**\n * An open section's fields: its common properties and any that hold a value.\n */\nfunction SectionBody({\n  section,\n  readOnlyReason,\n  orientation,\n  nodeId,\n  state,\n  breakpoint,\n  editor,\n  policy,\n  tokens,\n  prefersDark,\n  provenanceOf,\n  editing,\n  onChooseForm,\n  breakpoints,\n}: Omit<StyleSectionItemProps, \"open\" | \"hidden\">): React.JSX.Element {\n  const readOnly = readOnlyReason !== undefined;\n  const surroundings: StyleFieldSurroundings = {\n    orientation,\n    nodeId,\n    state,\n    breakpoint,\n    editor,\n    policy,\n    tokens,\n    prefersDark,\n    provenanceOf,\n    editing,\n    onChooseForm,\n    breakpoints,\n  };\n  const { shown, arrange } = useSectionRows(section, surroundings);\n  return (\n    <SectionFields\n      sectionKey={section.key}\n      shown={shown}\n      readOnly={readOnly}\n      surroundings={surroundings}\n      arrange={arrange}\n    />\n  );\n}\n\n/**\n * A section's rows drawn, with Layout's Arrange: the rows a section's plain\n * controls draw leave (Arrange's, and Inside its parent's Fill / Fit /\n * Fixed), and the panel's filter hides what it doesn't keep.\n */\nfunction useSectionRows(\n  section: StyleSection,\n  surroundings: StyleFieldSurroundings\n): {\n  shown: readonly InspectedStyleProperty[];\n  arrange: ArrangedSection[\"arrange\"];\n} {\n  const reading = useArrangeReading(surroundings, offersArrange(section));\n  const drawn = useDrawnChildRows(surroundings);\n  const arranged = arrangedSection(section.properties, reading);\n  const listed = withoutDrawn(section.key, arranged.listed, drawn);\n  return { shown: shownProperties(listed), arrange: arranged.arrange };\n}\n\n/** \"Inside its parent\"'s rows, less those its Fill / Fit / Fixed draw. */\nfunction withoutDrawn(\n  key: InspectorSectionKey,\n  listed: readonly InspectedStyleProperty[],\n  drawn: ReadonlySet<string>\n): readonly InspectedStyleProperty[] {\n  if (key !== \"inside-parent\") return listed;\n  return listed.filter(property => !drawn.has(property.property));\n}\n\n/** A Layout section's raw rows, and the Arrange drawn above them. */\ninterface ArrangedSection {\n  readonly listed: readonly InspectedStyleProperty[];\n  readonly arrange:\n    | {\n        readonly reading: ArrangeReading;\n        readonly spacing: readonly InspectedStyleProperty[];\n      }\n    | undefined;\n}\n\n/**\n * A container's Layout says its arrangement in plain words. Arrange's rows\n * hold the properties it draws, so they leave the raw rows, except\n * while it reads Custom, when the raw rows are what hold it.\n */\nfunction arrangedSection(\n  properties: readonly InspectedStyleProperty[],\n  reading: ArrangeReading | undefined\n): ArrangedSection {\n  if (reading === undefined) return { listed: properties, arrange: undefined };\n  if (reading.arrange.mode === \"custom\") {\n    return { listed: properties, arrange: { reading, spacing: [] } };\n  }\n  const { mode } = reading.arrange;\n  return {\n    listed: properties.filter(property => !arrangedAway(property, mode)),\n    arrange: {\n      reading,\n      spacing: properties.filter(property =>\n        SPACE_PROPERTIES.has(property.property)\n      ),\n    },\n  };\n}\n\n/**\n * \"Nothing set here yet\" for a section showing no row: not under Arrange,\n * whose rows are what a container's Layout shows. Its other properties are\n * added in \"CSS properties\".\n */\nfunction NothingSetNote({\n  shown,\n  arrange,\n}: {\n  shown: number;\n  arrange: ArrangedSection[\"arrange\"];\n}): React.JSX.Element | null {\n  if (shown > 0 || arrange !== undefined) return null;\n  return <p className=\"nx-inspector__note\">Nothing set here yet.</p>;\n}\n\n/**\n * What a section draws above its rows: Layout's Content width and Arrange,\n * Inside its parent's Width and Height, a Section's Padding above the spacing\n * box, Size's shortcuts.\n */\nfunction SectionLead({\n  sectionKey,\n  surroundings,\n  arrange,\n  minHeightDrawn,\n}: {\n  sectionKey: InspectorSectionKey;\n  surroundings: StyleFieldSurroundings;\n  arrange: ArrangedSection[\"arrange\"];\n  minHeightDrawn: boolean;\n}): React.JSX.Element | null {\n  if (sectionKey === \"layout\") {\n    return <LayoutLead surroundings={surroundings} arrange={arrange} />;\n  }\n  if (sectionKey === \"inside-parent\") {\n    return <InsideParentFields surroundings={surroundings} />;\n  }\n  // The block's text style first: the whole look its other fields adjust.\n  if (sectionKey === \"typography\") {\n    return <TextStylePicker surroundings={surroundings} />;\n  }\n  if (sectionKey === \"spacing\") {\n    return (\n      <SettingSlot tab=\"style\" ids={PADDING_PRESET_IDS}>\n        <SectionPaddingFields surroundings={surroundings} />\n      </SettingSlot>\n    );\n  }\n  if (sectionKey !== \"size\") return null;\n  return (\n    <SettingSlot tab=\"style\" ids={SHORTCUTS}>\n      <BlockShortcutsFields\n        surroundings={surroundings}\n        minHeightDrawn={minHeightDrawn}\n      />\n    </SettingSlot>\n  );\n}\n\n/** What leads a Layout section: Content width, then a container's Arrange. */\nfunction LayoutLead({\n  surroundings,\n  arrange,\n}: {\n  surroundings: StyleFieldSurroundings;\n  arrange: ArrangedSection[\"arrange\"];\n}): React.JSX.Element {\n  return (\n    <>\n      <SettingSlot tab=\"style\" ids={CONTENT_WIDTH_IDS}>\n        <ContentWidthFields surroundings={surroundings} />\n      </SettingSlot>\n      {arrange === undefined ? null : (\n        <ArrangeFields\n          surroundings={surroundings}\n          reading={arrange.reading}\n          spacing={arrange.spacing}\n        />\n      )}\n    </>\n  );\n}\n\n/**\n * A section's fields: the spacing box where the section draws one, then each\n * shown property as before.\n */\nfunction SectionFields({\n  sectionKey,\n  shown,\n  readOnly,\n  surroundings,\n  arrange,\n}: {\n  sectionKey: InspectorSectionKey;\n  shown: readonly InspectedStyleProperty[];\n  readOnly: boolean;\n  surroundings: StyleFieldSurroundings;\n  /** A container's Arrange, with the space fields it draws. */\n  arrange?: ArrangedSection[\"arrange\"];\n}): React.JSX.Element {\n  const target = React.useContext(StyleTargetContext);\n  const rings =\n    sectionKey === \"spacing\"\n      ? spacingRings(shown, surroundings.orientation)\n      : undefined;\n  return (\n    <fieldset className=\"nx-inspector__fields\" disabled={readOnly}>\n      <SectionHeld.Provider value={readOnly}>\n        <SectionLead\n          sectionKey={sectionKey}\n          surroundings={surroundings}\n          arrange={arrange}\n          minHeightDrawn={(rings?.rest ?? shown).some(\n            property => property.property === \"minHeight\"\n          )}\n        />\n        {rings === undefined ? null : (\n          <SettingSlot tab=\"style\" ids={SPACING_IDS}>\n            <SpacingBox\n              margin={rings.margin}\n              padding={rings.padding}\n              surroundings={surroundings}\n            />\n          </SettingSlot>\n        )}\n        {(rings?.rest ?? shown).map(property => (\n          <SettingSlot\n            key={`${surroundings.nodeId}:${property.property}`}\n            tab=\"style\"\n            // Min height draws a Section's Height presets over it, so the\n            // row is kept for those as well.\n            ids={\n              property.property === \"minHeight\"\n                ? [property.property, SHORTCUT_IDS.height]\n                : [property.property]\n            }\n          >\n            {property.property === \"minHeight\" ? (\n              <BlockPresetsOver surroundings={surroundings} />\n            ) : null}\n            {property.property === \"height\" ? (\n              <SpacerHeightPresets\n                surroundings={surroundings}\n                control={property.controls[0]}\n                stored={property.value}\n              />\n            ) : null}\n            <StylePropertyFields\n              property={withOverlayOffered(property, surroundings, target)}\n              namesSection={property.property === sectionKey}\n              {...surroundings}\n            />\n          </SettingSlot>\n        ))}\n        <NothingSetNote shown={shown.length} arrange={arrange} />\n      </SectionHeld.Provider>\n    </fieldset>\n  );\n}\n\n/** The background's overlay fields, offered only over an image. */\nconst OVERLAY_FIELDS: ReadonlySet<string> = new Set([\n  \"overlay\",\n  \"overlayStrength\",\n]);\n\n/** The leaf an image or a gradient is traced by. */\nconst BACKGROUND_IMAGE_LEAF: StyleLeaf = {\n  kind: \"cssValue\",\n  cssProperty: \"background-image\",\n  tokenKinds: [],\n};\n\n/**\n * The background's controls without its overlay while there is nothing for\n * one to cover: no image or gradient reaching what is edited (from the\n * cascade where it answers, else from what the target stores anywhere), and\n * no overlay of its own to clear.\n */\nfunction withOverlayOffered(\n  property: InspectedStyleProperty,\n  surroundings: StyleFieldSurroundings,\n  target: StyleTarget\n): InspectedStyleProperty {\n  if (property.property !== \"background\") return property;\n  if (overlayCovers(surroundings, target)) return property;\n  return {\n    ...property,\n    controls: property.controls.filter(\n      control => !OVERLAY_FIELDS.has(control.path[0] ?? \"\")\n    ),\n  };\n}\n\n/**\n * Whether the overlay has something to cover where it is edited, or an overlay\n * of its own to clear. Where the cascade answers, the image that wins here\n * decides, judged as the compiler paints it, so `none` covers nothing whatever\n * another device or state stores; where it cannot answer (a shared style being\n * edited, which the panel does not trace), what the target stores anywhere.\n */\nfunction overlayCovers(\n  surroundings: StyleFieldSurroundings,\n  target: StyleTarget\n): boolean {\n  const { styles } = fieldStyles(\n    target,\n    surroundings.editor,\n    surroundings.nodeId\n  );\n  if (anyAddress(styles, storesOverlay)) return true;\n  const answer = surroundings.provenanceOf(BACKGROUND_IMAGE_LEAF);\n  if (answer !== undefined) return winningImagePaints(answer.provenance);\n  return anyAddress(styles, paintsImage);\n}\n\n/**\n * Whether the image a provenance names paints one: a value rather than a\n * keyword that clears it, by the compiler's own judgement. The image and the\n * gradient both write `background-image`, so the trace often cannot say which\n * control wrote the winner; it is still the winner, and its value decides.\n */\nfunction winningImagePaints(provenance: StyleProvenance): boolean {\n  return (\n    provenance.kind !== \"unset\" &&\n    paintsBackgroundImage(\"gradient\", provenance.entry.value)\n  );\n}\n\n/** Whether any state and device of these styles holds what `test` asks. */\nfunction anyAddress(\n  styles: NodeStyles | undefined,\n  test: (values: StyleValues | undefined) => boolean\n): boolean {\n  return Object.values(styles ?? {}).some(byBreakpoint =>\n    Object.values(byBreakpoint ?? {}).some(test)\n  );\n}\n\n/** One address's background, when it is an object. */\nfunction backgroundAt(\n  values: StyleValues | undefined\n): Record<string, unknown> | undefined {\n  const background = values?.background;\n  return typeof background === \"object\" &&\n    background !== null &&\n    !Array.isArray(background)\n    ? (background as Record<string, unknown>)\n    : undefined;\n}\n\n/** Whether one address stores an overlay of its own. */\nfunction storesOverlay(values: StyleValues | undefined): boolean {\n  const background = backgroundAt(values);\n  return (\n    background !== undefined &&\n    [...OVERLAY_FIELDS].some(field => Object.hasOwn(background, field))\n  );\n}\n\n/**\n * Whether one address's values paint an image or a gradient, judged as the\n * compiler judges it: `none` clears an image, and an overlay over it would\n * cover nothing.\n */\nfunction paintsImage(values: StyleValues | undefined): boolean {\n  return (\n    paintsBackgroundImage(\"gradient\", values?.backgroundGradient) ||\n    paintsBackgroundImage(\"url\", backgroundAt(values)?.url)\n  );\n}\n","\"use client\";\n\n/**\n * The Style tab: editing the selected block's style values.\n *\n * Draws what `style-inspector` decides and decides nothing itself — which\n * sections a block offers, which properties sit in each, and which control each\n * property draws all live there, where they can be asserted without a DOM.\n *\n * **Sections fold on their own**, and stay as the author left them across\n * selections and visits (`panel-folds`), because an author working on spacing\n * selects one block after another and means to keep Spacing open; a section\n * nothing remembers opens when it holds a value or is the first.\n *\n * **Text commits on blur, discrete controls immediately**, the same rule the\n * content tab follows and for the same reason: undo is built from op inverses,\n * so an op per keystroke would make one undo remove one character.\n *\n * **Clearing is not writing an empty value.** An emptied field removes the\n * entry, so the property falls back through the cascade to whatever a class, a\n * block default or a wider breakpoint set — which is what an author asking to\n * reset a control means. Writing `\"\"` would instead pin the property to nothing\n * here and beat the tier they wanted back.\n *\n * **A refused value is shown, not swallowed.** The catalog's own message sits\n * under the control that produced it, because a field that silently keeps its\n * old value after an edit reads as an editor that dropped the keystroke.\n *\n * ## Where each part lives\n *\n * This file holds the panel itself and its body. The rest:\n *\n * - `style-panel-sections.tsx`: the sections a block offers, each section's\n *   fields, the overlay offer and More properties.\n * - `style-block-shortcuts.tsx`: the columns layout, block shortcuts and\n *   presets.\n * - `spacing-box-fields.tsx`: the spacing box as drawn (box, ring, side\n *   frame).\n * - `style-property-fields.tsx`: one control per property, and the form\n *   toggle.\n * - `style-field-shell.tsx`: the label, control field, issue line, and the\n *   reset and jump actions.\n * - `style-provenance-indicators.tsx`: the shared value line, the provenance\n *   dot and its description, and the breakpoint label.\n * - `style-control-value.tsx`: which control a property draws.\n * - `style-colour-field.tsx`: the colour field and its picker.\n * - `style-value-fields.tsx`, `style-numeric-field.tsx` and\n *   `style-text-field.tsx`: the value fields.\n * - `style-field-target.ts`: what a field reads and writes.\n * - `style-panel-reading.ts`: what the panel reads about the selection.\n * - `style-field-surroundings.ts`: the shapes and contexts every part reads.\n *\n * @module style-inspector-panel\n */\nimport {\n  findNode,\n  walkNodes,\n  type BreakpointId,\n  type BreakpointSet,\n  type NamedClass,\n  type SiteTokenSet,\n  type TokenMode,\n  type StyleState,\n  previewContainerName,\n} from \"@nextlyhq/blocks-engine\";\nimport type { PageStyleCascade } from \"@nextlyhq/blocks-react\";\nimport * as React from \"react\";\n\nimport { useCanvasFrame } from \"../../canvas/canvas-frame-context\";\nimport {\n  CanvasTokenModeProvider,\n  useCanvasTokenModeAt,\n} from \"../../canvas/prefers-dark\";\nimport type { EditorState } from \"../../editor-state\";\nimport {\n  FontChoicesContext,\n  type FontChoices,\n} from \"../../panels/design/font-family-field\";\nimport { layerLabel } from \"../../panels/layers/layers\";\nimport {\n  breakpointQueries,\n  matchedBreakpoints,\n} from \"../../styles/breakpoints\";\nimport type { SideOrientation } from \"../../styles/side-orientation\";\nimport type { StylePolicy } from \"../../styles/style-values\";\nimport { CssNamesProvider } from \"../css-names-context\";\nimport { PanelFoldsProvider } from \"../panel-folds-context\";\n\nimport { FocalFrame } from \"./focal-frame\";\nimport { ParentArrangementContext } from \"./plain-parent-controls\";\nimport { SpacingApplyToProvider } from \"./spacing-side\";\nimport {\n  BLOCK_TARGET,\n  StyleTargetContext,\n  TypesLiveContext,\n  TokenPrefixContext,\n  tokenPrefixOf,\n  type StyleFieldSurroundings,\n  AppliedAtTier,\n  BeneathAtTier,\n  type EditedAddress,\n} from \"./style-field-surroundings\";\nimport {\n  fieldStyles,\n  sharedStyleNamer,\n  targetProvenance,\n  targetReadOnly,\n  targetCascade,\n  targetStyles,\n} from \"./style-field-target\";\nimport { inspectStyle, type StyleInspection } from \"./style-inspector\";\nimport {\n  appliedAtReader,\n  beneathAtReader,\n  selectedSubject,\n  cascadeFor,\n  provenanceReader,\n} from \"./style-panel-reading\";\nimport { StyleSections, rendersMedia } from \"./style-panel-sections\";\nimport { breakpointLabel } from \"./style-provenance-indicators\";\nimport type { StyleTarget } from \"./style-target\";\nimport { TextStyleLibrary } from \"./text-style-picker\";\n\nexport { commitsFor, supersedes } from \"./style-colour-field\";\nexport { pickedReference } from \"./style-control-value\";\n// Part of this module's exported names; no importer in the package reads it.\n// fallow-ignore-next-line unused-type\nexport type { EditedAddress } from \"./style-field-surroundings\";\nexport { describedWithUnit } from \"./style-numeric-field\";\nexport {\n  breakpointLabel,\n  describeProvenance,\n} from \"./style-provenance-indicators\";\n\nexport interface StyleInspectorPanelProps {\n  /**\n   * The mode the selected block is drawn in, when the caller already reads\n   * it for a sibling surface: one canvas subscription, not two.\n   */\n  tokenMode?: TokenMode;\n  /**\n   * The editor whose selected block this styles.\n   *\n   * The whole state rather than a document and an `apply` separately, for the\n   * reason the content tab takes it: a write is built from the node in a\n   * particular document, and passing them apart lets a caller hand a node from\n   * one render to an `apply` bound to another.\n   */\n  editor: EditorState;\n  /**\n   * What the site allows, forwarded to both the arm choice and the write.\n   *\n   * Carried rather than defaulted: the engine ships no host list of its own, so\n   * omitting it does not mean \"allow\" — it means the question was never asked.\n   */\n  policy?: StylePolicy;\n  /**\n   * The element the selected node is DRAWN as, or `undefined` when nobody can\n   * say.\n   *\n   * Only the typographic baseline needs it: those rules land on `h1` itself, so\n   * nothing in the document says whether one reaches this node — `core/heading`\n   * takes its tag from a prop, and `core/rich-text` renders a `div` with its\n   * headings inside.\n   *\n   * Resolved by the caller rather than read here, the same way `cascade` and\n   * `liveBreakpoints` are. Reading it needs a subscription to the canvas, and\n   * the reader that decides which control shows a value should not also own\n   * one. Omitted, a heading's baseline is reported as reaching nothing, which\n   * is the quiet answer a host that cannot supply a canvas should get rather\n   * than a guess.\n   */\n  renderedTag?: string;\n  /**\n   * How the selected node's element runs, when the canvas could be read.\n   *\n   * `undefined` is NOT KNOWN rather than left-to-right. A per-side property is\n   * drawn as a box only when this resolves, because the arrangement is a claim\n   * about which physical edge each logical side is and only the edited element\n   * settles it. Resolved by the wrapper, which owns the canvas subscription.\n   */\n  sideOrientation?: SideOrientation;\n  /**\n   * The interaction state being edited. `base` when the host says nothing.\n   *\n   * A host that renders a canvas should hand the SAME value to\n   * `Canvas.forcedState`, and the two are one decision rather than two.\n   * Provenance depends on it: this panel states no `liveStates`, so\n   * `styleProvenance` falls back to the edited state plus base — correct\n   * exactly when the canvas is simulating the state being edited, and wrong the\n   * moment it is not. Wired from one value, that precondition holds by\n   * construction; wired from two, a control reports a value the browser is not\n   * showing and nothing says so.\n   *\n   * Measuring the real pseudo-classes instead was considered and declined. The\n   * pointer is in the inspector whenever anyone is reading the panel, so a\n   * measured `:hover` is false every time and every hover control would report\n   * unset permanently — the affordance switched off in the exact state the\n   * author opened it to inspect.\n   */\n  state?: StyleState;\n  /** The breakpoint being edited. The unconditional one when the host says nothing. */\n  breakpoint?: BreakpointId;\n  /**\n   * The site's design tokens, so a colour control can offer them and resolve\n   * one it is shown.\n   *\n   * Separate from `policy.tokens`, which cannot serve this: a `TokenLookup` is\n   * `{ kindOf(name) }` and answers ABOUT a name the caller already has. It can\n   * confirm a reference and cannot enumerate one, so a picker sourced from it\n   * would have nothing to list.\n   *\n   * Carried rather than defaulted, exactly as `policy` is: omitting it does not\n   * mean the site has no tokens, it means the question was never asked. A\n   * control with no table offers no token picker and shows a stored reference\n   * by the identity the document holds, because that is the only name it has.\n   */\n  tokens?: SiteTokenSet;\n  /**\n   * The declarations the compiler wrote for this document, WITH the tree they\n   * describe.\n   *\n   * What lets a control say where its value came from. Supplied by the host\n   * rather than compiled here, and that is the point: the panel renders once per\n   * control, so compiling in this component would walk the cascade per control\n   * — the thing this file's own comments say must not happen.\n   *\n   * The tree travels with the entries rather than being taken from\n   * {@link editor}, because the two are one answer. Read-time repair can change\n   * WHICH node owns an id: a duplicated id whose first node is condition-gated\n   * leaves a later node rendering under it, and a lookup in the raw document\n   * then returns a node with different classes, a different type and a different\n   * chain of ancestors than the declarations belong to. A visibly applied class\n   * is reported as unset, or attributed to the wrong tier.\n   *\n   * Absent means the question was never asked, not that nothing is inherited: a\n   * host that supplies no cascade gets no indicators, which is the honest answer\n   * for a surface that cannot compile.\n   */\n  cascade?: PageStyleCascade;\n  /**\n   * The site's breakpoints, for deciding which declarations are live.\n   *\n   * Carried rather than derived from {@link breakpoint}: which rules are in PLAY\n   * is a fact about the width being viewed, and the edited breakpoint only says\n   * which of them counts as authored here.\n   */\n  breakpoints?: BreakpointSet;\n  /**\n   * The container the page's breakpoints were compiled against, when the canvas\n   * is previewing rather than rendering at the browser's own width.\n   *\n   * Carried because this panel decides which declarations are LIVE, and that is\n   * a question about the queries the sheet was EMITTED under. Given only the\n   * breakpoint set, it compares the window against `@media` rules a preview\n   * compile never wrote — a confident wrong answer rather than a stale one,\n   * since a narrow admin window then reports the small breakpoints live while a\n   * wide canvas box is showing the large ones.\n   */\n  previewContainer?: string;\n  /**\n   * Which breakpoints the canvas is ACTUALLY applying, when the host can say.\n   *\n   * Needed in preview and unnecessary otherwise. Rendering at the browser's own\n   * width, this panel asks `matchMedia` and answers for itself; previewing\n   * inside a box, the queries are about that box and only whoever owns it can\n   * observe them.\n   *\n   * Absent while previewing, no indicator is drawn at all. Reporting the\n   * window's answer there would name the wrong tier as the visible winner,\n   * which is worse than naming none.\n   */\n  liveBreakpoints?: readonly BreakpointId[];\n  /**\n   * Move the canvas to a breakpoint, for a control offering to go where its\n   * value was set.\n   *\n   * The panel cannot do this itself: which tier the canvas shows is a fact\n   * about the surface that OWNS the canvas width, and this panel sits several\n   * layers below it. Supplied, each control whose value came from another tier\n   * offers the jump; omitted, none does — a host with no canvas to move would\n   * otherwise draw a button that does nothing, which reads as broken rather\n   * than absent.\n   */\n  onJumpToBreakpoint?: (breakpoint: BreakpointId) => void;\n  /**\n   * What an edit changes: the block, or one of the shared styles it wears.\n   * The block when omitted. The Style tab holds the choice and its bar shows\n   * it; the controls read and write the target's values, so the two cannot\n   * disagree about what an edit changes.\n   */\n  target?: StyleTarget;\n  /**\n   * The site's fonts, for the Font control. It lists only what the site can\n   * draw: its font variables, the families it has files for, and the system\n   * families. Absent, it lists the variables and the system families.\n   */\n  fonts?: FontChoices;\n  /**\n   * The site's class library, for the Text section's \"Text style\" picker,\n   * which lists the text styles in it. Absent: no picker is drawn.\n   */\n  classLibrary?: readonly NamedClass[];\n  /**\n   * Whether the tab says above its controls why a held block's design can't\n   * be changed. True when omitted. A host that says it already, as the\n   * inspector's block card does, turns it off, so the reason is said once.\n   */\n  showReadOnlyReason?: boolean;\n}\n\n/**\n * Why this panel has nothing to style, drawn, or `null` when it does.\n *\n * All four ask ONE question — can an edit here mean what it appears to mean —\n * and each is refused for a different reason. Gathered so the panel body holds\n * one branch instead of four: the reasons are stable and the panel is not, and\n * a large function that grows a branch per release is how one arrives over the\n * complexity gate without anyone deciding to.\n */\ntype StyleAvailability =\n  | { readonly available: false; readonly reason: React.JSX.Element }\n  | { readonly available: true; readonly inspection: StyleInspection };\n\nfunction styleUnavailable(\n  editor: EditorState,\n  inspection: StyleInspection | null\n): StyleAvailability {\n  if (editor.selection.ids.length > 1) {\n    return {\n      available: false,\n      reason: (\n        <div className=\"nx-style-inspector\" data-empty=\"many-selected\">\n          <p className=\"nx-inspector__note\">\n            {editor.selection.ids.length} blocks selected. Select one to style\n            it.\n          </p>\n        </div>\n      ),\n    };\n  }\n\n  /*\n   * A block whose id is not unique cannot be styled, and saying so is the only\n   * honest answer this panel has.\n   *\n   * The compiler already reaches this conclusion for the same reason, and its\n   * words are worth keeping: a class is derived from the id, so two nodes\n   * sharing one share a class, and \"writing corrupts a node the author did not\n   * touch\". It refuses to emit their rules.\n   *\n   * The editor has to refuse for a second reason the compiler does not face. The\n   * cascade is read from the PREPARED tree, where read-time repair has already\n   * dropped the later duplicate — but gating runs first, so a gated first node\n   * leaves a LATER one owning that id there, while every lookup in the stored\n   * document returns the first. The controls would then show and write one\n   * block while the provenance dots describe another, and typing into a field\n   * would silently change a block that is not on screen.\n   *\n   * Refused rather than reconciled: pointing the controls at the rendered node\n   * would not help, because a write is addressed by id and would still land on\n   * the first. There is no edit here that means what it appears to mean.\n   */\n  if (editor.selectedId !== null && sharesItsId(editor, editor.selectedId)) {\n    return {\n      available: false,\n      reason: (\n        <div className=\"nx-style-inspector\" data-empty=\"duplicate-id\">\n          <p className=\"nx-inspector__note\">\n            Another block on this page has the same id, so styles written here\n            could not be told apart. Give one of them a new id to style either.\n          </p>\n        </div>\n      ),\n    };\n  }\n\n  if (inspection === null) {\n    return {\n      available: false,\n      reason: (\n        <div className=\"nx-style-inspector\" data-empty=\"no-selection\">\n          <p className=\"nx-inspector__note\">Select a block to style it.</p>\n        </div>\n      ),\n    };\n  }\n\n  /*\n   * A block offering no style properties is NOT unavailable, and that is the\n   * distinction this function turns on. The three refusals above are about\n   * there being no single node an edit could address — a multi-selection, an\n   * ambiguous id, nothing selected. This one is only about the block's own\n   * controls, and named classes compile independently of them: such a block\n   * can still carry a class, so the class surface has to survive it.\n   */\n  return { available: true, inspection };\n}\n\n/**\n * The Style tab. The site's fonts reach the Font control through a context, so\n * they are not handed down every section and row between here and there.\n */\nexport function StyleInspectorPanel(\n  props: StyleInspectorPanelProps\n): React.JSX.Element {\n  return (\n    <FontChoicesContext.Provider value={props.fonts}>\n      {/* The library the Text section's \"Text style\" picker lists from. */}\n      <TextStyleLibrary.Provider value={props.classLibrary}>\n        {/* The panel's own folds where nothing above lends them. */}\n        <PanelFoldsProvider>\n          <SpacingApplyToProvider>\n            <CssNamesProvider>\n              {props.tokenMode === undefined ? (\n                <StyleInspectorOwnMode {...props} />\n              ) : (\n                <StyleInspectorBody {...props} tokenMode={props.tokenMode} />\n              )}\n            </CssNamesProvider>\n          </SpacingApplyToProvider>\n        </PanelFoldsProvider>\n      </TextStyleLibrary.Provider>\n    </FontChoicesContext.Provider>\n  );\n}\n\n/** The panel reading its block's mode itself, where no caller hands it one. */\nfunction StyleInspectorOwnMode(\n  props: StyleInspectorPanelProps\n): React.JSX.Element {\n  const tokenMode = useCanvasTokenModeAt(props.editor.selectedId);\n  return <StyleInspectorBody {...props} tokenMode={tokenMode} />;\n}\n\nfunction StyleInspectorBody({\n  editor,\n  renderedTag,\n  sideOrientation,\n  policy,\n  tokens,\n  state,\n  breakpoint,\n  cascade,\n  breakpoints,\n  previewContainer,\n  liveBreakpoints,\n  onJumpToBreakpoint,\n  target = BLOCK_TARGET,\n  showReadOnlyReason = true,\n  tokenMode,\n}: StyleInspectorPanelProps & { tokenMode: TokenMode }): React.JSX.Element {\n  // The form an author chose at a union position, keyed by property and path.\n  // Panel state rather than document state: it is only consulted where nothing\n  // is stored, so there is nothing to persist — the moment a value exists, the\n  // value decides its own form.\n  const [chosenForms, setChosenForms] = React.useState<Record<string, number>>(\n    {}\n  );\n  // The mode the selected block is drawn in, its nearest theme marker first\n  // and the device after, read once above and handed to every control below.\n  const prefersDark = tokenMode === \"dark\";\n  /*\n   * What the browser is applying, or `undefined` when nobody can say.\n   *\n   * ONE call, because the component must not hold the two inputs separately.\n   * It did, and they disagreed: the decision to draw an indicator asked whether\n   * a preview name was STATED while the set being judged asked whether the host\n   * had supplied one, so a refused name arriving beside a live set had the\n   * box-derived tiers used against a published compile. Fixing either half\n   * alone left the other standing, which is the tell that the two questions\n   * were one question with two answers.\n   */\n  const live = useLiveBreakpoints(\n    breakpoints,\n    previewContainer,\n    liveBreakpoints\n  );\n\n  // Recomputed each render rather than memoised, as the content tab is: an\n  // inspection is only valid against the document it was read from, and an edit\n  // anywhere changes both the document and the values shown.\n  /*\n   * ONE subject for the whole panel, and one live-breakpoint set.\n   *\n   * Every control on this panel asks about the SAME node, so building either per\n   * control would walk the document per control — which is the cost this file's\n   * own comments say the indicator must not pay. The inspection reads it too,\n   * to judge which tier's controls show by the display the cascade applies.\n   *\n   * Recomputed each render rather than memoised, exactly as the inspection is:\n   * both are only valid against the document they were read from, and an edit\n   * anywhere changes the document and the values shown together.\n   */\n  // The picture the canvas draws for the node, lent by the inspector.\n  const renderedPicture = React.useContext(FocalFrame).picture;\n  const subject = selectedSubject(editor, cascade, renderedTag);\n  const inspection = inspectStyle(editor.document, editor.selectedId, {\n    ...policy,\n    state,\n    breakpoint,\n    variantAt: (property, path) => chosenForms[formKey(property, path)],\n    media: rendersMedia(renderedTag, renderedPicture),\n    breakpoints,\n    cascade: targetCascade(target, cascadeFor(cascade, subject)),\n    // A shared target's values are the style's own, so the controls show\n    // and offer what the style stores rather than what the block does.\n    styles: targetStyles(target),\n  });\n\n  const chooseForm = (property: string, path: readonly string[], arm: number) =>\n    setChosenForms(current => ({ ...current, [formKey(property, path)]: arm }));\n\n  /*\n   * Several blocks selected: a different panel, not a thinner one.\n   *\n   * `selectedId` is the PRIMARY of the selection, so inspecting it would draw\n   * writable controls that change one block while the canvas outlines six —\n   * two surfaces answering different questions with the same words. The\n   * inspector wrapper makes the same refusal for the content half; this one\n   * makes it for itself because it is exported standalone, and a host mounting\n   * it directly gets no wrapper.\n   *\n   * Editing one property across a whole selection — one field showing \"Mixed\"\n   * and writing to every block — is a different surface with its own rules\n   * about what a shared value means, and it does not exist yet.\n   */\n  /*\n   * One branch here, four inside. Narrowed through the RESULT rather than\n   * re-tested afterwards: a second `inspection === null` check in this body\n   * would put the branch back that the extraction removed, and a non-null\n   * assertion would state as fact what the guard already proved.\n   */\n  const availability = styleUnavailable(editor, inspection);\n  if (!availability.available) return availability.reason;\n  const inspected = availability.inspection;\n\n  /*\n   * What the panel is editing, so an inherited label can say what DIFFERS from\n   * it. Built once beside the subject for the same reason: every control is\n   * asking about one node at one address.\n   */\n  const editing: EditedAddress = {\n    nodeId: inspected.nodeId,\n    blockType: subject?.blockType,\n    state: inspected.state,\n    breakpoint: inspected.breakpoint,\n    labelOf: id => breakpointLabel(breakpoints, id),\n    sharedStyleName: sharedStyleNamer(target),\n    nameOf: id => {\n      const node = findNode(editor.document.nodes, id);\n      return node === undefined ? undefined : layerLabel(node);\n    },\n  };\n  const blockProvenance = provenanceReader({\n    cascade,\n    subject,\n    live,\n    state: inspected.state,\n    breakpoint: inspected.breakpoint,\n    breakpoints,\n    onJumpToBreakpoint,\n  });\n  /*\n   * The cascade traces the block, so its dots describe the block's values;\n   * a shared target's values are the style's, which say where they come\n   * from in their own line (set on this block, Move to) instead.\n   */\n  const provenanceOf = targetProvenance(target, blockProvenance);\n\n  /*\n   * Why the design is read-only, read from the document's own locks: the\n   * same answer the write path refuses by, so the controls drawn and the\n   * writes allowed cannot disagree. A shared target is read-only for its own\n   * reasons (locked, or the author may not change the site's design), and\n   * the block's lock does not hold a site-wide style.\n   */\n  const readOnlyReason = targetReadOnly(target, editor, inspected.nodeId);\n  /*\n   * What every section and field below needs from this panel, assembled once.\n   *\n   * One object rather than ten props repeated at the call site: the section\n   * forwards the identical set to each property, so a value spelled here and\n   * again there is a value that can go missing from one of them silently.\n   */\n  const surroundings: StyleFieldSurroundings = {\n    orientation: sideOrientation,\n    nodeId: inspected.nodeId,\n    state: inspected.state,\n    breakpoint: inspected.breakpoint,\n    editor,\n    policy,\n    tokens,\n    prefersDark,\n    provenanceOf,\n    editing,\n    onChooseForm: chooseForm,\n    breakpoints,\n  };\n\n  return (\n    <StyleTargetContext.Provider value={target}>\n      {/* A block's own fields: the canvas follows what is typed in them. */}\n      <TypesLiveContext.Provider value={true}>\n        <TokenPrefixContext.Provider value={tokenPrefixOf(cascade)}>\n          <ParentArrangementContext.Provider value={inspection?.parentLayout}>\n            <AppliedAtTier.Provider\n              value={appliedAtReader({\n                cascade,\n                subject,\n                state: inspected.state,\n                breakpoints,\n                nodeId: inspected.nodeId,\n              })}\n            >\n              <BeneathAtTier.Provider\n                value={beneathAtReader({\n                  cascade,\n                  subject,\n                  state: inspected.state,\n                  breakpoints,\n                  nodeId: inspected.nodeId,\n                })}\n              >\n                <CanvasTokenModeProvider value={tokenMode}>\n                  {/*\n                   * Spell-check off for the tab's fields: they hold numbers,\n                   * lengths, colours and keywords, which a spell-checker marks as\n                   * misspelt with the same red line an error would show. Set once\n                   * here because the attribute is inherited by every field inside,\n                   * including the ones other components draw and any added later.\n                   * The Content tab is a different element and keeps its own.\n                   */}\n                  <div\n                    className=\"nx-style-inspector\"\n                    data-style-target={target.kind}\n                    spellCheck={false}\n                  >\n                    {showReadOnlyReason ? (\n                      <ReadOnlyNote target={target} reason={readOnlyReason} />\n                    ) : null}\n                    <NoStyleProperties count={inspected.sections.length} />\n                    <StyleSections\n                      sections={inspected.sections}\n                      readOnlyReason={readOnlyReason}\n                      surroundings={surroundings}\n                      fit={inspected.objectFit}\n                      report={{\n                        shared: target.kind === \"shared\",\n                        styles: editedStyles(target, editor),\n                        parent: inspected.parent,\n                      }}\n                    />\n                  </div>\n                </CanvasTokenModeProvider>\n              </BeneathAtTier.Provider>\n            </AppliedAtTier.Provider>\n          </ParentArrangementContext.Provider>\n        </TokenPrefixContext.Provider>\n      </TypesLiveContext.Provider>\n    </StyleTargetContext.Provider>\n  );\n}\n\n/**\n * The breakpoints whose rules the browser is applying right now.\n *\n * Modelled on `usePrefersDark` in `prefers-dark.ts`, and for the same reason:\n * a media query's state is a fact about the viewer that nothing in React tells\n * this panel, so it is read and then subscribed to.\n *\n * Starts from the unconditional contexts and widens after mount, so a server\n * render and the first client render agree — React discards a subtree whose two\n * renders disagree, which would take the whole Style tab with it. The cost is\n * one frame reporting fewer origins than apply; the alternative is a hydration\n * mismatch.\n */\nfunction useLiveBreakpoints(\n  breakpoints: BreakpointSet | undefined,\n  previewContainer: string | undefined,\n  stated: readonly BreakpointId[] | undefined\n): readonly BreakpointId[] | undefined {\n  /*\n   * NORMALISED here, so no caller decides for itself whether a name counts.\n   *\n   * A stated name is not an active preview: `previewContainerName` refuses an\n   * empty, reserved, malformed or oversized string, and a refused name makes\n   * the compile published — viewport tiers emit ordinary `@media`, which the\n   * window can answer for. Read raw, every indicator was withheld from surfaces\n   * that were not previewing at all.\n   */\n  const preview = previewContainerName(previewContainer);\n  /*\n   * The emission the sheet was compiled under, carried so this asks the SAME\n   * queries. Without it the window is compared against `@media` rules a preview\n   * compile never wrote, which is not a stale answer but a confident wrong one:\n   * a narrow admin window reports the small breakpoints live while a wide canvas\n   * box is showing the large ones.\n   */\n  const options = React.useMemo(\n    () => (preview === undefined ? undefined : { previewContainer: preview }),\n    [preview]\n  );\n  const never = React.useCallback(() => false, []);\n  const [matches, setMatches] = React.useState<readonly BreakpointId[]>(() =>\n    matchedBreakpoints(breakpoints, never, options)\n  );\n  /*\n   * The CANVAS's window, a frame's when the canvas is in one. A frame is as\n   * wide as the device it previews, so its media queries are the ones the\n   * page's breakpoints answer to; the editor's window is as wide as the\n   * admin, and asking it reports the tiers of a screen nobody is previewing.\n   */\n  const view = useCanvasFrame().window;\n  React.useEffect(() => {\n    // Detected by CALLABILITY rather than presence, the lesson `usePrefersDark`\n    // records: `\"matchMedia\" in window` is true under jsdom while the value is\n    // not a function, so the property test passes and the call throws.\n    if (view === null || typeof view.matchMedia !== \"function\") return;\n    const ask = (query: string): boolean => view.matchMedia(query).matches;\n    const read = (): void =>\n      setMatches(matchedBreakpoints(breakpoints, ask, options));\n    read();\n    /*\n     * Subscribed to every emitted query, not to a resize. A resize fires\n     * continuously and would re-measure on each frame of a drag, while a media\n     * query change event fires exactly when an answer here would differ.\n     */\n    const lists = breakpointQueries(breakpoints, options).map(query =>\n      view.matchMedia(query)\n    );\n    for (const list of lists) list.addEventListener(\"change\", read);\n    return () => {\n      for (const list of lists) list.removeEventListener(\"change\", read);\n    };\n  }, [breakpoints, options, view]);\n  /*\n   * Previewing, the window is not the authority and the host is.\n   *\n   * A `matchMedia` caller cannot evaluate a container query, so under a preview\n   * compile `matches` reduces to the base context alone — which is not silence\n   * but the claim that base is what the browser applies. Whoever owns the box\n   * is the only one that can observe it, so `undefined` there means nobody has\n   * looked yet and the caller must say nothing rather than guess.\n   *\n   * Published, the window IS the authority, and a set the host offers describes\n   * a box that is not deciding anything — so it is ignored rather than\n   * preferred.\n   */\n  return preview === undefined ? matches : stated;\n}\n\n/**\n * The note shown when a block offers no style properties at all.\n *\n * A component rather than a conditional in the panel's own body: the panel\n * decides what to draw, and \"there is nothing to draw\" is this element's own\n * business. It returns nothing when there is something.\n *\n * @param props - how many sections the block offers\n * @returns the note, or nothing\n */\nfunction NoStyleProperties({\n  count,\n}: {\n  count: number;\n}): React.JSX.Element | null {\n  if (count > 0) return null;\n  return (\n    <p className=\"nx-inspector__note\" data-empty=\"no-style-support\">\n      This block does not offer style properties.\n    </p>\n  );\n}\n\n/** The panel-state key for one union position. */\nfunction formKey(property: string, path: readonly string[]): string {\n  return [property, ...path].join(\".\");\n}\n\n/**\n * Why the controls are read-only, above them, for the block. A shared\n * target's reason (locked, or no right to change design) is said in the bar\n * already, and once is enough.\n */\nfunction ReadOnlyNote({\n  target,\n  reason,\n}: {\n  target: StyleTarget;\n  reason: string | undefined;\n}): React.JSX.Element | null {\n  if (reason === undefined || target.kind === \"shared\") return null;\n  return (\n    <p className=\"nx-inspector__note\" data-read-only=\"style\">\n      {reason}\n    </p>\n  );\n}\n\n/**\n * Whether the stored document holds this id more than once.\n *\n * Asked of the STORED document rather than of the cascade's tree, which is the\n * whole point: preparation drops the later duplicate, so the tree the\n * declarations describe never contains one and could never report this.\n *\n * `walkNodes` rather than a walk written here — it is cycle-safe and\n * depth-bounded, and it deliberately visits the same node object twice when it\n * sits in two slots, which is precisely the shape being counted.\n */\nfunction sharesItsId(editor: EditorState, id: string): boolean {\n  let seen = 0;\n  walkNodes(editor.document.nodes, node => {\n    if (node.id === id) seen += 1;\n  });\n  return seen > 1;\n}\n\n/**\n * The edited target's own styles at every state and device, as the controls\n * read them: a shared style's while one is the target, the block's otherwise.\n */\nfunction editedStyles(target: StyleTarget, editor: EditorState): unknown {\n  if (editor.selectedId === null) return undefined;\n  return fieldStyles(target, editor, editor.selectedId).styles;\n}\n","/**\n * Apply a shared style to the selected block: a search field over the site's\n * shared styles, and the list it narrows. The inspector's bar opens it from\n * \"Apply shared style\".\n *\n * A surface over {@link class-library}, which holds every rule this draws, so\n * the rules stay testable without a DOM. It applies existing styles only: a\n * shared style is made from a block (\"Save as shared style…\"), so no typed\n * name becomes an empty one. Removing a style from the block is on its chip\n * in the bar, and renaming is in Design's Shared styles tab.\n *\n * Every control reports an intent and stores nothing: the block's classes are\n * written by the inspector through the editor.\n *\n * @module class-selector\n */\n\nimport type { NamedClass } from \"@nextlyhq/blocks-engine\";\nimport { Input } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  nodeHasRoom,\n  selectorOptions,\n  unappliedNodeClassCount,\n  withClassApplied,\n  type ClassOption,\n} from \"./class-library\";\nimport {\n  searchSharedStyles,\n  sharedStyleRows,\n  sharedStylesOnly,\n  sharedStyleSearchText,\n} from \"./shared-style-library\";\n\n/**\n * Why the last application did not land.\n *\n * - `node-full`: the block already lists as many as the page applies.\n * - `not-written`: the document refused the write (a page at its byte cap).\n */\ntype SelectorFailure = { readonly kind: \"node-full\" | \"not-written\" };\n\n/**\n * The failure to show for this node, or `null` once it no longer describes it.\n *\n * Scoped by BOTH the node and what it holds: two blocks with no classes show\n * the same empty list, and the same block whose classes have since changed has\n * left the state the refusal was raised against.\n */\nfunction liveFailure(\n  failure: {\n    about: string;\n    whenIds: readonly string[];\n    issue: SelectorFailure;\n  } | null,\n  nodeId: string,\n  nodeClassIds: readonly string[]\n): SelectorFailure | null {\n  if (failure === null) return null;\n  if (failure.about !== nodeId) return null;\n  if (!sameClassIds(failure.whenIds, nodeClassIds)) return null;\n  if (failure.issue.kind === \"node-full\" && nodeHasRoom(nodeClassIds)) {\n    return null;\n  }\n  return failure.issue;\n}\n\n/** Two id lists by value, since a caller may hand a fresh `[]` every render. */\nfunction sameClassIds(a: readonly string[], b: readonly string[]): boolean {\n  return a.length === b.length && a.every((id, index) => id === b[index]);\n}\n\n/** What the author is told, per cause. */\nfunction failureMessage(failure: SelectorFailure): string {\n  return failure.kind === \"not-written\"\n    ? \"This change could not be applied to the document.\"\n    : \"This block already lists as many shared styles as the page applies.\";\n}\n\n/** Whether a write to the selected node's classes reached the document. */\nexport type ClassWriteOutcome = \"applied\" | \"refused\";\n\nexport interface ClassSelectorProps {\n  /** Which block this is editing, to scope a refusal to it. */\n  nodeId: string;\n  /**\n   * The site's shared styles, or `undefined` while there are none to show:\n   * a read in flight or one that failed, which\n   * {@link ClassSelectorProps.libraryAbsence} tells apart.\n   */\n  library: readonly NamedClass[] | undefined;\n  /** Why there is no library, when there is none. */\n  libraryAbsence?: \"pending\" | \"failed\";\n  /** The class ids the selected node carries, as stored. */\n  nodeClassIds: readonly string[];\n  /**\n   * The node's classes after an apply, and whether it landed: the document\n   * can refuse a write these rules cannot anticipate, and the typed query is\n   * kept when it does.\n   */\n  onNodeClassesChange: (classIds: string[]) => ClassWriteOutcome;\n  /** Focus the search field when it mounts, as a picker just opened does. */\n  autoFocus?: boolean;\n}\n\n/** A search over the site's shared styles that applies the one chosen. */\nexport function ClassSelector({\n  nodeId,\n  library,\n  libraryAbsence,\n  nodeClassIds,\n  onNodeClassesChange,\n  autoFocus = false,\n}: ClassSelectorProps): React.ReactElement {\n  const [query, setQuery] = React.useState(\"\");\n  const [active, setActive] = React.useState(0);\n  const [failure, setFailure] = React.useState<{\n    readonly about: string;\n    readonly whenIds: readonly string[];\n    readonly issue: SelectorFailure;\n  } | null>(null);\n  const listId = React.useId();\n  // The shared styles any block may wear; a look is picked from its tiles.\n  const offered = React.useMemo(\n    () => (library === undefined ? undefined : sharedStylesOnly(library)),\n    [library]\n  );\n  const matches = useStyleSearch(offered, query);\n\n  // Cleared, not merely hidden, once it stops describing the node: React's\n  // adjust-state-during-render, which converges once the state is null.\n  if (failure !== null && liveFailure(failure, nodeId, nodeClassIds) === null) {\n    setFailure(null);\n  }\n\n  if (library === undefined) {\n    return (\n      <div className=\"nx-classes\">\n        <p className=\"nx-inspector__note\">\n          {libraryAbsence === \"failed\"\n            ? \"This site's shared styles could not be read.\"\n            : \"Loading shared styles…\"}\n        </p>\n      </div>\n    );\n  }\n\n  const { options, hidden } = selectorOptions(\n    offered ?? library,\n    nodeClassIds,\n    matches\n  );\n  const unapplied = unappliedNodeClassCount(nodeClassIds);\n  const shown = liveFailure(failure, nodeId, nodeClassIds);\n  // Clamped rather than reset on every keystroke, so narrowing the list keeps\n  // a highlight instead of sending Enter back to the first row.\n  const highlighted = Math.min(active, Math.max(options.length - 1, 0));\n  const nameOf = (option: ClassOption): string => styleName(library, option);\n\n  const commit = (option: ClassOption | undefined): void => {\n    if (option === undefined) return;\n    // The per-node bound lives in one place, asked rather than restated.\n    const outcome = withClassApplied(nodeClassIds, option.choice.id);\n    if (!outcome.ok) {\n      setFailure({\n        about: nodeId,\n        whenIds: nodeClassIds,\n        issue: { kind: \"node-full\" },\n      });\n      return;\n    }\n    if (onNodeClassesChange(outcome.classIds) === \"refused\") {\n      // The query survives: nothing the author typed is lost to a refusal.\n      setFailure({\n        about: nodeId,\n        whenIds: nodeClassIds,\n        issue: { kind: \"not-written\" },\n      });\n      return;\n    }\n    setFailure(null);\n    setQuery(\"\");\n    setActive(0);\n  };\n\n  return (\n    <div className=\"nx-classes\">\n      <Input\n        className=\"nx-classes__query\"\n        value={query}\n        role=\"combobox\"\n        autoFocus={autoFocus}\n        aria-expanded={options.length > 0}\n        aria-controls={listId}\n        aria-activedescendant={\n          options.length > 0 ? optionDomId(listId, highlighted) : undefined\n        }\n        aria-label=\"Search shared styles\"\n        placeholder=\"Search shared styles…\"\n        onChange={event => {\n          setQuery(event.target.value);\n          setActive(0);\n        }}\n        onKeyDown={event =>\n          handleKey(event, {\n            count: options.length,\n            highlighted,\n            setActive,\n            commit: () => commit(options[highlighted]),\n          })\n        }\n      />\n      <OptionList\n        id={listId}\n        options={options}\n        highlighted={highlighted}\n        nameOf={nameOf}\n        onChoose={commit}\n        onHighlight={setActive}\n      />\n      <SelectorNotes\n        empty={options.length === 0}\n        searched={query.trim() !== \"\"}\n        hidden={hidden}\n        failure={shown}\n        unapplied={unapplied}\n      />\n    </div>\n  );\n}\n\n/** A style as the Shared styles tab names it: its label, else its slug. */\nfunction styleName(\n  library: readonly NamedClass[],\n  option: ClassOption\n): string {\n  const label = library\n    .find(entry => entry.id === option.choice.id)\n    ?.label?.trim();\n  return label === undefined || label === \"\" ? option.choice.slug : label;\n}\n\n/** What the picker says under its list: nothing to show, more, or a refusal. */\nfunction SelectorNotes({\n  empty,\n  searched,\n  hidden,\n  failure,\n  unapplied,\n}: {\n  empty: boolean;\n  searched: boolean;\n  hidden: number;\n  failure: SelectorFailure | null;\n  unapplied: number;\n}): React.ReactElement {\n  return (\n    <>\n      {empty ? (\n        <p className=\"nx-inspector__note\">\n          {searched\n            ? \"No shared style matches.\"\n            : \"This site has no other shared styles yet.\"}\n        </p>\n      ) : null}\n      {hidden > 0 ? (\n        <p className=\"nx-inspector__note\">\n          {`${hidden} more — keep typing to narrow the list.`}\n        </p>\n      ) : null}\n      {failure !== null ? (\n        <p className=\"nx-classes__issue\" role=\"alert\">\n          {failureMessage(failure)}\n        </p>\n      ) : null}\n      {unapplied > 0 ? (\n        <p className=\"nx-classes__issue\" role=\"status\">\n          {`This block lists ${unapplied} more shared ${unapplied === 1 ? \"style\" : \"styles\"} than the page applies. They style nothing, and removing one can bring another into use.`}\n        </p>\n      ) : null}\n    </>\n  );\n}\n\n/**\n * Which styles a query finds, by the Shared styles tab's own search: the name\n * as written and the class name, and any property or value, with case,\n * spaces and dashes aside. One rule, so a style is found the same way in the\n * tab and here. The searchable text is built once per library.\n */\nfunction useStyleSearch(\n  library: readonly NamedClass[] | undefined,\n  query: string\n): (choice: { id: string }) => boolean {\n  const rows = React.useMemo(\n    () => (library === undefined ? [] : sharedStyleRows(library, NO_IDS)),\n    [library]\n  );\n  const texts = React.useMemo(\n    () => new Map(rows.map(row => [row.id, sharedStyleSearchText(row)])),\n    [rows]\n  );\n  const found = new Set(\n    searchSharedStyles(rows, query, row => texts.get(row.id) ?? \"\").map(\n      row => row.id\n    )\n  );\n  return choice => found.has(choice.id);\n}\n\n/** No code-supplied ids: the picker lists what may be applied, from anywhere. */\nconst NO_IDS: ReadonlySet<string> = new Set();\n\n/** The DOM id of one option row, for `aria-activedescendant`. */\nfunction optionDomId(listId: string, index: number): string {\n  return `${listId}-option-${index}`;\n}\n\n/** The field's keys: arrows move the highlight, wrapping; Enter applies it. */\nfunction handleKey(\n  event: React.KeyboardEvent<HTMLInputElement>,\n  ctx: {\n    count: number;\n    highlighted: number;\n    setActive: (next: number) => void;\n    commit: () => void;\n  }\n): void {\n  if (ctx.count === 0) return;\n  if (event.key === \"ArrowDown\") {\n    event.preventDefault();\n    ctx.setActive((ctx.highlighted + 1) % ctx.count);\n    return;\n  }\n  if (event.key === \"ArrowUp\") {\n    event.preventDefault();\n    ctx.setActive((ctx.highlighted - 1 + ctx.count) % ctx.count);\n    return;\n  }\n  if (event.key === \"Enter\") {\n    event.preventDefault();\n    ctx.commit();\n  }\n}\n\n/** The styles the query matches, in the order Enter would take them. */\nfunction OptionList({\n  id,\n  options,\n  highlighted,\n  nameOf,\n  onChoose,\n  onHighlight,\n}: {\n  id: string;\n  options: readonly ClassOption[];\n  highlighted: number;\n  nameOf: (option: ClassOption) => string;\n  onChoose: (option: ClassOption) => void;\n  onHighlight: (index: number) => void;\n}): React.ReactElement | null {\n  if (options.length === 0) return null;\n  return (\n    <ul className=\"nx-classes__options\" id={id} role=\"listbox\">\n      {options.map((option, index) => (\n        <li\n          key={option.choice.id}\n          id={optionDomId(id, index)}\n          role=\"option\"\n          // Not in the tab sequence: with `aria-activedescendant` focus stays\n          // in the field and the arrows move the active row.\n          tabIndex={-1}\n          aria-selected={index === highlighted}\n          className={\n            index === highlighted\n              ? \"nx-classes__option nx-classes__option--active\"\n              : \"nx-classes__option\"\n          }\n          onMouseEnter={() => onHighlight(index)}\n          onClick={() => onChoose(option)}\n        >\n          {/*\n           * The name in the interface's own type and the class name in mono, each\n           * cut short rather than broken mid-word, the whole of it in a tooltip.\n           */}\n          <span className=\"nx-classes__option-name\" title={nameOf(option)}>\n            {nameOf(option)}\n          </span>\n          <code\n            className=\"nx-classes__option-class\"\n            title={`.${option.choice.className}`}\n          >\n            .{option.choice.className}\n          </code>\n        </li>\n      ))}\n    </ul>\n  );\n}\n","\"use client\";\n\n/**\n * What the Style tab edits, and the bar that chooses it.\n *\n * A style edit writes to the selected block unless the author has chosen one\n * of the shared styles it wears as the target. The choice is held here, per\n * block (selecting another block returns to \"This block\"), and handed both to\n * the bar, which shows and changes it, and to the style controls, which read\n * and write the target's values. One holder, so the bar and the controls can\n * never disagree about what an edit changes.\n *\n * The bar's target menu's actions live here too: applying an existing shared\n * style to a block that wears none, \"Save as shared style…\" (the block verb\n * every menu offers), and each worn style's Detach and Remove, all page edits\n * through the editor.\n *\n * @module style-target\n */\n\nimport type {\n  BreakpointSet,\n  NamedClass,\n  NodeStyles,\n  SiteTokenSet,\n  StyleState,\n  TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport { findNode, getBlock } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport type {\n  PageClassBlocks,\n  SharedStylesAccess,\n} from \"../../panels/design/shared-styles-panel\";\nimport { useSurvivingReport } from \"../../shell/builder-notices\";\nimport { ClassSelector } from \"../../styles/class-selector\";\nimport {\n  sharedStyleReachSentence,\n  type SharedStyleReach,\n  type SharedStyleRow,\n} from \"../../styles/shared-style-library\";\nimport {\n  nodeSharedStyles,\n  planDetachSharedStyle,\n  planRemoveSharedStyle,\n  NO_DESIGN_RIGHT,\n  type SharedStyleChange,\n} from \"../../styles/shared-style-target\";\nimport type { CardVerbs } from \"../block-card\";\nimport { designReadOnlyReason, lockViewOf } from \"../inspector\";\n\nimport {\n  type ApplyOffer,\n  type BarOffer,\n  EditingBar,\n  type EditingBarChip,\n  type EditTarget,\n} from \"./editing-bar\";\nimport { lookLineWords } from \"./look-tiles\";\nimport { LookTiles } from \"./look-tiles-view\";\n\n/**\n * What the host lends the Style tab for shared styles.\n *\n * @experimental Settles with the shared-styles editor.\n */\nexport interface SharedStylesHost {\n  /** Whether the author may change the site's design (`update-site-style`). */\n  readonly mayChange: boolean;\n  /**\n   * Apply one change to a shared style's styles and store them. The host\n   * applies it to the styles as they stand after every write it has queued,\n   * so two edits made before the first is stored both survive. Resolves to the\n   * refusal in words, or `undefined` once stored (or when nothing changed).\n   */\n  readonly writeStyles: (\n    classId: string,\n    change: SharedStyleChange\n  ) => Promise<string | undefined>;\n  /** How widely styles are used across the site, for the target's reach. */\n  readonly usage?: SharedStylesAccess[\"usage\"];\n  /** The blocks on the open page wearing each style. */\n  readonly pageBlocks?: PageClassBlocks;\n}\n\n/**\n * What the style controls edit.\n *\n * `worn` is every shared style the block wears, so a control can say a value\n * comes from one, or that the block overrides one.\n */\nexport type StyleTarget =\n  | { readonly kind: \"block\"; readonly worn: readonly SharedStyleRow[] }\n  | {\n      readonly kind: \"shared\";\n      readonly worn: readonly SharedStyleRow[];\n      readonly style: SharedStyleRow;\n      /** Why its values can't be changed, when they can't. */\n      readonly readOnly: string | undefined;\n      /** Apply a change to its styles and store it; resolves to the refusal, or nothing. */\n      readonly write: (\n        change: SharedStyleChange\n      ) => Promise<string | undefined>;\n    };\n\n/** The words for a locked shared style's values. */\nfunction lockedStyleReason(name: string): string {\n  return `${name} is locked. Its properties can't be changed.`;\n}\n\n/** Nothing worn, as one value rather than a fresh array each render. */\nconst NONE: readonly SharedStyleRow[] = Object.freeze([]);\n\n/**\n * The target for the selected block: the chosen shared style while the block\n * still wears it, else the block. Keyed by block, so the choice never travels\n * to the next selection.\n */\nexport function useStyleTarget(\n  editor: EditorState,\n  library: readonly NamedClass[] | undefined,\n  host: SharedStylesHost | undefined\n): {\n  target: StyleTarget;\n  choose: (id: string | null) => void;\n  /**\n   * Why the selected block's design is held, or `undefined`: the one\n   * reading the target falls back on and the bar holds its chips by, so\n   * what an author may choose and where an edit goes cannot disagree.\n   */\n  held: string | undefined;\n} {\n  const nodeId = editor.selectedId;\n  const [chosen, setChosen] = React.useState<{\n    nodeId: string;\n    id: string;\n  } | null>(null);\n  const node =\n    nodeId === null ? undefined : findNode(editor.document.nodes, nodeId);\n  const worn =\n    library === undefined || node === undefined\n      ? NONE\n      : nodeSharedStyles(library, node.classes ?? []);\n  const choose = React.useCallback(\n    (id: string | null) => {\n      setChosen(id === null || nodeId === null ? null : { nodeId, id });\n    },\n    [nodeId]\n  );\n  // A block whose design is held (locked, or inside contentOnly) keeps the\n  // block as the target: its shared style's values are its design here, and\n  // editing them from this block would change that design all the same. A\n  // choice made before the hold landed falls back with it.\n  const held =\n    nodeId === null\n      ? undefined\n      : designReadOnlyReason(editor.document, nodeId, lockViewOf(editor));\n  const read =\n    chosen !== null &&\n    chosen.nodeId === nodeId &&\n    host !== undefined &&\n    held === undefined\n      ? worn.find(row => row.id === chosen.id)\n      : undefined;\n  const queued = useQueuedStyles(read, host);\n  if (read === undefined || host === undefined || queued === undefined) {\n    return { target: { kind: \"block\", worn }, choose, held };\n  }\n  return {\n    target: {\n      kind: \"shared\",\n      worn,\n      style: queued.style,\n      readOnly: !host.mayChange\n        ? NO_DESIGN_RIGHT\n        : read.locked\n          ? lockedStyleReason(read.name)\n          : undefined,\n      write: queued.write,\n    },\n    choose,\n    held,\n  };\n}\n\n/**\n * The target for a look edited on its own, with no block selected: the look,\n * read and written as a shared style is, its edits queued the same way.\n * `undefined` while there is no look, or no host to store it.\n *\n * @experimental Settles with the Design panel's Block looks group.\n */\nexport function useLookTarget(\n  look: SharedStyleRow | undefined,\n  host: SharedStylesHost | undefined\n): StyleTarget | undefined {\n  const queued = useQueuedStyles(look, host);\n  if (look === undefined || host === undefined || queued === undefined) {\n    return undefined;\n  }\n  return {\n    kind: \"shared\",\n    worn: NONE,\n    style: queued.style,\n    readOnly: !host.mayChange\n      ? NO_DESIGN_RIGHT\n      : look.locked\n        ? lockedStyleReason(look.name)\n        : undefined,\n    write: queued.write,\n  };\n}\n\n/**\n * The target's styles as the edits queued since the last read leave them,\n * and the write that queues one.\n *\n * Every write still goes to the host as an address-level change, which the\n * host applies to what it has queued and judges unchanged or not there. The\n * controls show the edits on their way, so a value changed and changed back\n * before the first is read back is a change to the field (and so a write)\n * rather than a match with the stale read. A new read replaces them. A\n * refused edit stays shown, with its refusal beside the field, as a refused\n * block edit keeps the author's draft, until the next read. Design's text\n * styles are edited through it too.\n */\nexport function useQueuedStyles(\n  read: SharedStyleRow | undefined,\n  host: SharedStylesHost | undefined\n):\n  | {\n      style: SharedStyleRow;\n      write: (change: SharedStyleChange) => Promise<string | undefined>;\n    }\n  | undefined {\n  const [queued, setQueued] = React.useState<{\n    id: string;\n    over: NodeStyles;\n    styles: NodeStyles;\n  } | null>(null);\n  const write = React.useCallback(\n    (change: SharedStyleChange): Promise<string | undefined> => {\n      if (read === undefined || host === undefined) {\n        return Promise.resolve(\"This shared style is no longer the target.\");\n      }\n      setQueued(current => {\n        const base =\n          current !== null &&\n          current.id === read.id &&\n          current.over === read.styles\n            ? current.styles\n            : read.styles;\n        const next = change(base);\n        return next.kind === \"write\"\n          ? { id: read.id, over: read.styles, styles: next.styles }\n          : current;\n      });\n      return host.writeStyles(read.id, change);\n    },\n    [read, host]\n  );\n  if (read === undefined) return undefined;\n  // Only while the read they were made over is still the read in hand.\n  const showing =\n    queued !== null && queued.id === read.id && queued.over === read.styles\n      ? { ...read, styles: queued.styles }\n      : read;\n  return { style: showing, write };\n}\n\n/**\n * How widely a style reaches, in words, while it is the target: the blocks on\n * this page, then the documents the site's index counts. Read when the\n * target changes; \"\" until something is known.\n */\nfunction useReachSentence(\n  id: string | undefined,\n  host: SharedStylesHost | undefined\n): string {\n  const usage = host?.usage;\n  const [reach, setReach] = React.useState<{\n    id: string;\n    reach: SharedStyleReach;\n  } | null>(null);\n  React.useEffect(() => {\n    if (id === undefined || usage === undefined) return;\n    const controller = new AbortController();\n    usage([id], controller.signal).then(\n      answer => {\n        const found = answer.styles.get(id);\n        if (found !== undefined) setReach({ id, reach: found });\n      },\n      // A failed read leaves the reach unsaid rather than guessed: the page\n      // count below still stands on its own.\n      () => undefined\n    );\n    return () => controller.abort();\n  }, [id, usage]);\n  if (id === undefined) return \"\";\n  const pageBlocks = host?.pageBlocks;\n  const blocks =\n    pageBlocks === undefined\n      ? undefined\n      : {\n          count: pageBlocks.counts.get(id) ?? 0,\n          complete: pageBlocks.complete,\n        };\n  return sharedStyleReachSentence(\n    blocks,\n    reach?.id === id ? reach.reach : undefined\n  );\n}\n\n/** The bar's target, as it says it. */\nfunction editTargetOf(target: StyleTarget, reach: string): EditTarget {\n  if (target.kind === \"block\") return { kind: \"block\" };\n  return {\n    kind: \"shared\",\n    id: target.style.id,\n    name: target.style.name,\n    className: target.style.className,\n    reach,\n  };\n}\n\nexport interface StyleTargetBarProps {\n  readonly editor: EditorState;\n  readonly target: StyleTarget;\n  readonly onChoose: (id: string | null) => void;\n  /** Why the block's design is held, as {@link useStyleTarget} read it. */\n  readonly held: string | undefined;\n  readonly library: readonly NamedClass[] | undefined;\n  /** The site's tokens, for drawing the look tiles as the canvas shows them. */\n  readonly tokens?: SiteTokenSet;\n  /** The mode the selected block is drawn in, which the tiles draw in. */\n  readonly tokenMode: TokenMode;\n  readonly libraryAbsence?: \"pending\" | \"failed\";\n  readonly host: SharedStylesHost | undefined;\n  /** The shared block verbs, for \"Save as shared style…\". */\n  readonly verbs: CardVerbs | undefined;\n  /** The device the canvas shows: \"Desktop\". */\n  readonly device: string;\n  /** The devices an edit reaches, in words: \"All devices\". */\n  readonly deviceReach?: string;\n  /** The device's glyph, as the top bar draws it. */\n  readonly deviceIcon?: React.ComponentType<{ className?: string }>;\n  /** The site's breakpoints, so Detach weighs a later style's narrower values. */\n  readonly breakpoints?: BreakpointSet;\n  readonly state: StyleState;\n  readonly stateControl?: React.ReactNode;\n  /** Opens Design's Block styles at a block type, from under the tiles. */\n  readonly onEditBlockStyles?: ((blockType: string) => void) | undefined;\n}\n\n/**\n * Apply the ops of a chip's page edit, or say why not: the plan's refusal\n * (the block's lock), or the page refusing the change (its limits). Said\n * through the shell, since the menu that asked has closed.\n */\nfunction applyPlan(\n  editor: EditorState,\n  plan: { ok: true; ops: BuilderOp[] } | { ok: false; reason: string },\n  refusedWords: string,\n  report: (reason: string) => void\n): void {\n  if (!plan.ok) {\n    report(plan.reason);\n    return;\n  }\n  if (editor.applyAll(plan.ops) === null) report(refusedWords);\n}\n\n/**\n * Each chip's menu actions, page edits through the editor: take the style off\n * the block, or detach it (the block keeps the look the worn styles give it).\n * None without a selected block.\n */\nfunction chipActions(\n  editor: EditorState,\n  nodeId: string | null,\n  worn: readonly SharedStyleRow[],\n  report: (reason: string) => void,\n  breakpoints: BreakpointSet | undefined\n): {\n  onRemove?: (id: string) => void;\n  onDetach?: (id: string) => void;\n  detachHeld?: (id: string) => string | undefined;\n} {\n  if (nodeId === null) return {};\n  return {\n    onRemove: id =>\n      applyPlan(\n        editor,\n        planRemoveSharedStyle(editor.document, nodeId, id, lockViewOf(editor)),\n        `${nameOf(worn, id)} could not be taken off this block: the page could not take the change.`,\n        report\n      ),\n    onDetach: id => {\n      const plan = detachPlan(id);\n      if (plan === undefined) return;\n      applyPlan(\n        editor,\n        plan,\n        `${nameOf(worn, id)} could not be detached from this block: the page could not take the change.`,\n        report\n      );\n    },\n    // The same plan, read before the click, so a refusal holds the item.\n    detachHeld: id => {\n      const plan = detachPlan(id);\n      return plan === undefined || plan.ok ? undefined : plan.reason;\n    },\n  };\n  function detachPlan(id: string) {\n    const style = worn.find(row => row.id === id);\n    if (style === undefined || nodeId === null) return undefined;\n    return planDetachSharedStyle(\n      editor.document,\n      nodeId,\n      style,\n      worn,\n      lockViewOf(editor),\n      breakpoints\n    );\n  }\n}\n\n/** A worn style's name by its id, for words about it. */\nfunction nameOf(worn: readonly SharedStyleRow[], id: string): string {\n  return worn.find(row => row.id === id)?.name ?? \"This shared style\";\n}\n\n/**\n * The Block style section, then the \"what you're editing\" bar under it, over\n * the target this tab holds.\n */\nexport function StyleTargetBar({\n  editor,\n  target,\n  onChoose,\n  held,\n  library,\n  libraryAbsence,\n  host,\n  verbs,\n  breakpoints,\n  tokens,\n  tokenMode,\n  onEditBlockStyles,\n  // The device and the state, the canvas's own, handed to the bar whole.\n  ...context\n}: StyleTargetBarProps): React.JSX.Element {\n  const nodeId = editor.selectedId;\n  // The bar has no line of its own for a refusal, so it speaks through the\n  // shell's notices, which outlive the menu that asked.\n  const survive = useSurvivingReport();\n  const report = (reason: string): void => survive(reason, () => false);\n  const shared = target.kind === \"shared\" ? target : undefined;\n  const reach = useReachSentence(shared?.style.id, host);\n  const worn = target.worn;\n  return (\n    <>\n      <LookTiles\n        editor={editor}\n        library={library}\n        held={held}\n        tokens={tokens}\n        mode={tokenMode}\n        onRefused={report}\n        onEditBlockStyles={onEditBlockStyles}\n      />\n      <EditingBar\n        {...context}\n        target={editTargetOf(target, reach)}\n        chips={barChips(editor, nodeId, worn)}\n        // Without a host there is nowhere to write a shared style's values.\n        {...(host === undefined ? {} : { onTargetChange: onChoose })}\n        {...chipActions(editor, nodeId, worn, report, breakpoints)}\n        chipActionsHeld={held}\n        // The shared styles too: choosing one would edit the held design.\n        targetHeld={held}\n        sharedReadOnly={shared?.readOnly}\n        apply={applyOffer({\n          editor,\n          nodeId,\n          worn,\n          held,\n          library,\n          libraryAbsence,\n        })}\n        save={saveOffer(verbs)}\n      />\n    </>\n  );\n}\n\n/**\n * The worn styles as the target menu lists them. A block style says what\n * choosing it does (\"Edit Outline for every button that uses it\"), since an\n * edit to it reaches every block of the type that wears it.\n */\nfunction barChips(\n  editor: EditorState,\n  nodeId: string | null,\n  worn: readonly SharedStyleRow[]\n): EditingBarChip[] {\n  const node =\n    nodeId === null ? undefined : findNode(editor.document.nodes, nodeId);\n  const label =\n    node === undefined\n      ? \"block\"\n      : (getBlock(node.type)?.editor?.label ?? \"block\");\n  // A text style is chosen and changed from the Text section's picker, so\n  // it is no target here: its values are typography alone.\n  return worn\n    .filter(row => row.text !== true)\n    .map(row => ({\n      id: row.id,\n      name: row.name,\n      className: row.className,\n      locked: row.locked,\n      ...(row.look === true\n        ? { hint: lookLineWords(row.name, label).everywhere }\n        : {}),\n    }));\n}\n\n/** Why \"Save as shared style…\" is held where the host offers no save. */\nconst NO_SAVE = \"Shared styles can't be saved here.\";\n\n/**\n * \"Save as shared style…\": the block verb every menu runs, held with the\n * reason its rule gives, so the bar and the block's ⋯ menu agree.\n */\nfunction saveOffer(verbs: CardVerbs | undefined): BarOffer {\n  const save = verbs?.actions.find(\n    action => action.id === \"save-as-shared-style\"\n  );\n  if (verbs === undefined || save === undefined) return { held: NO_SAVE };\n  if (!save.enabled) return { held: save.reason ?? NO_SAVE };\n  return { run: () => verbs.run(\"save-as-shared-style\") };\n}\n\n/**\n * \"Apply a shared style…\": the site's styles to choose from, for a block that\n * wears no shared style and whose design isn't held. One per block in the\n * first release; a block style is worn beside one, so it holds nothing.\n */\nfunction applyOffer({\n  editor,\n  nodeId,\n  worn,\n  held,\n  library,\n  libraryAbsence,\n}: {\n  editor: EditorState;\n  nodeId: string | null;\n  worn: readonly SharedStyleRow[];\n  held: string | undefined;\n  library: readonly NamedClass[] | undefined;\n  libraryAbsence: \"pending\" | \"failed\" | undefined;\n}): ApplyOffer {\n  // A block style and a text style are worn beside a shared style.\n  const wearing = worn.find(row => row.look !== true && row.text !== true);\n  if (nodeId === null) return { held: \"Select a block first.\" };\n  if (held !== undefined) return { held };\n  if (wearing !== undefined) {\n    return { held: `This block already uses ${wearing.name}.` };\n  }\n  const nodeClassIds = findNode(editor.document.nodes, nodeId)?.classes ?? [];\n  return {\n    // Opened from the chip itself, once the menu has closed.\n    picker: close => (\n      <ClassSelector\n        key={nodeId}\n        nodeId={nodeId}\n        library={library}\n        libraryAbsence={libraryAbsence}\n        nodeClassIds={nodeClassIds}\n        autoFocus\n        onNodeClassesChange={classIds => {\n          // Asked of the live document at the moment of the write.\n          if (\n            designReadOnlyReason(\n              editor.document,\n              nodeId,\n              lockViewOf(editor)\n            ) !== undefined\n          ) {\n            return \"refused\";\n          }\n          const applied = editor.applyAll([\n            { kind: \"update\", id: nodeId, patch: { classes: classIds } },\n          ]);\n          if (applied === null) return \"refused\";\n          close();\n          return \"applied\";\n        }}\n      />\n    ),\n  };\n}\n","\"use client\";\n\n/**\n * The inspector's Style tab: the bar that says what an edit changes, on which\n * device and in which state, then the style controls themselves. While a\n * state other than Normal is edited, the controls sit on a tint of the\n * state's amber under a line that says so, so an author scrolled deep into\n * the tab still sees they are not editing the normal look.\n *\n * @module inspector-style-tab\n */\n\nimport {\n  BASE_BREAKPOINT,\n  breakpointContexts,\n  type BreakpointId,\n  type BreakpointSet,\n  type NodeStyles,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { useCanvasTokenModeAt } from \"../canvas/prefers-dark\";\nimport type { CanvasReading } from \"../canvas/use-canvas-reading\";\nimport { deviceOptions, tierIcon } from \"../shell/breakpoint-switcher\";\n\nimport type { selectedNode } from \"./inspector\";\nimport type {\n  InspectorPanelProps,\n  StyleStateBinding,\n} from \"./inspector-panel-types\";\nimport { editedStyleState } from \"./inspector-style-state\";\nimport { FirstSectionAbove } from \"./panel-folds-context\";\nimport { stateLookLine } from \"./style-inspector/editing-bar\";\nimport { FocalFrame } from \"./style-inspector/focal-frame\";\nimport {\n  blockStyleTilesOf,\n  RenderedSample,\n  type BlockSample,\n} from \"./style-inspector/look-tiles-view\";\nimport {\n  RenderedLengths,\n  type RenderedLengthsValue,\n} from \"./style-inspector/rendered-lengths\";\nimport { StyleStateField } from \"./style-inspector/state-switcher\";\nimport {\n  breakpointLabel,\n  StyleInspectorPanel,\n  type StyleInspectorPanelProps,\n} from \"./style-inspector/style-inspector-panel\";\nimport { StyleTargetBar, useStyleTarget } from \"./style-inspector/style-target\";\n\n/** No sizes read: the block isn't drawn, or not yet. */\nconst NO_LENGTHS: RenderedLengthsValue = {};\n\n/**\n * Where an edit lands, as the bar's device chip says it: the device the top\n * bar shows, named and drawn as the top bar names and draws it, and the\n * devices the value reaches, in words rather than as a breakpoint's id.\n */\nfunction barPlace(\n  breakpoints: BreakpointSet | undefined,\n  breakpoint: BreakpointId | undefined\n): {\n  device: string;\n  deviceReach: string;\n  deviceIcon: React.ComponentType<{ className?: string }>;\n} {\n  const id = breakpoint ?? BASE_BREAKPOINT;\n  // The top bar's own list, so the chip says what the switcher says; a\n  // container tier, which it does not offer, goes by its definition's label.\n  const option = deviceOptions(breakpoints).find(each => each.id === id);\n  return {\n    device: option?.label ?? breakpointLabel(breakpoints, id),\n    deviceReach: editReach(breakpoints, id),\n    // The base is drawn as a screen, as the top bar draws it.\n    deviceIcon: tierIcon(id === BASE_BREAKPOINT ? undefined : option?.preview),\n  };\n}\n\n/**\n * The State menu the bar carries, bound to the host's choice, or nothing when\n * the host cannot act on one. Its dots read the TARGET's styles (the block's,\n * or the shared style being edited), so a state is marked where the edit goes.\n */\nfunction stateControlFor(\n  state: StyleState,\n  styleState: StyleStateBinding | undefined,\n  holder: { styles?: NodeStyles } | null,\n  breakpoints: BreakpointSet | undefined\n): React.JSX.Element | undefined {\n  if (styleState?.onChange === undefined) return undefined;\n  return (\n    <StyleStateField\n      state={state}\n      onSelect={styleState.onChange}\n      node={holder}\n      breakpoints={breakpoints}\n    />\n  );\n}\n\n/**\n * The Style tab: the bar that says what an edit changes, then the style\n * controls themselves.\n */\nexport function StyleTab({\n  editor,\n  styleNode,\n  renderedTag,\n  rendered,\n  sideOrientation,\n  styleState,\n  policy,\n  breakpoint,\n  cascade,\n  breakpoints,\n  previewContainer,\n  liveBreakpoints,\n  onJumpToBreakpoint,\n  tokens,\n  fonts,\n  // The bar's own inputs, kept together: the library, the host and the verbs.\n  ...shared\n}: Pick<\n  InspectorPanelProps,\n  | \"editor\"\n  | \"styleState\"\n  | \"policy\"\n  | \"breakpoint\"\n  | \"cascade\"\n  | \"breakpoints\"\n  | \"previewContainer\"\n  | \"liveBreakpoints\"\n  | \"onJumpToBreakpoint\"\n  | \"tokens\"\n  | \"classLibrary\"\n  | \"classLibraryAbsence\"\n  | \"sharedStyles\"\n  | \"verbs\"\n  | \"fonts\"\n  | \"onEditBlockStyles\"\n> & {\n  styleNode: ReturnType<typeof selectedNode>;\n  renderedTag: StyleInspectorPanelProps[\"renderedTag\"];\n  /** What the canvas draws of the block: its picture, where it places it, and its quotation. */\n  rendered: Pick<\n    CanvasReading,\n    \"picture\" | \"picturePosition\" | \"words\" | \"lengths\"\n  >;\n  sideOrientation: StyleInspectorPanelProps[\"sideOrientation\"];\n}): React.JSX.Element {\n  const state = editedStyleState(styleState);\n  // ONE holder of what an edit changes, read by the bar and the controls.\n  const { target, choose, held } = useStyleTarget(\n    editor,\n    shared.classLibrary,\n    shared.sharedStyles\n  );\n  // The mode the selected block is drawn in, read once for the look tiles and\n  // the controls below, so the canvas is watched by one subscription.\n  const tokenMode = useCanvasTokenModeAt(editor.selectedId);\n  // The state switch for what the bar edits: a shared style's own values\n  // while one is edited, the block's otherwise.\n  const stateControl = stateControlFor(\n    state,\n    styleState,\n    target.kind === \"shared\" ? target.style : styleNode,\n    breakpoints\n  );\n  return (\n    <>\n      {/*\n      ABOVE the controls, because it decides what every one of them reads\n      and writes. Below them it would be a filter applied after the fact,\n      and an author would have edited a value before meeting the thing\n      that says which state the value belongs to.\n    */}\n      <SampledBar\n        rendered={{ picture: rendered.picture, words: rendered.words }}\n        editor={editor}\n        tokens={tokens}\n        tokenMode={tokenMode}\n        target={target}\n        onChoose={choose}\n        held={held}\n        library={shared.classLibrary}\n        libraryAbsence={shared.classLibraryAbsence}\n        host={shared.sharedStyles}\n        verbs={shared.verbs}\n        // \"Edit block styles\", under the Block style tiles, where the host\n        // can open Design.\n        onEditBlockStyles={shared.onEditBlockStyles}\n        {...barPlace(breakpoints, breakpoint)}\n        breakpoints={breakpoints}\n        state={state}\n        stateControl={stateControl}\n      />\n      {/* The Block style section above the bar is the tab's first where it\n        is drawn, so the first section under the bar does not also open for\n        being first. */}\n      <FirstSectionAbove.Provider\n        value={blockStyleTilesOf(editor, shared.classLibrary) !== undefined}\n      >\n        <StateTinted state={state}>\n          {/* The picture the canvas draws, for the focal point aimed over it. */}\n          <FocalFrame.Provider\n            value={{\n              picture: rendered.picture,\n              position: rendered.picturePosition,\n            }}\n          >\n            {/* The sizes the block is drawn at, for a size field a variable\n                reaches (Site text's): shown as that size, never as its CSS. */}\n            <RenderedLengths.Provider value={rendered.lengths ?? NO_LENGTHS}>\n              <StyleInspectorPanel\n                editor={editor}\n                tokenMode={tokenMode}\n                // The block card above says why a held block can't be changed.\n                showReadOnlyReason={false}\n                renderedTag={renderedTag}\n                sideOrientation={sideOrientation}\n                policy={policy}\n                state={state}\n                breakpoint={breakpoint}\n                cascade={cascade}\n                breakpoints={breakpoints}\n                previewContainer={previewContainer}\n                liveBreakpoints={liveBreakpoints}\n                onJumpToBreakpoint={onJumpToBreakpoint}\n                tokens={tokens}\n                target={target}\n                fonts={fonts}\n                // The Text section's \"Text style\" picker lists from it.\n                classLibrary={shared.classLibrary}\n              />\n            </RenderedLengths.Provider>\n          </FocalFrame.Provider>\n        </StateTinted>\n      </FirstSectionAbove.Provider>\n    </>\n  );\n}\n\n/**\n * The bar, with what the canvas draws of the block (its picture and its\n * quotation) handed to the Block style tiles in it, which draw it in each\n * style.\n */\nfunction SampledBar({\n  rendered,\n  ...bar\n}: React.ComponentProps<typeof StyleTargetBar> & {\n  readonly rendered: BlockSample;\n}): React.JSX.Element {\n  return (\n    <RenderedSample.Provider value={rendered}>\n      <StyleTargetBar {...bar} />\n    </RenderedSample.Provider>\n  );\n}\n\n/**\n * The Style tab's sections, on a tint of the state's colour under a line\n * that names the state while one other than Normal is edited: the bar can\n * scroll far from a control, and the words stay beside it.\n */\nfunction StateTinted({\n  state,\n  children,\n}: {\n  state: StyleState;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-style-tab__body\" data-state={state}>\n      {state === \"base\" ? null : (\n        <p className=\"nx-style-tab__state-line\" data-editing-state-line=\"\">\n          {stateLookLine(state)}\n        </p>\n      )}\n      {children}\n    </div>\n  );\n}\n\n/**\n * The devices an edit at one tier reaches: the unconditional tier reaches\n * \"All devices\"; a narrower one reaches itself and every narrower one on its\n * axis (\"Tablet and smaller\"), or only itself when it is the narrowest\n * (\"Mobile\"). Read from the site's own breakpoints in the engine's order\n * (`breakpointContexts`: each axis widest first), named by each definition's\n * own label, so a site with its own breakpoints is described in its words.\n */\nfunction editReach(\n  breakpoints: BreakpointSet | undefined,\n  id: BreakpointId\n): string {\n  if (id === BASE_BREAKPOINT) return \"All devices\";\n  const contexts = breakpointContexts(breakpoints);\n  const at = contexts.findIndex(context => context.id === id);\n  const label = breakpointLabel(breakpoints, id);\n  if (at === -1) return label;\n  const axis = contexts[at]?.axis;\n  const narrower = contexts\n    .slice(at + 1)\n    .some(context => context.axis === axis);\n  return narrower ? `${label} and smaller` : label;\n}\n","/**\n * \"Make this a setting of the component\", from a placement's inspector: the\n * component's own props a field could fill that are not settings yet, and\n * the host service that adds one.\n *\n * Adding a setting changes the component, a document of its own that every\n * page placing it reads, so the host holds that change and writes it with\n * the page's next save. The page's side is one edit, binding the placement's\n * new setting to the field picked, so one undo takes both back: the host's\n * held change counts only while the page still holds that binding.\n *\n * @module make-component-setting\n */\nimport {\n  addressPropOf,\n  authoredText,\n  bindablePropKind,\n  ENTRY_LINK_PROPS,\n  getBlock,\n  isPlainRecord,\n  walkNodes,\n  type BlockNode,\n  type ComponentDocument,\n  type PropSchema,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { propLabel } from \"./prop-label\";\n\n/**\n * The kinds of value a new setting may hold: text, an address and a\n * picture, the settings a placement binds to data. A rich-text passage is\n * edited on the canvas, and a number or a choice is the component's design.\n */\nconst SETTING_KINDS: ReadonlySet<string> = new Set([\"text\", \"link\", \"image\"]);\n\n/** The props a link's entry reference is stored in, set with its address. */\nconst ENTRY_LINK_NAMES: ReadonlySet<string> = new Set(\n  Object.values(ENTRY_LINK_PROPS)\n);\n\n/**\n * One prop of the component a placement may make a setting.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport interface SettingCandidate {\n  /** The component's block that holds it, by its id in the component. */\n  readonly nodeId: string;\n  readonly propPath: string;\n  /** How the panel lists it: the block's name, then the prop's. */\n  readonly label: string;\n  /** The prop as the block declares it, which the field picker fits. */\n  readonly schema: PropSchema;\n  /** What the component holds there now, the setting's default. */\n  readonly value: unknown;\n}\n\n/**\n * What a host is asked to add: a setting of the component filled by one of\n * its block's props, named as given.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport interface ComponentSettingAsk {\n  readonly componentId: string;\n  readonly nodeId: string;\n  readonly propPath: string;\n  readonly label: string;\n}\n\n/**\n * The new setting's id, which the placement binds under, or why the host\n * would not add it.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport type ComponentSettingAnswer =\n  | { readonly settingId: string }\n  | { readonly refusal: string };\n\n/** The settings a definition declares, by the block and prop each fills. */\nfunction exposedTargets(definition: ComponentDocument): ReadonlySet<string> {\n  const exposed: unknown = definition.exposed;\n  const targets = new Set<string>();\n  if (!Array.isArray(exposed)) return targets;\n  for (const entry of exposed as unknown[]) {\n    if (!isPlainRecord(entry)) continue;\n    const { nodeId, propPath } = entry;\n    if (typeof nodeId === \"string\" && typeof propPath === \"string\") {\n      targets.add(`${nodeId}\\u0000${propPath}`);\n    }\n  }\n  return targets;\n}\n\n/** What the panel calls a block: its own name, else its kind's. */\nfunction blockNameOf(node: BlockNode): string {\n  const own = node.name;\n  if (typeof own === \"string\" && own.trim() !== \"\") return own;\n  return getBlock(node.type)?.editor?.label ?? node.type;\n}\n\n/**\n * Whether a block's prop may become a setting: content whose value a field\n * can be, not a setting already and not bound to a field already. Never a\n * setting of how the block is linked or drawn: a link's entry reference is\n * set with its address.\n */\nfunction offered(\n  node: BlockNode,\n  propPath: string,\n  schema: PropSchema,\n  taken: ReadonlySet<string>\n): boolean {\n  if (!SETTING_KINDS.has(bindablePropKind(schema) ?? \"\")) return false;\n  if (schema.role !== \"content\" || ENTRY_LINK_NAMES.has(propPath)) {\n    return false;\n  }\n  if (propPath === LINK_ADDRESS_PROP && linksToEntry(node.props)) return false;\n  if (mediaDrawnInstead(node, propPath)) return false;\n  if (taken.has(`${node.id}\\u0000${propPath}`)) return false;\n  return !(\n    isPlainRecord(node.bindings) && Object.hasOwn(node.bindings, propPath)\n  );\n}\n\n/** The prop a link's typed address is stored in, which `linkFor` reads. */\nconst LINK_ADDRESS_PROP = \"href\";\n\n/**\n * Whether a block links to an entry, which the renderer follows before its\n * typed address: a setting of that address would change nothing a visitor\n * sees while the entry link stands.\n */\nfunction linksToEntry(props: unknown): boolean {\n  if (!isPlainRecord(props)) return false;\n  const named = (key: string): boolean => {\n    const value = props[key];\n    return typeof value === \"string\" && value.trim() !== \"\";\n  };\n  return named(ENTRY_LINK_PROPS.collection) && named(ENTRY_LINK_PROPS.id);\n}\n\n/**\n * Whether `propPath` is the address a media prop of the block keeps its\n * image by ({@link addressPropOf}), while that media prop is picked or\n * bound: the renderer draws the media before the address, and a bound one\n * in its place, so a setting of the address would change nothing a visitor\n * sees. Read from the block's declared pairing, never guessed by name.\n */\nfunction mediaDrawnInstead(node: BlockNode, propPath: string): boolean {\n  const declared = getBlock(node.type)?.props;\n  const props = isPlainRecord(node.props) ? node.props : {};\n  const bindings = isPlainRecord(node.bindings) ? node.bindings : {};\n  return Object.keys(declared ?? {}).some(\n    media =>\n      addressPropOf(declared, media) === propPath &&\n      (authoredText(props[media]) !== \"\" || Object.hasOwn(bindings, media))\n  );\n}\n\n/** One block's props a placement may make a setting, in declared order. */\nfunction candidatesOf(\n  node: BlockNode,\n  taken: ReadonlySet<string>\n): SettingCandidate[] {\n  // A placement's type is reserved, so no block declares props for it: a\n  // component placed inside this one offers none of its own.\n  const declared = getBlock(node.type)?.props ?? {};\n  const props = isPlainRecord(node.props) ? node.props : {};\n  return Object.entries(declared).flatMap(([propPath, schema]) =>\n    schema === undefined || !offered(node, propPath, schema, taken)\n      ? []\n      : [\n          {\n            nodeId: node.id,\n            propPath,\n            label: `${blockNameOf(node)} · ${propLabel(propPath, schema)}`,\n            schema,\n            value: Object.hasOwn(props, propPath) ? props[propPath] : undefined,\n          },\n        ]\n  );\n}\n\n/**\n * The props of a component a placement may make a setting: each text, link\n * and image prop its blocks declare, inside their slots too, that is not a\n * setting yet and not bound to a field already, in the component's order.\n *\n * @experimental Settles with the editor's binding controls.\n */\nexport function settingCandidates(\n  definition: ComponentDocument\n): SettingCandidate[] {\n  const taken = exposedTargets(definition);\n  const found: SettingCandidate[] = [];\n  walkNodes(definition.nodes, node => {\n    found.push(...candidatesOf(node, taken));\n  });\n  return found;\n}\n","\"use client\";\n\n/**\n * \"Make this a setting of the component\", in a placement's inspector: the\n * component's props a field could fill that are not settings yet, each with\n * the field picker. A pick asks the host to add the setting, named after the\n * field, and binds this placement's new setting to that field in one edit;\n * the host writes the component with the page's next save.\n *\n * @module make-component-setting-section\n */\nimport {\n  settingBindingKey,\n  type BlockDocument,\n  type BuilderOp,\n  type ComponentDocument,\n} from \"@nextlyhq/blocks-engine\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@nextlyhq/ui\";\nimport { Check, Database } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { BindingPicker, pickOp } from \"../bindings/binding-picker\";\nimport {\n  settingCandidates,\n  type SettingCandidate,\n} from \"../make-component-setting\";\n\nimport type { ContentServices } from \"./content/content-controls\";\n\n/** What the section needs of the placement and the editor. */\nexport interface MakeSettingPlacement {\n  readonly nodeId: string;\n  readonly componentId: string;\n  /** The component's name, as the panel titles it. */\n  readonly label: string;\n  /** How many pages place the component, where the library can say. */\n  readonly usedOn: number | undefined;\n  /** The component, or `undefined` where it could not be read. */\n  readonly definition: ComponentDocument | undefined;\n  /** Whether the lookup held the component, as the panel's rows read it. */\n  readonly definitionFound: boolean;\n  /** Whether the placement is locked, which offers no new setting. */\n  readonly locked: boolean;\n  readonly document: BlockDocument;\n  readonly services: ContentServices | undefined;\n  /** Apply one op as an edit; `false` where the editor refused it. */\n  readonly onApply: (op: BuilderOp) => boolean;\n}\n\n/** A pick, as the field picker hands it. */\ntype Picked = Parameters<typeof pickOp>[1];\n\n/** What a pick said: the setting made, or why not. */\ninterface MadeNote {\n  readonly text: string;\n  readonly tone: \"kept\" | \"refused\";\n}\n\n/** The note under a row, in the binding notes' look. */\nfunction RowNote({ note }: { note: MadeNote }): React.JSX.Element {\n  return (\n    <p className=\"nx-binding-note\" data-tone={note.tone} role=\"status\">\n      {note.tone === \"kept\" ? <Check aria-hidden=\"true\" size={14} /> : null}\n      <span>{note.text}</span>\n    </p>\n  );\n}\n\n/** Said where the editor refused the binding's edit. */\nconst EDIT_REFUSED = \"The page refused this edit, so nothing changed.\";\n\n/** What the section says the change reaches, once, above its rows. */\nfunction reachLine(label: string, usedOn: number | undefined): string {\n  const where =\n    usedOn === undefined\n      ? `${label} is placed on other pages too`\n      : `${label} is used on ${usedOn} ${usedOn === 1 ? \"page\" : \"pages\"}`;\n  return `${where}. A new setting keeps showing what each one shows now, until a page binds it or sets it.`;\n}\n\n/**\n * The section, or nothing where the host adds no settings or the component\n * has nothing left to offer.\n */\nexport function MakeSettingSection(\n  props: MakeSettingPlacement\n): React.JSX.Element | null {\n  const headingId = React.useId();\n  const candidates = React.useMemo(\n    () =>\n      props.definition === undefined || !props.definitionFound || props.locked\n        ? []\n        : settingCandidates(props.definition),\n    [props.definition, props.definitionFound, props.locked]\n  );\n  // Said by the section, not the row: a setting made leaves the list, as\n  // it is a setting now, and its row with it.\n  const [note, setNote] = React.useState<MadeNote | null>(null);\n  if (props.services?.makeComponentSetting === undefined) return null;\n  if (candidates.length === 0 && note === null) return null;\n  return (\n    <section aria-labelledby={headingId}>\n      <h3 id={headingId} className=\"nx-inspector__heading\">\n        Make this a setting of the component\n      </h3>\n      <p className=\"nx-inspector__note\">\n        {reachLine(props.label, props.usedOn)}\n      </p>\n      <div className=\"nx-inspector__fields\">\n        {candidates.map(candidate => (\n          <CandidateRow\n            key={`${props.nodeId}:${candidate.nodeId}:${candidate.propPath}`}\n            placement={props}\n            candidate={candidate}\n            onNote={setNote}\n          />\n        ))}\n      </div>\n      {note === null ? null : <RowNote note={note} />}\n    </section>\n  );\n}\n\n/** One prop the placement may make a setting, with its picker. */\nfunction CandidateRow({\n  placement,\n  candidate,\n  onNote,\n}: {\n  placement: MakeSettingPlacement;\n  candidate: SettingCandidate;\n  /** Say what a pick came to, under the section. */\n  onNote: (note: MadeNote) => void;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const setNote = onNote;\n  const [pending, setPending] = React.useState(false);\n  // The document as the editor holds it when the host answers: the bind is\n  // planned against that, so an edit made meanwhile stays.\n  const latest = React.useRef(placement.document);\n  latest.current = placement.document;\n  const mounted = React.useRef(true);\n  React.useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n    };\n  }, []);\n\n  const make = async (picked: Picked): Promise<void> => {\n    const ask = placement.services?.makeComponentSetting;\n    if (ask === undefined) return;\n    setPending(true);\n    let answer: Awaited<ReturnType<typeof ask>>;\n    try {\n      answer = await ask({\n        componentId: placement.componentId,\n        nodeId: candidate.nodeId,\n        propPath: candidate.propPath,\n        label: picked.label,\n      });\n    } catch {\n      answer = { refusal: \"The setting could not be added. Try again.\" };\n    }\n    // A row gone meanwhile holds a document the editor no longer does, and a\n    // bind planned against it would undo what the author did since: the\n    // answer is dropped, and the host's plan, bound by nothing, with it.\n    if (!mounted.current) return;\n    setPending(false);\n    if (\"refusal\" in answer) {\n      setNote({ text: answer.refusal, tone: \"refused\" });\n      return;\n    }\n    const { op } = pickOp(\n      {\n        document: latest.current,\n        nodeId: placement.nodeId,\n        prop: settingBindingKey(answer.settingId),\n        clearsOnBind: undefined,\n        entryLink: undefined,\n      },\n      picked,\n      undefined\n    );\n    if (op === null || !placement.onApply(op)) {\n      setNote({ text: EDIT_REFUSED, tone: \"refused\" });\n      return;\n    }\n    setNote({\n      text: `“${picked.label}” is a setting of ${placement.label} now, bound to that field here. The change to ${placement.label} is saved with the page.`,\n      tone: \"kept\",\n    });\n  };\n\n  const name = candidate.label;\n  return (\n    <div className=\"nx-binding-row\">\n      <div className=\"nx-binding-row__field\">\n        <span className=\"nx-inspector__label\">{name}</span>\n      </div>\n      <Popover open={open} onOpenChange={setOpen}>\n        <PopoverTrigger asChild>\n          <button\n            type=\"button\"\n            className=\"nx-binding-row__bind\"\n            aria-label={`Make ${name} a setting, bound to a field`}\n            title={`Make ${name} a setting, bound to a field`}\n            disabled={pending}\n            data-open={open ? \"\" : undefined}\n          >\n            <Database aria-hidden=\"true\" size={14} />\n          </button>\n        </PopoverTrigger>\n        <PopoverContent align=\"end\" className=\"nx-binding-popover\">\n          <BindingPicker\n            prop={{\n              name: `${candidate.nodeId}.${candidate.propPath}`,\n              schema: { ...candidate.schema, label: name },\n              value: candidate.value,\n              supported: true,\n              options: [],\n              offered: true,\n              readOnly: false,\n            }}\n            blockLabel={placement.label}\n            document={placement.document}\n            nodeId={placement.nodeId}\n            services={placement.services}\n            current={undefined}\n            entryLink={undefined}\n            onPick={picked => {\n              setOpen(false);\n              void make(picked);\n            }}\n          />\n        </PopoverContent>\n      </Popover>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The variant a selected placement uses, and the control that changes it.\n *\n * Draws what `component-variants` decides. A placement's own values are kept\n * whatever variant it picks: they are written over the variant's, so changing\n * the variant changes only the fields the placement has not set itself.\n *\n * A placement holding the key of a variant the component no longer has says\n * so, \"Variant removed, showing defaults\", with Clear, rather than showing an\n * empty choice: the key is kept so a restored version brings the variant back,\n * and the author decides whether to let it go.\n *\n * @module variant-picker\n */\nimport {\n  findNode,\n  readableDefinition,\n  type ComponentDocument,\n  type ComponentLookup,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Label,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport { CircleAlert } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport {\n  chooseVariantOp,\n  variantChoiceOf,\n  type VariantChoice,\n} from \"../panels/components/component-variants\";\n\n/**\n * What the picker's control spells \"no variant\". Every variant's own value is\n * prefixed, so no stored key can collide with it.\n */\nconst NONE = \"none\";\n\nfunction encodeVariant(id: string): string {\n  return `=${id}`;\n}\n\n/**\n * The picker for one placement, or nothing when its component offers no\n * variants and it holds none.\n *\n * @experimental Settles when the component editor ships.\n */\nexport function VariantPicker({\n  editor,\n  nodeId,\n  definition,\n  disabled,\n}: {\n  editor: EditorState;\n  nodeId: string;\n  definition: ComponentDocument | undefined;\n  /** True while the placement is locked, so it cannot change. */\n  disabled?: boolean;\n}): React.JSX.Element | null {\n  const node = findNode(editor.document.nodes, nodeId);\n  const id = React.useId();\n  // A definition that could not be loaded says so below; reading its\n  // absence as \"this variant was removed\" would say something untrue.\n  if (node === undefined || definition === undefined) return null;\n  const choice = variantChoiceOf(definition, node);\n  if (choice.options.length === 0 && choice.chosen === undefined) return null;\n\n  // Read the node again at commit: a choice made after another edit replaced\n  // the node must not write back the older props.\n  const choose = (variantId: string | undefined) => {\n    const now = findNode(editor.document.nodes, nodeId);\n    if (now !== undefined) editor.apply(chooseVariantOp(now, variantId));\n  };\n\n  return (\n    // A row like the fields below it, its label beside the menu, inside the\n    // fields' container so it stacks with them when the rail is narrow.\n    <section\n      className=\"nx-inspector__fields nx-variant-picker\"\n      data-variant-picker=\"\"\n    >\n      <div className=\"nx-inspector__field\">\n        <Label htmlFor={id}>Variant</Label>\n        {choice.removed ? (\n          <RemovedVariant\n            onClear={() => choose(undefined)}\n            disabled={disabled}\n          />\n        ) : (\n          <Select\n            value={\n              choice.chosen === undefined ? NONE : encodeVariant(choice.chosen)\n            }\n            disabled={disabled}\n            onValueChange={next =>\n              choose(next === NONE ? undefined : next.slice(1))\n            }\n          >\n            <SelectTrigger id={id} size=\"sm\">\n              <SelectValue />\n            </SelectTrigger>\n            <SelectContent>\n              <SelectItem value={NONE}>Default</SelectItem>\n              {choice.options.map(option => (\n                <SelectItem key={option.id} value={encodeVariant(option.id)}>\n                  {optionLabel(option)}\n                </SelectItem>\n              ))}\n            </SelectContent>\n          </Select>\n        )}\n      </div>\n    </section>\n  );\n}\n\n/** What the picker calls a variant, marked when it presets nothing. */\nfunction optionLabel(option: VariantChoice[\"options\"][number]): string {\n  return option.empty ? `${option.label} (no changes)` : option.label;\n}\n\n/** The notice for a placement whose variant was deleted, with Clear. */\nfunction RemovedVariant({\n  onClear,\n  disabled,\n}: {\n  onClear: () => void;\n  disabled: boolean | undefined;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-variant-picker__removed\" role=\"status\">\n      <CircleAlert size={14} aria-hidden=\"true\" />\n      <span>Variant removed, showing defaults</span>\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"sm\"\n        disabled={disabled}\n        aria-label=\"Clear the removed variant\"\n        onClick={onClear}\n      >\n        Clear\n      </Button>\n    </div>\n  );\n}\n\n/**\n * The definition a placement resolves against, from the lookup the canvas\n * composes with.\n *\n * @experimental Settles when the component editor ships.\n */\nexport function placedDefinition(\n  definitions: ComponentLookup,\n  componentId: string | undefined\n): ComponentDocument | undefined {\n  // Under the resolver's own rule for a supplied definition, so the picker\n  // offers the variants of exactly the definition the canvas draws.\n  if (componentId === undefined) return undefined;\n  return readableDefinition(definitions.get(componentId));\n}\n","\"use client\";\n\n/**\n * The inspector for a selected component INSTANCE: its exposed properties.\n *\n * Draws what `instance-inspector` decides and decides nothing itself — which\n * rows an instance offers, what each shows, where its value came from and the\n * op that changes it all live there, where they can be asserted without a DOM.\n *\n * **This replaces the block inspector's tabs rather than adding to them.** An\n * instance is one node whose content is a definition's, inlined at render:\n * its own node carries no props a schema describes, and it renders as no\n * element of its own, so a Style tab and an Advanced tab would offer controls\n * over nothing. What it has instead is the surface the design names — exposed\n * properties now, variants, slots and the change list later.\n *\n * **Every row says where its value came from, and every override says how to\n * take it back.** An author reading \"Site name\" cannot tell from the value\n * alone whether they typed it or the component did, and the reset for an\n * override they made is offered ON the row, visibly. The one editor that\n * hides its reset behind a context menu is the one whose users had to ask\n * where it was.\n *\n * Text commits on blur, for the reason the block inspector's does: undo is\n * built from op inverses, and an op per keystroke would make one undo remove\n * one letter.\n *\n * @module instance-inspector-panel\n */\n\nimport {\n  exposedValueFits,\n  findNode,\n  isRichTextValue,\n  isUnsetOverride,\n  neededFor,\n  oneParagraphLines,\n  richTextToPlainText,\n  settingBindingKey,\n  type BlockDocument,\n  type BuilderOp,\n  type ComponentDocument,\n  type OverrideValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Input,\n  Label,\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n  Switch,\n  Textarea,\n} from \"@nextlyhq/ui\";\nimport {\n  CircleSlash,\n  Layers,\n  Link2,\n  Lock,\n  PenLine,\n  RotateCcw,\n  SquarePen,\n  Unlink,\n} from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { BindableField } from \"../bindings/binding-controls\";\nimport { unbindOp } from \"../bindings/binding-ops\";\nimport type { UnbindPlanAnswer } from \"../bindings/binding-services\";\nimport { CanvasPassageContext } from \"../canvas/canvas-passage\";\nimport { markExposedParts } from \"../canvas/exposed-outline\";\nimport type { EditorState } from \"../editor-state\";\nimport { refusalAnnouncement } from \"../move-refusal\";\nimport { useStoredDraft } from \"../stored-draft\";\n\nimport { BlockCard, type CardVerbs } from \"./block-card\";\nimport {\n  ChosenMedia,\n  ContentServicesContext,\n  MediaChoice,\n  RichTextField,\n  type ContentServices,\n  type PickedMedia,\n} from \"./content/content-controls\";\nimport { HeldByLock, HeldHere } from \"./held-by-lock\";\nimport { lockOp, lockStatusOf, lockViewOf, renameOp } from \"./inspector\";\nimport {\n  resetOverrideOp,\n  setOverrideOp,\n  withPlacementLists,\n  type ExposedRow,\n  type InstanceInspection,\n  type OrphanedOverride,\n} from \"./instance-inspector\";\nimport { MakeSettingSection } from \"./make-component-setting-section\";\nimport { VariantPicker } from \"./variant-picker\";\n\n/**\n * What the row's badge says for each source.\n *\n * A record over the closed set rather than a chain of comparisons, so a\n * source the resolver adds later is a build failure here until it has words.\n */\nconst SOURCE_LABEL: Readonly<Record<ExposedRow[\"source\"], string>> = {\n  // In the editor's words for a component: where the value comes from, said\n  // as a quiet line rather than an internal term in capitals.\n  definition: \"From the component\",\n  variant: \"From variant\",\n  instance: \"Set on this page\",\n};\n\n/**\n * The badge's icon for each state, beside its words, so the four states differ\n * by shape as well as by label and never by colour alone: \"Cleared\" (a value\n * deliberately removed) and \"Inherited\" (nothing set here) are the pair an\n * author most needs to tell apart, and the one a colour-blind author could\n * not tell apart by tint.\n */\nconst SOURCE_ICON: Readonly<\n  Record<ExposedRow[\"source\"] | \"cleared\", LucideIcon>\n> = {\n  definition: Link2,\n  variant: Layers,\n  instance: PenLine,\n  cleared: CircleSlash,\n};\n\n/**\n * A cleared value, said by whoever cleared it: a variant's clearing is not\n * this page's, and there is no page value to reset.\n */\nconst CLEARED_LABEL: Readonly<Record<ExposedRow[\"source\"], string>> = {\n  definition: \"Empty in the component\",\n  variant: \"Cleared by variant\",\n  instance: \"Cleared on this page\",\n};\n\n/** The words a row's badge shows: its source, or who cleared it. */\nfunction sourceBadgeLabel(row: Pick<ExposedRow, \"source\" | \"cleared\">): string {\n  return (row.cleared ? CLEARED_LABEL : SOURCE_LABEL)[row.source];\n}\n\n/**\n * The control's spelling of a definition's option value, and back.\n *\n * EVERY value wears a one-character prefix. A definition may offer `\"\"` as a\n * choice — \"none\", for a select whose other options are class names — and the\n * validator accepts it, while the primitive underneath the select throws at\n * render on an item whose value is the empty string, which it reserves for\n * \"no selection\". A sentinel spelling `\"\"` alone collides with the option\n * whose value IS that sentinel — an option's value is free text, so no string\n * is safe — and two items then share one value: the control draws the later\n * of them for either, and choosing one while the other is held changes\n * nothing. A prefix on every value cannot collide: distinct values stay\n * distinct, and no spelling is empty.\n */\nconst OPTION_PREFIX = \"=\";\n\nfunction encodeOption(value: string): string {\n  return `${OPTION_PREFIX}${value}`;\n}\n\nfunction decodeOption(value: string): string {\n  return value.slice(OPTION_PREFIX.length);\n}\n\n/**\n * What an exposed type is called in a sentence telling the author it cannot be\n * edited here yet. The engine's names are code; these are words.\n */\nconst TYPE_LABEL: Readonly<Record<ExposedRow[\"type\"], string>> = {\n  text: \"text\",\n  richText: \"rich text\",\n  image: \"image\",\n  link: \"link\",\n  visibility: \"visibility\",\n  select: \"choice\",\n};\n\nexport function InstanceInspectorPanel({\n  inspection,\n  editor,\n  verbs,\n  definition,\n  canvasRoot,\n}: {\n  inspection: InstanceInspection;\n  editor: EditorState;\n  /** The shared block verbs for the card's menu, as a block's card gets. */\n  verbs?: CardVerbs | undefined;\n  /** The definition the placement resolves against, for its variant picker. */\n  definition?: ComponentDocument | undefined;\n  /**\n   * The canvas's root, where the placement's exposed parts are marked; the\n   * page's document when the host names none. Scoped so a canvas drawn in a\n   * frame is reached, and another editor's marks are left alone.\n   */\n  canvasRoot?: HTMLElement | null | undefined;\n}): React.JSX.Element {\n  // Read the node at commit time rather than closing over one. A field\n  // committing on blur can fire after another edit has already replaced the\n  // node, and an override record rebuilt from the older copy would resurrect\n  // overrides that edit removed.\n  const nodeNow = React.useCallback(\n    () => findNode(editor.document.nodes, inspection.nodeId),\n    [editor.document, inspection.nodeId]\n  );\n  // Answers the document the write produced, or `null` when it was refused,\n  // so a field holding words only it has (a rich-text passage) can keep them.\n  const set: SetExposed = React.useCallback(\n    (id: string, value: OverrideValue) => {\n      const node = nodeNow();\n      return node === undefined\n        ? null\n        : editor.apply(setOverrideOp(node, id, value));\n    },\n    [editor, nodeNow]\n  );\n  const reset = React.useCallback(\n    (id: string) => {\n      const node = nodeNow();\n      if (node !== undefined) editor.apply(resetOverrideOp(node, id));\n    },\n    [editor, nodeNow]\n  );\n\n  const bind = useSettingBinding(editor, inspection);\n\n  const headingId = React.useId();\n  // The selected placement's editable parts, outlined on the canvas while it\n  // is selected: after every render, since the canvas redraws with the\n  // document this panel reads, and cleared when the selection moves on.\n  const composed = editor.composed();\n  React.useEffect(() => {\n    const root: ParentNode = canvasRoot ?? globalThis.document;\n    markExposedParts(root, inspection.nodeId, composed);\n    return () => markExposedParts(root, null, undefined);\n  }, [inspection.nodeId, composed, canvasRoot]);\n  // The card's lock line, which every held row points to while the placement\n  // is locked in Layers. Its own lock control stays live above, so it can be\n  // unlocked.\n  const lockedReasonId = React.useId();\n  const locked = inspection.identity.locked;\n  const onCanvas = React.useContext(CanvasPassageContext);\n\n  return (\n    <OnCanvasHere.Provider\n      value={\n        onCanvas?.placementId === inspection.nodeId\n          ? onCanvas.exposureId\n          : undefined\n      }\n    >\n      <div className=\"nx-inspector\" data-instance=\"\">\n        {/*\n        The same card every block gets. Its description says what this IS —\n        \"Component\", for the author who clicked into a header and is wondering\n        why the Style tab went — with the usage count beside it when the\n        library could say, because an edit to this component's definition\n        reaches every one of those pages.\n      */}\n        <BlockCard\n          // Keyed by node so a rename half-typed for one instance does not carry\n          // to the next, exactly as the block inspector's does.\n          key={`${inspection.nodeId}:card`}\n          // The editor's fallback mark: no block icon names a component.\n          icon={undefined}\n          type={inspection.label}\n          name={inspection.identity.name}\n          description={`Component${variantPhrase(inspection.variant)}${\n            inspection.usedOn === undefined\n              ? \"\"\n              : ` · used on ${inspection.usedOn} ${inspection.usedOn === 1 ? \"page\" : \"pages\"}`\n          }`}\n          lock={lockStatusOf(\n            editor.document,\n            inspection.nodeId,\n            lockViewOf(editor)\n          )}\n          onRename={name => editor.apply(renameOp(inspection.nodeId, name))}\n          onLock={locked => editor.apply(lockOp(inspection.nodeId, locked))}\n          verbs={verbs}\n          // The lock is said once, by the card's own line, and the rows and the\n          // values no longer exposed point at it; a second sentence below said\n          // the same thing again.\n          reasonId={lockedReasonId}\n        />\n        <EditComponentButton verbs={verbs} />\n\n        <VariantPicker\n          editor={editor}\n          nodeId={inspection.nodeId}\n          definition={definition}\n          disabled={inspection.identity.locked}\n        />\n\n        {!inspection.definitionFound ? (\n          /*\n           * The same state the canvas draws as could-not-be-loaded, in words. A\n           * `status` region rather than an alert: it is a standing fact about\n           * this selection, not an event.\n           */\n          <p className=\"nx-inspector__note\" role=\"status\">\n            This component could not be loaded, so its properties cannot be\n            edited here. It may have been deleted, or the library was too large\n            to load whole.\n          </p>\n        ) : inspection.rows.length === 0 ? (\n          /*\n           * Zero exposed properties is a locked, reusable block — a footer — not\n           * a broken component, so this says what there is to do rather than\n           * that something is missing: the content lives on the definition, and\n           * the definition has a screen.\n           */\n          <NoFieldsNote verbs={verbs} />\n        ) : (\n          <section aria-labelledby={headingId}>\n            <h3 id={headingId} className=\"nx-inspector__heading\">\n              Fields\n            </h3>\n            <HeldByLock reasonId={locked ? lockedReasonId : undefined}>\n              <div className=\"nx-inspector__fields\">\n                {inspection.rows.map(row => (\n                  <ExposedField\n                    // Keyed by node AND property, for the reason the block\n                    // inspector keys its fields: a bare id would let React reuse\n                    // one instance's field for the next instance's same-named\n                    // property, and the input would keep the previous one's\n                    // uncommitted text.\n                    key={`${inspection.nodeId}:${row.id}`}\n                    row={row}\n                    onSet={set}\n                    onReset={reset}\n                    bind={bind}\n                  />\n                ))}\n              </div>\n            </HeldByLock>\n          </section>\n        )}\n\n        <MakeSettingSection\n          nodeId={inspection.nodeId}\n          componentId={inspection.componentId}\n          label={inspection.label}\n          usedOn={inspection.usedOn}\n          definition={definition}\n          definitionFound={inspection.definitionFound}\n          locked={locked}\n          document={editor.document}\n          services={bind.services}\n          onApply={bind.onApply}\n        />\n\n        {inspection.orphaned.length > 0 ? (\n          // Held by the same Layers lock as the rows: discarding a stored value\n          // is an edit of the placement too.\n          <HeldByLock reasonId={locked ? lockedReasonId : undefined}>\n            <OrphanedOverrides\n              orphaned={inspection.orphaned}\n              onDiscard={reset}\n            />\n          </HeldByLock>\n        ) : null}\n      </div>\n    </OnCanvasHere.Provider>\n  );\n}\n\n/**\n * The variant this placement uses, as a phrase after \"Component\", or nothing.\n * A variant the component no longer offers is said once, by the variant\n * picker's notice beside its Clear, rather than here as well.\n */\nfunction variantPhrase(variant: InstanceInspection[\"variant\"]): string {\n  if (variant?.label === undefined) return \"\";\n  return ` · ${variant.label} variant`;\n}\n\n/**\n * One exposed property: its label, where its value came from, the control\n * that changes it, and the way back.\n */\nfunction ExposedField({\n  row,\n  onSet,\n  onReset,\n  bind,\n}: {\n  row: ExposedRow;\n  onSet: SetExposed;\n  onReset: (id: string) => void;\n  /** What binding a setting to data needs; absent, no setting is bound. */\n  bind?: SettingBinding | undefined;\n}): React.JSX.Element {\n  // Unique per MOUNTED ROW, not per property: a page can hold two blocks\n  // fields, each with its own editor, and a fixed id per property made both\n  // labels resolve to the first editor's control — which then carried two\n  // labels and a doubled name, while the second's input had none.\n  const id = `${React.useId()}-${row.id}`;\n  // What a reset would remove is this row's OWN override, which is not the\n  // same fact as its source: a row shadowed by a neighbour holding the\n  // override reads `instance` too, and a reset offered there removes nothing.\n  const overridden = row.ownOverride;\n  // A label points at a control, and two kinds of row draw none: the label\n  // then names the row without claiming to label an input that is not there.\n  const hasControl = row.shadowedBy === undefined && row.supported;\n  const state = row.cleared ? \"cleared\" : row.source;\n  const Icon = SOURCE_ICON[state];\n  const reasonId = `${id}-held`;\n\n  return (\n    <div\n      className=\"nx-inspector__field nx-inspector__field--exposed\"\n      data-source={state}\n    >\n      {/*\n        The row's name and where its value comes from, in the label column:\n        the source a quiet note under the label, as an inherited Style value\n        says where it comes from, so the row is one row beside the 28px\n        Style rows rather than a label, a field and a line under it.\n      */}\n      <div className=\"nx-inspector__exposed-name\">\n        {/* Its id names a control no `for` can reach: a rich-text passage. */}\n        <Label id={`${id}-label`} {...(hasControl ? { htmlFor: id } : {})}>\n          {row.label}\n        </Label>\n        {/*\n          The source is VISIBLE, and words rather than the label's styling:\n          \"Set on this page\" is what tells an author the reset beside the field\n          undoes their own edit rather than the component's design.\n        */}\n        <span className=\"nx-inspector__source\" data-source={state}>\n          <Icon aria-hidden=\"true\" className=\"nx-inspector__source-icon\" />\n          {sourceBadgeLabel(row)}\n        </span>\n      </div>\n      <div className=\"nx-inspector__exposed\">\n        {/*\n          Only the value is held. Reset stays live: a value the page gave\n          before the component locked the block is one the save keeps and\n          lets the page drop, so the way back is never closed.\n        */}\n        <HeldByLock reasonId={row.heldBy === undefined ? undefined : reasonId}>\n          <BindableSetting row={row} bind={bind}>\n            <ExposedControl id={id} row={row} onSet={onSet} />\n          </BindableSetting>\n        </HeldByLock>\n        {/*\n          Why the row is held, UNDER the field as its helper text: the field\n          keeps its place beside its label, and the reason reads as a fact\n          about the value above it.\n        */}\n        {row.heldBy === undefined ? null : (\n          <p id={reasonId} className=\"nx-inspector__held-reason\">\n            <Lock aria-hidden=\"true\" className=\"nx-inspector__source-icon\" />\n            <span>{refusalAnnouncement(row.heldBy)}</span>\n          </p>\n        )}\n        <HeldBindingRemoval row={row} bind={bind} />\n      </div>\n      {/* Kept when empty, so every control ends at one edge, set or not. */}\n      <span className=\"nx-inspector__exposed-reset-slot\">\n        {overridden ? (\n          <Button\n            type=\"button\"\n            variant=\"ghost\"\n            size=\"icon\"\n            className=\"nx-inspector__exposed-reset\"\n            aria-label={`Reset ${row.label}`}\n            title=\"Undo this page's change\"\n            onClick={() => onReset(row.id)}\n          >\n            <RotateCcw size={14} aria-hidden=\"true\" />\n          </Button>\n        ) : null}\n      </span>\n    </div>\n  );\n}\n\n/**\n * The way back from a binding the page gave a setting its component has since\n * locked: the field and its chip are held, but removing the binding gives\n * the component's own value back, which the lock allows, so it is offered\n * here, outside the held controls.\n */\nfunction HeldBindingRemoval({\n  row,\n  bind,\n}: {\n  row: ExposedRow;\n  bind: SettingBinding | undefined;\n}): React.JSX.Element | null {\n  if (bind === undefined || row.heldBy === undefined) return null;\n  if (row.binding === undefined) return null;\n  const remove = (): void => {\n    const op = unbindOp(bind.document, bind.nodeId, settingBindingKey(row.id), {\n      set: {},\n    });\n    if (op !== null) bind.onApply(op);\n  };\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"sm\"\n      aria-label={`Unbind ${row.label}`}\n      disabled={bind.locked}\n      onClick={remove}\n    >\n      <Unlink size={14} aria-hidden=\"true\" />\n      Unbind\n    </Button>\n  );\n}\n\n/** What binding one of the placement's settings to data needs. */\ninterface SettingBinding {\n  readonly nodeId: string;\n  /** The component's name, as the panel titles it. */\n  readonly label: string;\n  readonly document: BlockDocument;\n  readonly services: ContentServices | undefined;\n  /** Whether the placement is locked, which holds every bind. */\n  readonly locked: boolean;\n  readonly onApply: (op: BuilderOp) => boolean;\n}\n\n/**\n * The binding controls' services for a setting: the host's, with an unbind\n * that keeps the value the placement stores for the setting. A setting's\n * value is the placement's own, stored as it was before the bind, so the\n * unbind writes nothing in its place.\n */\nfunction settingServices(\n  services: ContentServices | undefined\n): ContentServices | undefined {\n  if (services === undefined) return undefined;\n  return {\n    ...services,\n    planUnbind: (): Promise<UnbindPlanAnswer> =>\n      Promise.resolve({\n        kept: { set: {} },\n        answer: { kept: \"own\", reason: \"The setting keeps its own value.\" },\n      }),\n  };\n}\n\n/** What the setting rows of the selected placement bind with. */\nfunction useSettingBinding(\n  editor: EditorState,\n  inspection: InstanceInspection\n): SettingBinding {\n  const contentServices = React.useContext(ContentServicesContext);\n  const services = React.useMemo(\n    () => settingServices(contentServices),\n    [contentServices]\n  );\n  // Each list item binding a setting row writes names its list.\n  const onApply = React.useCallback(\n    (op: BuilderOp) =>\n      editor.apply(withPlacementLists(editor.document, op)) !== null,\n    [editor]\n  );\n  return {\n    nodeId: inspection.nodeId,\n    label: inspection.label,\n    document: editor.document,\n    services,\n    locked: inspection.identity.locked,\n    onApply,\n  };\n}\n\n/**\n * A setting's control inside the binding controls, where it may be bound: a\n * bind button beside it, and once bound, the field in its place. Written on\n * the placement under the setting's key (`overrides.<id>`), which composing\n * the component writes onto the prop the setting fills.\n */\nfunction BindableSetting({\n  row,\n  bind,\n  children,\n}: {\n  row: ExposedRow;\n  bind: SettingBinding | undefined;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  // A shadowed row is not what the page shows, so a binding of it would be\n  // a value nobody sees.\n  if (\n    bind === undefined ||\n    row.bindable === undefined ||\n    row.shadowedBy !== undefined\n  ) {\n    return <>{children}</>;\n  }\n  return (\n    <BindableField\n      nodeId={bind.nodeId}\n      prop={{\n        name: settingBindingKey(row.id),\n        schema: row.bindable,\n        value: row.value,\n        supported: true,\n        options: [],\n        offered: true,\n        readOnly: row.heldBy !== undefined,\n      }}\n      blockLabel={bind.label}\n      binding={row.binding}\n      document={bind.document}\n      services={bind.services}\n      disabled={bind.locked || row.heldBy !== undefined}\n      onApply={bind.onApply}\n    >\n      {children}\n    </BindableField>\n  );\n}\n\n/**\n * The control for one row, or the sentence explaining why there is none.\n *\n * Two reasons a row has no control, and they are told apart because the\n * remedies differ. A SHADOWED row is not what the page shows — another\n * exposure writes the same target after it — so editing it would change a\n * value nobody sees; the sentence names the row that is in force. An\n * UNSUPPORTED type has no control yet; the row still shows its value, so an\n * author can read what the component holds without being able to change it.\n */\nfunction ExposedControl({\n  id,\n  row,\n  onSet,\n}: {\n  id: string;\n  row: ExposedRow;\n  onSet: SetExposed;\n}): React.JSX.Element {\n  if (row.shadowedBy !== undefined) {\n    return (\n      <p className=\"nx-inspector__note\">\n        Set by “{row.shadowedBy.label}”, which the page shows instead of this.\n      </p>\n    );\n  }\n  // A type this panel has no control for, OR a value its control could not\n  // represent. The second is not a shape problem to report: `OverrideValue` is\n  // unconstrained and a host block may declare a text or link prop as an\n  // object, which a text field renders as a blank — and the first edit then\n  // replaces the whole value with what was typed into that blank. Shown rather\n  // than offered for editing, so nothing is lost to a control that cannot hold\n  // it.\n  if (!row.supported || !editableRow(row)) return <NotEditable row={row} />;\n  if (row.type === \"visibility\") {\n    return <ExposedVisibilityField id={id} row={row} onSet={onSet} />;\n  }\n  if (row.type === \"image\") {\n    return <ExposedImageField id={id} row={row} onSet={onSet} />;\n  }\n  if (row.type === \"richText\") {\n    return <ExposedRichTextField id={id} row={row} onSet={onSet} />;\n  }\n  if (row.type === \"select\") {\n    return (\n      <Select\n        value={\n          typeof row.value === \"string\" ? encodeOption(row.value) : undefined\n        }\n        onValueChange={next => onSet(row.id, decodeOption(next))}\n      >\n        <SelectTrigger id={id}>\n          <SelectValue placeholder=\"Choose\" />\n        </SelectTrigger>\n        <SelectContent>\n          {row.options.map(option => (\n            <SelectItem key={option.value} value={encodeOption(option.value)}>\n              {option.label}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    );\n  }\n  return <ExposedTextField id={id} row={row} onSet={onSet} />;\n}\n\n/**\n * A stored value as a line an author can read — empty only for a value that\n * is empty.\n *\n * {@link storedText} answers what a TEXT FIELD can hold, and a structured\n * value is not that: a rich-text document, a link or an image object, a list.\n * Read through it, a value that is there and one that is not both came out\n * empty, so a row showed nothing where the page shows a passage and an\n * orphan read as holding no value. Rich text is read as its words, through\n * the engine's own reader; a list says how many entries it holds; any other\n * structure shows its data; a cleared override says so.\n */\nfunction valueSummary(value: OverrideValue): string {\n  if (isUnsetOverride(value)) return \"(cleared)\";\n  if (isRichTextValue(value)) return clipped(richTextToPlainText(value));\n  if (Array.isArray(value)) {\n    return value.length === 1 ? \"1 item\" : `${String(value.length)} items`;\n  }\n  if (typeof value === \"object\" && value !== null) {\n    return clipped(dataOf(value));\n  }\n  return storedText(value);\n}\n\n/** How many characters of a summary a row shows before it trails off. */\nconst SUMMARY_LENGTH = 80;\n\n/** One line of at most {@link SUMMARY_LENGTH} characters, whitespace folded. */\nfunction clipped(text: string): string {\n  const line = text.replace(/\\s+/g, \" \").trim();\n  return line.length <= SUMMARY_LENGTH\n    ? line\n    : `${line.slice(0, SUMMARY_LENGTH - 1)}…`;\n}\n\n/**\n * A structured value as JSON, or a plain statement that it is one.\n *\n * Stored values arrive as JSON and serialise back; one a hook built in memory\n * can hold a cycle or a bigint, which `JSON.stringify` refuses, and a summary\n * must not take the panel down over it.\n */\nfunction dataOf(value: object): string {\n  try {\n    return JSON.stringify(value);\n  } catch (error) {\n    if (error instanceof TypeError) return \"(structured value)\";\n    throw error;\n  }\n}\n\n/**\n * Whether this row's control can hold the value in force.\n *\n * Only the TEXT controls can fail this, and only on a structured value: a\n * blank is what the field is meant to show, and a boolean or a number reads\n * back as itself. A CLEARED row is a blank too and needs no case of its own —\n * the resolver normalises a cleared value to `undefined` rather than handing\n * the sentinel on, which is the contract `instanceExposure` states.\n *\n * A select and a visibility row always pass. Neither carries the old value into\n * what it writes — choosing an option or ticking a box replaces it outright —\n * so a value they cannot show is repairable by using the control, and hiding it\n * would strand the property instead.\n */\n/** Writes one exposed field's value: the document written, or `null` if refused. */\ntype SetExposed = (id: string, value: OverrideValue) => BlockDocument | null;\n\n/**\n * A row with no control: its value in words, so an author can read what the\n * component holds without being offered a control that could not keep it.\n */\nfunction NotEditable({ row }: { row: ExposedRow }): React.JSX.Element {\n  const shown = valueSummary(row.value);\n  return (\n    <p className=\"nx-inspector__note\">\n      {shown === \"\" ? null : `“${shown}” — `}\n      Not editable here yet ({TYPE_LABEL[row.type]}).\n    </p>\n  );\n}\n\n/**\n * A placement's own passage, edited with the admin's one rich-text editor,\n * the control the Content tab's rich text uses. Opened on what the page\n * shows (the component's passage until the page has its own), written once\n * when the field is left, so an edit is one step of the history. Without the\n * host's editor the row says it cannot be edited here: the canvas's passage\n * is the component's, so the Content tab's \"edit it on the canvas\" would not\n * be true of it.\n */\n/**\n * The exposure of the placement shown whose passage the canvas is editing in\n * place, if any: its field is held meanwhile.\n */\nconst OnCanvasHere = React.createContext<string | undefined>(undefined);\n\nfunction ExposedRichTextField({\n  id,\n  row,\n  onSet,\n}: {\n  id: string;\n  row: ExposedRow;\n  onSet: SetExposed;\n}): React.JSX.Element {\n  const services = React.useContext(ContentServicesContext);\n  // Held by the placement's Layers lock or a lock inside the component.\n  const held = React.useContext(HeldHere);\n  // Held while the canvas edits this passage in place: one editor serves\n  // both, and opening it here would take the passage from under the caret.\n  const onCanvas = React.useContext(OnCanvasHere) === row.id;\n  if (services?.loadRichTextEditor === undefined) {\n    return <NotEditable row={row} />;\n  }\n  return (\n    <>\n      <RichTextField\n        id={id}\n        labelledBy={`${id}-label`}\n        value={row.value}\n        // Passed to the passage itself: a held row's wrapper disables its\n        // fieldset, which does not stop typing in a `contenteditable`.\n        disabled={held || onCanvas}\n        onCommit={value => onSet(row.id, value)}\n        services={services}\n      />\n      {onCanvas ? (\n        <p className=\"nx-inspector__note\" data-held=\"canvas\">\n          This passage is being edited on the canvas. Finish there to edit it\n          here.\n        </p>\n      ) : null}\n    </>\n  );\n}\n\n/**\n * A Text's one paragraph, exposed as text: its words are what a text field\n * holds, and what a placement sets in its place (`textRowValue`).\n */\nfunction textParagraph(row: ExposedRow): boolean {\n  return row.type === \"text\" && isRichTextValue(row.value);\n}\n\n/** Whether a row's value is one its control can hold. */\nfunction editableRow(row: ExposedRow): boolean {\n  return representable(row) || textParagraph(row);\n}\n\nfunction representable(row: ExposedRow): boolean {\n  if (row.type === \"visibility\" || row.type === \"select\") return true;\n  const { value } = row;\n  if (value === undefined || value === null) return true;\n  // A passage is one the editor can open. Plain words are a passage to the\n  // page but not to the editor, which would open them EMPTY, and the first\n  // keystroke would replace what the page shows; they stay shown instead.\n  if (row.type === \"richText\") return isRichTextValue(value);\n  // An image row shows a cleared override as nothing chosen.\n  // An image is a file's id, a string, or a cleared override; anything else\n  // stays shown as it is rather than offered to a picker that would replace\n  // it behind a blank-looking control.\n  if (row.type === \"image\") {\n    return typeof value === \"string\" || isUnsetOverride(value);\n  }\n  return typeof value !== \"object\";\n}\n\n/**\n * An image exposure, chosen from the host's media library as the Content\n * tab's image is: Choose or Replace opens it, and Remove clears this\n * placement's image, which reads as Cleared rather than falling back to the\n * component's. Where the host offers no library, it says so rather than\n * offering a button that does nothing.\n */\nfunction ExposedImageField({\n  id,\n  row,\n  onSet,\n}: {\n  id: string;\n  row: ExposedRow;\n  onSet: (id: string, value: OverrideValue) => void;\n}): React.JSX.Element {\n  const services = React.useContext(ContentServicesContext);\n  const Picker = services?.MediaPicker;\n  // What the last pick was called, for this session; a stored id shows as set.\n  const [picked, setPicked] = React.useState<PickedMedia | null>(null);\n  const stored =\n    typeof row.value === \"string\" && row.value !== \"\" ? row.value : null;\n  const name = picked?.id === stored ? picked?.filename : undefined;\n  return (\n    <div\n      // The field's label names the Choose button, a labelable control; with\n      // no library there is no control, and the group carries the name.\n      {...(Picker === undefined ? { id } : {})}\n      className=\"nx-inspector__media\"\n      role=\"group\"\n      aria-label={row.label}\n    >\n      <ChosenMedia\n        mediaId={stored}\n        read={services?.readMedia}\n        pickedName={name}\n        fallback=\"An image from the media library.\"\n      />\n      {Picker === undefined ? (\n        <p className=\"nx-inspector__note\">\n          The media library is not available here.\n        </p>\n      ) : (\n        <MediaChoice\n          id={id}\n          Picker={Picker}\n          label={row.label}\n          stored={stored}\n          accept=\"image/*\"\n          disabled={false}\n          onChoose={first => {\n            setPicked(first);\n            onSet(row.id, first.id);\n          }}\n        />\n      )}\n      {stored === null ? null : (\n        <Button\n          type=\"button\"\n          size=\"sm\"\n          variant=\"ghost\"\n          aria-label={`Remove ${row.label}`}\n          onClick={() => onSet(row.id, { $unset: true })}\n        >\n          Remove\n        </Button>\n      )}\n    </div>\n  );\n}\n\n/** A value as editable text, or empty when it is not representable. */\nfunction storedText(value: OverrideValue): string {\n  if (value === undefined || value === null) return \"\";\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\" || typeof value === \"boolean\") {\n    return String(value);\n  }\n  return \"\";\n}\n\n/**\n * A text exposure the author types into.\n *\n * Holds its own value while focused and reports it on blur, for the reason the\n * block inspector's text field does. **An emptied field CLEARS the property**\n * rather than writing an empty string: the whole reason the `$unset` sentinel\n * exists is so an author can take away a subtitle the definition fills in, and\n * a field that wrote `\"\"` would leave them with a value the definition may\n * treat as meaningful and no way to say \"nothing\".\n */\n/**\n * What a text row's field holds: the stored words, or, for a value in force\n * that is a Text's one paragraph (the component's own, with its marks), its\n * words. A placement then sets plain words in its place, as a placement's\n * text always is; an untouched field writes nothing.\n */\nfunction textRowValue(value: OverrideValue): string {\n  return isRichTextValue(value) ? oneParagraphLines(value) : storedText(value);\n}\n\n/** Words with lines, edited in a field that keeps them; leaving commits. */\nfunction LinesField({\n  id,\n  draft,\n  problem,\n  onDraft,\n  onLeave,\n}: {\n  id: string;\n  draft: string;\n  problem: string | null;\n  onDraft: (next: string) => void;\n  onLeave: () => void;\n}): React.JSX.Element {\n  const problemId = `${id}-problem`;\n  return (\n    <>\n      <Textarea\n        id={id}\n        rows={3}\n        value={draft}\n        aria-invalid={problem === null ? undefined : true}\n        aria-describedby={problem === null ? undefined : problemId}\n        onChange={event => onDraft(event.target.value)}\n        onBlur={onLeave}\n      />\n      <RefusedValue id={problemId} problem={problem} />\n    </>\n  );\n}\n\n/** Why a typed value was refused, under its field, while it is. */\nfunction RefusedValue({\n  id,\n  problem,\n}: {\n  id: string;\n  problem: string | null;\n}): React.JSX.Element | null {\n  if (problem === null) return null;\n  return (\n    <p id={id} className=\"nx-inspector__problem\" role=\"alert\">\n      {problem}\n    </p>\n  );\n}\n\nfunction ExposedTextField({\n  id,\n  row,\n  onSet,\n}: {\n  id: string;\n  row: ExposedRow;\n  onSet: (id: string, value: OverrideValue) => void;\n}): React.JSX.Element {\n  // Only a primitive becomes text, for the reason the block inspector gives:\n  // an unrepresentable value shows empty, and because `send` compares against\n  // this, an untouched field writes nothing.\n  const stored = textRowValue(row.value);\n  const [draft, setDraft] = useStoredDraft(stored);\n  // A value the store would refuse is held here with the reason rather than\n  // written: a link the renderer would not draw is the case a text field can\n  // produce. The draft stays, so the author can correct it. The refusal is\n  // held against the stored value it was made over: once that changes (a\n  // reset, an undo, an edit on the canvas), the field shows the new value and\n  // the refusal no longer describes it.\n  const [refusal, setRefusal] = React.useState<{\n    readonly over: string;\n    readonly message: string;\n  } | null>(null);\n  const problem = refusal?.over === stored ? refusal.message : null;\n  const problemId = `${id}-problem`;\n\n  const send = () => {\n    if (draft === stored) {\n      setRefusal(null);\n      return;\n    }\n    const next = draft === \"\" ? { $unset: true } : draft;\n    if (!exposedValueFits(row, next)) {\n      setRefusal({ over: stored, message: `${row.label} ${neededFor(row)}.` });\n      return;\n    }\n    setRefusal(null);\n    onSet(row.id, next);\n  };\n\n  // A Text's lines, or words already holding one, are edited in a field that\n  // keeps them; Enter is a new line there, and leaving the field commits.\n  if (textParagraph(row) || stored.includes(\"\\n\")) {\n    return (\n      <LinesField\n        id={id}\n        draft={draft}\n        problem={problem}\n        onDraft={setDraft}\n        onLeave={send}\n      />\n    );\n  }\n  return (\n    <>\n      <Input\n        id={id}\n        value={draft}\n        aria-invalid={problem === null ? undefined : true}\n        aria-describedby={problem === null ? undefined : problemId}\n        // Keyed for an address when the exposure is one, as the block inspector\n        // keys a url prop: the value is the same string either way.\n        inputMode={row.type === \"link\" ? \"url\" : undefined}\n        onChange={event => setDraft(event.target.value)}\n        onBlur={send}\n        // Enter commits as well as blur, as every single-line field here does.\n        onKeyDown={event => {\n          if (event.key === \"Enter\") {\n            event.preventDefault();\n            send();\n          }\n        }}\n      />\n      {problem === null ? null : (\n        <p id={problemId} className=\"nx-inspector__problem\" role=\"alert\">\n          {problem}\n        </p>\n      )}\n    </>\n  );\n}\n\n/**\n * A visibility exposure: whether the node it aims at is served on this page.\n *\n * A checkbox, committed at once — there is nothing to coalesce. It writes\n * `true` or `false` and nothing else, because those are the two values the\n * resolver reads there: a cleared override hides, and anything else is\n * ignored with the component's own rule left in force. So checked means\n * \"shown\", and an INHERITED row reads as shown: the component's rule is to\n * serve the node unless the definition gates it itself, and the source badge\n * beside the box says which it is.\n */\nfunction ExposedVisibilityField({\n  id,\n  row,\n  onSet,\n}: {\n  id: string;\n  row: ExposedRow;\n  onSet: (id: string, value: OverrideValue) => void;\n}): React.JSX.Element {\n  const shown = row.value !== false && !row.cleared;\n  return (\n    // A switch named by its row, whose state says whether it is shown: a\n    // checkbox beside \"Shown on this page\" wrapped onto two lines.\n    <Switch\n      id={id}\n      checked={shown}\n      onCheckedChange={checked => onSet(row.id, checked === true)}\n    />\n  );\n}\n\n/**\n * Values this instance stores for properties the definition no longer\n * exposes.\n *\n * Their own section rather than rows among the properties: they are not\n * properties any more. Each shows the stored value — the id is the only name\n * it has left — and offers to discard it, which is the one thing that can be\n * done with it. Nothing is discarded silently; that is the point.\n */\nfunction OrphanedOverrides({\n  orphaned,\n  onDiscard,\n}: {\n  orphaned: readonly OrphanedOverride[];\n  onDiscard: (id: string) => void;\n}): React.JSX.Element {\n  const headingId = React.useId();\n  return (\n    <section aria-labelledby={headingId} className=\"nx-inspector__orphaned\">\n      <h3 id={headingId} className=\"nx-inspector__heading\">\n        No longer exposed\n      </h3>\n      <p className=\"nx-inspector__note\">\n        This instance holds values for properties the component no longer\n        exposes. They do nothing until the component exposes them again.\n      </p>\n      <ul className=\"nx-inspector__orphans\">\n        {orphaned.map(entry => (\n          <li key={entry.id} className=\"nx-inspector__orphan\">\n            <code>{entry.id}</code>\n            <span className=\"nx-inspector__orphan-value\">\n              {valueSummary(entry.value) === \"\"\n                ? \"(empty)\"\n                : valueSummary(entry.value)}\n            </span>\n            <Button\n              type=\"button\"\n              variant=\"ghost\"\n              size=\"sm\"\n              aria-label={`Discard the stored value for ${entry.id}`}\n              onClick={() => onDiscard(entry.id)}\n            >\n              Discard\n            </Button>\n          </li>\n        ))}\n      </ul>\n    </section>\n  );\n}\n\n/**\n * \"Edit component\", where the host offers it for this placement: the verb the\n * toolbar and the palette run, drawn here as the panel's first action because\n * an author looking at a placement's fields is the one most likely to want the\n * component's own design next.\n */\n/**\n * What a component with no fields says. It points at Edit component only\n * where that button is offered: an author who may not edit components is not\n * sent to an action they lack.\n */\nfunction NoFieldsNote({\n  verbs,\n}: {\n  verbs: CardVerbs | undefined;\n}): React.JSX.Element {\n  return (\n    <p className=\"nx-inspector__note\">\n      This component has no fields to change on this page.\n      {editComponentOffered(verbs)\n        ? \" Use Edit component to change its content.\"\n        : null}\n    </p>\n  );\n}\n\n/** Whether the host offers Edit component, enabled, for this placement. */\nfunction editComponentOffered(verbs: CardVerbs | undefined): boolean {\n  return (\n    verbs?.actions.some(\n      action => action.id === \"edit-component\" && action.enabled\n    ) === true\n  );\n}\n\nfunction EditComponentButton({\n  verbs,\n}: {\n  verbs: CardVerbs | undefined;\n}): React.JSX.Element | null {\n  if (verbs === undefined || !editComponentOffered(verbs)) return null;\n  return (\n    <Button\n      type=\"button\"\n      variant=\"outline\"\n      size=\"sm\"\n      className=\"nx-inspector__edit-component\"\n      onClick={() => verbs.run(\"edit-component\")}\n    >\n      <SquarePen size={14} aria-hidden=\"true\" />\n      Edit component\n    </Button>\n  );\n}\n","/**\n * The inspector while a look is edited on its own, from the Design panel's\n * Block looks group, with no block selected: the look's name, a bar that says\n * who an edit reaches and how to go back, and the Style controls bound to the\n * look.\n *\n * The bar carries the same State switch a block's Style tab has (Normal,\n * Hover, Focus, Pressed) and names the device the top bar edits, so a look's\n * hover and other states, at each device, are set where its normal values\n * are. The choice is the look editor's own, held per look: no block is\n * selected while a look is edited, so the host's choice, which is what the\n * selected block shows on the canvas, stays Normal.\n *\n * The controls are the Style tab's own, read and written as a shared style\n * is. They are drawn over a stand-in editor holding one block of the look's\n * type, so they offer what that block type supports; it takes no page edit,\n * so nothing the controls do can reach the page except through the look.\n *\n * A look has no element of its own on the canvas, so its sides and corners\n * are named in the site's own direction, read from the canvas root: the same\n * Top, Right, Bottom, Left box a block of that site shows, mirrored on a\n * right-to-left site.\n *\n * @module look-inspector\n * @experimental Settles with the Design panel's Block looks group.\n */\n\nimport {\n  BASE_BREAKPOINT,\n  type BlockDocument,\n  type BlockNode,\n  type BreakpointId,\n  type BreakpointSet,\n  type NamedClass,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport { ArrowLeft } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useSiteOrientation } from \"../canvas/use-canvas-reading\";\nimport type { EditorState } from \"../editor-state\";\nimport { blockLabel } from \"../panels/add/inserter\";\nimport {\n  lookReachWords,\n  type BlockLookRow,\n  type LookKey,\n} from \"../panels/design/block-look-rows\";\nimport { deviceLabel } from \"../shell/breakpoint-switcher\";\n\nimport { stateLookLine } from \"./style-inspector/editing-bar\";\nimport { lookReach, markLookReach } from \"./style-inspector/look-reach\";\nimport { StyleStateField } from \"./style-inspector/state-switcher\";\nimport {\n  StyleInspectorPanel,\n  type StyleInspectorPanelProps,\n} from \"./style-inspector/style-inspector-panel\";\nimport { breakpointLabel } from \"./style-inspector/style-provenance-indicators\";\nimport {\n  useLookTarget,\n  type SharedStylesHost,\n} from \"./style-inspector/style-target\";\n\n/** What the host lends the inspector while a look is edited on its own. */\nexport interface LookEditing {\n  /** The look being edited, by its id and block type. */\n  readonly look: LookKey;\n  /** Leave look editing, back to editing blocks. */\n  readonly onExit: () => void;\n}\n\nexport interface LookInspectorProps\n  extends Omit<\n    StyleInspectorPanelProps,\n    \"editor\" | \"target\" | \"sideOrientation\" | \"state\"\n  > {\n  readonly editor: EditorState;\n  readonly look: BlockLookRow;\n  readonly host: SharedStylesHost | undefined;\n  readonly onExit: () => void;\n  /** The site's class library, which decides the look each block wears. */\n  readonly library: readonly NamedClass[];\n  /**\n   * The canvas, where the blocks the edit reaches are marked, and whose root\n   * says which way the site runs.\n   */\n  readonly canvasRoot?: HTMLElement | null;\n}\n\n/** Why an own look whose id another entry in the library carries is held. */\nconst SHARED_ID_REASON =\n  \"Another look or shared style on this site has the same id, so this one can't be edited here. Give one of them its own name in your site's code.\";\n\n/** The stand-in block's id, which no document block can share. */\nconst STAND_IN_ID = \"nx-look-stand-in\";\n\n/**\n * The editor the controls read: one block of the look's type, selected, and\n * no page edit taken, so a control that would write the block writes nothing.\n */\nfunction standInEditor(editor: EditorState, blockType: string): EditorState {\n  const node: BlockNode = {\n    id: STAND_IN_ID,\n    type: blockType,\n    version: 1,\n    props: {},\n  };\n  const document: BlockDocument = { ...editor.document, nodes: [node] };\n  return {\n    ...editor,\n    document,\n    selectedId: STAND_IN_ID,\n    selection: {\n      ...editor.selection,\n      ids: [STAND_IN_ID],\n      primary: STAND_IN_ID,\n    },\n    select: () => {},\n    apply: () => null,\n    applyAll: () => null,\n  };\n}\n\n/**\n * What an edit to the look changes, under the bar's first line: every block\n * of the type for its own look, which every other look is laid on, and every\n * block of the type using it for any other.\n */\nfunction lookChangeWords(look: BlockLookRow, title: string): string {\n  return look.own\n    ? `Changes every ${title} on every page. Where another look, a shared style or the block's own values set something, they win.`\n    : `Changes every ${title} using ${look.name} on every page`;\n}\n\n/**\n * The controls on the tint a block's Style tab draws them on, under the line\n * that names the state while one other than Normal is edited.\n */\nfunction StateTint({\n  state,\n  children,\n}: {\n  readonly state: StyleState;\n  readonly children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-style-tab__body\" data-state={state}>\n      {state === \"base\" ? null : (\n        <p className=\"nx-style-tab__state-line\" data-editing-state-line=\"\">\n          {stateLookLine(state)}\n        </p>\n      )}\n      {children}\n    </div>\n  );\n}\n\n/** The device an edit lands on, named as the top bar's switcher names it. */\nfunction editedDevice(\n  breakpoints: BreakpointSet | undefined,\n  breakpoint: BreakpointId | undefined\n): string {\n  const id = breakpoint ?? BASE_BREAKPOINT;\n  return deviceLabel(breakpoints, id) ?? breakpointLabel(breakpoints, id);\n}\n\n/**\n * Which state the look editor edits, for the look open now: a look opened\n * afresh, another one chosen, or one returned to starts at Normal. The\n * choice is replaced as soon as another look is open, during that render,\n * so a look left at Hover never comes back at Hover.\n */\nfunction useLookState(\n  look: LookKey\n): readonly [StyleState, (state: StyleState) => void] {\n  const key = JSON.stringify([look.blockType, look.id]);\n  const [chosen, setChosen] = React.useState<{\n    readonly key: string;\n    readonly state: StyleState;\n  }>({ key, state: \"base\" });\n  if (chosen.key !== key) setChosen({ key, state: \"base\" });\n  const choose = React.useCallback(\n    (state: StyleState) => setChosen({ key, state }),\n    [key]\n  );\n  return [chosen.key === key ? chosen.state : \"base\", choose];\n}\n\n/**\n * Where the look's edit lands: the device the top bar edits, and the State\n * switch, its dots read from the look's own styles, so a state is marked\n * where the look sets something.\n */\nfunction LookPlace({\n  state,\n  onState,\n  styles,\n  breakpoints,\n  breakpoint,\n}: {\n  readonly state: StyleState;\n  readonly onState: (state: StyleState) => void;\n  readonly styles: BlockLookRow[\"styles\"] | undefined;\n  readonly breakpoints: BreakpointSet | undefined;\n  readonly breakpoint: BreakpointId | undefined;\n}): React.JSX.Element {\n  return (\n    <p className=\"nx-look-bar__place\">\n      <span className=\"nx-look-bar__device\">\n        {editedDevice(breakpoints, breakpoint)}\n      </span>\n      <StyleStateField\n        state={state}\n        onSelect={onState}\n        node={styles === undefined ? null : { styles }}\n        breakpoints={breakpoints}\n      />\n    </p>\n  );\n}\n\nexport function LookInspector({\n  editor,\n  look,\n  host,\n  onExit,\n  library,\n  canvasRoot,\n  ...style\n}: LookInspectorProps): React.JSX.Element {\n  const read = useLookTarget(look, host);\n  const [state, setState] = useLookState(look);\n  // An own look whose id another look or shared style carries is held: a\n  // write by id would reach both, so the bar says why and nothing is written.\n  const target =\n    read !== undefined && read.kind === \"shared\" && look.sharedId\n      ? { ...read, readOnly: SHARED_ID_REASON }\n      : read;\n  // The blocks on this page the edit reaches, marked while the look is edited.\n  // Over the page as the canvas draws it, components composed in, so a block\n  // a placement draws is marked too. Keyed as JSON, which spells any id.\n  const reachKey = JSON.stringify([\n    ...lookReach(editor.composed() ?? editor.document, library, look),\n  ]);\n  React.useEffect(() => {\n    if (canvasRoot === null || canvasRoot === undefined) return;\n    markLookReach(canvasRoot, new Set(JSON.parse(reachKey) as string[]));\n    return () => markLookReach(canvasRoot, null);\n  }, [canvasRoot, reachKey]);\n  const stand = React.useMemo(\n    () => standInEditor(editor, look.blockType),\n    [editor, look.blockType]\n  );\n  // The site's direction names the look's sides, as a block's box names its\n  // own. Re-read on the signals that can restyle the page.\n  const sideOrientation = useSiteOrientation(canvasRoot, {\n    document: editor.document,\n    state,\n    breakpoint: style.breakpoint,\n    cascade: style.cascade,\n    previewContainer: style.previewContainer,\n  });\n  const title = blockLabel(look.blockType);\n  return (\n    <div className=\"nx-inspector nx-look-inspector\" data-look={look.id}>\n      <div className=\"nx-look-inspector__head\">\n        <span className=\"nx-look-inspector__name\">{look.name}</span>\n        <span className=\"nx-look-inspector__kind\">\n          {`A look for ${title} blocks`}\n        </span>\n      </div>\n      <LookBar\n        look={look}\n        title={title}\n        onExit={onExit}\n        readOnly={target?.kind === \"shared\" ? target.readOnly : undefined}\n        place={\n          <LookPlace\n            state={state}\n            onState={setState}\n            styles={target?.kind === \"shared\" ? target.style.styles : undefined}\n            breakpoints={style.breakpoints}\n            breakpoint={style.breakpoint}\n          />\n        }\n      />\n      {target === undefined ? (\n        <p className=\"nx-inspector__note\">\n          {\n            \"This look can't be changed here: the site's shared styles aren't available.\"\n          }\n        </p>\n      ) : (\n        <StateTint state={state}>\n          <StyleInspectorPanel\n            {...style}\n            state={state}\n            editor={stand}\n            target={target}\n            sideOrientation={sideOrientation}\n          />\n        </StateTint>\n      )}\n    </div>\n  );\n}\n\n/**\n * The bar above the controls: which look is edited and who the edit reaches,\n * what it changes, and the way back to editing blocks. Esc goes back too.\n */\nfunction LookBar({\n  look,\n  title,\n  onExit,\n  readOnly,\n  place,\n}: {\n  readonly look: BlockLookRow;\n  readonly title: string;\n  readonly onExit: () => void;\n  /** Why the look's values can't be changed, when they can't. */\n  readonly readOnly: string | undefined;\n  /** The device and the State switch the edit lands on. */\n  readonly place: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <div\n      className=\"nx-look-bar\"\n      role=\"group\"\n      aria-label={`Editing ${look.name}`}\n      onKeyDown={event => {\n        if (event.key !== \"Escape\") return;\n        event.preventDefault();\n        onExit();\n      }}\n    >\n      <p className=\"nx-look-bar__line\">\n        <span className=\"nx-look-bar__label\">Editing</span>{\" \"}\n        <span className=\"nx-look-bar__chip\">{look.name}</span>{\" \"}\n        <span className=\"nx-look-bar__reach\">\n          {`· ${lookReachWords(look, title)}`}\n        </span>\n      </p>\n      <p className=\"nx-look-bar__note\">{lookChangeWords(look, title)}</p>\n      {place}\n      {/* The controls below are held: the bar says why, as the editing bar\n          does for a shared style the block wears. */}\n      {readOnly === undefined ? null : (\n        <p className=\"nx-look-bar__held\" role=\"note\">\n          {readOnly}\n        </p>\n      )}\n      <button type=\"button\" className=\"nx-look-bar__back\" onClick={onExit}>\n        <ArrowLeft aria-hidden=\"true\" size={12} />\n        Back to block editing\n        <kbd className=\"nx-look-bar__key\">Esc</kbd>\n      </button>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The inspector when several blocks are selected: how many, and the lock,\n * the one control well defined across a set.\n *\n * @module many-blocks-panel\n */\n\nimport * as React from \"react\";\n\nimport { selectionLock } from \"../canvas/selection-ops\";\nimport type { EditorState } from \"../editor-state\";\n\nimport { SelectionCard } from \"./block-card\";\nimport {\n  lockStateOf,\n  layersLockChangeable,\n  lockStatusOf,\n  lockViewOf,\n  type LockState,\n} from \"./inspector\";\n\n/**\n * The inspector when several blocks are selected.\n *\n * Says how many, and offers in its menu the one control that is well defined\n * across a set: the lock. From a set that is partly locked, the menu LOCKS\n * everything — the alternative is a first press that appears to do nothing to\n * the blocks that were already unlocked, and every file manager and design\n * tool resolves it the same way.\n *\n * Planned only over the blocks whose own lock may change here. A block inside\n * a `contentOnly` area has its lock pinned by that area, and the edit is\n * applied as one group, so planning it would have the save refuse the whole\n * edit and change none of the others. The card says how many are held and why.\n */\nexport function ManyBlocksPanel({\n  editor,\n  count,\n  lock,\n}: {\n  editor: EditorState;\n  count: number;\n  lock: LockState;\n}): React.JSX.Element {\n  const view = lockViewOf(editor);\n  const changeable = editor.selection.ids.filter(id =>\n    layersLockChangeable(lockStatusOf(editor.document, id, view))\n  );\n  // The direction is read from the blocks it would change, so a held block\n  // already in the other state cannot leave the menu with nothing to do.\n  const unlocking =\n    changeable.length > 0 &&\n    lockStateOf(editor.document, changeable) === \"locked\";\n  const plan = selectionLock(editor.document, changeable, !unlocking);\n\n  return (\n    <div className=\"nx-inspector\" data-selection=\"many\">\n      <SelectionCard\n        count={count}\n        lock={lock}\n        unlocking={unlocking}\n        held={editor.selection.ids.length - changeable.length}\n        onLock={plan === null ? undefined : () => editor.applyAll(plan.ops)}\n      />\n      <p className=\"nx-inspector__note\">\n        Editing properties across several blocks is not available yet. Select\n        one block to edit what it holds.\n      </p>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The block panel's options menu (⋯), beside its tabs: Expand all and\n * Collapse all fold every section of the tab that is showing, and Show CSS\n * names prints what each control writes under its label.\n *\n * @module panel-options\n */\nimport {\n  DropdownMenu,\n  DropdownMenuCheckboxItem,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { Ellipsis } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useCssNames } from \"./css-names-context\";\nimport { withTabFold } from \"./panel-folds\";\nimport { usePanelFolds } from \"./panel-folds-context\";\nimport { useSearchFolds, useSettingsMatch } from \"./settings-filter\";\n\n/** The ⋯ menu for the tab that is showing. */\nexport function PanelOptions({ tab }: { tab: string }): React.JSX.Element {\n  const { change } = usePanelFolds();\n  const cssNames = useCssNames();\n  const match = useSettingsMatch();\n  const searchFolds = useSearchFolds();\n  // While filtered, the menu folds what the filter shows, and the author's\n  // own folds wait for it to be cleared.\n  const foldAll = (open: boolean) =>\n    match.active\n      ? searchFolds.set(tab, { kind: \"all\", open })\n      : change(current => withTabFold(current, tab, open));\n  return (\n    // Not modal: a modal menu marks the editor around it aria-hidden while\n    // its controls stay focusable (axe: aria-hidden-focus).\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild>\n        <button\n          type=\"button\"\n          className=\"nx-inspector__options\"\n          aria-label=\"Panel options\"\n        >\n          <Ellipsis size={16} aria-hidden=\"true\" />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align=\"end\">\n        <DropdownMenuItem onSelect={() => foldAll(true)}>\n          Expand all\n        </DropdownMenuItem>\n        <DropdownMenuItem onSelect={() => foldAll(false)}>\n          Collapse all\n        </DropdownMenuItem>\n        <DropdownMenuSeparator />\n        {/* For developers: each control's CSS property names, printed\n            small under its label. */}\n        <DropdownMenuCheckboxItem\n          checked={cssNames.shown}\n          onCheckedChange={shown => cssNames.set(shown === true)}\n        >\n          Show CSS names\n        </DropdownMenuCheckboxItem>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n","/**\n * The selected block's settings as entries of the settings index, read from\n * what each tab draws: the block's inspection for Content and Advanced (with\n * the builder's own Visibility and HTML rows), the Style tab's sections for\n * Style.\n *\n * @module settings-entries\n */\nimport {\n  BASE_BREAKPOINT,\n  type BlockNode,\n  type BreakpointSet,\n  type PropSchema,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  COLUMNS_LAYOUTS,\n  COLUMNS_ROW,\n  stackOf,\n  stackTiers,\n} from \"../canvas/columns-layout\";\nimport { propLabel } from \"../prop-label\";\nimport {\n  BUTTON_BLOCK,\n  ICON_BLOCK,\n  SECTION_BLOCK,\n  sizesOffered,\n  type ShortcutAt,\n} from \"../styles/block-shortcuts\";\nimport {\n  childAxisRows,\n  LAYOUT_CSS_NAMES,\n  offersChildAxis,\n  type ChildAxis,\n  type ParentArrangement,\n  type PlainFlow,\n} from \"../styles/plain-layout\";\nimport { readStyleValue } from \"../styles/style-values\";\n\nimport { BUILT_IN_WRITES } from \"./code-hints\";\nimport {\n  ACCORDION_BLOCK,\n  ACCORDION_ICON_WORDS,\n  ACCORDION_ICONS,\n  accordionIconHoldsValue,\n} from \"./content/accordion-icon\";\nimport {\n  galleryColumnsHoldValue,\n  GALLERY_COLUMNS,\n  GALLERY_MOBILE,\n} from \"./content/gallery-columns\";\nimport { GALLERY_BLOCK } from \"./content/gallery-pictures\";\nimport {\n  CUSTOM_CSS_KEY,\n  CUSTOM_CSS_SECTION,\n  CUSTOM_CSS_SETTING,\n} from \"./custom-css\";\nimport {\n  builderContentSectionsOf,\n  contentRowsOf,\n  type BlockInspection,\n  type EditableProp,\n} from \"./inspector\";\nimport {\n  advancedRowsBySection,\n  HTML_SECTION,\n  VISIBILITY_SECTION,\n} from \"./inspector-advanced-tab\";\nimport { offersNeverQuote } from \"./never-quote\";\nimport {\n  sectionEntries,\n  type IndexedRow,\n  type SettingEntry,\n} from \"./settings-index\";\nimport {\n  HEIGHT_LABELS,\n  SHORTCUT_IDS,\n  SIZE_LABELS,\n} from \"./style-inspector/block-shortcuts-field\";\nimport { CONTENT_WIDTH_CHOICES } from \"./style-inspector/content-width-control\";\nimport {\n  addableRows,\n  arrangeCssProperties,\n  CSS_PROPERTIES_SECTION,\n  writtenCss,\n  type CssPropertyRow,\n} from \"./style-inspector/css-properties\";\nimport { CHILD_SIZE_IDS } from \"./style-inspector/plain-parent-controls\";\nimport type { StyleSection } from \"./style-inspector/style-inspector\";\nimport { keywordLabel } from \"./style-inspector/style-keyword-labels\";\n\n/** What a prop writes into the page, every spelling its schema gives. */\nfunction writesOf(schema: Pick<PropSchema, \"code\">): readonly string[] {\n  const { code } = schema;\n  if (code === undefined) return [];\n  return typeof code === \"string\" ? [code] : Object.values(code);\n}\n\n/** An option's label, where the schema names one. */\nfunction optionLabelOf(schema: PropSchema, option: string): string {\n  const labels = (schema as { optionLabels?: Readonly<Record<string, string>> })\n    .optionLabels;\n  return labels?.[option] ?? option;\n}\n\n/** A drawn prop as an index row; a binding of its own counts as set. */\nfunction propRow(row: EditableProp, bound: ReadonlySet<string>): IndexedRow {\n  return {\n    id: row.name,\n    label: propLabel(row.name, row.schema),\n    // As the author reads them: a select's labels, not its stored values.\n    options: row.options.map(option => optionLabelOf(row.schema, option)),\n    css: writesOf(row.schema),\n    set: row.value !== undefined || bound.has(row.name),\n  };\n}\n\n/** The props a block binds to data, which hold a setting of their own. */\nfunction boundProps(node: BlockNode | undefined): ReadonlySet<string> {\n  const bindings = (node as { bindings?: Record<string, unknown> } | undefined)\n    ?.bindings;\n  return new Set(Object.keys(bindings ?? {}));\n}\n\n/** The props a section draws. */\nfunction drawnRows(\n  rows: readonly EditableProp[],\n  bound: ReadonlySet<string>\n): IndexedRow[] {\n  return rows.filter(row => row.offered).map(row => propRow(row, bound));\n}\n\n/**\n * The controls a Gallery's builder-drawn sections hold: Add images in\n * Pictures, and Columns and On mobile in Layout, the latter only where the\n * site has a mobile tier, as the section draws it.\n */\nfunction galleryRows(\n  node: BlockNode,\n  section: string,\n  breakpoints: BreakpointSet | undefined\n): IndexedRow[] {\n  if (section === \"Pictures\") {\n    return [{ id: \"galleryAddImages\", label: \"Add images\", set: false }];\n  }\n  const tiers = stackTiers(breakpoints);\n  const set = galleryColumnsHoldValue(node, tiers);\n  const columns: IndexedRow = {\n    id: \"galleryColumns\",\n    label: \"Columns\",\n    options: GALLERY_COLUMNS.map(String),\n    css: [\"grid-template-columns\"],\n    set,\n  };\n  if (tiers.mobile === undefined) return [columns];\n  return [\n    columns,\n    {\n      id: \"galleryMobile\",\n      label: \"On mobile\",\n      options: GALLERY_MOBILE.map(String),\n      css: [\"grid-template-columns\"],\n      set,\n    },\n  ];\n}\n\n/**\n * The controls a builder-drawn Content section holds: Columns' Layout tiles,\n * Stack on and its Reverse, set as the section's own dot says; a Gallery's,\n * by section.\n */\nfunction builderRows(\n  node: BlockNode | undefined,\n  breakpoints: BreakpointSet | undefined,\n  section: string\n): IndexedRow[] {\n  if (node?.type === GALLERY_BLOCK) {\n    return galleryRows(node, section, breakpoints);\n  }\n  // An Accordion's Icon: the questions' icon, a style value.\n  if (node?.type === ACCORDION_BLOCK) {\n    return [\n      {\n        id: \"disclosureIcon\",\n        label: \"Icon\",\n        options: ACCORDION_ICONS.map(each => ACCORDION_ICON_WORDS[each]),\n        set: accordionIconHoldsValue(node),\n      },\n    ];\n  }\n  if (node === undefined || node.type !== COLUMNS_ROW) return [];\n  const tiers = stackTiers(breakpoints);\n  const template = readStyleValue(node.styles, {\n    state: \"base\",\n    breakpoint: BASE_BREAKPOINT,\n    property: \"gridTemplateColumns\",\n    path: [],\n  });\n  const stacked = stackOf(node, tiers, \"base\").on !== \"never\";\n  const layout: IndexedRow = {\n    id: \"columnsLayout\",\n    label: \"Layout\",\n    // The tiles' own words: \"2 equal\", \"Wide left\".\n    options: COLUMNS_LAYOUTS.map(each => each.label),\n    css: [\"grid-template-columns\"],\n    set: template !== undefined,\n  };\n  // Stack on is drawn only where the site has a tablet or mobile tier.\n  if (tiers.tablet === undefined && tiers.mobile === undefined) return [layout];\n  return [\n    layout,\n    { id: \"stackOn\", label: \"Stack on\", css: [\"flex-direction\"], set: stacked },\n    {\n      id: \"reverseStacked\",\n      label: \"Reverse when stacked\",\n      css: [\"flex-direction\"],\n      set: stacked,\n    },\n  ];\n}\n\n/** The Content tab's settings: the builder's own section, then the block's. */\nexport function contentEntries(\n  inspection: BlockInspection,\n  node: BlockNode | undefined,\n  breakpoints?: BreakpointSet\n): SettingEntry[] {\n  const bound = boundProps(node);\n  // The builder's own sections come first, drawn whatever else the tab holds.\n  const builder = builderContentSectionsOf(inspection.blockName).flatMap(own =>\n    sectionEntries(\n      \"content\",\n      { key: own, label: own },\n      builderRows(node, breakpoints, own)\n    )\n  );\n  const sections = inspection.sections.content;\n  if (sections.length === 0 && builder.length === 0) {\n    // A block with no sections draws its Content rows bare.\n    return sectionEntries(\n      \"content\",\n      { key: \"\", label: \"\" },\n      drawnRows(contentRowsOf(inspection), bound)\n    );\n  }\n  const own = sections.flatMap(section =>\n    sectionEntries(\n      \"content\",\n      { key: section.label, label: section.label },\n      drawnRows(section.rows, bound)\n    )\n  );\n  // An Accordion's Icon is drawn after its Behaviour, so it is read there.\n  return inspection.blockName === ACCORDION_BLOCK\n    ? [...own, ...builder]\n    : [...builder, ...own];\n}\n\n/** Whether a block is hidden on any device. */\nfunction hiddenSomewhere(node: BlockNode | undefined): boolean {\n  const devices = node?.visibility?.devices;\n  return devices !== undefined && Object.values(devices).some(shown => !shown);\n}\n\n/** The Advanced tab's settings: Visibility, HTML, then the block's own. */\nexport function advancedEntries(\n  inspection: BlockInspection,\n  node: BlockNode | undefined,\n  /**\n   * Whether Advanced draws Custom CSS, for a person who may change site\n   * code: only then can a search find it or Only changed count it.\n   */\n  offersCustomCss = false\n): SettingEntry[] {\n  const bound = boundProps(node);\n  const { htmlRows, visibilityRows, others } = advancedRowsBySection(\n    inspection.sections.advanced\n  );\n  const conditions = node?.visibility?.conditions;\n  const visibility: IndexedRow[] = [\n    { id: \"hideOn\", label: \"Hide on\", set: hiddenSomewhere(node) },\n    {\n      id: \"showWhen\",\n      label: \"Show when\",\n      set: Array.isArray(conditions) && conditions.length > 0,\n    },\n    ...(node !== undefined && offersNeverQuote(node)\n      ? [\n          {\n            id: \"neverQuote\",\n            label: \"Keep out of search previews\",\n            css: [BUILT_IN_WRITES.searchPreviews],\n            set: node.nosnippet === true,\n          },\n        ]\n      : []),\n    ...drawnRows(visibilityRows, bound),\n  ];\n  const { cssId, attributes } = inspection.html;\n  const otherAttributes = Object.keys(attributes ?? {}).filter(\n    name => name !== \"class\"\n  );\n  const html: IndexedRow[] = [\n    ...drawnRows(htmlRows, bound),\n    {\n      id: \"anchor\",\n      label: \"Anchor (ID)\",\n      css: [BUILT_IN_WRITES.anchor],\n      set: cssId !== undefined,\n    },\n    {\n      id: \"cssClasses\",\n      label: \"CSS classes\",\n      css: [BUILT_IN_WRITES.cssClasses],\n      set: typeof node?.cssClasses === \"string\" && node.cssClasses !== \"\",\n    },\n    {\n      id: \"attributes\",\n      label: \"Attributes\",\n      css: otherAttributes,\n      set: otherAttributes.length > 0,\n    },\n  ];\n  return [\n    ...sectionEntries(\n      \"advanced\",\n      { key: \"visibility\", label: VISIBILITY_SECTION },\n      visibility\n    ),\n    ...sectionEntries(\"advanced\", { key: \"html\", label: HTML_SECTION }, html),\n    ...others.flatMap(section =>\n      sectionEntries(\n        \"advanced\",\n        { key: `own:${section.label}`, label: section.label },\n        drawnRows(section.rows, bound)\n      )\n    ),\n    // Last, as the tab draws it; set by the one answer its dot reads.\n    ...(offersCustomCss\n      ? sectionEntries(\n          \"advanced\",\n          { key: CUSTOM_CSS_KEY, label: CUSTOM_CSS_SECTION },\n          [\n            {\n              id: CUSTOM_CSS_SETTING,\n              label: CUSTOM_CSS_SECTION,\n              set: inspection.hasCustomCss,\n            },\n          ]\n        )\n      : []),\n  ];\n}\n\n/**\n * A block setting Style draws with a control of its own, given that\n * control's choices: Content width's Boxed and Full width.\n */\nfunction withDrawnChoices(row: IndexedRow): IndexedRow {\n  if (row.id !== CONTAINED_PROP) return row;\n  return {\n    ...row,\n    options: CONTENT_WIDTH_CHOICES.map(choice => choice.label),\n  };\n}\n\n/** The prop Content width's choice is stored in. */\nconst CONTAINED_PROP = \"contained\";\n\n/**\n * The shortcuts the Size section draws above its fields: a Section's Height,\n * a Button's Size and Full width, by the words they're drawn with, each set\n * where the block stores what it writes at the edited address.\n */\nfunction shortcutRows(\n  node: BlockNode | undefined,\n  at: ShortcutAt\n): IndexedRow[] {\n  if (node === undefined) return [];\n  const stores = (property: string) =>\n    readStyleValue(node.styles, {\n      state: at.state,\n      breakpoint: at.breakpoint,\n      property,\n      path: [],\n    }) !== undefined;\n  if (node.type === SECTION_BLOCK) {\n    return [\n      {\n        id: SHORTCUT_IDS.height,\n        label: \"Height\",\n        options: Object.values(HEIGHT_LABELS),\n        css: [\"min-height\"],\n        set: stores(\"minHeight\"),\n      },\n    ];\n  }\n  if (node.type === ICON_BLOCK) {\n    return [\n      {\n        id: SHORTCUT_IDS.size,\n        label: \"Size\",\n        options: Object.values(SIZE_LABELS),\n        css: [\"font-size\"],\n        set: stores(\"fontSize\"),\n      },\n    ];\n  }\n  if (node.type !== BUTTON_BLOCK) return [];\n  return [\n    ...(sizesOffered(node)\n      ? [\n          {\n            id: SHORTCUT_IDS.size,\n            label: \"Size\",\n            options: Object.values(SIZE_LABELS),\n            css: [\"padding\", \"font-size\"],\n            set: stores(\"padding\") || stores(\"fontSize\"),\n          },\n        ]\n      : []),\n    {\n      id: SHORTCUT_IDS.fullWidth,\n      label: \"Full width\",\n      css: [\"width\"],\n      set: stores(\"width\"),\n    },\n  ];\n}\n\n/**\n * \"Inside its parent\"'s Width, and its Height under a Row or a Grid, by the\n * words they're drawn with, set where the block holds a share of its own.\n * None where the parent isn't known: nothing draws them.\n */\nfunction childSizeRows(\n  parent: ParentArrangement | undefined,\n  sections: readonly StyleSection[],\n  flow: PlainFlow | undefined\n): IndexedRow[] {\n  if (parent === undefined) return [];\n  const choices = [\"Fill\", \"Fit\", \"Fixed\"];\n  // Each axis is set by what it writes, wherever its rows are (a width is\n  // Size's): a share's or an order's value says nothing of the other axis.\n  const stored = new Set(\n    sections\n      .flatMap(section => section.properties)\n      .filter(property => property.set)\n      .map(property => property.property)\n  );\n  const holds = (properties: readonly string[]) =>\n    properties.some(property => stored.has(property));\n  return [\n    {\n      id: CHILD_SIZE_IDS.width,\n      label: \"Width\",\n      options: choices,\n      css: cssNamesOf(written(\"width\")),\n      set: holds(written(\"width\")),\n    },\n    ...(offersChildAxis(parent, \"height\", flow)\n      ? [\n          {\n            id: CHILD_SIZE_IDS.height,\n            label: \"Height\",\n            options: choices,\n            css: cssNamesOf(written(\"height\")),\n            set: holds(written(\"height\")),\n          },\n        ]\n      : []),\n  ];\n\n  /** What a size's choices write, its own size included. */\n  function written(axis: ChildAxis): string[] {\n    return [axis, ...childAxisRows(parent as ParentArrangement, axis, flow)];\n  }\n}\n\n/** Layout properties by their CSS names, as a search spells them. */\nfunction cssNamesOf(properties: readonly string[]): string[] {\n  return properties.map(property => LAYOUT_CSS_NAMES[property] ?? property);\n}\n\n/**\n * A Style property's choices, in the words its controls draw them with\n * (Position's \"Sticky\"), so a choice is found by its name.\n */\nfunction optionsOf(property: StyleSection[\"properties\"][number]): string[] {\n  const labels = new Set<string>();\n  for (const control of property.controls) {\n    const leaf = control.leaf as {\n      readonly kind: string;\n      readonly cssProperty?: string;\n      readonly values?: readonly string[];\n    };\n    if (leaf.kind !== \"keyword\" || leaf.cssProperty === undefined) continue;\n    for (const keyword of leaf.values ?? []) {\n      labels.add(keywordLabel(leaf.cssProperty, keyword));\n    }\n  }\n  return [...labels];\n}\n\n/**\n * \"CSS properties\"' settings: those holding a value, drawn as its rows, and\n * those the block can use but doesn't show, which a search offers to add. By\n * their plain names, found by their CSS names too.\n */\nfunction cssPropertyEntries(extras: readonly CssPropertyRow[]): SettingEntry[] {\n  const addable = new Set(addableRows(extras, new Set()));\n  return sectionEntries(\n    \"style\",\n    CSS_PROPERTIES_SECTION,\n    extras\n      .filter(each => each.row.set || addable.has(each))\n      .map(each => ({\n        id: each.id,\n        label: each.plainName,\n        options: optionsOf(each.row),\n        css: [each.cssName, ...writtenCss(each.row)],\n        set: each.row.set,\n        addable: !each.row.set,\n      }))\n  );\n}\n\n/**\n * The Style tab's settings: each section's properties it draws, and the\n * block's own settings it draws there (Content width, a Section's Height),\n * under the section that draws them; then \"CSS properties\".\n */\nexport function styleEntries(\n  sections: readonly StyleSection[],\n  inspection: BlockInspection | null,\n  shortcuts?: { node: BlockNode | undefined; at: ShortcutAt },\n  parent?: ParentArrangement,\n  flow?: PlainFlow,\n  arranges?: boolean\n): SettingEntry[] {\n  const props = inspection?.sections.styleProps ?? [];\n  // Arranged as the tab draws them, so a search finds a row where it is\n  // drawn, and nothing it doesn't draw.\n  // The block's own shortcuts are drawn only where it is edited itself.\n  const arranged = arrangeCssProperties(sections, {\n    blockType: shortcuts?.node?.type,\n    arranges,\n  });\n  return [\n    ...arranged.sections.flatMap(section => {\n      const own = props.find(each => each.key === section.key)?.rows ?? [];\n      return sectionEntries(\"style\", section, [\n        ...(section.key === \"inside-parent\"\n          ? childSizeRows(parent, sections, flow)\n          : []),\n        ...(section.key === \"size\" && shortcuts !== undefined\n          ? shortcutRows(shortcuts.node, shortcuts.at)\n          : []),\n        ...drawnRows(own, new Set()).map(withDrawnChoices),\n        ...section.properties\n          .filter(property => property.common)\n          .map(property => ({\n            id: property.property,\n            label: property.label,\n            options: optionsOf(property),\n            css: writtenCss(property),\n            set: property.set,\n          })),\n      ]);\n    }),\n    ...cssPropertyEntries(arranged.extras),\n  ];\n}\n","\"use client\";\n\n/**\n * The inspector: editing the selected block's props.\n *\n * Draws what `inspector` decides and decides nothing itself — which props a\n * block exposes, in what order, and the patch that changes one all live there,\n * where they can be asserted without a DOM.\n *\n * **Text writes as it is typed**, so the canvas follows every keystroke. Undo\n * is built from op inverses, and an op per character would make one undo\n * remove one letter, so the writes of one stretch of typing share a run\n * (`live-draft.ts`, over `typing-run.ts`) that the history keeps as ONE step:\n * undo takes back the whole edit, which is what an author means by \"undo that\n * change\". Blur and Enter end the run. A value that is not one yet (`12p`,\n * half a hex colour) writes nothing, so the canvas keeps the last valid one.\n * A shared style is the exception: it is stored on the site at once, so its\n * fields write when the edit ends.\n *\n * Discrete controls — a checkbox, a select — commit immediately. There is no\n * typing to group, and waiting for blur on a checkbox would leave the canvas\n * disagreeing with a control the author has already changed.\n *\n * This module draws the panel, its three tabs and the surface a selection\n * gets, and is the entry for the rest: what the panel takes is in\n * `inspector-panel-types.ts`, the style state it edits and the tab it shows\n * in `inspector-style-state.ts`, the Content tab in `inspector-content-tab.tsx`\n * and its generated fields in `inspector-content-fields.tsx`, the Style tab\n * in `inspector-style-tab.tsx`, the Advanced tab in\n * `inspector-advanced-tab.tsx`, and the panel for several blocks in\n * `many-blocks-panel.tsx`.\n *\n * @module inspector-panel\n */\n\nimport {\n  BASE_BREAKPOINT,\n  findNode,\n  type BlockDocument,\n  type BlockNode,\n  STYLE_STATES,\n  type BreakpointId,\n  type BreakpointSet,\n  type ComponentLookup,\n  type StyleState,\n} from \"@nextlyhq/blocks-engine\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { CanvasPassageContext } from \"../canvas/canvas-passage\";\nimport { useCanvasReading } from \"../canvas/use-canvas-reading\";\nimport type { EditorState } from \"../editor-state\";\nimport { EDITOR_WORDS } from \"../editor-words\";\nimport { FieldsOfDocument } from \"../field-edit\";\nimport { TypingCancel } from \"../live-draft\";\nimport {\n  blockLookGroups,\n  sameLook,\n  type BlockLookRow,\n} from \"../panels/design/block-look-rows\";\nimport type { PlainFlow } from \"../styles/plain-layout\";\n\nimport { useAskedSetting } from \"./asked-setting\";\nimport { BlockCard, type CardVerbs } from \"./block-card\";\nimport {\n  ComponentFieldsContext,\n  ComponentFieldsScope,\n  ExposedFieldsList,\n  type ComponentFieldsBinding,\n} from \"./component-fields-panel\";\nimport {\n  ComponentVariantsContext,\n  ComponentVariantsSection,\n} from \"./component-variants-panel\";\nimport { ContentServicesContext } from \"./content/content-controls\";\nimport { galleryPictureOf } from \"./content/gallery-pictures\";\nimport { CssNamesProvider } from \"./css-names-context\";\nimport { CustomCssStyleLine } from \"./custom-css-section\";\nimport { HiddenStatus } from \"./hide-on\";\nimport {\n  inspectorTabsOf,\n  inspectSelection,\n  lockOp,\n  lockStateOf,\n  layersLockChangeable,\n  lockStatusOf,\n  lockViewOf,\n  renameOp,\n  selectedNode,\n  type BlockInspection,\n  type InspectorTab,\n} from \"./inspector\";\nimport { AdvancedTab } from \"./inspector-advanced-tab\";\nimport { commitProp, ContentTab } from \"./inspector-content-tab\";\nimport type {\n  ComponentLibrary,\n  DocumentSettingsView,\n  InspectorPanelProps,\n  StyleStateBinding,\n} from \"./inspector-panel-types\";\nimport { openingTabFor, shownTab } from \"./inspector-style-state\";\nimport { StyleTab } from \"./inspector-style-tab\";\nimport { inspectInstance, type InstanceInspection } from \"./instance-inspector\";\nimport { InstanceInspectorPanel } from \"./instance-inspector-panel\";\nimport { LookInspector } from \"./look-inspector\";\nimport { ManyBlocksPanel } from \"./many-blocks-panel\";\nimport { PanelFoldsProvider } from \"./panel-folds-context\";\nimport { PanelOptions } from \"./panel-options\";\nimport {\n  advancedEntries,\n  contentEntries,\n  styleEntries,\n} from \"./settings-entries\";\nimport {\n  ChangedElsewhere,\n  FilterNote,\n  SettingsFilterProvider,\n  SettingsMatchProvider,\n  SettingsSearchRow,\n  settingsMatch,\n  TabCount,\n  StyleReportContext,\n  useFilterState,\n  useFindShortcut,\n  type ReportedStyle,\n  type SettingsMatch,\n} from \"./settings-filter\";\nimport {\n  changedElsewhere,\n  filtering,\n  type SettingEntry,\n  type SettingsFilter,\n  type StoredStyles,\n} from \"./settings-index\";\nimport { blockStyleEntries } from \"./style-inspector/look-tiles-view\";\nimport { stateLabel } from \"./style-inspector/state-switcher\";\nimport { inspectStyle } from \"./style-inspector/style-inspector\";\nimport { breakpointLabel } from \"./style-inspector/style-provenance-indicators\";\nimport { placedDefinition } from \"./variant-picker\";\n\n// What the panel takes, the style state it edits, the Content and Style tabs,\n// the Content tab's fields and the panel for several blocks live in modules\n// of their own beside it; every name this module exported still is.\n// Part of this module's exported names; no importer in the package reads them.\n// fallow-ignore-next-line unused-type\nexport type { ComponentLibrary } from \"./inspector-panel-types\";\n// fallow-ignore-next-line unused-type\nexport type { StyleStateBinding } from \"./inspector-panel-types\";\nexport type {\n  BlockInspectorResolver,\n  InspectorPanelProps,\n} from \"./inspector-panel-types\";\nexport { editedStyleState } from \"./inspector-style-state\";\n\n/**\n * The inspector's tabs: what the block says, shows or links to; how it looks;\n * and how it is built into the page (where and when it shows, its HTML).\n *\n * Three, as Elementor, Divi and Breakdance split a block's settings, so the\n * settings that change the HTML but not what a visitor reads have a place of\n * their own rather than a fold at the end of Content. A block has only the\n * tabs that hold something for it (`inspectorTabsOf`).\n */\nconst INSPECTOR_TABS: readonly { value: InspectorTab; label: string }[] = [\n  { value: \"content\", label: EDITOR_WORDS.content },\n  { value: \"style\", label: EDITOR_WORDS.style },\n  { value: \"advanced\", label: EDITOR_WORDS.advanced },\n];\n\n/** The inspector's tab names, in order, as an author reads them. */\nexport function inspectorTabLabels(): string[] {\n  return INSPECTOR_TABS.map(tab => tab.label);\n}\n\n/**\n * What a host that supplies no library is judged under: nothing resolves, so an\n * instance reads as one whose definition could not be loaded. A shared instance\n * rather than a fresh one per render, because the inspection is recomputed\n * every render and a fresh empty map is a new identity for nothing.\n */\nconst NO_LIBRARY: ComponentLibrary = { definitions: new Map(), components: [] };\n\n/** The selected instance, under the library the host supplied or the empty one. */\nfunction selectedInstance(\n  editor: EditorState,\n  library: ComponentLibrary = NO_LIBRARY\n): InstanceInspection | null {\n  return inspectInstance(\n    editor.document,\n    editor.selectedId,\n    library.definitions,\n    library.components,\n    lockViewOf(editor)\n  );\n}\n\n/**\n * Which surface a selection gets: one drawn WITHOUT the tab strip, or the\n * block whose tabs apply.\n *\n * A discriminated answer rather than \"an element or null\", so the caller that\n * goes on to draw the tabs holds a BLOCK inspection by type rather than a\n * maybe it has to re-check.\n *\n * Three selections get a surface of their own, and the order is the rule.\n * Several blocks first: a selection of several instances is still several\n * blocks, and the lock is still the one thing well defined across them. An\n * instance next, before the empty case: the block inspection IS empty for an\n * instance — its type is not in the registry — and answering \"select a block\"\n * to an author who just clicked a component was the state that surface\n * replaces. Nothing selected last: the document's own settings, and no\n * tabs.\n */\nfunction surfaceFor(\n  editor: EditorState,\n  instance: InstanceInspection | null,\n  inspection: BlockInspection | null,\n  verbs: CardVerbs | undefined,\n  fields: ComponentFieldsBinding | undefined,\n  definitions: ComponentLookup,\n  /** The canvas's root, where the instance panel marks a placement's parts. */\n  canvasRoot: HTMLElement | null | undefined,\n  /** The host's view of the open document, drawn while nothing is selected. */\n  documentSettings: DocumentSettingsView | undefined\n):\n  | { readonly tabless: React.JSX.Element }\n  | { readonly block: BlockInspection } {\n  /*\n   * Several blocks selected: a different panel, not a thinner one.\n   *\n   * Showing the primary's name and props while six blocks are selected would\n   * describe one block and act on one block, on a screen where the canvas shows\n   * six outlined and the toolbar's delete removes all of them. The two surfaces\n   * would be answering different questions with the same words.\n   *\n   * Per-property batch editing — one field showing \"Mixed\" and writing to every\n   * block — is Plan 05's batch edit and is deliberately not here. What IS here\n   * is the one property that is well defined across any set today, because it\n   * is a flag rather than a value: the lock.\n   */\n  if (editor.selection.ids.length > 1) {\n    return {\n      tabless: (\n        <ManyBlocksPanel\n          editor={editor}\n          count={editor.selection.ids.length}\n          lock={lockStateOf(editor.document, editor.selection.ids)}\n        />\n      ),\n    };\n  }\n  if (instance !== null) {\n    return {\n      tabless: (\n        <InstanceInspectorPanel\n          inspection={instance}\n          editor={editor}\n          verbs={verbs}\n          definition={placedDefinition(definitions, instance.componentId)}\n          canvasRoot={canvasRoot}\n        />\n      ),\n    };\n  }\n  /*\n   * Nothing selected: the open document's own settings, drawn by the host\n   * (a page's title, address and header & footer), in the same frame and so\n   * at the same width, so the canvas never rescales on a click. Tabs are\n   * withheld: a Style tab over no selection would offer an author somewhere\n   * to click that can never show anything.\n   *\n   * In a component's own view, nothing selected means the component itself\n   * is what is being looked at, so its exposed fields are listed, and the\n   * variants that preset them under those, handed to the host to place\n   * among its own rows.\n   */\n  if (editor.selectedId === null) {\n    const own =\n      inspection === null && fields !== undefined ? (\n        <ExposedFieldsList binding={fields} editor={editor}>\n          <ComponentVariantsSection\n            editor={editor}\n            component={fields.context.component}\n          />\n        </ExposedFieldsList>\n      ) : null;\n    return {\n      tabless: (\n        <div className=\"nx-inspector\" data-empty=\"no-selection\">\n          {documentSettings === undefined ? own : documentSettings(own)}\n        </div>\n      ),\n    };\n  }\n  // A block whose type this site does not register: nothing to edit it with.\n  if (inspection === null) {\n    return {\n      tabless: (\n        <div className=\"nx-inspector\" data-empty=\"unregistered\">\n          <p className=\"nx-inspector__note\">\n            {\"This block can't be edited here: its type isn't on this site.\"}\n          </p>\n        </div>\n      ),\n    };\n  }\n  return { block: inspection };\n}\n\n/**\n * The inspector, inside the component's own view when the document is a\n * component: the scope holds the removal dialog and hands every control the\n * binding, so the panel below draws the same whichever document it edits.\n */\nexport function InspectorPanel({\n  componentFields,\n  componentVariants,\n  canvasPassage = null,\n  regionCard,\n  ...panel\n}: InspectorPanelProps): React.JSX.Element {\n  // A header or footer selected on the canvas: the host's card for it, in\n  // the panel's frame, so the canvas keeps its width. Never beside a block's\n  // settings, which a region's selection has already cleared.\n  if (regionCard !== undefined && panel.editor.selectedId === null) {\n    return (\n      <div className=\"nx-inspector\" data-empty=\"region\">\n        {regionCard}\n      </div>\n    );\n  }\n  const look = editedLook(panel);\n  if (look !== undefined && panel.lookEditing !== undefined) {\n    // The host's services reach a look's Style controls as they reach a\n    // block's, so a look's background image is chosen from the Media library\n    // too rather than only pasted as a link.\n    return (\n      <ContentServicesContext.Provider value={panel.contentServices}>\n        <LookInspector\n          editor={panel.editor}\n          look={look}\n          host={panel.sharedStyles}\n          onExit={panel.lookEditing.onExit}\n          library={panel.classLibrary ?? []}\n          canvasRoot={panel.canvasRoot}\n          policy={panel.policy}\n          breakpoint={panel.breakpoint}\n          cascade={panel.cascade}\n          breakpoints={panel.breakpoints}\n          previewContainer={panel.previewContainer}\n          liveBreakpoints={panel.liveBreakpoints}\n          onJumpToBreakpoint={panel.onJumpToBreakpoint}\n          tokens={panel.tokens}\n          fonts={panel.fonts}\n        />\n      </ContentServicesContext.Provider>\n    );\n  }\n  return (\n    <ComponentFieldsScope editor={panel.editor} host={componentFields}>\n      <ComponentVariantsContext.Provider value={componentVariants}>\n        <CanvasPassageContext.Provider value={canvasPassage}>\n          <PanelFoldsProvider>\n            <CssNamesProvider>\n              <SettingsFilterProvider>\n                {/* Escape in a field being typed puts its writes back, and\n                    a draft here is the page's until it is written. */}\n                <TypingCancel.Provider value={panel.editor.cancelTyping}>\n                  <FieldsOfDocument.Provider value={true}>\n                    <SelectionInspector {...panel} />\n                  </FieldsOfDocument.Provider>\n                </TypingCancel.Provider>\n              </SettingsFilterProvider>\n            </CssNamesProvider>\n          </PanelFoldsProvider>\n        </CanvasPassageContext.Provider>\n      </ComponentVariantsContext.Provider>\n    </ComponentFieldsScope>\n  );\n}\n\n/**\n * The look the inspector edits on its own: the one the host names, while no\n * block is selected and the look is still one the site renders or reads.\n * Selecting a block edits the block, whatever look was chosen.\n */\nfunction editedLook(\n  panel: Pick<InspectorPanelProps, \"editor\" | \"classLibrary\" | \"lookEditing\">\n): BlockLookRow | undefined {\n  const key = panel.lookEditing?.look;\n  if (key === undefined || panel.editor.selectedId !== null) return undefined;\n  return blockLookGroups(panel.classLibrary ?? [], new Set())\n    .flatMap(group => group.rows)\n    .find(row => sameLook(row, key));\n}\n\n/**\n * The tab the panel shows, and the author's choice of one.\n *\n * OPENS ON STYLE when a host mounts with a state already chosen. A binding\n * naming a non-base state is a host restoring what an author was editing, and\n * this panel's contract is that such a state and `Canvas.forcedState` are the\n * same value — so opening on Content would leave the canvas drawing a block\n * mid-hover with the only control that explains or clears it behind a tab\n * nobody was told to open. The rule that drops the state on leaving Style\n * cannot catch that: it acts on a CHANGE of tab, and a mount is not one.\n * Honouring the state rather than clearing it, for the reason the multi-\n * selection case does the same: the host asked for it deliberately, and\n * resetting would silently discard what it restored.\n *\n * The tab on screen is the author's, or the selected block's first where it\n * lacks the author's (`shownTab`).\n *\n * Leaving Style drops the forced interaction state. The state control sits\n * inside the Style tab and goes off screen with it, so a state left on would\n * be a canvas drawing a button mid-press with no control on screen saying\n * why. However Style is left — a click on another tab, or a block that shows\n * its first tab because it lacks the author's — the canvas goes back to\n * Normal. On a CHANGE of the tab shown, compared with the last one, rather\n * than on every render: a mount, or a render that reasserts the same tab, is\n * no leaving, and a host that restored a state deliberately keeps it.\n *\n * @param styleState - the state the host restored, and its setter\n * @param asked - the count of the latest ask to fix a list's sort, which is\n *   on the Content tab\n * @param inspection - the selected block, whose tabs decide the one shown\n */\nfunction useInspectorTab(\n  styleState: StyleStateBinding | undefined,\n  asked: number | undefined,\n  inspection: BlockInspection | null\n): { readonly shown: string; readonly choose: (tab: string) => void } {\n  // The tab the AUTHOR chose, kept whichever block is selected.\n  const [tab, setTab] = React.useState<string>(() => openingTabFor(styleState));\n  // A list's sort asked for from its canvas note is on the Content tab, so\n  // the author is taken there, once per ask, from wherever they were.\n  // Each ask moves the tab once: a new style-state setter is no new ask.\n  const answeredAsk = React.useRef<number | undefined>(undefined);\n  React.useEffect(() => {\n    if (asked === undefined || asked === answeredAsk.current) return;\n    answeredAsk.current = asked;\n    setTab(\"content\");\n  }, [asked]);\n\n  const shown =\n    inspection === null ? tab : shownTab(tab, inspectorTabsOf(inspection));\n  const onStyleStateChange = styleState?.onChange;\n  const lastShown = React.useRef(shown);\n  React.useEffect(() => {\n    const left = lastShown.current === \"style\" && shown !== \"style\";\n    lastShown.current = shown;\n    if (left) onStyleStateChange?.(\"base\");\n  }, [shown, onStyleStateChange]);\n  return { shown, choose: setTab };\n}\n\n/** The tab list: one Tab stop, with arrows, Home and End between the tabs. */\nfunction InspectorTabList({\n  tabs,\n}: {\n  tabs: readonly InspectorTab[];\n}): React.JSX.Element {\n  // Compact underlined tabs at the start of the panel; the classes carry the\n  // inspector's own tab rules over the shared tabs'. The options menu is at\n  // the end of the search row below, after \"Only changed\", so the keyboard\n  // meets the panel's head in the order it reads.\n  return (\n    <div className=\"nx-inspector__tabrow\">\n      <InspectorTabs tabs={tabs} />\n    </div>\n  );\n}\n\n/** The tabs themselves: one Tab stop, with arrows, Home and End. */\nfunction InspectorTabs({\n  tabs,\n}: {\n  tabs: readonly InspectorTab[];\n}): React.JSX.Element {\n  return (\n    <TabsList className=\"nx-inspector__tablist\">\n      {INSPECTOR_TABS.filter(tab => tabs.includes(tab.value)).map(tab => (\n        <TabsTrigger\n          key={tab.value}\n          value={tab.value}\n          className=\"nx-inspector__tab\"\n        >\n          {tab.label}\n          <TabCount tab={tab.value} />\n        </TabsTrigger>\n      ))}\n    </TabsList>\n  );\n}\n\n/**\n * The Content tab's panel, where the block has one; a block without a\n * Content tab mounts none.\n */\nfunction ContentTabPanel({\n  tabs,\n  shown,\n  onChoose,\n  status,\n  ...content\n}: {\n  tabs: readonly InspectorTab[];\n  shown: string;\n  /** Show another tab, from the filter's \"2 in Advanced\". */\n  onChoose: (tab: string) => void;\n  /** Where the block is hidden, said at the top of the tab. */\n  status: React.ReactNode;\n} & Omit<\n  React.ComponentProps<typeof ContentTab>,\n  \"onScreen\"\n>): React.JSX.Element | null {\n  if (!tabs.includes(\"content\")) return null;\n  return (\n    <TabsContent\n      value=\"content\"\n      forceMount\n      hidden={shown !== \"content\"}\n      // No Tab stop of its own: Tab goes from the panel's head to its first\n      // control. Every tab has one, and the head names the tab.\n      tabIndex={-1}\n    >\n      {status}\n      <FilterNote tab=\"content\" onChoose={onChoose} />\n      <ContentTab {...content} onScreen={shown === \"content\"} />\n    </TabsContent>\n  );\n}\n\n/**\n * The selected block's card: its icon, type, name and lock, and the verbs\n * its menu offers.\n */\nfunction SelectedBlockCard({\n  block,\n  editor,\n  verbs,\n  reasonId,\n  editingIn,\n}: {\n  block: BlockInspection;\n  editor: InspectorPanelProps[\"editor\"];\n  verbs: InspectorPanelProps[\"verbs\"];\n  reasonId: string;\n  /** The region edited in place, which the card's title names. */\n  editingIn: string | undefined;\n}): React.JSX.Element {\n  const lock = lockStatusOf(editor.document, block.nodeId, lockViewOf(editor));\n  // A picture in a gallery reads by its place there, with a way back to it.\n  const inGallery = galleryPictureOf(editor.document, block.nodeId);\n  return (\n    <BlockCard\n      placedIn={\n        inGallery === undefined\n          ? undefined\n          : {\n              title: `Picture ${String(inGallery.position)}`,\n              within: `in ${inGallery.galleryName}`,\n              backLabel: \"← Back to the gallery\",\n              onBack: () => editor.select(inGallery.galleryId),\n            }\n      }\n      inRegion={editingIn}\n      icon={block.icon}\n      type={block.label}\n      name={block.identity.name}\n      description={block.description}\n      lock={lock}\n      // Withheld while a Layers lock holds the block, its own or one around\n      // it: renaming is a change like any other, and the op layer refuses it.\n      onRename={\n        lock.layers || lock.inheritedFrom !== undefined\n          ? undefined\n          : name => editor.apply(renameOp(block.nodeId, name))\n      }\n      onLock={locked => editor.apply(lockOp(block.nodeId, locked))}\n      // Held inside a `contentOnly` area, which pins the node's own lock\n      // with its design: the save would refuse the change. The one predicate\n      // the multi-selection card asks too, so a block's Lock is offered alike\n      // however it was selected; inside a block locked in Layers it stays\n      // offered, since a change to the lock alone is always allowed.\n      lockHeld={\n        layersLockChangeable(lock)\n          ? undefined\n          : \"The area it sits in fixes this.\"\n      }\n      verbs={verbs}\n      reasonId={reasonId}\n    />\n  );\n}\n\nfunction SelectionInspector({\n  editor,\n  canvasRoot,\n  styleState,\n  breakpoint,\n  cascade,\n  previewContainer,\n  blocks,\n  componentLibrary,\n  inspectors,\n  verbs,\n  contentServices,\n  breakpointsStatus = \"ready\",\n  documentSettings,\n  customCss,\n  // What only the Style tab reads, carried to it whole.\n  ...styleOnly\n}: Omit<\n  InspectorPanelProps,\n  \"componentFields\" | \"componentVariants\"\n>): React.JSX.Element {\n  // Recomputed each render rather than memoised: an inspection is only valid\n  // against the document it was read from, and an edit anywhere changes both\n  // the document and the values shown.\n  // Owned here rather than in the style tab: reading it needs a subscription to\n  // the canvas, and the panel that decides which control shows a value should\n  // not also hold one. Passed down as an answer, exactly as `cascade` is.\n  const canvas = useCanvasReading(canvasRoot, editor.selectedId, {\n    document: editor.document,\n    state: styleState?.state,\n    breakpoint,\n    cascade,\n    previewContainer,\n  });\n  const inspection = inspectSelection(\n    editor.document,\n    editor.selectedId,\n    lockViewOf(editor)\n  );\n  /*\n   * Asked beside the block inspection rather than instead of it, and the two\n   * cannot both answer: a node is an instance or a registered block, never\n   * both, and `inspectSelection` already answers nothing for a type the\n   * registry does not hold. Asked here, before the early returns, because the\n   * hooks below have to run on every render whichever surface is drawn.\n   */\n  const instance = selectedInstance(editor, componentLibrary);\n  /*\n   * The NODE rather than the inspection, because the marker is about stored\n   * styles and an inspection describes editable props. `selectedNode` answers\n   * for a block the registry does not know as well, which is right here: an\n   * unregistered block still has styles, and refusing to say which states carry\n   * them would be a worse answer than saying none.\n   */\n  const styleNode = selectedNode(editor.document, editor.selectedId);\n\n  // Declared before the early returns below, because a hook has to run on\n  // every render of this component and \"no selection\" is one of them.\n  const { shown, choose } = useInspectorTab(\n    styleState,\n    editor.sortFieldAsked?.seq,\n    inspection\n  );\n  // \"Find a setting\" and \"Only changed\", kept across selections above this.\n  const filter = useFilterState();\n  const find = useFindShortcut();\n  // What the Style tab draws, while it is open, for the target it edits.\n  const [reportedStyle, setReportedStyle] = React.useState<\n    ReportedStyle | undefined\n  >(undefined);\n\n  const commit = React.useCallback(\n    (name: string, value: unknown): BlockDocument | null => {\n      const id = editor.selectedId;\n      if (id === null) return null;\n      // Read at commit time rather than closed over: a field committing on\n      // blur can fire after another edit has already replaced the node. The\n      // document written is answered, for a caller storing it straight away.\n      return commitProp(editor, editor.document, id, name, value);\n    },\n    [editor]\n  );\n\n  // The lock reason's id, which every held control points to. Made before\n  // the early return, as every hook here is.\n  const reasonId = React.useId();\n  // The component's own view, when the document is a component.\n  const fields = React.useContext(ComponentFieldsContext);\n  // Where the panel reads a block's settings from, for the filter and for a\n  // setting asked for from outside the panel alike.\n  const reading: MatchReading = {\n    state: styleState?.state,\n    breakpoint,\n    breakpoints: styleOnly.breakpoints,\n    reportedStyle,\n    orientation: canvas.orientation,\n    editor,\n    library: styleOnly.classLibrary,\n    // Custom CSS is found and counted only where Advanced draws it.\n    offersCustomCss: customCss !== undefined,\n  };\n  // The panel's root, where a setting asked for from a page check is found.\n  const root = React.useRef<HTMLDivElement>(null);\n  useAskedSetting({\n    asked: editor.settingAsked,\n    nodeId: inspection?.nodeId,\n    choose,\n    entries: () => entriesOf(editor.document, inspection, reading),\n    root,\n  });\n\n  const surface = surfaceFor(\n    editor,\n    instance,\n    inspection,\n    verbs,\n    fields,\n    (componentLibrary ?? NO_LIBRARY).definitions,\n    canvasRoot,\n    documentSettings\n  );\n  // A tabless surface still reaches the host's media library: a component\n  // placement's exposed image chooses a file as the Content tab does.\n  if (\"tabless\" in surface) {\n    return (\n      <ContentServicesContext.Provider value={contentServices}>\n        {surface.tabless}\n      </ContentServicesContext.Provider>\n    );\n  }\n  const block = surface.block;\n  const tabs = inspectorTabsOf(block);\n  const match = blockMatch(\n    editor.document,\n    block,\n    filter,\n    matchAtFor(block, reading)\n  );\n\n  // Where the block is hidden, at the top of every tab; \"Change\" goes to\n  // Hide on from the tabs it is not on.\n  const hidden = {\n    editor,\n    nodeId: block.nodeId,\n    breakpoints: styleOnly.breakpoints,\n  };\n\n  return (\n    // The \"/\" shortcut is the panel's: from anywhere in it but a text field.\n    <div className=\"nx-inspector\" onKeyDown={find.onKeyDown} ref={root}>\n      <SelectedBlockCard\n        // Keyed by node, so a rename half-typed for one block does not carry\n        // to the next.\n        key={`${block.nodeId}:card`}\n        block={block}\n        editor={editor}\n        verbs={verbs}\n        reasonId={reasonId}\n        editingIn={styleOnly.editingIn}\n      />\n\n      {/*\n        Held HERE, so the chosen tab survives a change of selection — an author\n        styling one block after another means to stay on Style. This element's\n        position does not change, so the state lives across every selection; a\n        `key` on the node id would reset it on every click. A block without\n        the chosen tab shows its first, and the next block that has the\n        chosen one shows it again.\n      */}\n      <StyleReportContext.Provider value={setReportedStyle}>\n        <SettingsMatchProvider value={match}>\n          <Tabs\n            value={shown}\n            onValueChange={choose}\n            className=\"nx-inspector__tabs\"\n          >\n            <InspectorTabList tabs={tabs} />\n            {/* Under the tabs, on every tab; before the panels in the page's\n            order, so a sticky header can hold the two together. */}\n            <SettingsSearchRow\n              field={find.field}\n              end={<PanelOptions tab={shown} />}\n            />\n\n            {/*\n          FORCE-MOUNTED, Content and Advanced both: a field commits on blur\n          and the tabs activate on mousedown, before the blur, and Advanced\n          holds a draft, so unmounting either threw away what the author\n          typed and why a refused row was not saved. HIDDEN here, not by\n          Radix, which ties mounting to showing; `hidden` takes it out of the\n          accessibility tree as unmounting did. A block without a Content tab\n          mounts none.\n        */}\n            <ContentTabPanel\n              tabs={tabs}\n              shown={shown}\n              onChoose={choose}\n              status={<HiddenStatus {...hidden} onChoose={choose} />}\n              block={block}\n              editor={editor}\n              onCommit={commit}\n              inspectors={inspectors}\n              services={contentServices}\n              reasonId={reasonId}\n              fields={fields}\n              around={{\n                breakpoints: styleOnly.breakpoints,\n                cascade,\n                renderedTag: canvas.tag,\n              }}\n            />\n\n            <TabsContent value=\"style\" tabIndex={-1}>\n              <HiddenStatus {...hidden} onChoose={choose} />\n              {/* That the block also has custom CSS, never the CSS: Style\n                  draws plain controls only, and links to Advanced for a\n                  person who may change it. */}\n              <CustomCssStyleLine\n                nodeId={block.nodeId}\n                hasCustomCss={block.hasCustomCss}\n                access={customCss}\n                editor={editor}\n              />\n              <FilterNote tab=\"style\" onChoose={choose} />\n              <StyleChangedElsewhere\n                styles={\n                  // The Style tab's target, a shared style's own values\n                  // while one is edited; the block's otherwise.\n                  reportedStyle?.nodeId === block.nodeId\n                    ? reportedStyle.styles\n                    : styleNode?.styles\n                }\n                state={styleState}\n                breakpoint={breakpoint}\n                breakpoints={styleOnly.breakpoints}\n                onJumpToBreakpoint={styleOnly.onJumpToBreakpoint}\n              />\n              {/* The Style tab reaches the host's media library too: the\n                  background image picks and uploads as the Content tab does. */}\n              <ContentServicesContext.Provider value={contentServices}>\n                <StyleTab\n                  {...styleOnly}\n                  editor={editor}\n                  styleNode={styleNode}\n                  renderedTag={canvas.tag}\n                  rendered={canvas}\n                  sideOrientation={canvas.orientation}\n                  styleState={styleState}\n                  breakpoint={breakpoint}\n                  cascade={cascade}\n                  previewContainer={previewContainer}\n                  verbs={verbs}\n                />\n              </ContentServicesContext.Provider>\n            </TabsContent>\n\n            <TabsContent\n              value=\"advanced\"\n              forceMount\n              hidden={shown !== \"advanced\"}\n              tabIndex={-1}\n            >\n              {/* No \"Change\" here: Hide on is on this tab. */}\n              <HiddenStatus {...hidden} />\n              <FilterNote tab=\"advanced\" onChoose={choose} />\n              <AdvancedTab\n                block={block}\n                editor={editor}\n                onCommit={commit}\n                services={contentServices}\n                blocks={blocks}\n                onScreen={shown === \"advanced\"}\n                reasonId={reasonId}\n                fields={fields}\n                breakpoints={styleOnly.breakpoints}\n                breakpoint={breakpoint}\n                breakpointsStatus={breakpointsStatus}\n                customCss={customCss}\n              />\n            </TabsContent>\n          </Tabs>\n        </SettingsMatchProvider>\n      </StyleReportContext.Provider>\n    </div>\n  );\n}\n\n/**\n * Where else the selected block holds styles, under Style while Only changed\n * is on: by device at the edited state, by state at the edited device.\n */\nfunction StyleChangedElsewhere({\n  styles,\n  state,\n  breakpoint,\n  breakpoints,\n  onJumpToBreakpoint,\n}: {\n  styles: unknown;\n  state: StyleStateBinding | undefined;\n  breakpoint: BreakpointId | undefined;\n  breakpoints: BreakpointSet | undefined;\n  onJumpToBreakpoint: ((breakpoint: BreakpointId) => void) | undefined;\n}): React.JSX.Element | null {\n  const { onlyChanged } = useFilterState();\n  if (!onlyChanged || styles === undefined) return null;\n  const devices = [\n    BASE_BREAKPOINT,\n    ...(breakpoints?.viewport ?? [])\n      .map(each => each.id)\n      .filter(id => id !== BASE_BREAKPOINT),\n  ];\n  const counts = changedElsewhere(\n    styles as StoredStyles | undefined,\n    {\n      state: state?.state ?? \"base\",\n      device: breakpoint ?? BASE_BREAKPOINT,\n    },\n    {\n      devices: devices.map(id => ({\n        id,\n        label: breakpointLabel(breakpoints, id),\n      })),\n      states: STYLE_STATES.map(id => ({ id, label: stateLabel(id) })),\n    }\n  );\n  return (\n    <ChangedElsewhere\n      devices={counts.devices}\n      states={counts.states}\n      onDevice={onJumpToBreakpoint}\n      onState={showState(state?.onChange)}\n    />\n  );\n}\n\n/** A link's way to show a state, where the host lets the panel change it. */\nfunction showState(\n  onChange: ((state: StyleState) => void) | undefined\n): ((id: string) => void) | undefined {\n  return onChange === undefined ? undefined : id => onChange(id as StyleState);\n}\n\n/**\n * What the filter keeps of the selected block: its settings on every tab,\n * read from the same inspections the tabs draw. Read only while a filter is\n * on, so an unfiltered panel builds no index.\n */\nfunction blockMatch(\n  document: BlockDocument,\n  block: BlockInspection,\n  filter: SettingsFilter,\n  at: MatchAt\n): SettingsMatch {\n  if (!filtering(filter)) return settingsMatch([], filter);\n  return settingsMatch(blockEntries(document, block, at), filter);\n}\n\n/**\n * The selected block's settings on every tab, read from the same inspections\n * the tabs draw: what the filter keeps from, and where a setting asked for\n * from outside the panel is drawn.\n */\nfunction blockEntries(\n  document: BlockDocument,\n  block: BlockInspection,\n  at: MatchAt\n): SettingEntry[] {\n  const { sections, parent } = styleOfBlock(document, block, at);\n  const node = findNode(document.nodes, block.nodeId);\n  return [\n    ...contentEntries(block, node, at.breakpoints),\n    ...styleEntries(\n      sections,\n      block,\n      shortcutsAt(node, at),\n      parent,\n      at.flow,\n      // Whether Arrange owns the space rows, as the open Style tab reads it.\n      at.reported?.arranges\n    ),\n    ...advancedEntries(block, node, at.offersCustomCss),\n    // The Block style section, drawn above the Style tab's bar.\n    ...blockStyleEntries(at.editor, at.library),\n  ];\n}\n\n/** Where the selected block is edited, for what the filter keeps of it. */\n/** What the panel holds that a block's settings are read against. */\ninterface MatchReading\n  extends Pick<\n    MatchAt,\n    | \"state\"\n    | \"breakpoint\"\n    | \"breakpoints\"\n    | \"editor\"\n    | \"library\"\n    | \"offersCustomCss\"\n  > {\n  /** What the Style tab reported drawing, for whichever block it was. */\n  reportedStyle: ReportedStyle | undefined;\n  /** Which way the block's lines run, as the canvas measured it. */\n  orientation: ReturnType<typeof useCanvasReading>[\"orientation\"];\n}\n\n/** Where the panel reads a block's settings from, for the filter and an ask alike. */\nfunction matchAtFor(block: BlockInspection, reading: MatchReading): MatchAt {\n  const { reportedStyle, orientation, ...at } = reading;\n  return {\n    ...at,\n    reported:\n      reportedStyle?.nodeId === block.nodeId ? reportedStyle : undefined,\n    // What Inside its parent's Width and Height are sized by.\n    flow: {\n      writingMode: orientation?.writingMode ?? \"horizontal-tb\",\n      rtl: orientation?.direction === \"rtl\",\n    },\n  };\n}\n\n/** The shown block's settings on every tab, or none while it shows none. */\nfunction entriesOf(\n  document: BlockDocument,\n  block: BlockInspection | null,\n  reading: MatchReading\n): SettingEntry[] {\n  return block === null\n    ? []\n    : blockEntries(document, block, matchAtFor(block, reading));\n}\n\ninterface MatchAt {\n  state: StyleState | undefined;\n  breakpoint: BreakpointId | undefined;\n  breakpoints: BreakpointSet | undefined;\n  /** What the Style tab draws, while it is open, for its target. */\n  reported: ReportedStyle | undefined;\n  flow: PlainFlow;\n  /** The editor and the site's library, which the Block style tiles read. */\n  editor: EditorState;\n  library: InspectorPanelProps[\"classLibrary\"];\n  /** Whether Advanced draws Custom CSS for this person. */\n  offersCustomCss: boolean;\n}\n\n/**\n * The Style tab's own sections while it is open: the target it edits may be\n * a shared style. Closed, it edits the block, read here the same way. With\n * them, what \"Inside its parent\" offers: none for a shared style, worn\n * wherever.\n */\nfunction styleOfBlock(\n  document: BlockDocument,\n  block: BlockInspection,\n  at: MatchAt\n): {\n  sections: ReportedStyle[\"sections\"];\n  parent: ReportedStyle[\"parent\"];\n} {\n  const { reported } = at;\n  if (reported !== undefined) {\n    return {\n      sections: reported.sections,\n      parent: reported.shared ? undefined : reported.parent,\n    };\n  }\n  const inspected = inspectStyle(document, block.nodeId, {\n    state: at.state ?? \"base\",\n    breakpoint: at.breakpoint ?? BASE_BREAKPOINT,\n  });\n  return { sections: inspected?.sections ?? [], parent: inspected?.parent };\n}\n\n/**\n * The block's own shortcuts at the edited address, or none while a shared\n * style is edited: only the block's own draw them.\n */\nfunction shortcutsAt(\n  node: BlockNode | undefined,\n  at: MatchAt\n): Parameters<typeof styleEntries>[2] {\n  if (at.reported?.shared === true) return undefined;\n  return {\n    node,\n    at: {\n      state: at.state ?? \"base\",\n      breakpoint: at.breakpoint ?? BASE_BREAKPOINT,\n    },\n  };\n}\n","\"use client\";\n\n/**\n * The banner over a component's own view: which component this is, how many\n * pages a change to it reaches, and the one way back to where the author came\n * from, named for where it goes.\n *\n * A component edited here changes every page that shows it, which the canvas\n * does not say: it draws the component as one placement would. So the banner\n * stays for as long as the view is open, above the editor's own bar, tinted\n * with the component's hue so the whole view reads as \"the shared thing\".\n *\n * ONE Back. The editor's own exit arrow is withheld while this one is offered\n * (the host decides that), since two arrows going to two places is a choice\n * the author should not have to make blind.\n *\n * Draws only. Where Back goes, its name, and how far the change reaches are\n * the host's answers, handed in.\n *\n * @module component-banner\n */\nimport { Button } from \"@nextlyhq/ui\";\nimport { ArrowLeft, Component } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { ComponentFieldsHost } from \"../panels/components/component-fields\";\nimport { BUILDER_TOKENS_CLASS } from \"../shell-state\";\n\n/**\n * What the banner says a change reaches, from the host's count of the pages\n * showing the component (directly, inside another component, or in a Layout\n * around them), or nothing while there is no count. A floor is said as \"at\n * least\", and only a floor: an exact count is said as it is.\n */\nexport function reachSentence(\n  pages: ComponentFieldsHost[\"pages\"]\n): string | undefined {\n  if (pages === undefined) return undefined;\n  if (pages.count === 0) {\n    return pages.complete ? \"Not on any page yet\" : undefined;\n  }\n  const noun = pages.count === 1 ? \"page\" : \"pages\";\n  return pages.complete\n    ? `Changes reach ${pages.count} ${noun}`\n    : `Changes reach at least ${pages.count} ${noun}`;\n}\n\n/** What the band says on hover and to a screen reader: when the change lands. */\nconst BAND_HINT = \"Every page that uses it updates when you save.\";\n\n/** @experimental Settles when the component editor ships. */\nexport interface ComponentBannerProps {\n  /** The component's name, or nothing while it is not known. */\n  readonly name: string | undefined;\n  /** How many pages a change reaches; nothing while it is not counted. */\n  readonly pages: ComponentFieldsHost[\"pages\"];\n  /**\n   * The way back: where it goes, said as \"Back to <to>\", and the move.\n   * Omitted, no Back is offered.\n   */\n  readonly back?:\n    | { readonly to: string; readonly onBack: () => void }\n    | undefined;\n}\n\n/** @experimental Settles when the component editor ships. */\nexport function ComponentBanner({\n  name,\n  pages,\n  back,\n}: ComponentBannerProps): React.JSX.Element {\n  const said = reachSentence(pages);\n  const hintId = React.useId();\n  return (\n    <div\n      // The builder's own tokens, so the component hue resolves here too: the\n      // band sits above the shell, outside the chrome that declares them.\n      className={`nx-component-banner ${BUILDER_TOKENS_CLASS}`}\n      role=\"region\"\n      aria-label=\"Editing a component\"\n      // The pill this replaced, as the band's tooltip and its description.\n      title={BAND_HINT}\n      aria-describedby={hintId}\n    >\n      <span id={hintId} className=\"nx-sr-only\">\n        {BAND_HINT}\n      </span>\n      {back === undefined ? null : (\n        <>\n          <Button\n            type=\"button\"\n            variant=\"ghost\"\n            size=\"sm\"\n            className=\"nx-component-banner__back\"\n            onClick={back.onBack}\n          >\n            <ArrowLeft size={16} aria-hidden=\"true\" />\n            Back <span className=\"nx-component-banner__to\">to {back.to}</span>\n          </Button>\n          <span className=\"nx-component-banner__rule\" aria-hidden=\"true\" />\n        </>\n      )}\n      <p className=\"nx-component-banner__text\">\n        <span className=\"nx-component-banner__editing\">\n          <Component\n            size={15}\n            aria-hidden=\"true\"\n            className=\"nx-component-banner__glyph\"\n          />\n          Editing component\n        </span>\n        <strong className=\"nx-component-banner__name\">\n          {name ?? \"this component\"}\n        </strong>\n        {said === undefined ? null : (\n          <span className=\"nx-component-banner__reach\">· {said}</span>\n        )}\n      </p>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The variant open in a component's own view, previewed on the canvas.\n *\n * Opening a variant's values in the inspector draws the component on the\n * canvas as that variant does, so a designer setting \"Featured\" sees Featured\n * rather than the defaults, and a tag over the canvas says so. Closing it, or\n * deleting the variant, draws the defaults again.\n *\n * The host holds the open variant (one hook, here), hands its binding to the\n * variants section, and draws the canvas from the document this answers. The\n * preview keeps every node's id (the engine's {@link variantPreview}), so the\n * canvas still selects and edits the component's own blocks under it.\n *\n * @module variant-preview\n */\nimport {\n  isComponentDocument,\n  variantOptions,\n  variantPreview,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\nimport { Eye } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { VariantPreviewBinding } from \"../panels/components/component-variants\";\n\n/** What the host draws the canvas from, and hands the variants section. */\nexport interface VariantPreviewState {\n  /** For the variants section: which variant is open, and how to open one. */\n  readonly binding: VariantPreviewBinding;\n  /** What the canvas draws: the document, as the open variant draws it. */\n  readonly document: BlockDocument;\n  /** The name of the variant the canvas previews, or nothing. */\n  readonly previewing: string | undefined;\n}\n\n/**\n * The open variant of the component `document` is, and the document the\n * canvas draws while it is open. A page, or a variant no longer on the\n * component, previews nothing.\n *\n * @experimental Settles when the component editor ships.\n */\nexport function useVariantPreview(\n  document: BlockDocument\n): VariantPreviewState {\n  const [chosen, setChosen] = React.useState<string | undefined>(undefined);\n  const component = isComponentDocument(document) ? document : undefined;\n  // Asked of the document as it stands, so a deleted variant stops previewing\n  // without anything having to close it.\n  const option =\n    component === undefined || chosen === undefined\n      ? undefined\n      : variantOptions(component).find(entry => entry.id === chosen);\n  const open = option?.id;\n  const drawn = React.useMemo(\n    () =>\n      component === undefined || open === undefined\n        ? document\n        : variantPreview(component, open),\n    [component, document, open]\n  );\n  const binding = React.useMemo<VariantPreviewBinding>(\n    () => ({ open, onOpen: setChosen }),\n    [open]\n  );\n  return { binding, document: drawn, previewing: option?.label };\n}\n\n/**\n * The tag over the canvas naming the variant it previews; nothing while the\n * canvas draws the defaults. A status, so the change is announced.\n *\n * @experimental Settles when the component editor ships.\n */\nexport function VariantPreviewTag({\n  name,\n}: {\n  name: string | undefined;\n}): React.JSX.Element | null {\n  if (name === undefined) return null;\n  return (\n    <p className=\"nx-variant-preview-tag\" role=\"status\">\n      <Eye size={14} aria-hidden=\"true\" />\n      Previewing {name}\n    </p>\n  );\n}\n","\"use client\";\n\n/**\n * The tags over the canvas saying it is not drawn as it would be by default:\n * today, the variant of a component previewed.\n *\n * They sit in ONE row at the frame's top right, where the variant's tag has\n * always been, so a tag added later is read beside it and never drawn over\n * it. The row is drawn only while a tag is.\n *\n * The site's light or dark preview has no tag: the top bar's switch shows\n * which mode the canvas is drawn in, wherever the author is in the editor.\n *\n * @module canvas-preview-tags\n */\nimport * as React from \"react\";\n\nimport { VariantPreviewTag } from \"./variant-preview\";\n\n/** @experimental Settles with the canvas's mode preview. */\nexport interface CanvasPreviewTagsProps {\n  /** The name of the variant the canvas previews, or nothing. */\n  variant: string | undefined;\n}\n\n/**\n * The row of preview tags over the canvas; nothing while the canvas previews\n * no variant.\n *\n * @experimental Settles with the canvas's mode preview.\n */\nexport function CanvasPreviewTags({\n  variant,\n}: CanvasPreviewTagsProps): React.JSX.Element | null {\n  if (variant === undefined) return null;\n  return (\n    <div className=\"nx-canvas-tags\">\n      <VariantPreviewTag name={variant} />\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * What the Add panel says about its libraries: a list cut short, a list that\n * may be out of date, and a list that could not be read, each with its retry.\n *\n * @module insert-panel-notices\n */\n\nimport * as React from \"react\";\n\nimport type { InsertPanelProps, LibraryTierState } from \"./insert-panel-types\";\n\n/**\n * That a tier of the library was cut, or could not be read, said where an\n * author looks for what is missing.\n *\n * `status` regions rather than alerts: each is a standing fact about this\n * read, present from the moment the panel opens, and an alert would interrupt\n * a screen reader mid-sentence to announce something that is not an event.\n * Drawn above the tiles so they are read BEFORE an author searches in vain —\n * a note at the end of a long list is one they reach after giving up.\n *\n * Named per tier, because the remedy the author reaches for differs: a pattern\n * left out is one they cannot insert, while a component left out is also one\n * already on the page drawing as could-not-be-loaded, and that second half is\n * the sentence nothing else says. A tier that could not be read at all gets\n * its own sentence and the retry, because that is a state with a remedy the\n * author can reach from here — and a tier that could not be RE-read gets a\n * third, since beside the tiles it left standing the second would be false.\n */\nexport function LibraryNotices({\n  library,\n  tier,\n}: {\n  library: InsertPanelProps[\"library\"];\n  /** The tier the surface offers: patterns as sections, or components. */\n  tier: LibraryTier;\n}): React.JSX.Element {\n  return (\n    <>\n      <CutNotice tiers={tiersIn(library, \"cut\", tier)} />\n      <StaleNotice\n        tiers={tiersIn(library, \"stale\", tier)}\n        retry={library?.retry}\n      />\n      <UnavailableNotice\n        tiers={tiersIn(library, \"unavailable\", tier)}\n        retry={library?.retry}\n      />\n    </>\n  );\n}\n\n/** A tier of the host's library, as a notice names it. */\nexport type LibraryTier = \"patterns\" | \"components\";\n\n/** The tiers a ceiling cut, and what a cut component means for the page. */\nfunction CutNotice({\n  tiers,\n}: {\n  tiers: string | undefined;\n}): React.JSX.Element | null {\n  if (tiers === undefined) return null;\n  return (\n    <p role=\"status\" className=\"nx-insert-panel__note nx-insert-panel__cut\">\n      The library is larger than the editor can load at once, so some {tiers}{\" \"}\n      are not offered here.\n      {tiers.includes(\"components\")\n        ? \" A component left out shows as “could not be loaded” on the page.\"\n        : null}\n    </p>\n  );\n}\n\n/**\n * The tiers whose last answer could not be refreshed. The tiles stand, so\n * what is said of them is that they may be out of date — and of a component\n * on the page, that it draws as it was.\n */\nfunction StaleNotice({\n  tiers,\n  retry,\n}: {\n  tiers: string | undefined;\n  retry: (() => void) | undefined;\n}): React.JSX.Element | null {\n  if (tiers === undefined) return null;\n  return (\n    <p role=\"status\" className=\"nx-insert-panel__note nx-insert-panel__cut\">\n      The site’s {tiers} could not be reloaded, so those offered may be out of\n      date.\n      {tiers.includes(\"components\")\n        ? \" A component already on the page draws as it was.\"\n        : null}{\" \"}\n      <RetryButton retry={retry} />\n    </p>\n  );\n}\n\n/** The tiers that could not be read at all, and what that means for the page. */\nfunction UnavailableNotice({\n  tiers,\n  retry,\n}: {\n  tiers: string | undefined;\n  retry: (() => void) | undefined;\n}): React.JSX.Element | null {\n  if (tiers === undefined) return null;\n  return (\n    <p role=\"status\" className=\"nx-insert-panel__note nx-insert-panel__cut\">\n      The site’s {tiers} could not be loaded, so none are offered here.\n      {tiers.includes(\"components\")\n        ? \" A component already on the page shows as “could not be loaded”.\"\n        : null}{\" \"}\n      <RetryButton retry={retry} />\n    </p>\n  );\n}\n\n/** The one remedy a failed read has, when the host supplied it. */\nfunction RetryButton({\n  retry,\n}: {\n  retry: (() => void) | undefined;\n}): React.JSX.Element | null {\n  if (retry === undefined) return null;\n  return (\n    <button type=\"button\" className=\"nx-insert-panel__retry\" onClick={retry}>\n      Try again\n    </button>\n  );\n}\n\n/**\n * The surface's own tier when it is in one state, as the word a sentence\n * names it with — or nothing. Each surface reports only the tier it offers,\n * so it never reports content that could not appear in it.\n */\nfunction tiersIn(\n  library: InsertPanelProps[\"library\"],\n  state: LibraryTierState,\n  tier: LibraryTier\n): LibraryTier | undefined {\n  return library?.[tier] === state ? tier : undefined;\n}\n","/**\n * Whether the locks let a block go in at a place, answered from the structure\n * around that place rather than by inserting it into a copy of the page.\n *\n * The Add panel shows every tile as available or not the moment it opens, and\n * again after every edit while it is open. Asking the editor's own lock\n * question for each tile tried an insert of every tile on a copy of the whole\n * page, which on a long page held the panel for seconds. An insert can break a\n * lock in two ways, and both are read off the place it lands:\n *\n * - **A Layers lock on the destination**: the container it goes into, or one\n *   around it, is locked. The engine's own rule (`layersLockBreak`) answers\n *   this from the page as it stands, and it is the same for every tile.\n * - **A slot's lock**: the slot it goes into fixes its blocks, declared by its\n *   block or inherited from a slot around it. Whether the slot is locked is\n *   read along the path to it (`slotLockOf`); only then is the engine's lock\n *   judgement (`lockRefusal`) asked, of that path alone, before and after the\n *   block is put in. Per block, because where a locked slot is already broken,\n *   putting back the block it is missing repairs it while any other block\n *   breaks it further.\n *\n * One more lock only shows on the composed page: a lock a component places on\n * the content a page puts inside it. A place inside a placed component is\n * therefore asked the editor's full lock question (`ask`), which composes\n * the page; every other place is answered from its structure alone.\n *\n * @module insert-lock\n */\n\nimport {\n  isComponentInstance,\n  layersLockBreak,\n  lockRefusal,\n  slotLockOf,\n  type ActiveSlotLock,\n  type BlockDocument,\n  type BlockNode,\n  type DocumentLimits,\n  type NestingSource,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { factsOfBreak, type LockRefusalFacts } from \"../../lock-refusal\";\nimport type { BuilderOp, OpPosition } from \"../../op-vocabulary\";\n\n/** What the lock rules are read from: the editor's own lock sources. */\nexport interface InsertLockSources {\n  readonly definitions: SlotDefaultSource;\n  readonly nesting?: NestingSource;\n  readonly limits: DocumentLimits;\n  /** The editor's full lock question, for a place inside a placed component. */\n  readonly ask: (ops: readonly BuilderOp[]) => LockRefusalFacts | undefined;\n}\n\n/** One block on the path to a place, and the slot of it the path goes into. */\ninterface PathStep {\n  readonly node: BlockNode;\n  readonly slot: string;\n}\n\n/**\n * What the locks say of any block at one place: read once per place, then\n * asked of each block with {@link InsertLock.of}.\n */\nexport interface InsertLock {\n  /** The refusal for putting `node` in at the place, or none. */\n  readonly of: (node: BlockNode) => LockRefusalFacts | undefined;\n}\n\n/** The locks at `at` in `document`, for every block an author might add there. */\nexport function insertLockAt(\n  document: BlockDocument,\n  at: OpPosition,\n  sources: InsertLockSources\n): InsertLock {\n  let destination: { facts: LockRefusalFacts | undefined } | undefined;\n  // The path is read only for a place inside a block, and once.\n  const path = at.parentId === undefined ? [] : pathTo(document.nodes, at);\n  const locked = path.length > 0 && slotIsLocked(path, sources.definitions);\n  const composed = path.some(step => isComponentInstance(step.node));\n  return {\n    of: node => {\n      if (composed) return sources.ask([{ kind: \"insert\", node, at }]);\n      // The destination's lock is the same for every block, so asked once.\n      destination ??= {\n        facts: destinationLock(document, { kind: \"insert\", node, at }),\n      };\n      if (destination.facts !== undefined) return destination.facts;\n      if (!locked) return undefined;\n      return slotLockBreak(document, path, at.index, node, sources);\n    },\n  };\n}\n\n/** A Layers lock the insert breaks, worded as every lock refusal is. */\nfunction destinationLock(\n  document: BlockDocument,\n  op: { kind: \"insert\"; node: BlockNode; at: OpPosition }\n): LockRefusalFacts | undefined {\n  const broken = layersLockBreak(document.nodes, op);\n  return broken === undefined ? undefined : factsOfBreak(document, op, broken);\n}\n\n/**\n * The blocks from the top of the page down to the place's own container, each\n * with the slot the path goes into, or none when the page no longer holds it.\n */\nfunction pathTo(nodes: readonly BlockNode[], at: OpPosition): PathStep[] {\n  if (at.parentId === undefined) return [];\n  const target = at.parentId;\n  const into = at.slot;\n  const found: PathStep[] = [];\n  const visit = (list: readonly unknown[]): boolean => {\n    for (const entry of list) {\n      const node = entry as BlockNode | null | undefined;\n      if (node === null || node === undefined) continue;\n      if (node.id === target) {\n        found.push({ node, slot: into });\n        return true;\n      }\n      for (const [slot, children] of Object.entries(node.slots ?? {})) {\n        if (!Array.isArray(children)) continue;\n        found.push({ node, slot });\n        if (visit(children)) return true;\n        found.pop();\n      }\n    }\n    return false;\n  };\n  return visit(nodes) ? found : [];\n}\n\n/** Whether the slot at the end of the path carries a lock, its own or inherited. */\nfunction slotIsLocked(\n  path: readonly PathStep[],\n  definitions: SlotDefaultSource\n): boolean {\n  let lock: ActiveSlotLock | undefined;\n  for (const step of path) {\n    lock = slotLockOf(definitions, step.node.type, step.slot, lock);\n  }\n  return lock !== undefined;\n}\n\n/**\n * The lock break putting `node` in at `index` of the path's last slot adds,\n * judged by the engine on the path alone: each block above keeps only the\n * child the path goes through, and the container keeps everything it holds.\n * What the cut-away blocks would add is the same before and after, so it adds\n * no break of its own.\n */\nfunction slotLockBreak(\n  document: BlockDocument,\n  path: readonly PathStep[],\n  index: number,\n  node: BlockNode,\n  sources: InsertLockSources\n): LockRefusalFacts | undefined {\n  const holder = path[path.length - 1];\n  if (holder === undefined) return undefined;\n  const held = holder.node.slots?.[holder.slot] ?? [];\n  const after = [...held];\n  after.splice(index, 0, node);\n  const region = (container: BlockNode): BlockDocument => {\n    let top = container;\n    for (let i = path.length - 2; i >= 0; i -= 1) {\n      const step = path[i];\n      if (step === undefined) break;\n      top = { ...step.node, slots: { [step.slot]: [top] } };\n    }\n    return { ...document, nodes: [top] };\n  };\n  return lockRefusal(\n    region(holder.node),\n    region({\n      ...holder.node,\n      slots: { ...holder.node.slots, [holder.slot]: after },\n    }),\n    {\n      definitions: sources.definitions,\n      ...(sources.nesting === undefined ? {} : { nesting: sources.nesting }),\n      limits: sources.limits,\n    }\n  );\n}\n","/**\n * Where a block added from the panel goes, said in words: \"Adding inside\n * Hero, at the end\", \"Adding after Heading, inside Hero\", \"Adding at the end\n * of the page\", \"Adding between Hero and Pricing\". One place says it, so the\n * Add panel, the Components panel, the editor's search and the sentence an\n * insert is announced with name a place the same way.\n *\n * @module insert-placement-words\n */\nimport { findNode, type BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport type * as React from \"react\";\n\nimport { layerLabel } from \"../layers/layers\";\n\nimport type { InsertionCandidate } from \"./inserter\";\n\n/**\n * One piece of a place's words: a place named by a block (\"after Heading\",\n * drawn bold), or the plain words between them.\n */\ninterface PlacePart {\n  readonly text: string;\n  readonly named: boolean;\n}\n\n/**\n * A place's words, in pieces: where it is beside or in a block, named as\n * Layers names it, then, where that place is itself inside a block, which.\n */\nfunction placeParts(\n  document: BlockDocument,\n  candidate: InsertionCandidate\n): readonly PlacePart[] {\n  const named = (text: string): PlacePart => ({ text, named: true });\n  const plain = (text: string): PlacePart => ({ text, named: false });\n  const name = (id: string | undefined): string => {\n    const node = id === undefined ? undefined : findNode(document.nodes, id);\n    // The ids come from this same document, so the guard holds; the words\n    // still say something true if it ever does not.\n    return node === undefined ? \"the selected block\" : layerLabel(node);\n  };\n  if (candidate.kind === \"document-end\") {\n    return [plain(\"at the end of the page\")];\n  }\n  if (candidate.kind === \"inside\") {\n    return [named(`inside ${name(candidate.insideId)}`), plain(\", at the end\")];\n  }\n  const beside =\n    candidate.kind !== \"between\"\n      ? `after ${name(candidate.afterId)}`\n      : candidate.afterId === undefined\n        ? `before ${name(candidate.beforeId)}`\n        : `between ${name(candidate.afterId)} and ${name(candidate.beforeId)}`;\n  const parentId = candidate.at.parentId;\n  return parentId === undefined\n    ? [named(beside)]\n    : [named(beside), plain(\", \"), named(`inside ${name(parentId)}`)];\n}\n\n/** A place in plain words: \"inside Hero, at the end\", \"after Heading, inside Hero\". */\nexport function placeWords(\n  document: BlockDocument,\n  candidate: InsertionCandidate\n): string {\n  return placeParts(document, candidate)\n    .map(part => part.text)\n    .join(\"\");\n}\n\n/** \"Adding after Heading, inside Hero\", say, with the places in bold. */\nexport function placementWords(\n  lead: string,\n  document: BlockDocument,\n  candidate: InsertionCandidate\n): React.ReactNode {\n  return (\n    <>\n      {`${lead} `}\n      {placeParts(document, candidate).map((part, index) =>\n        part.named ? <b key={index}>{part.text}</b> : part.text\n      )}\n    </>\n  );\n}\n\n/** The same place as one plain sentence, for a tile's description. */\nexport function placementSentence(\n  lead: string,\n  document: BlockDocument,\n  candidate: InsertionCandidate\n): string {\n  return `${lead} ${placeWords(document, candidate)}.`;\n}\n\n/**\n * What an insert is announced with: \"Heading added inside Hero, at the end\".\n * Read from the page as it was before the insert, where the place was named.\n */\nexport function insertedAnnouncement(\n  label: string,\n  document: BlockDocument,\n  candidate: InsertionCandidate\n): string {\n  return `${label} added ${placeWords(document, candidate)}`;\n}\n","/**\n * The blocks an author adds most: one count per block name, kept on this\n * device through the editor's preference port, and the six the in-place\n * picker shows from them.\n *\n * Counted on every insert of a block, from any surface that adds through the\n * Add panel's offers (the panel, its drag, the picker, the editor's search).\n * Saved sections and components are not counted: they are the site's own\n * content and change, and they are one search away.\n *\n * @module insert-usage\n */\n\nimport * as React from \"react\";\n\nimport type { PreferenceStore } from \"../../shell-state\";\n\nimport type { BlockInsertEntry, InsertEntry } from \"./inserter-types\";\n\n/**\n * The six an author with no history sees, in this order, and the order that\n * breaks a tie between equal counts.\n */\nexport const DEFAULT_MOST_USED: readonly string[] = [\n  \"core/heading\",\n  \"core/text\",\n  \"core/image\",\n  \"core/button\",\n  \"core/box\",\n  \"core/columns\",\n];\n\n/** How many blocks the picker shows at rest. */\nconst MOST_USED_SIZE = 6;\n\n/** How many times each block has been added, by block name. */\nexport type InsertCounts = Readonly<Record<string, number>>;\n\n/** No inserts yet. */\nconst NO_COUNTS: InsertCounts = {};\n\n/**\n * Where the author's insert counts are kept, provided by the host around the\n * editor. Absent, nothing is counted and the picker shows the default six.\n *\n * @experimental\n */\nexport const InsertUsageContext: React.Context<PreferenceStore | undefined> =\n  React.createContext<PreferenceStore | undefined>(undefined);\n\n/** The store the host provided for insert counts, if any. */\nexport function useInsertUsage(): PreferenceStore | undefined {\n  return React.useContext(InsertUsageContext);\n}\n\n/**\n * The counts a store holds, or none when it holds nothing readable. A store\n * may fail to read (private browsing, a blocked storage), and the editor must\n * not care, so a failure is an empty history.\n */\nexport function readInsertCounts(\n  store: PreferenceStore | undefined\n): InsertCounts {\n  if (store === undefined) return NO_COUNTS;\n  let raw: string | null;\n  try {\n    raw = store.read();\n  } catch {\n    return NO_COUNTS;\n  }\n  return raw === null ? NO_COUNTS : parseCounts(raw);\n}\n\n/** The counts a stored text names, keeping only whole, positive numbers. */\nfunction parseCounts(raw: string): InsertCounts {\n  let value: unknown;\n  try {\n    value = JSON.parse(raw);\n  } catch {\n    return NO_COUNTS;\n  }\n  const counts =\n    typeof value === \"object\" && value !== null\n      ? (value as { counts?: unknown }).counts\n      : undefined;\n  if (typeof counts !== \"object\" || counts === null) return NO_COUNTS;\n  const kept: Record<string, number> = {};\n  for (const [name, count] of Object.entries(counts)) {\n    if (Number.isSafeInteger(count) && (count as number) > 0) {\n      kept[name] = count as number;\n    }\n  }\n  return kept;\n}\n\n/**\n * Count one more insert of a block in the store. A store that cannot be\n * written keeps what it had; adding the block has already happened.\n */\nexport function recordInsert(\n  store: PreferenceStore | undefined,\n  blockName: string\n): void {\n  if (store === undefined) return;\n  const counts = readInsertCounts(store);\n  const next = { ...counts, [blockName]: (counts[blockName] ?? 0) + 1 };\n  try {\n    store.write(JSON.stringify({ counts: next }));\n  } catch {\n    // Nothing to do: the count is a convenience, never the author's work.\n  }\n}\n\n/**\n * The blocks the picker shows at rest: the offered blocks, most added first.\n * A tie, and an author with no history, falls back to\n * {@link DEFAULT_MOST_USED}'s order, then to the order offered. A block the\n * place refuses is not in `offered`, so the next one takes its seat and the\n * grid stays full wherever enough blocks are offered.\n *\n * Only a block's own entry is shown, never one of its variations: the count\n * is per block name.\n *\n * @param offered - the entries the place accepts, in the palette's order\n * @param counts - how many times each block was added\n * @returns at most {@link MOST_USED_SIZE} block entries\n */\nexport function mostUsedEntries(\n  offered: readonly InsertEntry[],\n  counts: InsertCounts\n): BlockInsertEntry[] {\n  const blocks = offered.filter(\n    (entry): entry is BlockInsertEntry =>\n      entry.kind === \"block\" && entry.variationName === undefined\n  );\n  const rank = (name: string): number => {\n    const index = DEFAULT_MOST_USED.indexOf(name);\n    return index === -1 ? DEFAULT_MOST_USED.length : index;\n  };\n  const order = new Map(blocks.map((entry, index) => [entry.id, index]));\n  return [...blocks]\n    .sort(\n      (a, b) =>\n        (counts[b.blockName] ?? 0) - (counts[a.blockName] ?? 0) ||\n        rank(a.blockName) - rank(b.blockName) ||\n        (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)\n    )\n    .slice(0, MOST_USED_SIZE);\n}\n","/**\n * What the Add panel offers at the place it inserts into: each entry with the\n * reason a place refuses it, kept while its inputs are, and the placement, lock\n * and wording each refusal is judged and said by.\n *\n * @module insert-panel-offers\n */\n\nimport {\n  allBlocks,\n  asPermittedList,\n  permittedLabel,\n  placementSiteIn,\n  planInsertPattern,\n  registryNestingSource,\n  type BlockDocument,\n  type ComponentLookup,\n  type NestingSource,\n  type NestingVerdict,\n  type OpPosition,\n  type PlacementSources,\n  type PlacementVerdict,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { numberedForPlace } from \"../../canvas/accordion-questions\";\nimport {\n  placementWording,\n  refusalWording,\n  type RefusalWording,\n} from \"../../canvas/drag-refusal\";\nimport {\n  entryContentRefusal,\n  offeredIn,\n  withEntryContentField,\n} from \"../../canvas/entry-content-rules\";\nimport { usePreviewedCollection } from \"../../canvas/previewed-entry\";\nimport type { EditorState } from \"../../editor-state\";\nimport { lockRefusalWording, type LockRefusalFacts } from \"../../lock-refusal\";\nimport { refusalAnnouncement } from \"../../move-refusal\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { withArticle } from \"../../with-article\";\n\nimport { insertLockAt, type InsertLock } from \"./insert-lock\";\nimport type { InsertPanelProps } from \"./insert-panel-types\";\nimport { insertedAnnouncement } from \"./insert-placement-words\";\nimport { recordInsert, useInsertUsage } from \"./insert-usage\";\nimport {\n  blockLabel,\n  blockSourceFor,\n  catalogFrom,\n  componentEntriesFrom,\n  entryVerdictAt,\n  insertionCandidates,\n  insertionFor,\n  nodeForComponentEntry,\n  nodeForEntry,\n  patternEntriesFrom,\n  registrySlotSource,\n  slotsShowingEmpty,\n  type BlockInsertEntry,\n  type ComponentInsertEntry,\n  type EntryPlacement,\n  type InsertionCandidate,\n  type InsertEntry,\n  type PatternInsertEntry,\n} from \"./inserter\";\nimport {\n  entryRoles,\n  type EntryRole,\n  type InsertionOptions,\n} from \"./insertion-candidates\";\n\n/**\n * One entry as the panel offers it at the current place: where a click puts\n * it, or why it cannot go there.\n */\nexport type EntryOffer =\n  | {\n      readonly entry: InsertEntry;\n      readonly place: InsertionCandidate;\n      /**\n       * Whether the place is not the one the placement line names (a Box\n       * goes after a selected Section while the line says \"inside\"), or is\n       * past it because it refuses this entry: the tile then says where it\n       * goes.\n       */\n      readonly climbed: boolean;\n      readonly refusal?: undefined;\n    }\n  | {\n      readonly entry: InsertEntry;\n      readonly place?: undefined;\n      readonly climbed?: undefined;\n      readonly refusal: string;\n    };\n\n/**\n * The lookup a host that supplies none is judged under: nothing resolves.\n *\n * One shared instance rather than a `new Map()` per render, because the\n * catalogue memo is keyed on it and a fresh empty map each render would\n * rebuild the catalogue on every keystroke of the filter.\n */\nconst NO_DEFINITIONS: ComponentLookup = new Map();\n\n/** No offers, while they are not being looked at. */\nconst NO_OFFERS: ReadonlyMap<string, EntryOffer> = new Map();\n\n/** What {@link useInsertOffers} reads: the panel's own sources of blocks. */\nexport type InsertOffersInputs = Pick<\n  InsertPanelProps,\n  | \"editor\"\n  | \"definitions\"\n  | \"patterns\"\n  | \"components\"\n  | \"componentDefinitions\"\n  | \"nesting\"\n  | \"inside\"\n  | \"after\"\n  | \"at\"\n  | \"onInsert\"\n> & {\n  /**\n   * Whether to judge the offers at all. The editor's search keeps this hook\n   * mounted while it is closed, and judging every entry against every place on\n   * each edit is work nobody is looking at. `true` when absent.\n   */\n  enabled?: boolean;\n};\n\n/** What can be added, where each would go, and the act of adding one. */\nexport interface InsertOffers {\n  /** Blocks, then saved patterns and components, in one list. */\n  readonly catalog: readonly InsertEntry[];\n  /** The places a content block's click may use, in the order they are tried. */\n  readonly candidates: readonly InsertionCandidate[];\n  /**\n   * The place the panel's line names at rest: the first of\n   * {@link InsertOffers.candidates} a content block on offer takes, or the\n   * first of them when none does. Absent when there is no place at all.\n   */\n  readonly rest: InsertionCandidate | undefined;\n  /**\n   * The sentence the last insert is announced with (\"Heading added inside\n   * Hero, at the end\"), for a polite live region; empty until one is made.\n   */\n  readonly announcement: string;\n  /** Each entry's offer, by entry id: its place, or why it has none. */\n  readonly offers: ReadonlyMap<string, EntryOffer>;\n  /** The definitions an insert builds a block's children from. */\n  readonly blockSource: Parameters<typeof nodeForEntry>[1];\n  /** Add an entry where its offer says, or nothing when it was refused. */\n  readonly insert: (offer: EntryOffer | undefined) => void;\n}\n\n/**\n * The Add panel's offers and its insert, as a hook.\n *\n * The panel and the editor's search both call this, so a search row says the\n * place a tile would and adds there by the same path: one answer to \"what can\n * be added here, and where does it go\".\n *\n * @experimental\n */\nexport function useInsertOffers({\n  editor,\n  definitions,\n  patterns,\n  components,\n  componentDefinitions,\n  nesting,\n  inside,\n  after,\n  at,\n  onInsert,\n  enabled = true,\n}: InsertOffersInputs): InsertOffers {\n  // Where the author's insert counts are kept, for the picker's most used.\n  const usage = useInsertUsage();\n  // ONE snapshot, taken per mount, that both the catalog and the default\n  // expansion below read. The panel documents its palette as read once per\n  // mount rather than subscribed to, and a second reading of the registry\n  // taken later is a different list: a plugin registering while the panel is\n  // open would leave a row offering one definition's version and props while\n  // its children came from another.\n  const palette = React.useMemo(\n    () => definitions ?? allBlocks(),\n    [definitions]\n  );\n  const source = React.useMemo(\n    () => nesting ?? registryNestingSource(),\n    [nesting]\n  );\n  // Blocks, then whatever saved patterns and components the host supplied.\n  // One list rather than three, because the offer, the tokens and the filter\n  // all run across every tier; the tabs then show their share of it. A block\n  // only a template may hold is offered only while one is open.\n  const documentKind = editor.document.kind;\n  const catalog = React.useMemo<InsertEntry[]>(\n    () => [\n      ...catalogFrom(palette).filter(entry =>\n        offeredIn(documentKind, entry.blockName)\n      ),\n      ...patternEntriesFrom(patterns ?? [], source, componentDefinitions),\n      ...componentEntriesFrom(\n        components ?? [],\n        componentDefinitions ?? NO_DEFINITIONS\n      ),\n    ],\n    [palette, patterns, components, componentDefinitions, source, documentKind]\n  );\n  // The field an Entry content block draws once placed: the template's\n  // collection's first top-level blocks field, so the stored choice is\n  // explicit from the start.\n  const blocksFields = usePreviewedCollection()?.blocksFields;\n  const firstBlocksField = blocksFields?.[0]?.name;\n  // Whether the field a placed Entry content block names can be filled: not\n  // while the collection's fields are on their way.\n  const entryFieldsKnown = blocksFields !== undefined;\n\n  // Inside a list the canvas shows empty, a block goes to its empty state.\n  const showingEmpty = editor.listsShowingEmpty;\n  const slotSource = React.useMemo(\n    () => slotsShowingEmpty(registrySlotSource(), showingEmpty),\n    [showingEmpty]\n  );\n\n  // Derived from the SAME snapshot the catalog is, so the row an author sees\n  // and the subtree an insert builds cannot come from two different readings.\n  // The palette may be a caller-supplied subset holding a definition the\n  // registry does not, and the block being inserted is the one whose\n  // declaration is read — so resolving only against the registry would offer\n  // that block and then insert it without the children it declares.\n  const blockSource = React.useMemo(() => blockSourceFor(palette), [palette]);\n\n  // What kind of block each entry adds, which orders the places it tries:\n  // read once per catalogue, from what its blocks declare.\n  const roles = React.useMemo(\n    () => entryRoles(catalog, definitions),\n    [catalog, definitions]\n  );\n\n  // Read from the CURRENT document and selection, and kept only while both are\n  // the ones they were read from. A place is only valid against the document\n  // it was read from, and an undo or a remote edit can move it without the\n  // selection changing, so the document itself is part of the key, never the\n  // selection alone. The panel draws several times as it opens and on each\n  // edit, and each kind's places walk the page, so a render that changed\n  // none of these reads them again for nothing.\n  const document = editor.document;\n  const selectedId = editor.selectedId;\n  const places = React.useMemo(() => {\n    const placeOptions: InsertionOptions = {\n      slots: slotSource,\n      ...(inside === undefined ? {} : { inside }),\n      ...(after === undefined ? {} : { after }),\n      ...(at === undefined ? {} : { at }),\n    };\n    const placesFor = (role: EntryRole): InsertionCandidate[] =>\n      insertionCandidates(document, selectedId, { ...placeOptions, role });\n    // The layout and band places only where the offers are judged: the\n    // closed search reads the content block's first place alone.\n    return {\n      content: placesFor(\"content\"),\n      ...(enabled\n        ? { layout: placesFor(\"layout\"), band: placesFor(\"band\") }\n        : {}),\n    };\n  }, [document, selectedId, slotSource, inside, after, at, enabled]);\n  const candidates = places.content;\n\n  // Remembered by what the verdicts depend on — the document, the places, the\n  // catalog, the rule's sources and the locks — and not by the query, so a\n  // keystroke asks no rule anything: judging a pattern walks its forest and a\n  // component composes its definition, once per entry and place.\n  const offerCache = React.useRef<OfferCache | undefined>(undefined);\n  const { offers, rest } = !enabled\n    ? { offers: NO_OFFERS, rest: candidates[0] }\n    : cachedOffers(offerCache, {\n        document: editor.document,\n        places: {\n          content: candidates,\n          layout: places.layout ?? [],\n          band: places.band ?? [],\n        },\n        roles,\n        catalog,\n        source,\n        components: componentDefinitions,\n        expansion: { definitions: blockSource, nesting },\n        editor,\n        entryFieldsKnown,\n      });\n\n  // The sentence the last insert is announced with. A live region reads only\n  // a changed text, so a repeat of the same sentence (five Text blocks in a\n  // row) gains a zero-width space, or loses it, to be read again each time.\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const announce = (message: string) =>\n    setAnnouncement(previous =>\n      previous === message ? `${message}\\u200b` : message\n    );\n  /*\n   * Add an entry where its offer says, or nothing when it was refused.\n   *\n   * The guard is the whole of what a refused tile does on a click or an Enter:\n   * it stays reachable so its reason can be read, and choosing it changes\n   * nothing.\n   */\n  const insert = (offer: EntryOffer | undefined) => {\n    if (offer?.place === undefined) return;\n    const { entry } = offer;\n    const place = offer.place.at;\n    // Named against the page as it is before the insert, where the place's\n    // blocks are the ones the line named.\n    const said = insertedAnnouncement(\n      entry.label,\n      editor.document,\n      offer.place\n    );\n    const inserted =\n      entry.kind === \"pattern\"\n        ? insertPattern(entry, place)\n        : entry.kind === \"component\"\n          ? insertComponent(entry, place)\n          : insertBlock(entry, place);\n    if (!inserted) return;\n    announce(said);\n    // Only a block is counted toward the most used: a saved section or a\n    // component is the site's own content, one search away.\n    if (entry.kind === \"block\") recordInsert(usage, entry.blockName);\n  };\n\n  /** Place one block, and whether it was placed. */\n  const insertBlock = (entry: BlockInsertEntry, at: OpPosition): boolean => {\n    // `nesting` rather than `source`. They differ exactly when the caller\n    // supplied no rules: `source` has already defaulted to the REGISTRY, which\n    // knows nothing about a supplied definition and so reports every one of its\n    // types as unrestricted. Passing it defeats the fallback in\n    // `expandSlotDefaults`, which derives the rules from these same\n    // definitions — the only source that can see a supplied block's `parent`\n    // and its slots' `allow`.\n    // A Question added to an Accordion takes the next number there.\n    const node = numberedForPlace(\n      withEntryContentField(\n        nodeForEntry(entry, blockSource, nesting),\n        firstBlocksField\n      ),\n      at,\n      editor.document\n    );\n    // `apply` is the only path a document changes by, so undo covers this\n    // insert for free. It answers null when the op is refused, and a refusal\n    // must not be reported as an insert — the panel offers only placements the\n    // rule permits, so a null here means the document moved underneath it.\n    if (editor.apply({ kind: \"insert\", node, at }) === null) return false;\n    // Selecting what was just added is what makes a second insert land after\n    // it, so repeated inserts build downward instead of stacking at one point.\n    editor.select(node.id);\n    onInsert?.(node);\n    return true;\n  };\n\n  /**\n   * Place a component: ONE insert of an instance node.\n   *\n   * No planner, because there is nothing to plan — a pattern is a forest that\n   * has to be re-identified and judged root by root against the destination,\n   * while an instance is a single node whose content lives in the definition.\n   * The placement was judged when the tile was offered, by the definition's\n   * roots, so a refusal here means the document moved underneath the panel.\n   */\n  const insertComponent = (\n    entry: ComponentInsertEntry,\n    at: OpPosition\n  ): boolean => {\n    const node = nodeForComponentEntry(entry);\n    // Whether the PAGE has room for it — the one refusal the tile could not\n    // make, because room moves with every edit — is the editor's own apply's\n    // to make: it asks the resolver with the node in place, under the caps it\n    // enforces, and tells the host why when it refuses. A null here is that\n    // refusal, or a document that moved under the panel.\n    if (editor.apply({ kind: \"insert\", node, at }) === null) return false;\n    editor.select(node.id);\n    onInsert?.(node);\n    return true;\n  };\n\n  /**\n   * Place a saved pattern: a whole forest, re-identified, as ONE edit.\n   *\n   * Through `planInsertPattern` rather than by building ops here. The planner\n   * is the dry run — it mints ids that do not collide with the page, records\n   * where each root was copied from, and refuses everything the apply would —\n   * so a second construction in this file would be a second answer to what\n   * inserting a pattern means.\n   *\n   * `applyAll`, so the whole group is one undo step. A pattern placed as\n   * several inserts would come back one root at a time, which is not what the\n   * author did.\n   */\n  const insertPattern = (\n    entry: PatternInsertEntry,\n    at: OpPosition\n  ): boolean => {\n    const plan = planInsertPattern(\n      editor.document,\n      { id: entry.patternId, document: entry.document },\n      at,\n      source,\n      // The same lookup the catalogue judged the tile's roots by, so the offer\n      // and the mutation resolve one forest. Without it the planner reads a\n      // nested instance as its own unregistered type: unrestricted under a\n      // parent rule, and barred by any slot naming what it admits.\n      componentDefinitions\n    );\n    // A refusal here means the document moved underneath the panel: the\n    // catalogue offers only patterns the planner accepts, judged against the\n    // same rules. Reported as no insert rather than as a failed one.\n    if (plan.pageOps === undefined) return false;\n    if (editor.applyAll(plan.pageOps) === null) return false;\n\n    // The FIRST root, so a second insert lands after the group rather than\n    // inside it — the same rule the block path follows by selecting what it\n    // just added.\n    const first = plan.pageOps.find((op: BuilderOp) => op.kind === \"insert\");\n    if (first === undefined || first.kind !== \"insert\") return true;\n    editor.select(first.node.id);\n    onInsert?.(first.node);\n    return true;\n  };\n\n  return {\n    catalog,\n    candidates,\n    rest,\n    announcement,\n    offers,\n    blockSource,\n    insert,\n  };\n}\n\n/** Each entry's offer, and the place the line names at rest. */\ninterface Judged {\n  readonly offers: ReadonlyMap<string, EntryOffer>;\n  readonly rest: InsertionCandidate | undefined;\n}\n\n/** What the offer was computed from, and the offer. */\ninterface OfferCache {\n  readonly document: unknown;\n  readonly places: string;\n  readonly roles: unknown;\n  readonly catalog: unknown;\n  readonly source: unknown;\n  readonly components: unknown;\n  readonly definitions: unknown;\n  readonly nesting: unknown;\n  readonly editor: unknown;\n  readonly entryFieldsKnown: boolean;\n  readonly judged: Judged;\n}\n\n/** What each entry's offer is judged from. */\ninterface OfferInputs {\n  readonly document: BlockDocument;\n  /** The places each kind of block tries, in order. */\n  readonly places: Readonly<Record<EntryRole, readonly InsertionCandidate[]>>;\n  /** What kind of block each entry adds, by entry id. */\n  readonly roles: ReadonlyMap<string, EntryRole>;\n  readonly catalog: readonly InsertEntry[];\n  readonly source: NestingSource;\n  readonly components: ComponentLookup | undefined;\n  readonly expansion: EntryPlacement[\"expansion\"];\n  /** The lock rules and caps a place's locks are read with (`insert-lock`). */\n  readonly editor: Pick<\n    EditorState,\n    \"lockDefinitions\" | \"limits\" | \"lockRefusalFor\"\n  >;\n  /** Whether the template's collection's blocks fields are known yet. */\n  readonly entryFieldsKnown: boolean;\n}\n\n/**\n * Each entry's offer, judged again only when an input the verdicts read has\n * changed. Every input is compared by identity except the places, which are\n * rebuilt per render and so are compared by value.\n */\nfunction cachedOffers(\n  cache: { current: OfferCache | undefined },\n  inputs: OfferInputs\n): Judged {\n  const places = JSON.stringify(inputs.places);\n  const held = cache.current;\n  if (\n    held !== undefined &&\n    held.document === inputs.document &&\n    held.places === places &&\n    held.roles === inputs.roles &&\n    held.catalog === inputs.catalog &&\n    held.source === inputs.source &&\n    held.components === inputs.components &&\n    held.definitions === inputs.expansion.definitions &&\n    held.nesting === inputs.expansion.nesting &&\n    held.editor === inputs.editor &&\n    held.entryFieldsKnown === inputs.entryFieldsKnown\n  ) {\n    return held.judged;\n  }\n  const judged = offersFor(inputs);\n  cache.current = {\n    document: inputs.document,\n    places,\n    roles: inputs.roles,\n    catalog: inputs.catalog,\n    source: inputs.source,\n    components: inputs.components,\n    definitions: inputs.expansion.definitions,\n    nesting: inputs.expansion.nesting,\n    editor: inputs.editor,\n    entryFieldsKnown: inputs.entryFieldsKnown,\n    judged,\n  };\n  return judged;\n}\n\n/** One place's identity, the same for the equal places two kinds of block try. */\nfunction placeKey(candidate: InsertionCandidate): string {\n  return JSON.stringify([candidate.at, candidate.target]);\n}\n\n/**\n * Each entry's offer: the first place that takes it, by\n * {@link insertionFor} over the places its kind of block tries, or — when\n * none does — the reason the FIRST of them refused it, which is the place\n * the author is asking about. And the place the line names at rest: the\n * first a content block on offer takes.\n */\nfunction offersFor(inputs: OfferInputs): Judged {\n  // What a place reads for every entry, worked out once per place, however\n  // many kinds of block try it.\n  const contexts = new Map<string, PlaceContext>();\n  const contextOf = (candidate: InsertionCandidate): PlaceContext => {\n    const key = placeKey(candidate);\n    const known = contexts.get(key);\n    if (known !== undefined) return known;\n    const context = placeContext(inputs, candidate);\n    contexts.set(key, context);\n    return context;\n  };\n  const taken = new Map<string, EntryOffer>();\n  for (const entry of inputs.catalog) {\n    taken.set(entry.id, offerOf(inputs, entry, contextOf));\n  }\n  const rest = restPlace(inputs, taken);\n  const restKey = rest === undefined ? undefined : placeKey(rest);\n  const offers = new Map<string, EntryOffer>();\n  for (const [id, offer] of taken) {\n    offers.set(\n      id,\n      offer.place === undefined\n        ? offer\n        : { ...offer, climbed: placeKey(offer.place) !== restKey }\n    );\n  }\n  return { offers, rest };\n}\n\n/** One entry's place, or why it has none, before it is compared to the line. */\nfunction offerOf(\n  inputs: OfferInputs,\n  entry: InsertEntry,\n  contextOf: (candidate: InsertionCandidate) => PlaceContext\n): EntryOffer {\n  // A rule about the whole document refuses the entry wherever it goes: a\n  // template's one Entry content block, already placed.\n  const anywhere =\n    entry.kind === \"block\"\n      ? entryContentRefusal(\n          inputs.document,\n          entry.blockName,\n          inputs.entryFieldsKnown\n        )\n      : undefined;\n  if (anywhere !== undefined) return { entry, refusal: anywhere };\n  const candidates = inputs.places[inputs.roles.get(entry.id) ?? \"content\"];\n  const first: { refusal: string | undefined } = { refusal: undefined };\n  const taken = insertionFor(candidates, candidate => {\n    const refusal = refusalAt(inputs, entry, candidate, contextOf(candidate));\n    if (candidate === candidates[0]) first.refusal = refusal;\n    return refusal === undefined ? candidate : undefined;\n  });\n  return taken === undefined\n    ? {\n        entry,\n        refusal: first.refusal ?? \"This can't be added to the page from here.\",\n      }\n    : { entry, place: taken.answer, climbed: false };\n}\n\n/**\n * The place the line names at rest: the first of a content block's places\n * that a content block on offer takes. With Columns selected (which hold\n * only Column blocks) that is after the Columns, where a Heading goes, not\n * inside them; with a Section selected, inside it, at the end.\n */\nfunction restPlace(\n  inputs: OfferInputs,\n  offers: ReadonlyMap<string, EntryOffer>\n): InsertionCandidate | undefined {\n  const content = inputs.places.content;\n  const takenKeys = new Set<string>();\n  for (const offer of offers.values()) {\n    if (offer.place === undefined) continue;\n    if ((inputs.roles.get(offer.entry.id) ?? \"content\") !== \"content\") continue;\n    takenKeys.add(placeKey(offer.place));\n  }\n  return content.find(place => takenKeys.has(placeKey(place))) ?? content[0];\n}\n\n/** What judging any entry at one place reads, asked once per place. */\ninterface PlaceContext {\n  readonly placement: EntryPlacement | undefined;\n  /** The locks at this place, read from the structure around it. */\n  readonly locks: InsertLock;\n  /**\n   * The locks' answer for the catalog's first block here, which a pattern or\n   * a component follows: each arrives as a block of its own type, which no\n   * lock's starting blocks name. Asked on first use.\n   */\n  readonly firstBlockLock: () => LockRefusalFacts | undefined;\n}\n\n/** {@link PlaceContext} for one place, its locks read lazily. */\nfunction placeContext(\n  inputs: OfferInputs,\n  candidate: InsertionCandidate\n): PlaceContext {\n  const firstBlock = inputs.catalog.find(\n    (entry): entry is BlockInsertEntry => entry.kind === \"block\"\n  );\n  const locks = insertLockAt(inputs.document, candidate.at, {\n    definitions: inputs.editor.lockDefinitions,\n    nesting: inputs.source,\n    limits: inputs.editor.limits,\n    ask: inputs.editor.lockRefusalFor,\n  });\n  const asked: { answer?: LockRefusalFacts; done: boolean } = { done: false };\n  return {\n    placement: placementAt(inputs, candidate.at),\n    locks,\n    firstBlockLock: () => {\n      if (!asked.done && firstBlock !== undefined) {\n        const answer = lockAt(inputs, locks, firstBlock);\n        if (answer !== undefined) asked.answer = answer;\n      }\n      asked.done = true;\n      return asked.answer;\n    },\n  };\n}\n\n/**\n * Why an entry cannot go at a place, in the words the author reads, or\n * nothing when it can: the one placement rule first, then the locks.\n *\n * Each block is judged by its own insert, the store's own question: where a\n * locked slot is already broken, inserting the block it is missing can repair\n * it while any other block breaks it further, so one block's answer is not\n * every block's.\n */\nfunction refusalAt(\n  inputs: OfferInputs,\n  entry: InsertEntry,\n  candidate: InsertionCandidate,\n  context: PlaceContext\n): string | undefined {\n  const verdict = entryVerdictAt(\n    entry,\n    candidate.target,\n    inputs.source,\n    inputs.components,\n    context.placement\n  );\n  if (!verdict.allowed) {\n    return (\n      belongsInsideWording(verdict, entry) ??\n      refusalAnnouncement(placementRefusal(verdict, entry, candidate))\n    );\n  }\n  const lock =\n    entry.kind === \"block\"\n      ? lockAt(inputs, context.locks, entry)\n      : context.firstBlockLock();\n  return lock === undefined\n    ? undefined\n    : refusalAnnouncement(lockRefusalWording(lock));\n}\n\n/**\n * What the locks say of inserting one block at a place, from the structure\n * there: no trial insert, which runs only for the block actually added, in\n * the editor's apply.\n */\nfunction lockAt(\n  inputs: OfferInputs,\n  locks: InsertLock,\n  entry: BlockInsertEntry\n): LockRefusalFacts | undefined {\n  return locks.of(\n    nodeForEntry(entry, inputs.expansion.definitions, inputs.expansion.nesting)\n  );\n}\n\n/**\n * The placement rule's refusal in the words a drop's refusal uses, so an\n * author reads one sentence for one rule wherever they meet it. A block is\n * the subject, and named beside whatever inside it was refused; a pattern or\n * a component is named by the block of it that was refused.\n */\nfunction placementRefusal(\n  verdict: Exclude<NestingVerdict | PlacementVerdict, { allowed: true }>,\n  entry: InsertEntry,\n  candidate: InsertionCandidate\n): RefusalWording {\n  const regionType =\n    candidate.target.kind === \"slot\" ? candidate.target.parentType : undefined;\n  if (\"blockType\" in verdict) {\n    return placementWording(\n      verdict,\n      entry.kind === \"block\" ? entry.blockName : verdict.blockType,\n      regionType\n    );\n  }\n  // Judged by the name rules alone, which name no block: the entry's own\n  // type, or its first root's.\n  return refusalWording(\n    { reason: verdict.reason, permitted: verdict.permitted },\n    subjectTypeOf(entry),\n    regionType\n  );\n}\n\n/**\n * A refusal whose rule names the containers an entry belongs inside, said as\n * one plain instruction: \"Goes inside an Accordion. Select an Accordion\n * first, or drag this into one.\"\n *\n * Generated from the rule, never per block: the containers are the rule's\n * own permitted list, and the second sentence offers only what the tile can\n * do (a block can be dragged; a pattern or a component cannot). Selecting\n * such a container works because a click falls back to inside the selection.\n * Anything else, or a rule about a block nested within the entry, keeps the\n * shared refusal wording.\n */\nfunction belongsInsideWording(\n  verdict: Exclude<NestingVerdict | PlacementVerdict, { allowed: true }>,\n  entry: InsertEntry\n): string | undefined {\n  if (\n    verdict.reason !== \"restricted-at-root\" &&\n    verdict.reason !== \"wrong-parent\"\n  ) {\n    return undefined;\n  }\n  if (\"blockType\" in verdict && verdict.blockType !== subjectTypeOf(entry)) {\n    return undefined;\n  }\n  const containers = verdict.permitted.map(name =>\n    withArticle(permittedLabel(name, blockLabel))\n  );\n  if (containers.length === 0) return undefined;\n  const select =\n    containers.length === 1\n      ? `Select ${containers[0]} first`\n      : \"Select one first\";\n  const drag = entry.kind === \"block\" ? \", or drag this into one.\" : \".\";\n  return `Goes inside ${asPermittedList(containers, \"or\")}. ${select}${drag}`;\n}\n\n/** The block type an entry is named by in a refusal. */\nfunction subjectTypeOf(entry: InsertEntry): string {\n  if (entry.kind === \"block\") return entry.blockName;\n  if (entry.kind === \"component\") return entry.roots[0] ?? entry.label;\n  return entry.document.nodes[0]?.type ?? entry.label;\n}\n\n/**\n * A place as the one placement rule sees it, with what its ancestors refuse.\n * Undefined when the position's parent is not in the document, which the\n * name rules then judge alone.\n *\n * The rule reads block declarations from the palette's own source, the one\n * its catalog and its inserts read, so a definition the host supplied is the\n * one judged rather than the registry's under the same name.\n */\nfunction placementAt(\n  inputs: OfferInputs,\n  at: OpPosition\n): EntryPlacement | undefined {\n  const sources: PlacementSources = {\n    nesting: inputs.source,\n    definitions: inputs.expansion.definitions,\n    ...(inputs.components === undefined\n      ? {}\n      : { components: inputs.components }),\n  };\n  const site = placementSiteIn(\n    inputs.document.nodes,\n    at.parentId === undefined\n      ? { kind: \"root\" }\n      : { kind: \"slot\", parentId: at.parentId, slot: at.slot ?? \"\" },\n    sources\n  );\n  return site === undefined\n    ? undefined\n    : { site, sources, expansion: inputs.expansion };\n}\n","/**\n * How the Add panel answers a press of an add control on the canvas, and\n * where its tile card is anchored. Kept beside the panel rather than in it:\n * each is one decision the panel only calls.\n *\n * @module insert-panel-summon\n */\nimport * as React from \"react\";\n\nimport { boxInFrameViewport } from \"../../canvas/geometry-dom\";\nimport type { Rect } from \"../../geometry\";\n\n/**\n * Where a tile's card is anchored: a point on the panel's right edge, as\n * tall as the tile and level with it. Placed to its right, the card sits\n * outside the panel whichever column the tile is in.\n *\n * @param panel - the panel's box\n * @param tile - the tile's box\n * @returns the anchor's box, no wider than a line\n */\nexport function besidePanel(panel: Rect, tile: Rect): DOMRect {\n  return new DOMRect(panel.x + panel.width, tile.y, 0, tile.height);\n}\n\n/**\n * Anything a popover can be anchored to: a point beside a tile, with the\n * tile as the element whose scrolling moves it, or nowhere while there is no\n * tile in the document to measure.\n */\nexport interface Measurable {\n  getBoundingClientRect(): DOMRect;\n  readonly contextElement?: Element;\n}\n\n/** The anchor for a popover with no tile under it: a point at the origin. */\nexport const NOWHERE: Measurable = {\n  getBoundingClientRect: () => new DOMRect(),\n};\n\n/**\n * A tile card's anchor: a point on the panel's right edge, level with the\n * tile, so the card drawn to its right sits outside the panel, never over\n * the tiles beside it. The tile is its context element, so the card moves\n * with the list as it scrolls. Boxes are read through the module that reads\n * them. `NOWHERE` while either is missing.\n */\nexport function cardAnchor(\n  panel: HTMLElement | null,\n  tile: HTMLElement | null\n): Measurable {\n  if (panel === null || tile === null) return NOWHERE;\n  return {\n    contextElement: tile,\n    getBoundingClientRect: () =>\n      besidePanel(boxInFrameViewport(panel), boxInFrameViewport(tile)),\n  };\n}\n\n/**\n * How many frames the search is held focused after a press, while the tab\n * the press opened draws: a Saved sections tab reads the site's sections\n * first, and draws its search again once they arrive.\n */\nconst FOCUS_FRAMES = 90;\n\n/** The open tab's search, or the panel's only one. */\nfunction searchOf(panel: HTMLElement): HTMLInputElement | null {\n  return (\n    panel.querySelector<HTMLInputElement>(\n      '[role=\"tabpanel\"][data-state=\"active\"] [cmdk-input]'\n    ) ?? panel.querySelector<HTMLInputElement>(\"[cmdk-input]\")\n  );\n}\n\n/**\n * Focus the panel's search, without scrolling the panel's region (the list\n * going to the top is the one movement the author should see), and keep it\n * there while the tab draws: a search drawn again takes the focus its last\n * drawing held. Lets go the moment focus is somewhere else on purpose, or\n * after a moment and a half. Answers the way to stop early.\n */\nfunction keepSearchFocused(panel: HTMLElement | null): () => void {\n  if (panel === null) return () => undefined;\n  const doc = panel.ownerDocument;\n  const view = doc.defaultView;\n  let frames = 0;\n  let handle = 0;\n  const hold = (): void => {\n    if (!panel.isConnected) return;\n    const search = searchOf(panel);\n    const active = doc.activeElement;\n    // Somewhere else on purpose: an author moved on.\n    const lost = active === null || active === doc.body;\n    if (search !== null && active !== search && (frames === 0 || lost)) {\n      search.focus({ preventScroll: true });\n    } else if (!lost && active !== search) {\n      return;\n    }\n    frames += 1;\n    if (frames < FOCUS_FRAMES && view !== null) {\n      handle = view.requestAnimationFrame(hold);\n    }\n  };\n  hold();\n  return () => view?.cancelAnimationFrame(handle);\n}\n\n/** How long the line naming the place stays highlighted after a press. */\nconst FLASH_MS = 1200;\n\n/**\n * The panel's answer to each press of an add control on the canvas: the\n * search focused, the list back at the top, and the press's count while the\n * line naming the place is highlighted (`undefined` after). Each count is\n * answered once, and said back through `onSummoned`.\n */\nexport function useSummonAnswer(\n  root: React.RefObject<HTMLDivElement | null>,\n  summoned: number | undefined,\n  onSummoned: ((count: number) => void) | undefined\n): number | undefined {\n  const [flash, setFlash] = React.useState<number | undefined>(undefined);\n  const answered = React.useRef<number | undefined>(undefined);\n  // The hold on the search outlives the press's own render, which the host\n  // answers at once by taking the press back, and this line itself, which a\n  // tab drawn again replaces; it ends by itself, or when the panel goes.\n  const stopHolding = React.useRef<() => void>(() => undefined);\n  React.useEffect(() => {\n    if (summoned === undefined || answered.current === summoned) return;\n    answered.current = summoned;\n    const panel = root.current;\n    stopHolding.current();\n    stopHolding.current = keepSearchFocused(panel);\n    const list = panel?.querySelector<HTMLElement>(\".nx-insert-panel__list\");\n    if (list !== null && list !== undefined) list.scrollTop = 0;\n    setFlash(summoned);\n    onSummoned?.(summoned);\n  }, [root, summoned, onSummoned]);\n  React.useEffect(() => {\n    if (flash === undefined) return;\n    const done = setTimeout(() => setFlash(undefined), FLASH_MS);\n    return () => clearTimeout(done);\n  }, [flash]);\n  return flash;\n}\n","\"use client\";\n\n/**\n * The Add panel's tiles: the touch hint, the highlighted tile, its popover and\n * placement line, the words beside a tile, and a drag that begins on one.\n *\n * @module insert-panel-tiles\n */\n\nimport {\n  COMPONENT_INSTANCE_TYPE,\n  type BlockDocument,\n  type NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n  useCommandHighlight,\n} from \"@nextlyhq/ui\";\nimport { CornerDownRight } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../../block-icon\";\nimport { isElement } from \"../../canvas/dom-kind\";\nimport { withEntryContentField } from \"../../canvas/entry-content-rules\";\nimport { usePublishInsertionPreview } from \"../../canvas/insertion-preview\";\n\nimport type { EntryOffer } from \"./insert-panel-offers\";\nimport { cardAnchor, NOWHERE, type Measurable } from \"./insert-panel-summon\";\nimport type { InsertPanelProps } from \"./insert-panel-types\";\nimport {\n  placementSentence,\n  placementWords,\n  placeWords,\n} from \"./insert-placement-words\";\nimport {\n  nodeForComponentEntry,\n  nodeForEntry,\n  type InsertGroup,\n  type InsertionCandidate,\n  type InsertEntry,\n} from \"./inserter\";\n\n/**\n * What a press does, for the pointer that has no other way to ask.\n *\n * A press moves the highlight, so the popover beside the panel describes the\n * tile under the finger before it lifts. That is the affordance a touch author\n * could not discover: on a pointer that cannot hover, the only way to read a\n * tile looked like the way to take it.\n *\n * WHAT IT DOES NOT CLAIM. An earlier wording offered \"slide off to cancel\",\n * and that is not reliably true: the canvas sits beside this panel and IS a\n * drop target, so a finger sliding horizontally out of the tile can start a\n * palette drag and insert on release. Only a release over nothing declines,\n * and which regions those are depends on the layout the host mounted. Both\n * clauses here hold wherever the panel is mounted — pressing reads, lifting\n * commits — and an author who knows lifting commits can hold and think.\n *\n * SHOWN FROM THE POINTER THAT WAS ACTUALLY USED, not from a media query.\n * `(pointer: coarse)` describes the PRIMARY pointer, so a touchscreen laptop\n * driven by its trackpad reports `fine` and hides this from the author the\n * moment they reach up and touch the screen. The pointer type on the event is\n * the input in hand rather than the one the device is classified by, and it\n * has the side benefit of appearing exactly when it is relevant: after the\n * first press, which is when the question arises.\n *\n * `aria-hidden`, deliberately. It describes a POINTER gesture, and a screen\n * reader on a touch device does not activate a control by lifting a finger\n * from it — the guidance would be wrong for exactly the people an accessible\n * name is for. The block's description reaches them through each tile's own\n * `aria-describedby` regardless.\n */\nexport function TouchGestureHint({\n  shown,\n}: {\n  shown: boolean;\n}): React.JSX.Element | null {\n  if (!shown) return null;\n  return (\n    <p aria-hidden className=\"nx-insert-panel__gesture-hint\">\n      Press to read · lift to insert\n    </p>\n  );\n}\n\n/**\n * The entry a command value names, among those in view, or nothing.\n *\n * Scoped to the GROUPS rather than to the whole catalog, because a filter can\n * remove the highlighted entry between renders, and describing something the\n * author cannot see is worse than describing nothing. No fallback to the first\n * entry: the popover describes a tile the author moved to, never one the\n * primitives happened to mark when the list drew.\n */\nfunction highlightedEntry(\n  groups: readonly InsertGroup<InsertEntry>[],\n  tokens: ReadonlyMap<string, string>,\n  active: string\n): InsertEntry | undefined {\n  if (active === \"\") return undefined;\n  for (const group of groups) {\n    for (const entry of group.entries) {\n      if (tokens.get(entry.id) === active) return entry;\n    }\n  }\n  return undefined;\n}\n\nexport { placementWords }; // For the importers of the panel's words.\n\n/**\n * The tile in the panel carrying a command value.\n *\n * Found by comparing the attribute rather than through a selector, because a\n * value is an id from `useId` and a selector would need it escaped.\n */\nfunction tileElement(\n  root: HTMLElement | null,\n  token: string | undefined\n): HTMLElement | null {\n  if (root === null || token === undefined) return null;\n  for (const item of root.querySelectorAll<HTMLElement>(\"[cmdk-item]\")) {\n    if (item.getAttribute(\"data-value\") === token) return item;\n  }\n  return null;\n}\n\n/**\n * The popover beside the panel, describing the tile the author moved to.\n *\n * Rendered INSIDE the palette, because that is where the highlight lives:\n * `useCommandHighlight` reads the palette's own store, so this follows a\n * pointer, an arrow key and a filter alike without the panel keeping a second\n * copy of which tile is current.\n *\n * Controlled, and open only once the author has moved through the tiles\n * (`shown`): the primitives mark their first item the moment the list draws,\n * and a popover opened on that would describe a tile nobody pointed at.\n *\n * `aria-hidden`, and it never takes focus: everything it says is the tile's\n * own accessible description already, so a screen reader hears it on the\n * tile, and focus has to stay in the search for typing and the arrow keys to\n * keep working. Anchored beside the panel at the tile's height, so it moves\n * down with the highlight and never covers a tile.\n */\nexport function TilePopover({\n  shown,\n  groups,\n  tokens,\n  offers,\n  root,\n  renderPreview,\n  document,\n  onDismiss,\n}: {\n  shown: boolean;\n  groups: readonly InsertGroup<InsertEntry>[];\n  tokens: ReadonlyMap<string, string>;\n  offers: ReadonlyMap<string, EntryOffer>;\n  root: React.RefObject<HTMLDivElement | null>;\n  renderPreview: InsertPanelProps[\"renderPreview\"];\n  document: BlockDocument;\n  onDismiss: () => void;\n}): React.JSX.Element | null {\n  const highlighted = useCommandHighlight();\n  const entry = shown\n    ? highlightedEntry(groups, tokens, highlighted)\n    : undefined;\n  const anchor = React.useRef<Measurable>(NOWHERE);\n  // Pointed at the tile after the commit has drawn it and BEFORE the anchor's\n  // own effect reads it: layout effects run ahead of passive ones, so the\n  // popover measures the tile it describes rather than the one before it.\n  React.useLayoutEffect(() => {\n    const panel = root.current;\n    const tile =\n      entry === undefined ? null : tileElement(panel, tokens.get(entry.id));\n    anchor.current = cardAnchor(panel, tile);\n  });\n  if (entry === undefined) return null;\n  const offer = offers.get(entry.id);\n  const refusal = offer?.refusal;\n  const preview = renderPreview?.(entry);\n  return (\n    <Popover\n      open\n      // Escape, or a press or focus outside the panel, closes it until the\n      // author moves through the tiles again.\n      onOpenChange={open => {\n        if (!open) onDismiss();\n      }}\n    >\n      <PopoverAnchor virtualRef={anchor} />\n      <PopoverContent\n        side=\"right\"\n        align=\"start\"\n        sideOffset={8}\n        // Never flipped back over the tiles where the right has no room.\n        avoidCollisions={false}\n        aria-hidden=\"true\"\n        className=\"nx-insert-popover\"\n        // Focus stays in the search, where typing and the arrow keys work.\n        onOpenAutoFocus={event => event.preventDefault()}\n        onCloseAutoFocus={event => event.preventDefault()}\n        // A press on a tile is how touch reads one, and focus stays in the\n        // search, so nothing inside the panel dismisses the popover.\n        onInteractOutside={event => {\n          const target = event.target;\n          // Asked through dom-kind, which answers for a node from any\n          // window, the canvas frame's included.\n          if (isElement(target) && root.current?.contains(target)) {\n            event.preventDefault();\n          }\n        }}\n      >\n        <div className=\"nx-insert-popover__preview\">\n          {preview ?? <BlockIconMark icon={entry.icon} size={28} />}\n        </div>\n        <b className=\"nx-insert-popover__name\">{entry.label}</b>\n        {entry.description === \"\" ? null : (\n          <span className=\"nx-insert-popover__description\">\n            {entry.description}\n          </span>\n        )}\n        {offer?.climbed === true ? (\n          <span className=\"nx-insert-popover__place\">\n            <CornerDownRight aria-hidden=\"true\" size={12} />\n            <span>{placementWords(\"Goes\", document, offer.place)}</span>\n          </span>\n        ) : null}\n        <span\n          className=\"nx-insert-popover__hint\"\n          data-refused={refusal === undefined ? undefined : \"true\"}\n        >\n          {refusal ?? howToAdd(entry)}\n        </span>\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/**\n * How a tile is added. A pattern cannot be dragged: it is a forest placed as\n * a group, with no one node a drag carries. A block and a component are each\n * one node, a component's an instance pointing at its definition.\n */\nfunction howToAdd(entry: InsertEntry): string {\n  return entry.kind === \"pattern\"\n    ? \"Click to add\"\n    : \"Click to add · drag to place\";\n}\n\n/**\n * The line under the search that says where the next block goes: where the\n * highlighted tile goes, or at rest where a content block goes (\"Adding\n * inside Hero, at the end\"), the place an author expects. Following the\n * highlight names a place before the click wherever a tile goes elsewhere: a\n * layout block after a selected Section, or past a region that refuses it.\n *\n * A polite live region at rest, because it changes with every selection and\n * an assertive one would interrupt a screen reader mid-sentence each time.\n * Not while it follows the highlight: the highlighted tile's own description\n * already says where it goes, so announcing the line too would say it twice\n * on every arrow key. The block is named as Layers names it, an author's own\n * name first, so the line agrees with the tree beside it.\n *\n * While a tile is highlighted the line names it, \"Heading goes inside Hero,\n * at the end\", and hands that place and those words to the canvas, which\n * draws its insertion line there (`insertion-preview`).\n */\nexport function PlacementLine({\n  document,\n  flash,\n  first,\n  shown,\n  groups,\n  tokens,\n  offers,\n}: {\n  document: BlockDocument;\n  /** The canvas press the panel answered, while its line is highlighted. */\n  flash: number | undefined;\n  first: InsertionCandidate;\n  shown: boolean;\n  groups: readonly InsertGroup<InsertEntry>[];\n  tokens: ReadonlyMap<string, string>;\n  offers: ReadonlyMap<string, EntryOffer>;\n}): React.JSX.Element {\n  const highlighted = useCommandHighlight();\n  const entry = shown\n    ? highlightedEntry(groups, tokens, highlighted)\n    : undefined;\n  const own = entry === undefined ? undefined : offers.get(entry.id)?.place;\n  const place = own ?? first;\n  // Named only where it has a place of its own: a tile refused here leaves\n  // the line at the resting place, which it does not take.\n  const lead =\n    entry === undefined || own === undefined ? \"Adding\" : `${entry.label} goes`;\n  usePublishInsertionPreview(\n    own === undefined || entry === undefined\n      ? null\n      : { at: own.at, words: `${lead} ${placeWords(document, own)}` }\n  );\n  return (\n    <p\n      className=\"nx-insert-panel__placement\"\n      data-flash={flash === undefined ? undefined : \"\"}\n      aria-live={entry === undefined ? \"polite\" : \"off\"}\n    >\n      <CornerDownRight aria-hidden=\"true\" size={14} />\n      <span>{placementWords(lead, document, place)}</span>\n    </p>\n  );\n}\n\n/**\n * Where an insert is announced: \"Heading added inside Hero, at the end\".\n *\n * Polite, so it waits for whatever a screen reader is saying, and hidden from\n * sight, since the block appearing selected on the canvas says it to the eye.\n * No status role: the editor's keyboard region is the one status region an\n * author's moves are read from, and this one speaks only after an insert.\n */\nexport function InsertAnnouncement({\n  text,\n  afterClose = false,\n}: {\n  text: string;\n  /**\n   * Whether the insert closes a modal dialog this region sits outside (the\n   * editor's search). The dialog hides the rest of the page from a screen\n   * reader while open, and the insert changes the text in the update that\n   * closes it, so the text is set a moment later, once the page is\n   * readable again.\n   */\n  afterClose?: boolean;\n}): React.JSX.Element {\n  const [shown, setShown] = React.useState(afterClose ? \"\" : text);\n  React.useEffect(() => {\n    if (!afterClose) return;\n    const timer = setTimeout(() => setShown(text), 0);\n    return () => clearTimeout(timer);\n  }, [afterClose, text]);\n  return (\n    <p className=\"nx-sr-only\" aria-live=\"polite\" data-insert-announcement=\"\">\n      {afterClose ? shown : text}\n    </p>\n  );\n}\n\n/**\n * Start an entry's drag, when the host has a canvas to drop onto.\n *\n * A block or a component. A drag carries ONE node to a drop target, and a\n * pattern is a forest placed as a group — so there is no node to hand the\n * drag, and offering the gesture would start something that cannot finish.\n *\n * A component lands as the instance node a click writes. The canvas judges\n * a drop by the node the drag builds, resolving an instance through the\n * lookup it draws with, so the drop and the tile judge the same roots.\n *\n * An entry the click places refuse is still dragged. Its tile says where it\n * belongs (\"drag this into one\"), and where a drop may land is the canvas's\n * question, judged at the destination, not the panel's.\n *\n * Shared by every panel that inserts, so a row is dragged the same way\n * wherever it is offered.\n */\nexport function beginEntryDrag(\n  event: Parameters<NonNullable<InsertPanelProps[\"beginInsertDrag\"]>>[0],\n  entry: InsertEntry,\n  drag: {\n    begin: InsertPanelProps[\"beginInsertDrag\"];\n    definitions: Parameters<typeof nodeForEntry>[1];\n    nesting: NestingSource | undefined;\n    onInserted: InsertPanelProps[\"onInsert\"];\n    /**\n     * The field an Entry content block draws once placed, as a click\n     * places it.\n     */\n    entryField?: string | undefined;\n    /**\n     * Why the entry cannot go anywhere in this document, which no drop can\n     * change: a template's one Entry content block, already placed. Such an\n     * entry is not dragged.\n     */\n    refusedEverywhere?: boolean;\n  }\n): void {\n  if (drag.refusedEverywhere === true) return;\n  if (entry.kind === \"component\") {\n    drag.begin?.(event, {\n      blockName: COMPONENT_INSTANCE_TYPE,\n      makeNode: () => nodeForComponentEntry(entry),\n      onInserted: drag.onInserted,\n    });\n    return;\n  }\n  if (entry.kind !== \"block\") return;\n  drag.begin?.(event, {\n    blockName: entry.blockName,\n    makeNode: () =>\n      withEntryContentField(\n        nodeForEntry(entry, drag.definitions, drag.nesting),\n        drag.entryField\n      ),\n    // The same notification the click path sends, so a host cannot see one\n    // kind of insert and miss the other.\n    onInserted: drag.onInserted,\n  });\n}\n\n/**\n * What a row says before what it is, where it is drawn: why it cannot go\n * here, or where it goes when that is past the place the placement line\n * names.\n */\nexport function tileAside(\n  offer: EntryOffer | undefined,\n  document: BlockDocument\n): string | undefined {\n  if (offer?.refusal !== undefined) return offer.refusal;\n  return offer?.climbed === true\n    ? placementSentence(\"Goes\", document, offer.place)\n    : undefined;\n}\n\n/**\n * What an Add panel tile tells a screen reader before what it is: why it\n * cannot go here, or where a click puts it (\"Goes inside Hero, at the\n * end.\"). Every tile says its place, not only those past the line's, so an\n * author arrowing through the tiles hears where each one lands.\n */\nexport function tileWhere(\n  offer: EntryOffer | undefined,\n  document: BlockDocument\n): string | undefined {\n  if (offer?.refusal !== undefined) return offer.refusal;\n  return offer?.place === undefined\n    ? undefined\n    : placementSentence(\"Goes\", document, offer.place);\n}\n\n/**\n * The keys the palette's primitives move the highlight with: the arrows,\n * Home and End, and the Ctrl bindings they also honour. A key outside these\n * leaves the panel at rest.\n */\nexport function movesTheHighlight(event: React.KeyboardEvent): boolean {\n  if ([\"ArrowDown\", \"ArrowUp\", \"Home\", \"End\"].includes(event.key)) return true;\n  return event.ctrlKey && [\"n\", \"j\", \"p\", \"k\"].includes(event.key);\n}\n","\"use client\";\n\n/**\n * The inserter: what an author can add, and adding it.\n *\n * **Draws what `inserter` decides and decides nothing itself.** Every question\n * with an answer worth testing — what may be offered here, what a query\n * matches, where the block lands, what node to build — lives in that module,\n * where it can be asserted without a DOM. This file is the surface: focus,\n * keyboard, markup and the words an author reads.\n *\n * **Interaction is composed from `@nextlyhq/ui`'s command primitives rather\n * than rebuilt.** They already own the roving focus, the ARIA listbox wiring\n * and the type-ahead that the command palette uses, so an inserter with its own\n * keyboard handling would be a second implementation of the same widget that\n * drifts from it the first time either is corrected — and the two sit one panel\n * apart in the same editor.\n *\n * `shouldFilter={false}` is the load-bearing half of that composition. cmdk\n * filters by default, so leaving it on would put a SECOND filter beside\n * `filterEntries` — two answers to \"does this row match\", disagreeing about\n * block names and keywords, with the tested one silently overruled.\n *\n * ## The layout is two-dimensional and the KEYBOARD is not\n *\n * Tiles sit in a grid, and Down still moves to the next tile rather than the\n * one below. That reads as an oversight and is a deliberate retreat from the\n * opposite, which was built and removed.\n *\n * The primitives publish a `listbox`, whose keyboard model is one-dimensional\n * by definition: a screen reader announces \"option 4 of 18\" and Down means the\n * next option. Moving by a ROW instead makes the announcement a lie — Down\n * silently skips two — so a grid keyboard is only honest alongside a grid\n * accessibility tree, with rows, cells and coordinates.\n *\n * That tree is not something this file can add on top. `aria-activedescendant`\n * and the scroll-into-view are driven from the primitives' own navigation, and\n * a controlled `value` set from outside updates neither: the highlight and\n * this panel's popover would follow while the announced option and the scroll\n * position stayed where they were. Owning them instead means owning roving\n * focus and the ARIA wiring — the second implementation of this widget that\n * the paragraphs above exist to refuse.\n *\n * So the grid is a LAYOUT. Reading order is left to right and then down, which\n * is the order the primitives already move in, and search is what makes a long\n * palette reachable without arrowing at all.\n *\n * ## A refused tile stays, and stays reachable\n *\n * A tile the place refuses — by the placement rule or by a lock — is drawn\n * greyed with its reason, rather than left out: an author who cannot see a\n * block has no way to learn where it would go. It is NOT the primitives'\n * `disabled`, and carries no `aria-disabled`, because the primitives skip\n * every item marked so when the arrow keys move: a keyboard author could then\n * never reach the reason. It is marked `data-refused` for the eye, its reason\n * leads its accessible description, and choosing it inserts nothing.\n *\n * ## Where the parts live\n *\n * This module is the panel and the entry for the rest: its props are in\n * `insert-panel-types.ts`, the notices about its libraries in\n * `insert-panel-notices.tsx`, its tiles in `insert-panel-tiles.tsx`, and what\n * it offers at a place in `insert-panel-offers.ts`. Every name it exported, it\n * still exports.\n *\n * @module insert-panel\n */\n\nimport {\n  Command,\n  CommandEmpty,\n  CommandGroup,\n  CommandInput,\n  CommandItem,\n  CommandList,\n  Tabs,\n  TabsContent,\n  TabsList,\n  TabsTrigger,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../../block-icon\";\nimport { isElement } from \"../../canvas/dom-kind\";\nimport { entryContentRefusal } from \"../../canvas/entry-content-rules\";\nimport { usePreviewedCollection } from \"../../canvas/previewed-entry\";\nimport { EDITOR_WORDS } from \"../../editor-words\";\n\nimport { LibraryNotices, type LibraryTier } from \"./insert-panel-notices\";\nimport { useInsertOffers } from \"./insert-panel-offers\";\nimport { useSummonAnswer } from \"./insert-panel-summon\";\nimport {\n  beginEntryDrag,\n  InsertAnnouncement,\n  movesTheHighlight,\n  PlacementLine,\n  tileWhere,\n  TilePopover,\n  TouchGestureHint,\n} from \"./insert-panel-tiles\";\nimport type { InsertPanelProps } from \"./insert-panel-types\";\nimport { recordInsert, useInsertUsage } from \"./insert-usage\";\nimport {\n  categoryHeading,\n  filterEntries,\n  paletteGroups,\n  UNCATEGORISED,\n  type InsertEntry,\n} from \"./inserter\";\n\n// The panel's props, its library notices, its tiles and what it offers where\n// live in modules of their own beside it; every name this module exported\n// still is.\nexport { LibraryNotices } from \"./insert-panel-notices\";\n// Part of this module's exported names; no importer in the package reads it.\n// fallow-ignore-next-line unused-type\nexport type { LibraryTier } from \"./insert-panel-notices\";\nexport {\n  type EntryOffer,\n  type InsertOffers,\n  type InsertOffersInputs,\n  useInsertOffers,\n} from \"./insert-panel-offers\";\nexport {\n  beginEntryDrag,\n  InsertAnnouncement,\n  tileAside,\n  placementWords,\n} from \"./insert-panel-tiles\";\nexport type { InsertPanelProps, LibraryTierState } from \"./insert-panel-types\";\n\n/** The panel's two tabs: blocks and the site's components, and patterns. */\ntype PanelTab = \"blocks\" | \"sections\";\n\n/** Each tab's own word, as a sentence reads it, from the editor's words. */\nconst TAB_WORDS: Readonly<Record<PanelTab, string>> = {\n  blocks: EDITOR_WORDS.blocks.toLowerCase(),\n  sections: EDITOR_WORDS.sections.toLowerCase(),\n};\n\n/** What the search says it searches, per tab. */\nconst SEARCH_PLACEHOLDERS: Readonly<Record<PanelTab, string>> = {\n  blocks: `Search ${TAB_WORDS.blocks} and ${EDITOR_WORDS.components.toLowerCase()}`,\n  sections: `Search ${TAB_WORDS.sections}`,\n};\n\n/** Which tab an entry is offered in. Patterns are Sections; the rest Blocks. */\nfunction tabOf(entry: InsertEntry): PanelTab {\n  return entry.kind === \"pattern\" ? \"sections\" : \"blocks\";\n}\n\n/**\n * How many tiles sit in a row.\n *\n * A CONSTANT rather than a count derived from the panel's measured width:\n * measuring would need the layout to have happened before anything could read\n * it. Three because the panel opens at 300px and its padding and gaps leave\n * about 85px per tile there — a glyph and a short word. It is also what keeps\n * the grid from REFLOWING while the author drags the panel's edge, which would\n * move a tile out from under the cursor mid-drag.\n *\n * LAYOUT ONLY. No keyboard behaviour derives from it, and that is deliberate\n * rather than an omission: arrow keys stepping by a row would contradict the\n * listbox semantics the palette announces. See this module's documentation.\n */\nconst GRID_COLUMNS = 3;\n\n/**\n * How many tiles sit in a row where each draws a picture of its saved\n * section: two, so a picture is wide enough to read at the panel's default\n * width. Fixed per tab for the reason {@link GRID_COLUMNS} is.\n */\nconst PICTURE_COLUMNS = 2;\n\n/**\n * The tier a tab offers: components among the blocks, patterns as sections.\n */\nfunction tierOf(tab: PanelTab): LibraryTier {\n  return tab === \"sections\" ? \"patterns\" : \"components\";\n}\n\nexport function InsertPanel({\n  library,\n  categoryOrder,\n  blockOrder,\n  beginInsertDrag,\n  renderPreview,\n  renderPicture,\n  // A canvas press to answer, handed to the line that answers it.\n  summoned,\n  onSummoned,\n  summonedTab,\n  // What it offers, and where: the sources the offers are judged from.\n  ...offerInputs\n}: InsertPanelProps): React.JSX.Element {\n  const { editor, nesting, onInsert } = offerInputs;\n  // Where a dragged block's insert is counted, as a clicked one's is.\n  const usage = useInsertUsage();\n  const [query, setQuery] = React.useState(\"\");\n  // Blocks first: what an author adds most. Sections holds the patterns.\n  const [tab, setTab] = usePanelTab(summoned, summonedTab);\n  /*\n   * Whether the author has moved through the tiles, and with what.\n   *\n   * The primitives mark their first item as current the moment the list\n   * draws, so the panel paints that mark — and opens the popover — only once\n   * an arrow key or a pointer has moved it. Which of the two is kept because\n   * a pointer that leaves the list returns the panel to rest, while the\n   * keyboard's highlight stays where the author left it.\n   */\n  const [moved, setMoved] = React.useState<\"pointer\" | \"keyboard\" | null>(null);\n  /*\n   * Whether a TOUCH has pressed a tile in this panel yet.\n   *\n   * Set from the pointer that was actually used rather than read from a media\n   * query, because `(pointer: coarse)` describes the device's PRIMARY pointer:\n   * a touchscreen laptop driven by its trackpad reports `fine`, and the\n   * guidance would be hidden from an author the moment they reach up and touch\n   * the screen. It also appears exactly when it is relevant — after the first\n   * press, which is when the question arises — and never for a pointer that\n   * reads a tile by hovering it.\n   */\n  const [touchPressed, setTouchPressed] = React.useState(false);\n  // The panel's own element, which the popover anchors inside and treats as\n  // \"not outside\".\n  const root = React.useRef<HTMLDivElement | null>(null);\n  // The panel answers a canvas press once, here, rather than in the line\n  // that shows it: the line is drawn again with the tab a press opens, and\n  // the highlight has to last through that.\n  const flash = useSummonAnswer(root, summoned, onSummoned);\n  // What can be added, where, and the act of adding it: shared with the\n  // editor's search, so a row there and a tile here are one answer.\n  const { catalog, rest, announcement, offers, blockSource, insert } =\n    useInsertOffers(offerInputs);\n  // The field a dragged Entry content block draws, as a click places it,\n  // and whether it can be known yet.\n  const blocksFields = usePreviewedCollection()?.blocksFields;\n  const firstBlocksField = blocksFields?.[0]?.name;\n  // The tab's share of the catalog, then the query. Refused entries stay, so\n  // an empty list means the query matched nothing, or the tab holds nothing.\n  const groups = paletteGroups(\n    filterEntries(\n      catalog.filter(entry => tabOf(entry) === tab),\n      query\n    ),\n    categoryOrder,\n    blockOrder\n  );\n\n  /*\n   * One opaque TOKEN per catalog entry, standing in for it everywhere the DOM\n   * needs a string: the command value, and the id `aria-describedby` points at.\n   *\n   * Opaque rather than the entry's own id, and that is load-bearing twice over.\n   *\n   * The command primitives TRIM the value they report, so two variation names\n   * differing only in trailing space — both valid, since nothing validates a\n   * variation name — collapse to one value. Pointing at the second would then\n   * describe and insert the first, silently. A token cannot collapse because\n   * it carries no author-supplied text at all.\n   *\n   * `aria-describedby` is a space-separated list of id REFERENCES, so an id\n   * built from `block#wide card` names two ids that do not exist and the tile\n   * is announced with no description — also silently, since a reference that\n   * resolves to nothing is not an error.\n   *\n   * Prefixed from `useId` because two inserters can be mounted at once — a\n   * panel and a palette, or two editors side by side — and duplicate ids would\n   * have every tile in one describe itself with the other's sentence.\n   *\n   * Built from the CATALOG rather than the filtered groups, so a token belongs\n   * to an entry for the life of the mount instead of changing as an author\n   * types.\n   */\n  const idPrefix = React.useId();\n  /*\n   * Allocated ONCE per entry and never reused, rather than taken from the\n   * entry's position.\n   *\n   * A host may replace `definitions` while the panel is mounted, and inserting\n   * one definition shifts the position of every entry after it. Positional\n   * tokens would then be reassigned underneath a highlight the palette is\n   * still holding: the same string would name a different block, so the\n   * popover would describe it and Enter would insert it.\n   *\n   * The allocation lives in a ref because it must survive re-renders without\n   * being one — it is DOM identity, not state, and nothing renders differently\n   * because a token was issued. Handing out a token for an id already in the\n   * store is what makes this idempotent, so a repeated call cannot renumber\n   * anything.\n   */\n  const issued = React.useRef({ next: 0, byEntry: new Map<string, string>() });\n  const tokens = React.useMemo(() => {\n    const store = issued.current;\n    const byEntry = new Map<string, string>();\n    for (const entry of catalog) {\n      const existing = store.byEntry.get(entry.id);\n      const token = existing ?? `${idPrefix}-b${store.next}`;\n      if (existing === undefined) {\n        store.next += 1;\n        store.byEntry.set(entry.id, token);\n      }\n      byEntry.set(entry.id, token);\n    }\n    return byEntry;\n  }, [catalog, idPrefix]);\n\n  const header = <h2 className=\"nx-insert-panel__title\">{EDITOR_WORDS.add}</h2>;\n  const firstPlace = rest;\n  if (firstPlace === undefined) {\n    // Only an explicit place can leave no place: the container an `inside`\n    // names is gone from the page, or holds no region a block can be put\n    // in. (A gap's `after` lasts only while its block is selected, so it is\n    // on the page.)\n    return (\n      <div className=\"nx-insert-panel\" data-empty=\"unplaceable\">\n        {header}\n        <p className=\"nx-insert-panel__note\">\n          The container chosen to add into is no longer on the page. Select a\n          block to add after it, or clear the selection to add at the end of the\n          page.\n        </p>\n      </div>\n    );\n  }\n\n  /*\n   * The palette, drawn inside whichever tab is open.\n   *\n   * The search, the placement line and the notices belong to it rather than\n   * to the frame above, so the tab's panel holds everything a tab switch\n   * changes, and the query carries over because it lives in this component.\n   */\n  const paletteView = (\n    <Command\n      className=\"nx-insert-panel__palette\"\n      shouldFilter={false}\n      label=\"Insert a block\"\n      onKeyDown={event => {\n        if (movesTheHighlight(event)) setMoved(\"keyboard\");\n      }}\n    >\n      <CommandInput\n        value={query}\n        onValueChange={setQuery}\n        placeholder={SEARCH_PLACEHOLDERS[tab]}\n      />\n      <PlacementLine\n        document={editor.document}\n        flash={flash}\n        first={firstPlace}\n        shown={moved !== null}\n        groups={groups}\n        tokens={tokens}\n        offers={offers}\n      />\n      <LibraryNotices library={library} tier={tierOf(tab)} />\n      <CommandList\n        className=\"nx-insert-panel__list\"\n        // A pointer that leaves the tiles returns the panel to rest; a\n        // keyboard highlight stays where the author left it.\n        onPointerLeave={() => {\n          setMoved(current => (current === \"pointer\" ? null : current));\n        }}\n      >\n        <CommandEmpty>{emptyStateText(tab, query)}</CommandEmpty>\n        {groups.map(group => (\n          <CommandGroup\n            key={group.category}\n            heading={groupHeading(group.category, tab)}\n          >\n            {group.entries.map(entry => {\n              const offer = offers.get(entry.id);\n              const token = tokens.get(entry.id);\n              const refusal = offer?.refusal;\n              // What the author needs before what the block is: why it\n              // cannot go here, or where a click puts it.\n              const aside = tileWhere(offer, editor.document);\n              // The aside's own id, beside the description's, so the tile\n              // is described by the aside first, then what it is.\n              const why = token === undefined ? undefined : `${token}-why`;\n              return (\n                <CommandItem\n                  // `value` is what cmdk reports on selection. The entry id is\n                  // unique across blocks AND their variations, while a label is\n                  // not — two plugins may both label a block \"Card\".\n                  key={entry.id}\n                  value={token}\n                  onSelect={() => insert(offer)}\n                  /*\n                   * NAMED by the block and DESCRIBED by its sentence, rather\n                   * than named by the two run together.\n                   *\n                   * An element with no label is named from its CONTENTS, and\n                   * that computation trims each node and joins them with no\n                   * separator — so a label and a description in adjacent spans\n                   * are announced as \"TextA paragraph of plain text\". Whether\n                   * any separator appears depends on the elements' `display`,\n                   * which makes the spoken name a property of the stylesheet\n                   * rather than of the markup.\n                   *\n                   * Stating both removes the guess: the block's name, then its\n                   * sentence, in that order and as two separate things. The\n                   * label is exactly the visible text, so a spoken command\n                   * still matches what is written on the tile.\n                   */\n                  aria-label={entry.label}\n                  aria-describedby={\n                    aside === undefined ? token : `${why} ${token}`\n                  }\n                  // Greyed by the stylesheet. Not `disabled`: see this\n                  // module's documentation on why a refused tile stays\n                  // reachable.\n                  data-refused={refusal === undefined ? undefined : \"true\"}\n                  // Beside `onSelect`, never instead of it. A press stays a\n                  // click until it has travelled far enough to mean a drag, so\n                  // this does not consume the row's own activation — and a host\n                  // that supplies no drag leaves the row exactly as it was.\n                  onPointerDown={event => {\n                    /*\n                     * The input in hand, recorded before anything else in this\n                     * handler can return early.\n                     */\n                    if (event.pointerType === \"touch\") setTouchPressed(true);\n                    /*\n                     * Describe this tile on the PRESS, not only on a hover.\n                     *\n                     * Replayed through the primitives' OWN handler rather\n                     * than by setting the highlight directly. They move it on\n                     * `pointermove`, which a touch screen never sends before\n                     * contact — so without this the popover on touch would\n                     * never open, and the tap that finally moves the\n                     * highlight is the same tap that inserts.\n                     *\n                     * Dispatching the event they already listen for keeps the\n                     * announced option and the scroll in step, which setting\n                     * the value from outside does not. The panel's own\n                     * pointer-move handler sees it too, which is what opens\n                     * the popover.\n                     */\n                    event.currentTarget.dispatchEvent(\n                      new PointerEvent(\"pointermove\", { bubbles: true })\n                    );\n                    beginEntryDrag(event, entry, {\n                      begin: beginInsertDrag,\n                      definitions: blockSource,\n                      nesting,\n                      // Counted toward the most used, as a click's is.\n                      onInserted: node => {\n                        if (entry.kind === \"block\") {\n                          recordInsert(usage, entry.blockName);\n                        }\n                        onInsert?.(node);\n                      },\n                      entryField: firstBlocksField,\n                      refusedEverywhere:\n                        entry.kind === \"block\" &&\n                        entryContentRefusal(\n                          editor.document,\n                          entry.blockName,\n                          blocksFields !== undefined\n                        ) !== undefined,\n                    });\n                  }}\n                >\n                  {tilePicture(entry, renderPicture) ?? (\n                    <BlockIconMark icon={entry.icon} size={20} />\n                  )}\n                  <span className=\"nx-insert-panel__label\">{entry.label}</span>\n                  {/* Kept in the tile and not drawn: `aria-describedby`\n                      needs an element to point at, and keeping it here is what\n                      stops a tile and the sentence describing it from being\n                      rendered apart. */}\n                  {aside === undefined ? null : (\n                    <span className=\"nx-insert-panel__description\" id={why}>\n                      {aside}\n                    </span>\n                  )}\n                  <span className=\"nx-insert-panel__description\" id={token}>\n                    {entry.description}\n                  </span>\n                </CommandItem>\n              );\n            })}\n          </CommandGroup>\n        ))}\n      </CommandList>\n      <TilePopover\n        shown={moved !== null}\n        groups={groups}\n        tokens={tokens}\n        offers={offers}\n        root={root}\n        renderPreview={renderPreview}\n        document={editor.document}\n        onDismiss={() => setMoved(null)}\n      />\n      {/*\n        Not drawn while nothing is offered: with the search filtered to no\n        matches the panel would show \"No blocks match\" beside an instruction\n        about pressing tiles, and spend scarce panel height doing it.\n      */}\n      <TouchGestureHint shown={touchPressed && groups.length > 0} />\n    </Command>\n  );\n\n  return (\n    <div\n      ref={root}\n      className=\"nx-insert-panel\"\n      /* The column count, handed to the stylesheet rather than spelled again\n         in it, so the layout has one source.\n\n         LAYOUT ONLY. Nothing reads it to move a highlight — arrow keys are the\n         command primitives' and step by one option, which is what their\n         listbox semantics announce. See this module's documentation.\n\n         On the PANEL rather than on each group, because the primitives own the\n         element the grid is applied to — their items container — and a\n         property set on a wrapper inside it would be inherited by the tiles\n         instead of read by the grid. */\n      style={\n        {\n          \"--nx-insert-columns\": picturesIn(tab, renderPicture)\n            ? PICTURE_COLUMNS\n            : GRID_COLUMNS,\n        } as React.CSSProperties\n      }\n      // The current tile is painted once the author has moved through the\n      // tiles, or typed a search whose first match Enter would take.\n      data-highlight={\n        moved !== null || query.trim() !== \"\" ? \"shown\" : undefined\n      }\n      // A pointer moving over a tile is a pointer pointing at it. Read here,\n      // where it bubbles, because the primitives own each tile's own\n      // pointer-move handler.\n      onPointerMove={event => {\n        const target = event.target;\n        if (isElement(target) && target.closest(\"[cmdk-item]\")) {\n          setMoved(\"pointer\");\n        }\n      }}\n    >\n      {header}\n      <InsertAnnouncement text={announcement} />\n      <Tabs\n        value={tab}\n        onValueChange={value =>\n          setTab(value === \"sections\" ? \"sections\" : \"blocks\")\n        }\n        className=\"nx-insert-panel__tabs\"\n      >\n        <TabsList className=\"nx-insert-panel__tablist\">\n          <TabsTrigger value=\"blocks\">{EDITOR_WORDS.blocks}</TabsTrigger>\n          <TabsTrigger value=\"sections\">{EDITOR_WORDS.sections}</TabsTrigger>\n        </TabsList>\n        {/* One tab panel per tab, so each trigger controls an element that\n            exists. A closed tab panel renders none of its children, so the\n            palette is drawn once, in the open one. */}\n        <TabsContent value=\"blocks\" className=\"nx-insert-panel__tab\">\n          {paletteView}\n        </TabsContent>\n        <TabsContent value=\"sections\" className=\"nx-insert-panel__tab\">\n          {paletteView}\n        </TabsContent>\n      </Tabs>\n    </div>\n  );\n}\n\n/**\n * The tab the panel shows, and the way to change it. A canvas press that\n * names a tab opens it in the very render that answers the press, so the\n * search the answer focuses is that tab's, not one a later render would\n * replace; opened for such a press, the panel starts on that tab.\n */\nfunction usePanelTab(\n  summoned: number | undefined,\n  summonedTab: PanelTab | undefined\n): readonly [PanelTab, (tab: PanelTab) => void] {\n  const [tab, setTab] = React.useState<PanelTab>(() =>\n    summoned !== undefined && summonedTab !== undefined ? summonedTab : \"blocks\"\n  );\n  const [tabbedPress, setTabbedPress] = React.useState(summoned);\n  if (tabbedPress !== summoned) {\n    setTabbedPress(summoned);\n    if (summoned !== undefined && summonedTab !== undefined) {\n      setTab(summonedTab);\n    }\n  }\n  return [tab, setTab];\n}\n\n/** Whether a tab's tiles draw pictures: the saved sections, given a host's. */\nfunction picturesIn(\n  tab: PanelTab,\n  renderPicture: InsertPanelProps[\"renderPicture\"]\n): boolean {\n  return tab === \"sections\" && renderPicture !== undefined;\n}\n\n/**\n * A saved section's picture for its tile, or nothing to keep the mark: only\n * a pattern has a document to draw, and a host may answer none for one.\n */\nfunction tilePicture(\n  entry: InsertEntry,\n  renderPicture: InsertPanelProps[\"renderPicture\"]\n): React.ReactNode {\n  if (entry.kind !== \"pattern\" || renderPicture === undefined) return null;\n  const picture = renderPicture(entry);\n  // A host writing `has(entry) && <Picture />` hands back `false` for none,\n  // which draws nothing; the tile keeps its mark for it, as for `null`.\n  return typeof picture === \"boolean\" ? null : picture;\n}\n\n/**\n * A group's heading. Patterns that declared no category are the Sections\n * tab's remainder, so they read as more sections rather than more blocks.\n */\nfunction groupHeading(category: string, tab: PanelTab): string {\n  return tab === \"sections\" && category === UNCATEGORISED\n    ? `More ${TAB_WORDS.sections}`\n    : categoryHeading(category);\n}\n\n/** What the list says when it shows nothing: the tab is empty, or the query matched nothing. */\nfunction emptyStateText(tab: PanelTab, query: string): string {\n  const searched = query.trim();\n  const word = TAB_WORDS[tab];\n  if (searched !== \"\") return `No ${word} match \"${searched}\".`;\n  return tab === \"sections\"\n    ? `No ${word} yet.`\n    : `No ${word} can be added here.`;\n}\n","/**\n * How the in-place picker's highlight moves with the keyboard, decided\n * without a DOM: the six at rest are a grid of three columns, where every\n * arrow moves, and the search's results are a list, where Up and Down do.\n *\n * The picker publishes the matching structure to assistive technology (a\n * grid of rows and cells, or a listbox), so what a screen reader says about\n * the highlight is what the arrow keys do with it.\n *\n * @module insert-picker-keys\n */\n\n/** How the picker's choices are laid out: the six at rest, or results. */\nexport type PickerLayout = \"grid\" | \"list\";\n\n/** How many cells a row of the six holds. */\nconst PICKER_COLUMNS = 3;\n\n/**\n * Where the highlight goes for a key, or `undefined` for a key that does not\n * move it (the key then does what it would in the search field).\n *\n * The highlight never wraps: at an edge the key keeps it where it is, so a\n * repeated press cannot carry an author from the last block to the first\n * without them noticing.\n *\n * @param layout - grid at rest, list while searching\n * @param index - the highlighted choice\n * @param count - how many choices there are\n * @param key - the pressed key's `key`\n * @returns the new highlighted index, or `undefined`\n */\nexport function movedHighlight(\n  layout: PickerLayout,\n  index: number,\n  count: number,\n  key: string\n): number | undefined {\n  if (count === 0) return undefined;\n  const last = count - 1;\n  const clamp = (next: number): number => Math.min(Math.max(next, 0), last);\n  if (key === \"Home\") return 0;\n  if (key === \"End\") return last;\n  if (layout === \"list\") {\n    if (key === \"ArrowDown\") return clamp(index + 1);\n    if (key === \"ArrowUp\") return clamp(index - 1);\n    return undefined;\n  }\n  return gridMove(index, last, key);\n}\n\n/** One arrow key in the grid; a row move that leaves the grid stays put. */\nfunction gridMove(\n  index: number,\n  last: number,\n  key: string\n): number | undefined {\n  const step: Readonly<Record<string, number>> = {\n    ArrowRight: 1,\n    ArrowLeft: -1,\n    ArrowDown: PICKER_COLUMNS,\n    ArrowUp: -PICKER_COLUMNS,\n  };\n  const delta = step[key];\n  if (delta === undefined) return undefined;\n  const next = index + delta;\n  return next < 0 || next > last ? index : next;\n}\n\n/** The grid's rows: each a run of {@link PICKER_COLUMNS} choices. */\nexport function gridRows<T>(items: readonly T[]): T[][] {\n  const rows: T[][] = [];\n  for (let start = 0; start < items.length; start += PICKER_COLUMNS) {\n    rows.push(items.slice(start, start + PICKER_COLUMNS));\n  }\n  return rows;\n}\n","\"use client\";\n\n/**\n * The in-place picker's choices: the six most used as a grid of three\n * columns at rest, and the search's results as a list. Each is the element\n * the search field controls, with the highlighted choice as its active\n * descendant, so focus stays in the search while the arrows move.\n *\n * @module insert-picker-choices\n */\n\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../../block-icon\";\n\nimport { gridRows } from \"./insert-picker-keys\";\nimport { categoryHeading, type InsertEntry } from \"./inserter\";\n\n/** What every choice is drawn and chosen with. */\ninterface ChoicesProps {\n  /** The id the search field's `aria-controls` names. */\n  readonly id: string;\n  readonly entries: readonly InsertEntry[];\n  readonly highlighted: number;\n  /** A choice's own id, for `aria-activedescendant`. */\n  readonly choiceId: (index: number) => string;\n  /** Where each choice goes, or why not, said after its name. */\n  readonly whereOf: (entry: InsertEntry) => string | undefined;\n  readonly onHighlight: (index: number) => void;\n  readonly onChoose: (index: number) => void;\n}\n\n/**\n * A press keeps focus in the search: the choice is taken on the click, and\n * the field the arrows and typing work in stays the one with focus.\n */\nfunction keepSearchFocus(event: React.MouseEvent): void {\n  event.preventDefault();\n}\n\n/** The six at rest, three to a row, as a grid. */\nexport function MostUsedGrid(props: ChoicesProps): React.JSX.Element {\n  const rows = gridRows(\n    props.entries.map((entry, index) => ({ entry, index }))\n  );\n  return (\n    <div\n      id={props.id}\n      role=\"grid\"\n      aria-label=\"Most used blocks\"\n      className=\"nx-insert-picker__grid\"\n    >\n      {rows.map(row => (\n        <div role=\"row\" key={row[0]?.index} className=\"nx-insert-picker__row\">\n          {row.map(({ entry, index }) => (\n            <Choice key={entry.id} role=\"gridcell\" {...props} index={index}>\n              <BlockIconMark icon={entry.icon} size={18} />\n              <span className=\"nx-insert-picker__name\">{entry.label}</span>\n            </Choice>\n          ))}\n        </div>\n      ))}\n    </div>\n  );\n}\n\n/** The search's results, one to a line, with the group each is in. */\nexport function ResultList(props: ChoicesProps): React.JSX.Element {\n  return (\n    <div\n      id={props.id}\n      role=\"listbox\"\n      aria-label=\"Matching blocks\"\n      className=\"nx-insert-picker__list\"\n    >\n      {props.entries.map((entry, index) => (\n        <Choice key={entry.id} role=\"option\" {...props} index={index}>\n          <BlockIconMark icon={entry.icon} size={16} />\n          <span className=\"nx-insert-picker__name\">{entry.label}</span>\n          <span className=\"nx-insert-picker__group\" aria-hidden=\"true\">\n            {categoryHeading(entry.category)}\n          </span>\n        </Choice>\n      ))}\n    </div>\n  );\n}\n\n/**\n * One choice: named by its block, described by where it goes, marked\n * selected while highlighted. A pointer moving over it highlights it, as\n * the arrows do, so the line names the place before the click.\n */\nfunction Choice({\n  role,\n  index,\n  entries,\n  highlighted,\n  choiceId,\n  whereOf,\n  onHighlight,\n  onChoose,\n  children,\n}: ChoicesProps & {\n  readonly role: \"gridcell\" | \"option\";\n  readonly index: number;\n  readonly children: React.ReactNode;\n}): React.JSX.Element | null {\n  const entry = entries[index];\n  if (entry === undefined) return null;\n  const id = choiceId(index);\n  const where = whereOf(entry);\n  return (\n    <div\n      id={id}\n      role={role}\n      aria-selected={index === highlighted}\n      aria-label={entry.label}\n      aria-describedby={where === undefined ? undefined : `${id}-where`}\n      data-highlighted={index === highlighted ? \"\" : undefined}\n      className=\"nx-insert-picker__choice\"\n      onPointerMove={() => {\n        if (index !== highlighted) onHighlight(index);\n      }}\n      onMouseDown={keepSearchFocus}\n      onClick={() => onChoose(index)}\n    >\n      {children}\n      {where === undefined ? null : (\n        <span id={`${id}-where`} className=\"nx-sr-only\">\n          {where}\n        </span>\n      )}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * One opening of the in-place picker: a non-modal dialog named \"Add a\n * block\", described by the line that says where a block goes, holding a\n * search, the six blocks the author adds most and \"Browse all blocks and\n * sections →\".\n *\n * **What it offers and where each goes is the Add panel's answer.** The\n * catalogue, the placement rule, the locks and the search's words all come\n * from {@link useInsertOffers}, the hook the panel and the editor's search\n * call, so the picker cannot place a block anywhere a panel click would not.\n * What is only true here is that a choice the place refuses is left out\n * rather than greyed: the picker is small, and a refusal's reason is the Add\n * panel's to give, one press away.\n *\n * **The keyboard is the picker's own, and honest about its shape.** The six\n * are a grid and every arrow moves through them; the results are a list\n * and Up and Down do. The search field is a combobox controlling whichever\n * is shown, with the highlighted choice as its active descendant, so focus\n * never leaves the field the author types in.\n *\n * @module insert-picker-body\n */\n\nimport type { BlockNode } from \"@nextlyhq/blocks-engine\";\nimport { Popover, PopoverAnchor, PopoverContent } from \"@nextlyhq/ui\";\nimport { CornerDownRight, Search } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { useCanvasFrame } from \"../../canvas/canvas-frame-context\";\n\nimport { useInsertOffers, type InsertOffers } from \"./insert-panel-offers\";\nimport { tileWhere } from \"./insert-panel-tiles\";\nimport { MostUsedGrid, ResultList } from \"./insert-picker-choices\";\nimport { movedHighlight, type PickerLayout } from \"./insert-picker-keys\";\nimport type {\n  InsertPickerProps,\n  InsertPickerRequest,\n  PickerOutcome,\n} from \"./insert-picker-types\";\nimport { insertedAnnouncement, placementWords } from \"./insert-placement-words\";\nimport {\n  mostUsedEntries,\n  readInsertCounts,\n  useInsertUsage,\n} from \"./insert-usage\";\nimport {\n  filterEntries,\n  paletteGroups,\n  type InsertEntry,\n  type InsertionCandidate,\n} from \"./inserter\";\n\n/** The picker's own words, exactly as decided. */\nconst PICKER_WORDS = {\n  name: \"Add a block\",\n  search: \"Search blocks\",\n  browseAll: \"Browse all blocks and sections →\",\n} as const;\n\n/** What one opening is handed by the picker that is always mounted. */\nexport interface OpenPickerProps\n  extends Omit<InsertPickerProps, \"request\" | \"onClose\" | \"onEditText\"> {\n  readonly request: InsertPickerRequest;\n  /** How the opening ended; called once. */\n  readonly onFinish: (outcome: PickerOutcome) => void;\n  /** The sentence an insert is announced with, said after the picker goes. */\n  readonly onSaid: (sentence: string) => void;\n}\n\nexport function OpenPicker({\n  request,\n  onFinish,\n  onSaid,\n  onBrowseAll,\n  categoryOrder,\n  blockOrder,\n  ...sources\n}: OpenPickerProps): React.JSX.Element {\n  const { editor } = sources;\n  const inserted = React.useRef<BlockNode | null>(null);\n  const place =\n    request.target.kind === \"place\" ? request.target.place : undefined;\n  const offerings = useInsertOffers({\n    ...sources,\n    ...place,\n    onInsert: node => {\n      inserted.current = node;\n      sources.onInsert?.(node);\n    },\n  });\n  const [query, setQuery] = React.useState(\"\");\n  const [highlighted, setHighlighted] = React.useState(0);\n  const choices = useChoices(offerings, query, { categoryOrder, blockOrder });\n  const index = Math.min(highlighted, Math.max(choices.entries.length - 1, 0));\n  const current = choices.entries[index];\n  const line = linePlace(request, offerings, current);\n\n  const done = React.useRef(false);\n  const finish = (outcome: PickerOutcome): void => {\n    if (done.current) return;\n    done.current = true;\n    onFinish(outcome);\n  };\n  useFrameDismiss(() => finish({ kind: \"dismissed\", returnFocus: true }));\n\n  const choose = (at: number): void => {\n    const entry = choices.entries[at];\n    const offer =\n      entry === undefined ? undefined : offerings.offers.get(entry.id);\n    if (entry === undefined || offer?.place === undefined) return;\n    // Named against the page before the insert, where its blocks are.\n    const said = insertedAnnouncement(\n      entry.label,\n      editor.document,\n      offer.place\n    );\n    inserted.current = null;\n    offerings.insert(offer);\n    const node = inserted.current;\n    if (node === null) return;\n    onSaid(said);\n    finish({ kind: \"inserted\", node });\n  };\n\n  const ids = usePickerIds();\n  const input = React.useRef<HTMLInputElement | null>(null);\n  // Focus stays in the search, so the list does not follow the highlight by\n  // itself: a choice the keyboard or a new search highlights is brought into\n  // view, as little as it takes, once it is drawn. A fresh object per request\n  // so a key that leaves the highlight where it is still shows it. A pointer\n  // highlight asks for nothing: the choice under the pointer is in view.\n  const [revealed, setRevealed] = React.useState<{ at: number } | null>(null);\n  React.useLayoutEffect(() => {\n    if (revealed === null) return;\n    input.current?.ownerDocument\n      .getElementById(ids.choice(revealed.at))\n      ?.scrollIntoView({ block: \"nearest\" });\n  }, [revealed, ids]);\n  const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>): void => {\n    // An input method composing text owns Enter and the arrows: they pick and\n    // confirm its characters, not a block.\n    if (composing(event.nativeEvent)) return;\n    const moved = movedHighlight(\n      choices.layout,\n      index,\n      choices.entries.length,\n      event.key\n    );\n    if (moved === undefined && event.key !== \"Enter\") return;\n    // The picker's own keys, kept from the editor's shortcuts beneath it.\n    event.preventDefault();\n    event.stopPropagation();\n    if (moved === undefined) {\n      choose(index);\n      return;\n    }\n    setHighlighted(moved);\n    setRevealed({ at: moved });\n  };\n\n  return (\n    <Popover\n      open\n      onOpenChange={open => {\n        if (!open) finish({ kind: \"dismissed\", returnFocus: true });\n      }}\n    >\n      <PopoverAnchor virtualRef={{ current: request.anchor }} />\n      <PopoverContent\n        side=\"bottom\"\n        align=\"start\"\n        sideOffset={8}\n        collisionPadding={8}\n        className=\"nx-insert-picker\"\n        aria-label={PICKER_WORDS.name}\n        aria-describedby={line === undefined ? undefined : ids.line}\n        onOpenAutoFocus={event => {\n          event.preventDefault();\n          input.current?.focus({ preventScroll: true });\n        }}\n        // Focus is put back by the picker itself, once it has gone.\n        onCloseAutoFocus={event => event.preventDefault()}\n        onEscapeKeyDown={event => {\n          event.preventDefault();\n          // An input method's Escape cancels what it was composing, and the\n          // search the author is typing stays open.\n          if (composing(event)) return;\n          finish({ kind: \"dismissed\", returnFocus: true });\n        }}\n        // Leaving by Tab goes where the author went: focus stays there.\n        onFocusOutside={event => {\n          event.preventDefault();\n          finish({ kind: \"dismissed\", returnFocus: false });\n        }}\n        // Escape is the picker's: the editor's Escape beneath it would clear\n        // the selection the picker was opened from.\n        onKeyDown={event => {\n          if (event.key === \"Escape\") event.stopPropagation();\n        }}\n      >\n        <div className=\"nx-insert-picker__search\">\n          <Search aria-hidden=\"true\" size={14} />\n          <input\n            ref={input}\n            className=\"nx-insert-picker__input\"\n            role=\"combobox\"\n            aria-label={PICKER_WORDS.search}\n            placeholder={PICKER_WORDS.search}\n            aria-expanded=\"true\"\n            aria-autocomplete=\"list\"\n            aria-haspopup={choices.layout === \"grid\" ? \"grid\" : \"listbox\"}\n            aria-controls={ids.choices}\n            aria-activedescendant={\n              current === undefined ? undefined : ids.choice(index)\n            }\n            value={query}\n            onChange={event => {\n              setQuery(event.target.value);\n              setHighlighted(0);\n              setRevealed({ at: 0 });\n            }}\n            onKeyDown={onKeyDown}\n          />\n        </div>\n        {line === undefined ? (\n          <p className=\"nx-insert-picker__line\" role=\"status\">\n            The place chosen to add at is no longer on the page.\n          </p>\n        ) : (\n          <p id={ids.line} className=\"nx-insert-picker__line\">\n            <CornerDownRight aria-hidden=\"true\" size={13} />\n            <span>{placementWords(\"Adding\", editor.document, line)}</span>\n          </p>\n        )}\n        <PickerChoices\n          layout={choices.layout}\n          query={query}\n          id={ids.choices}\n          entries={choices.entries}\n          highlighted={index}\n          choiceId={ids.choice}\n          whereOf={entry =>\n            tileWhere(offerings.offers.get(entry.id), editor.document)\n          }\n          onHighlight={setHighlighted}\n          onChoose={choose}\n        />\n        <button\n          type=\"button\"\n          className=\"nx-insert-picker__all\"\n          onClick={() => {\n            finish({ kind: \"browse\" });\n            onBrowseAll(request.target);\n          }}\n        >\n          {PICKER_WORDS.browseAll}\n        </button>\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/**\n * Whether a key belongs to an input method composing text: `isComposing`,\n * or the legacy 229 key code some browsers send instead.\n */\nfunction composing(event: KeyboardEvent): boolean {\n  return event.isComposing || event.keyCode === 229;\n}\n\n/** The grid or the list, and what it says when it holds nothing. */\nfunction PickerChoices({\n  layout,\n  query,\n  ...props\n}: React.ComponentProps<typeof ResultList> & {\n  readonly layout: PickerLayout;\n  readonly query: string;\n}): React.JSX.Element {\n  const Choices = layout === \"grid\" ? MostUsedGrid : ResultList;\n  const empty =\n    layout === \"grid\"\n      ? \"No blocks can be added here.\"\n      : `No blocks match \"${query.trim()}\".`;\n  return (\n    <>\n      <Choices {...props} />\n      {props.entries.length === 0 ? (\n        <p className=\"nx-insert-picker__empty\" role=\"status\">\n          {empty}\n        </p>\n      ) : null}\n    </>\n  );\n}\n\n/**\n * What the picker shows: at rest the six most used blocks the place takes,\n * and while typing every block, saved section and component it takes that\n * matches, in the Add panel's order and by its words.\n */\nfunction useChoices(\n  { catalog, offers }: InsertOffers,\n  query: string,\n  order: Pick<InsertPickerProps, \"categoryOrder\" | \"blockOrder\">\n): { readonly layout: PickerLayout; readonly entries: readonly InsertEntry[] } {\n  const usage = useInsertUsage();\n  // Read once per opening: an insert closes the picker, and the next\n  // opening reads the count it added.\n  const counts = React.useMemo(() => readInsertCounts(usage), [usage]);\n  const offered = React.useMemo(\n    () =>\n      paletteGroups(\n        catalog.filter(entry => offers.get(entry.id)?.place !== undefined),\n        order.categoryOrder,\n        order.blockOrder\n      ).flatMap(group => group.entries),\n    [catalog, offers, order.categoryOrder, order.blockOrder]\n  );\n  if (query.trim() === \"\") {\n    return { layout: \"grid\", entries: mostUsedEntries(offered, counts) };\n  }\n  return { layout: \"list\", entries: filterEntries(offered, query) };\n}\n\n/**\n * Where the line says a block goes. At a fixed place, that place. By the\n * rule, the highlighted block's own place, as the Add panel's line follows\n * its highlight; before anything is highlighted, where a content block goes.\n * `undefined` when a fixed place is gone from the page.\n */\nfunction linePlace(\n  request: InsertPickerRequest,\n  { offers, rest }: InsertOffers,\n  current: InsertEntry | undefined\n): InsertionCandidate | undefined {\n  if (request.target.kind === \"place\" || current === undefined) return rest;\n  return offers.get(current.id)?.place ?? rest;\n}\n\n/** The ids the dialog's parts point at one another by. */\nfunction usePickerIds(): {\n  readonly line: string;\n  readonly choices: string;\n  readonly choice: (index: number) => string;\n} {\n  const prefix = React.useId();\n  return React.useMemo(\n    () => ({\n      line: `${prefix}-line`,\n      choices: `${prefix}-choices`,\n      choice: (index: number) => `${prefix}-choice-${String(index)}`,\n    }),\n    [prefix]\n  );\n}\n\n/**\n * A press on the page closes the picker. The page is drawn in a frame of its\n * own, whose presses never reach the editor's document, where the popover\n * listens for presses outside it.\n */\nfunction useFrameDismiss(dismiss: () => void): void {\n  const frameDocument = useCanvasFrame().document;\n  const latest = React.useRef(dismiss);\n  latest.current = dismiss;\n  React.useEffect(() => {\n    if (frameDocument === null || frameDocument === globalThis.document) {\n      return;\n    }\n    const press = (): void => latest.current();\n    frameDocument.addEventListener(\"pointerdown\", press, true);\n    return () => frameDocument.removeEventListener(\"pointerdown\", press, true);\n  }, [frameDocument]);\n}\n","\"use client\";\n\n/**\n * The in-place block picker: a small dialog that opens where the author is\n * looking, with a search, the six blocks they add most and \"Browse all\n * blocks and sections →\", and adds a block without a trip to the Add panel.\n *\n * Always mounted, and drawn only while a request is open: the live region\n * that announces an insert has to outlast the picker it was made in, since\n * the insert is what closes it. Each opening is drawn fresh (keyed by its\n * count), so a second opening starts from an empty search.\n *\n * After an insert, the new block is selected (by the Add panel's own insert)\n * and, when it has text, opened for typing by the same verb Enter runs;\n * otherwise focus goes to the canvas, where the keyboard acts on the new\n * selection. Closed without adding, focus goes back to whatever opened it.\n *\n * @module insert-picker\n */\n\nimport * as React from \"react\";\n\nimport { returnFocusToCanvas } from \"../../canvas/canvas-escape\";\nimport { useCanvasFrame } from \"../../canvas/canvas-frame-context\";\nimport { isHTMLElement, isIFrame } from \"../../canvas/dom-kind\";\n\nimport type { Measurable } from \"./insert-panel-summon\";\nimport { InsertAnnouncement } from \"./insert-panel-tiles\";\nimport { OpenPicker } from \"./insert-picker-body\";\nimport type {\n  InsertPickerProps,\n  InsertPickerRequest,\n  InsertPickerTarget,\n  PickerOutcome,\n} from \"./insert-picker-types\";\n\n/**\n * The picker, drawn while `request` is open.\n *\n * @experimental\n */\nexport function InsertPicker({\n  request,\n  onClose,\n  onEditText,\n  ...props\n}: InsertPickerProps): React.JSX.Element {\n  const frame = useCanvasFrame().frame;\n  // The sentence the last insert is announced with; a repeat gains a\n  // zero-width space so a live region reads it again.\n  const [said, setSaid] = React.useState(\"\");\n  const editText = React.useRef(onEditText);\n  editText.current = onEditText;\n  const finish = (outcome: PickerOutcome): void => {\n    const opener = request?.opener ?? null;\n    onClose();\n    // Once the picker has gone, and the canvas has drawn what was added.\n    setTimeout(() => {\n      settleFocus(outcome, { opener, frame, editText: editText.current });\n    }, 0);\n  };\n  return (\n    <>\n      <InsertAnnouncement text={said} />\n      {request === null ? null : (\n        <OpenPicker\n          key={request.count}\n          {...props}\n          request={request}\n          onFinish={finish}\n          onSaid={sentence =>\n            setSaid(previous =>\n              previous === sentence ? `${sentence}​` : sentence\n            )\n          }\n        />\n      )}\n    </>\n  );\n}\n\n/** Where focus goes once an opening of the picker has ended. */\nfunction settleFocus(\n  outcome: PickerOutcome,\n  {\n    opener,\n    frame,\n    editText,\n  }: {\n    readonly opener: HTMLElement | null;\n    readonly frame: HTMLIFrameElement | null;\n    readonly editText: ((nodeId: string) => boolean) | undefined;\n  }\n): void {\n  if (outcome.kind === \"inserted\") {\n    // A block with text opens for typing; anything else, the canvas.\n    if (editText?.(outcome.node.id) !== true) focusCanvas(frame);\n    return;\n  }\n  if (outcome.kind === \"dismissed\" && outcome.returnFocus) focusOpener(opener);\n}\n\n/** Focus on the canvas's frame, with its outline, where there is one. */\nfunction focusCanvas(frame: HTMLIFrameElement | null): void {\n  if (frame !== null) returnFocusToCanvas(frame);\n}\n\n/**\n * Focus back on what opened the picker, while it is still on the page: the\n * canvas, the way Escape returns there, or the control itself.\n */\nfunction focusOpener(opener: HTMLElement | null): void {\n  if (opener === null || !opener.isConnected) return;\n  if (isIFrame(opener)) returnFocusToCanvas(opener);\n  else opener.focus({ preventScroll: true });\n}\n\n/** The picker's open request, and the ways to open and close it. */\nexport interface InsertPickerState {\n  readonly request: InsertPickerRequest | null;\n  /**\n   * Open the picker beside `anchor`. The element with focus now is where\n   * focus returns when the picker closes without adding.\n   */\n  readonly open: (target: InsertPickerTarget, anchor: Measurable) => void;\n  readonly close: () => void;\n}\n\n/**\n * The picker's state, for a host to hand to {@link InsertPicker} and to the\n * controls that open it.\n *\n * @experimental\n */\nexport function useInsertPicker(): InsertPickerState {\n  const [request, setRequest] = React.useState<InsertPickerRequest | null>(\n    null\n  );\n  const opened = React.useRef(0);\n  const open = React.useCallback(\n    (target: InsertPickerTarget, anchor: Measurable): void => {\n      opened.current += 1;\n      const active = document.activeElement;\n      setRequest({\n        target,\n        anchor,\n        opener: isHTMLElement(active) ? active : null,\n        count: opened.current,\n      });\n    },\n    []\n  );\n  const close = React.useCallback(() => setRequest(null), []);\n  return React.useMemo(\n    () => ({ request, open, close }),\n    [request, open, close]\n  );\n}\n","/**\n * Where the in-place picker is drawn beside: the control that opened it, or,\n * for \"/\", the selected block (or the end of the page), measured in the\n * editor's own window even when the page is drawn in a frame.\n *\n * @module insert-picker-anchor\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\n\nimport { nodeElement } from \"../../canvas/canvas-addressing\";\nimport { isIFrame } from \"../../canvas/dom-kind\";\nimport {\n  boxInFrameViewport,\n  framePointInHost,\n} from \"../../canvas/geometry-dom\";\n\nimport { NOWHERE, type Measurable } from \"./insert-panel-summon\";\n\n/**\n * A control the picker opens from, such as a \"+\": its own box, read each time\n * the picker is placed, so a scroll moves the picker with it.\n */\nexport function elementAnchor(element: Element | null): Measurable {\n  if (element === null) return NOWHERE;\n  return {\n    contextElement: element,\n    getBoundingClientRect: () => hostBox(element),\n  };\n}\n\n/**\n * The picker's anchor for \"/\": the selected block, or, with nothing selected,\n * the bottom edge of the page's last block, where a block will be added. The\n * part on screen is used, so a tall Section scrolled half away still places\n * the picker where the author is looking. `NOWHERE` while the canvas has not\n * drawn the block.\n *\n * @param root - the canvas root the blocks are drawn in\n * @param document - the page, for its last block\n * @param selectedId - the selected block, or `null`\n */\nexport function selectionAnchor(\n  root: HTMLElement | null,\n  document: BlockDocument,\n  selectedId: string | null\n): Measurable {\n  if (root === null) return NOWHERE;\n  const lastId = document.nodes.at(-1)?.id;\n  const id = selectedId ?? lastId;\n  const element = id === undefined ? root : (nodeElement(root, id) ?? root);\n  const atEnd = selectedId === null && lastId !== undefined;\n  return {\n    contextElement: element,\n    getBoundingClientRect: () => {\n      const box = onScreen(hostBox(element), viewportOf(element));\n      return atEnd ? new DOMRect(box.x, box.bottom, box.width, 0) : box;\n    },\n  };\n}\n\n/**\n * An element's box in the editor's window, read through the module that\n * reads boxes. Inside the canvas's frame, both corners are mapped out of the\n * frame, which is scaled to fit the well.\n */\nfunction hostBox(element: Element): DOMRect {\n  const box = boxInFrameViewport(element);\n  const frame = element.ownerDocument.defaultView?.frameElement;\n  if (!isIFrame(frame)) return new DOMRect(box.x, box.y, box.width, box.height);\n  const start = framePointInHost(frame, { x: box.x, y: box.y });\n  const end = framePointInHost(frame, {\n    x: box.x + box.width,\n    y: box.y + box.height,\n  });\n  return new DOMRect(start.x, start.y, end.x - start.x, end.y - start.y);\n}\n\n/** The editor window's size, for the element's own window or its frame's host. */\nfunction viewportOf(element: Element): { width: number; height: number } {\n  const own = element.ownerDocument.defaultView;\n  const frame = own?.frameElement;\n  const host = isIFrame(frame) ? frame.ownerDocument.defaultView : own;\n  return {\n    width: host?.innerWidth ?? Number.POSITIVE_INFINITY,\n    height: host?.innerHeight ?? Number.POSITIVE_INFINITY,\n  };\n}\n\n/**\n * The part of a box inside the window, or, for a box wholly off it, a line\n * at the nearest edge, so the picker is placed in view either way.\n */\nfunction onScreen(\n  box: DOMRect,\n  viewport: { readonly width: number; readonly height: number }\n): DOMRect {\n  const left = clamp(box.left, 0, viewport.width);\n  const right = clamp(box.right, 0, viewport.width);\n  const top = clamp(box.top, 0, viewport.height);\n  const bottom = clamp(box.bottom, 0, viewport.height);\n  return new DOMRect(left, top, right - left, bottom - top);\n}\n\n/** A number held between two bounds. */\nfunction clamp(value: number, low: number, high: number): number {\n  return Math.min(Math.max(value, low), high);\n}\n","\"use client\";\n\n/**\n * The Components panel: the site's components by name, a search, and placing\n * one where the Add panel would place a block.\n *\n * ## One placement path\n *\n * Every insert goes through the Add panel's own offers ({@link useInsertOffers})\n * with the components the host hands that panel, so a component placed from\n * here lands where its tile in Add would, refused where that tile is refused,\n * and by the same op. A drag starts through {@link beginEntryDrag}, the\n * function Add's tiles start theirs with. Two panels that inserted differently\n * would leave an author unable to predict either.\n *\n * ## A list of rows, not a listbox\n *\n * Add is a grid of tiles in a listbox. A component row also carries \"Edit\",\n * and a button cannot sit inside a listbox: its owned elements are options and\n * groups only, so the button would be invalid there and unreachable from the\n * arrow keys that move a listbox's highlight. Each row is therefore two\n * buttons in a list, reached with Tab. The arrow keys move between rows as a\n * shortcut, and Enter in the search places the first match, as it does in Add.\n *\n * ## What \"Edit\" opens\n *\n * The host's, because it knows the component's own view and whether this\n * author may update components. Absent, no row offers a way to change a\n * component, and placing one is all the panel does.\n *\n * @module components-panel\n */\n\nimport type { ComponentLookup, NestingSource } from \"@nextlyhq/blocks-engine\";\nimport { Input } from \"@nextlyhq/ui\";\nimport { CornerDownRight, PencilLine } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../../block-icon\";\nimport type { EditorState } from \"../../editor-state\";\nimport { EDITOR_WORDS } from \"../../editor-words\";\nimport {\n  beginEntryDrag,\n  InsertAnnouncement,\n  LibraryNotices,\n  placementWords,\n  tileAside,\n  useInsertOffers,\n  type EntryOffer,\n  type InsertPanelProps,\n  type LibraryTierState,\n} from \"../add/insert-panel\";\nimport {\n  filterEntries,\n  unplaceableComponentEntries,\n  type ComponentInsertEntry,\n  type SavedComponent,\n} from \"../add/inserter\";\n\nexport interface ComponentsPanelProps {\n  /** The editor whose document this places into, as Add is given it. */\n  editor: EditorState;\n  /**\n   * The site's components this author may read, as the Add panel is handed\n   * them: the one catalogue both panels and the editor's search offer.\n   */\n  components: readonly SavedComponent[];\n  /** The lookup the canvas resolves instances against, as Add is handed it. */\n  componentDefinitions: ComponentLookup;\n  /** Whether the read is still on its way: rows are drawn as placeholders. */\n  loading?: boolean;\n  /** Where the component read stands, and the retry, as Add says it. */\n  library?: {\n    readonly components?: LibraryTierState;\n    readonly retry?: () => void;\n  };\n  /**\n   * How many of the site's components the host left out because they cannot\n   * go in the document being edited: the component itself, and those that\n   * place it. With none offered, the panel says that rather than that the\n   * site has none.\n   */\n  withheld?: number;\n  /** How nesting is resolved. Defaults to the live registry, as in Add. */\n  nesting?: NestingSource;\n  /** The container a \"+\" chose to add inside, as Add is handed it. */\n  inside?: string;\n  /** The block a gap's \"+\" chose to add after, as Add is handed it. */\n  after?: string;\n  /** Any other place the author chose, by position, as Add is handed it. */\n  at?: InsertPanelProps[\"at\"];\n  /** Begins a drag onto the canvas, as Add's tiles do. */\n  beginInsertDrag?: InsertPanelProps[\"beginInsertDrag\"];\n  /** Notified after a placement, with the node that was added. */\n  onInsert?: InsertPanelProps[\"onInsert\"];\n  /**\n   * Opens a component alone, in its own view. Absent where this author may\n   * not update components, and then no row offers it.\n   */\n  onEditComponent?: (componentId: string) => void;\n  /**\n   * Whether this author may make a component, so the empty panel can say how.\n   */\n  mayCreate?: boolean;\n}\n\n/**\n * No blocks, for the offers: this panel offers components only, and judging\n * every registered block at every place would be work nothing shows.\n */\nconst NO_BLOCKS: NonNullable<InsertPanelProps[\"definitions\"]> = [];\n\n/** How many placeholder rows stand in while the read is on its way. */\nconst PLACEHOLDER_ROWS = 3;\n\n/**\n * What the panel says of a component with nothing in it that can be placed:\n * one saved without content, or with none the canvas could draw. It is\n * listed so it can be opened and filled, and refused where Add leaves it out.\n */\nconst NOTHING_TO_PLACE = \"Nothing in it can be placed yet.\";\n\n/**\n * Every row the panel lists, in the library's order, as Add offers its\n * component tiles: the catalogue's entry for a component, or for one it\n * offers none, its entry with nothing to place.\n */\nfunction componentRows(\n  components: readonly SavedComponent[],\n  catalog: ReturnType<typeof useInsertOffers>[\"catalog\"],\n  unplaceable: readonly ComponentInsertEntry[],\n  query: string\n): readonly ComponentInsertEntry[] {\n  const byId = new Map<string, ComponentInsertEntry>();\n  for (const entry of [...unplaceable, ...catalog]) {\n    if (entry.kind === \"component\") byId.set(entry.componentId, entry);\n  }\n  const rows = components.flatMap(component => {\n    const entry = byId.get(component.id);\n    return entry === undefined ? [] : [entry];\n  });\n  return filterEntries(rows, query);\n}\n\n/** Move focus to the row before or after `from`, or back to the search. */\nfunction moveFocus(\n  list: HTMLElement | null,\n  search: HTMLElement | null,\n  from: HTMLElement | null,\n  step: 1 | -1\n): void {\n  const rows = Array.from(\n    list?.querySelectorAll<HTMLElement>(\"[data-component-row-place]\") ?? []\n  );\n  const at = from === null ? -1 : rows.indexOf(from);\n  const next = at + step;\n  if (next < 0) {\n    search?.focus();\n    return;\n  }\n  rows[Math.min(next, rows.length - 1)]?.focus();\n}\n\nexport function ComponentsPanel({\n  editor,\n  components,\n  componentDefinitions,\n  loading = false,\n  library,\n  withheld = 0,\n  nesting,\n  inside,\n  after,\n  at,\n  beginInsertDrag,\n  onInsert,\n  onEditComponent,\n  mayCreate = false,\n}: ComponentsPanelProps): React.JSX.Element {\n  const [query, setQuery] = React.useState(\"\");\n  const { catalog, rest, announcement, offers, blockSource, insert } =\n    useInsertOffers({\n      editor,\n      definitions: NO_BLOCKS,\n      components,\n      componentDefinitions,\n      nesting,\n      inside,\n      after,\n      at,\n      onInsert,\n    });\n  const unplaceable = React.useMemo(\n    () => unplaceableComponentEntries(components, catalog),\n    [components, catalog]\n  );\n  const listed = componentRows(components, catalog, unplaceable, \"\");\n  const entries = componentRows(components, catalog, unplaceable, query);\n  const searchRef = React.useRef<HTMLInputElement | null>(null);\n  const listRef = React.useRef<HTMLUListElement | null>(null);\n\n  // The heading, the placement line and the notes are drawn with Add's own\n  // classes, so the two panels on one rail read as one design.\n  const header = (\n    <h2 className=\"nx-insert-panel__title\">{EDITOR_WORDS.components}</h2>\n  );\n  const firstPlace = rest;\n  if (firstPlace === undefined) {\n    // Only an `inside` can leave no place, as in Add.\n    return (\n      <div className=\"nx-components-panel\" data-empty=\"unplaceable\">\n        {header}\n        <p className=\"nx-insert-panel__note\">\n          The container chosen to add into is no longer on the page. Select a\n          block to add after it, or clear the selection to add at the end of the\n          page.\n        </p>\n      </div>\n    );\n  }\n\n  const place = (entry: ComponentInsertEntry) => insert(offers.get(entry.id));\n  const drag = (\n    event: React.PointerEvent<HTMLElement>,\n    entry: ComponentInsertEntry\n  ) =>\n    beginEntryDrag(event, entry, {\n      begin: beginInsertDrag,\n      definitions: blockSource,\n      nesting,\n      onInserted: onInsert,\n    });\n  const move = (from: HTMLElement | null, step: 1 | -1) =>\n    moveFocus(listRef.current, searchRef.current, from, step);\n\n  return (\n    <div className=\"nx-components-panel\" aria-busy={loading || undefined}>\n      {header}\n      <InsertAnnouncement text={announcement} />\n      <ComponentSearch\n        query={query}\n        onQuery={setQuery}\n        inputRef={searchRef}\n        onFirst={() => move(null, 1)}\n        onPlaceFirst={() => {\n          const first = entries[0];\n          if (first !== undefined) place(first);\n        }}\n      />\n      <p className=\"nx-insert-panel__placement\" aria-live=\"polite\">\n        <CornerDownRight aria-hidden=\"true\" size={14} />\n        <span>{placementWords(\"Adding\", editor.document, firstPlace)}</span>\n      </p>\n      <LibraryNotices library={library} tier=\"components\" />\n      <PanelBody\n        loading={loading}\n        anyListed={listed.length > 0}\n        unavailable={library?.components === \"unavailable\"}\n        query={query}\n        matches={entries.length}\n        empty={<EmptyComponents withheld={withheld} mayCreate={mayCreate} />}\n      >\n        <ul\n          ref={listRef}\n          className=\"nx-components-panel__list\"\n          aria-label={EDITOR_WORDS.components}\n        >\n          {entries.map((entry, index) => (\n            <ComponentRow\n              key={entry.id}\n              entry={entry}\n              offer={offers.get(entry.id)}\n              document={editor.document}\n              firstMatch={query.trim() !== \"\" && index === 0}\n              onPlace={() => place(entry)}\n              onDrag={event => drag(event, entry)}\n              onMove={move}\n              {...(onEditComponent === undefined\n                ? {}\n                : { onEdit: () => onEditComponent(entry.componentId) })}\n            />\n          ))}\n        </ul>\n      </PanelBody>\n    </div>\n  );\n}\n\n/**\n * The search: ArrowDown moves into the rows, and Enter with a query places\n * the first match, as Enter takes the first tile in Add.\n */\nfunction ComponentSearch({\n  query,\n  onQuery,\n  inputRef,\n  onFirst,\n  onPlaceFirst,\n}: {\n  query: string;\n  onQuery: (query: string) => void;\n  inputRef: React.Ref<HTMLInputElement>;\n  onFirst: () => void;\n  onPlaceFirst: () => void;\n}): React.JSX.Element {\n  const words = `Search ${EDITOR_WORDS.components.toLowerCase()}`;\n  return (\n    <div className=\"nx-components-panel__search\">\n      <Input\n        ref={inputRef}\n        type=\"search\"\n        value={query}\n        onChange={event => onQuery(event.target.value)}\n        onKeyDown={event => {\n          if (event.key === \"ArrowDown\") {\n            event.preventDefault();\n            onFirst();\n          } else if (event.key === \"Enter\" && query.trim() !== \"\") {\n            event.preventDefault();\n            onPlaceFirst();\n          }\n        }}\n        placeholder={words}\n        aria-label={words}\n      />\n    </div>\n  );\n}\n\n/**\n * What stands under the placement line: placeholders while the read is on\n * its way, the empty panel, a search that matched nothing, or the rows.\n *\n * A read that failed says so in its notice above and nothing here, since\n * \"none yet\" beside \"could not be loaded\" would be false.\n */\nfunction PanelBody({\n  loading,\n  anyListed,\n  unavailable,\n  query,\n  matches,\n  empty,\n  children,\n}: {\n  loading: boolean;\n  anyListed: boolean;\n  unavailable: boolean;\n  query: string;\n  /** How many rows the search leaves. */\n  matches: number;\n  empty: React.ReactNode;\n  children: React.ReactNode;\n}): React.JSX.Element | null {\n  if (loading && !anyListed) {\n    return (\n      <div className=\"nx-components-panel__body\">\n        <p role=\"status\" className=\"nx-sr-only\">\n          Loading {EDITOR_WORDS.components.toLowerCase()}…\n        </p>\n        <ul aria-hidden=\"true\" className=\"nx-components-panel__list\">\n          {Array.from({ length: PLACEHOLDER_ROWS }, (_, index) => (\n            <li key={index} className=\"nx-components-panel__placeholder\" />\n          ))}\n        </ul>\n      </div>\n    );\n  }\n  if (!anyListed) return unavailable ? null : <>{empty}</>;\n  if (matches === 0) {\n    return (\n      <p className=\"nx-insert-panel__note\">\n        No {EDITOR_WORDS.components.toLowerCase()} match “{query.trim()}”.\n      </p>\n    );\n  }\n  return <>{children}</>;\n}\n\n/**\n * One component: the button that places it, by click, Enter or a drag, and\n * Edit at the row's end when the host offers it.\n *\n * The button is NAMED by the component and DESCRIBED by where it goes (when\n * past the placement line, or why it cannot go here) and then its sentence,\n * as Add's tiles are, so a screen reader hears the name alone first.\n */\nfunction ComponentRow({\n  entry,\n  offer,\n  document,\n  firstMatch,\n  onPlace,\n  onDrag,\n  onMove,\n  onEdit,\n}: {\n  entry: ComponentInsertEntry;\n  offer: EntryOffer | undefined;\n  document: EditorState[\"document\"];\n  /** Whether Enter in the search places this row. */\n  firstMatch: boolean;\n  onPlace: () => void;\n  onDrag: (event: React.PointerEvent<HTMLElement>) => void;\n  onMove: (from: HTMLElement, step: 1 | -1) => void;\n  onEdit?: () => void;\n}): React.JSX.Element {\n  const id = React.useId();\n  // Every entry the catalogue holds has an offer; one without is a component\n  // with nothing to place.\n  const placeable = offer !== undefined;\n  const aside = placeable ? tileAside(offer, document) : NOTHING_TO_PLACE;\n  const described = [\n    aside === undefined ? undefined : `${id}-where`,\n    entry.description === \"\" ? undefined : `${id}-what`,\n  ]\n    .filter(part => part !== undefined)\n    .join(\" \");\n  return (\n    <li\n      className=\"nx-components-panel__row\"\n      data-refused={\n        placeable && offer.refusal === undefined ? undefined : \"true\"\n      }\n      data-first-match={firstMatch ? \"true\" : undefined}\n    >\n      <button\n        type=\"button\"\n        className=\"nx-components-panel__place\"\n        data-component-row-place=\"\"\n        aria-describedby={described === \"\" ? undefined : described}\n        onClick={onPlace}\n        onKeyDown={event => {\n          if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\") return;\n          event.preventDefault();\n          onMove(event.currentTarget, event.key === \"ArrowDown\" ? 1 : -1);\n        }}\n        onPointerDown={onDrag}\n      >\n        <BlockIconMark icon={entry.icon} size={16} />\n        <span className=\"nx-components-panel__text\">\n          <span className=\"nx-components-panel__name\">{entry.label}</span>\n          {/* Named by the name it draws, not a label over the row, which\n              would have to hold these words too; they describe it instead,\n              so they are hidden from its name. */}\n          {aside === undefined ? null : (\n            <span\n              id={`${id}-where`}\n              className=\"nx-components-panel__aside\"\n              aria-hidden=\"true\"\n            >\n              {aside}\n            </span>\n          )}\n          {entry.description === \"\" ? null : (\n            <span\n              id={`${id}-what`}\n              className=\"nx-components-panel__description\"\n              aria-hidden=\"true\"\n            >\n              {entry.description}\n            </span>\n          )}\n        </span>\n      </button>\n      {onEdit === undefined ? null : (\n        <button\n          type=\"button\"\n          className=\"nx-components-panel__edit\"\n          aria-label={`Edit ${entry.label}`}\n          title=\"Edit component\"\n          onClick={onEdit}\n        >\n          <PencilLine aria-hidden=\"true\" size={14} />\n        </button>\n      )}\n    </li>\n  );\n}\n\n/**\n * The panel with nothing to offer: that the site has no components, or that\n * none of them can go in the component being edited, and how to make one.\n */\nfunction EmptyComponents({\n  withheld,\n  mayCreate,\n}: {\n  withheld: number;\n  mayCreate: boolean;\n}): React.JSX.Element {\n  if (withheld > 0) {\n    return (\n      <p className=\"nx-insert-panel__note\">\n        No other component can be placed inside this one.\n      </p>\n    );\n  }\n  return (\n    <div className=\"nx-insert-panel__note\" data-empty=\"none\">\n      <p>This site has no components yet.</p>\n      <p>\n        A component is a group of blocks made once and placed on many pages. A\n        change to it reaches every page that places it.\n      </p>\n      {mayCreate ? (\n        <p>\n          {/* The menu item's own name, so the author can find it. */}\n          To make one, select blocks on the page and choose Turn into component\n          in the block’s menu.\n        </p>\n      ) : null}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The parts every small picture of a document shares: when it is first seen,\n * the scale that fits its composed width into its box, and the inert surface\n * the document is drawn on at that width.\n *\n * Shared by the entry page's miniature and the editor's pictures (a saved\n * section, a header & footer set), so \"draw this document small\" has one\n * answer. Each surface still decides its own box: the entry page shows the\n * page as tall as it is, a picture fits a fixed frame.\n *\n * ## `transform`, never `zoom`\n *\n * The canvas uses `zoom`, because hit-testing and drag geometry are measured in\n * the scaled box's own coordinates. Nothing in a picture is interactive, so\n * that buys nothing here and costs a reflow of the whole drawn tree on every\n * resize. `transform` alone leaves the element in the layout flow, though, so\n * the scaled element is absolutely positioned: only then is the frame's width\n * the box's width rather than the composed one.\n *\n * ## An unmeasurable box draws UNSCALED\n *\n * A box reports zero width before layout, and in any environment that does\n * not lay out. Scaling by zero would draw nothing, a blank frame that looks\n * like an empty document. Drawn unscaled it is wrong only in how much shows,\n * and visibly so.\n *\n * @module miniature-surface\n */\nimport {\n  createStandaloneContext,\n  previewContainerStyle,\n  type PageContext,\n} from \"@nextlyhq/blocks-react\";\nimport {\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useState,\n  type JSX,\n  type ReactNode,\n  type RefObject,\n} from \"react\";\n\n/**\n * The width a document is composed at before it is scaled down: the desktop\n * preview's. Composed narrower, a page draws its MOBILE layout, a true picture\n * of a viewport the author was not looking at.\n */\nexport const MINIATURE_RENDER_WIDTH = 1280;\n\n/**\n * Margin around the viewport that counts as seen, so a picture starts drawing\n * just before it scrolls on screen rather than after.\n */\nconst AHEAD = \"200px\";\n\n/**\n * Whether an element has come into view yet. Drawn the first time it is seen,\n * and kept drawn. Where there is no observer to ask (an older engine, a test\n * without layout) the answer is \"seen\", so a picture is never left blank.\n *\n * @param target - the element whose view is asked about\n * @param already - seen before, so drawn at once without waiting to be seen\n */\nexport function useFirstSeen(\n  target: RefObject<Element | null>,\n  already = false\n): boolean {\n  const [seen, setSeen] = useState(\n    () => already || typeof IntersectionObserver === \"undefined\"\n  );\n\n  useEffect(() => {\n    const element = target.current;\n    if (seen || already || element === null) return;\n    const observer = new IntersectionObserver(\n      entries => {\n        if (!entries.some(entry => entry.isIntersecting)) return;\n        setSeen(true);\n        observer.disconnect();\n      },\n      { rootMargin: AHEAD }\n    );\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, [seen, already, target]);\n\n  return seen || already;\n}\n\n/**\n * The scale that fits the composed width into the box, kept current as the\n * box resizes. Zero width means \"not laid out\", never \"zero wide\", so it\n * scales by one there (see the module's documentation). Not `active`, it\n * measures nothing and watches nothing: a box with no drawing has nothing to\n * scale.\n */\nexport function useWidthScale(\n  frame: RefObject<HTMLElement | null>,\n  renderWidth: number,\n  active = true\n): number {\n  const [scale, setScale] = useState(1);\n  useLayoutEffect(() => {\n    const element = frame.current;\n    if (!active || !element) return;\n    const measure = (): void => {\n      const width = element.clientWidth;\n      setScale(width > 0 ? width / renderWidth : 1);\n    };\n    measure();\n    // Guarded: a host without the observer must still draw the document.\n    if (typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(measure);\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, [frame, renderWidth, active]);\n  return scale;\n}\n\n/** What {@link MiniatureSurface} draws a document at, and on. */\nexport interface MiniatureSurfaceProps {\n  /** The scaled element, for a surface that measures what it drew. */\n  scaledRef?: RefObject<HTMLDivElement | null>;\n  /** The width the document is composed at. */\n  renderWidth: number;\n  scale: number;\n  /** The container the sheet's responsive rules resolve against, if any. */\n  previewContainer: string | undefined;\n  /** Moves the drawn document down inside the box, in on-screen pixels. */\n  offsetTop?: number;\n  /** The `data-slot` prefix the two elements are named with. */\n  slot?: string;\n  children: ReactNode;\n}\n\n/**\n * The document at its composed width, scaled into the box, and inert.\n *\n * Everything inside is `inert` and `aria-hidden`: a page is full of links,\n * buttons and headings, and left reachable a picture would put a second\n * document into the tab order of whatever holds it.\n *\n * A submit raised anywhere in the document is refused on the way down. A page\n * holding a form block draws a form, and a picture inside the entry screen's\n * own form would nest one: the drawn form's submit must not reach the outer\n * one. Matched by the event rather than by a block's name, so a host's own\n * form-rooted block is refused by the same line.\n */\nexport function MiniatureSurface({\n  scaledRef,\n  renderWidth,\n  scale,\n  previewContainer,\n  offsetTop = 0,\n  slot = \"miniature\",\n  children,\n}: MiniatureSurfaceProps): JSX.Element {\n  return (\n    <div\n      ref={scaledRef}\n      data-slot={`${slot}-scaled`}\n      style={{\n        // Absolute: see the module's documentation.\n        position: \"absolute\",\n        left: 0,\n        top: offsetTop,\n        width: `${renderWidth}px`,\n        transform: `scale(${scale})`,\n        transformOrigin: \"top left\",\n        // The container the compiled responsive rules resolve against, on the\n        // element whose width they answer for: the COMPOSED width.\n        ...previewContainerStyle(previewContainer),\n      }}\n    >\n      <div\n        data-slot={`${slot}-surface`}\n        inert\n        aria-hidden=\"true\"\n        onSubmitCapture={event => event.preventDefault()}\n      >\n        {children}\n      </div>\n    </div>\n  );\n}\n\n/**\n * What the pictures of one editing session share: one page context, so what\n * an async block drew (an image, a button) is kept between pictures and\n * between openings of a panel instead of blinking out, and which documents\n * have been seen, so a picture shown before is drawn at once when its row\n * comes back.\n *\n * Seen is kept by the document's identity: a document read again unchanged is\n * the same object, and a changed or newly published one is a new object that\n * is drawn anew.\n */\nexport interface MiniatureSession {\n  readonly context: PageContext;\n  readonly seen: WeakSet<object>;\n}\n\n/**\n * A session of its own, for a host that keeps one for as long as it edits,\n * drawing with `context`: the host's read-only resolvers (its media, its\n * icons), so an image chosen from the host's library is drawn in the picture\n * as on the canvas. Without one, nothing is resolved.\n */\nexport function createMiniatureSession(\n  context: PageContext = createStandaloneContext()\n): MiniatureSession {\n  return { context, seen: new WeakSet() };\n}\n\n/**\n * One session for as long as the calling component is mounted and `context`\n * is the same object: a new context is a new session.\n */\nexport function useMiniatureSession(context?: PageContext): MiniatureSession {\n  return useMemo(() => createMiniatureSession(context), [context]);\n}\n","\"use client\";\n\n/**\n * A small picture of a document, wherever an author chooses one: a saved\n * section in the Add panel, a header & footer set in a menu.\n *\n * Drawn by the same `PageRenderer` as the canvas, at the desktop preview's\n * width, scaled to the picture's box and inert. A picture with its own drawing\n * path would be a second answer to \"what does this look like\", and the two\n * drift where nobody looks.\n *\n * **Generic.** It draws the documents it is handed, top to bottom with a thin\n * gap between them (a set's header above its footer), and knows nothing of\n * sets, sections or templates: the host decides what to draw and with what.\n *\n * **It never holds anything up.** Nothing is drawn until the picture's box is\n * on screen, so a panel or a menu opens at once and a long list draws only\n * the rows scrolled to. A document already seen in the host's session is\n * drawn straight away when its row comes back.\n *\n * **A plain icon in place of a broken picture.** With nothing to draw (an\n * empty set, \"None\") it shows the empty-frame icon. When the host says the\n * document can't be drawn, or when the renderer had to leave a placeholder\n * for any block in it (a type no block is registered for, a component that\n * could not be loaded, a block that threw: the renderer contains each of\n * those itself), it shows the item's own type icon.\n *\n * **Light or dark, as the canvas is previewed.** The mode is stated on the\n * drawn surface as the site's own theme marker, so a site's dark tokens apply\n * exactly as they do on the canvas, and the drawing is not redone for a switch.\n *\n * The picture is `aria-hidden`: it is the row's picture, and the row's own\n * name is what a screen reader reads.\n *\n * @module document-miniature\n */\nimport {\n  DARK_MODE_ATTRIBUTE,\n  type BlockDocument,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport { PageRenderer, type PageRendererProps } from \"@nextlyhq/blocks-react\";\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../block-icon\";\nimport { siteSurface } from \"../canvas/canvas-site-surface\";\n\nimport {\n  MINIATURE_RENDER_WIDTH,\n  MiniatureSurface,\n  useFirstSeen,\n  useWidthScale,\n  type MiniatureSession,\n} from \"./miniature-surface\";\n\n/**\n * What a picture is drawn with: the renderer's inputs for this site, except\n * the document, its context and the editor-only switches, which the picture\n * decides itself.\n */\nexport type MiniatureRender = Omit<\n  PageRendererProps,\n  \"document\" | \"context\" | \"nodeAttribute\" | \"keepAsyncOutputs\" | \"prepared\"\n>;\n\nexport interface DocumentMiniatureProps {\n  /**\n   * What to draw, top to bottom: one document, or a set's header above its\n   * footer. None draws the empty-frame icon.\n   */\n  documents: readonly BlockDocument[];\n  /** This site's rendering: its sheet, its blocks, its breakpoints. */\n  render: MiniatureRender;\n  /**\n   * The mode the canvas is previewed in, when one is picked. Absent, the\n   * document's own, as on the canvas.\n   */\n  mode?: TokenMode;\n  /** The item's type icon, shown in place of a picture that can't be drawn. */\n  icon?: string;\n  /** The host already knows the documents can't be drawn. */\n  failed?: boolean;\n  /** What the host's pictures share for as long as it edits. */\n  session: MiniatureSession;\n  /** The width to compose at before scaling. The desktop preview's by default. */\n  renderWidth?: number;\n}\n\n/** The gap between two documents drawn one above the other, in composed px. */\nconst STACK_GAP = 16;\n\n/** An empty frame: a dashed box, for nothing to draw. */\nfunction EmptyFrameIcon(): React.JSX.Element {\n  return (\n    <svg\n      className=\"nx-picture__empty\"\n      width=\"24\"\n      height=\"16\"\n      viewBox=\"0 0 24 16\"\n      fill=\"none\"\n      aria-hidden=\"true\"\n    >\n      <rect\n        x=\"1\"\n        y=\"1\"\n        width=\"22\"\n        height=\"14\"\n        rx=\"2\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeDasharray=\"3 2\"\n      />\n    </svg>\n  );\n}\n\n/**\n * The marker the renderer leaves where a block could not be drawn: a type no\n * block is registered for, a component that could not be loaded, a block that\n * threw. A picture with one in it is a broken picture.\n */\nconst PLACEHOLDER_SELECTOR = \"[data-nx-block-placeholder]\";\n\n/**\n * The height the documents were drawn at, in composed px, kept current as\n * what they draw settles (an image arriving moves everything below it), and\n * whether any block in them could not be drawn, asked at the same moments.\n */\nfunction useDrawnLayout(\n  scaled: React.RefObject<HTMLDivElement | null>,\n  drawn: boolean,\n  onBroken: () => void\n): number {\n  const [height, setHeight] = React.useState(0);\n  React.useLayoutEffect(() => {\n    const element = scaled.current;\n    if (!drawn || !element) return;\n    const measure = (): void => {\n      if (element.querySelector(PLACEHOLDER_SELECTOR) !== null) onBroken();\n      setHeight(element.offsetHeight);\n    };\n    measure();\n    // A block that gives up after the drawing (an async block that rejects)\n    // leaves a hidden placeholder that need not change the drawing's size,\n    // so the drawing's content is watched as well as its size.\n    const view = element.ownerDocument.defaultView;\n    const changes =\n      view?.MutationObserver === undefined\n        ? null\n        : new view.MutationObserver(measure);\n    changes?.observe(element, { childList: true, subtree: true });\n    const sizes =\n      typeof ResizeObserver === \"undefined\"\n        ? null\n        : new ResizeObserver(measure);\n    sizes?.observe(element);\n    return () => {\n      changes?.disconnect();\n      sizes?.disconnect();\n    };\n  }, [scaled, drawn, onBroken]);\n  return height;\n}\n\n/** What the picture shows: nothing to draw, the icon, or the documents. */\ntype PictureState = \"empty\" | \"failed\" | \"drawn\";\n\nfunction stateOf(\n  documents: readonly BlockDocument[],\n  failed: boolean\n): PictureState {\n  // A document with no blocks draws nothing either: the empty frame says so.\n  if (documents.every(document => document.nodes.length === 0)) return \"empty\";\n  return failed ? \"failed\" : \"drawn\";\n}\n\n/**\n * The documents as first handed in, for as long as the host hands the same\n * ones: a host building `[document]` inline hands a new list on every render\n * of its own (each keystroke in a panel's search), and the drawing below is\n * memoised on the list.\n */\nfunction useSameDocuments(\n  documents: readonly BlockDocument[]\n): readonly BlockDocument[] {\n  const [held, setHeld] = React.useState(documents);\n  if (held === documents) return held;\n  const same =\n    held.length === documents.length &&\n    held.every((document, index) => document === documents[index]);\n  if (same) return held;\n  // Derived state, set while rendering as React allows for it: the next\n  // render holds the new list.\n  setHeld(documents);\n  return documents;\n}\n\n/**\n * The device's colour scheme, for the ground of a picture with no previewed\n * mode: the canvas's frame follows the device then, and so does the site's\n * dark sheet, so a picture grounded in the admin's own scheme would put a\n * light page on a dark ground. Undefined until read after mount (a server\n * render has no device), or while a mode is previewed, when nothing listens.\n */\nfunction useDeviceScheme(listen: boolean): TokenMode | undefined {\n  const [scheme, setScheme] = React.useState<TokenMode | undefined>(undefined);\n  React.useEffect(() => {\n    // Asked by callability: jsdom has the property without the function.\n    if (!listen || typeof globalThis.matchMedia !== \"function\") return;\n    const query = globalThis.matchMedia(\"(prefers-color-scheme: dark)\");\n    const read = (): void => setScheme(query.matches ? \"dark\" : \"light\");\n    read();\n    query.addEventListener(\"change\", read);\n    return () => query.removeEventListener(\"change\", read);\n  }, [listen]);\n  return listen ? scheme : undefined;\n}\n\n/** The documents, one above the other, held apart from the scale. */\nfunction useDrawnDocuments(\n  documents: readonly BlockDocument[],\n  render: MiniatureRender,\n  session: MiniatureSession\n): React.ReactNode {\n  /*\n   * Each drawn document compiles its stylesheet under a scope of its own:\n   * block ids are unique within a document, not across them (an imported\n   * section keeps its ids), and unscoped rules from one picture would match\n   * every other picture's blocks in the same panel.\n   */\n  const scopeBase = `nx-picture-scope-${React.useId().replace(/[^\\w-]/g, \"\")}`;\n  /*\n   * Held apart from the measured scale and the mode, which change without the\n   * documents changing: rebuilt inline, every resize would rerun the whole\n   * render beneath it.\n   */\n  return React.useMemo(\n    () =>\n      documents.map((document, index) => (\n        <div\n          // Position is identity here: the list is the host's fixed order\n          // (a header, then a footer) and never reorders.\n          key={index}\n          style={index === 0 ? undefined : { marginTop: STACK_GAP }}\n          className=\"nx-picture__document\"\n        >\n          <PageRenderer\n            {...render}\n            // Without a style context the renderer compiles no page sheet,\n            // so there is nothing to scope.\n            styleContext={\n              render.styleContext === undefined\n                ? undefined\n                : {\n                    ...render.styleContext,\n                    scope: `${scopeBase}-${String(index)}`,\n                  }\n            }\n            document={document}\n            context={session.context}\n            // What async blocks drew is kept between pictures and openings,\n            // as on the canvas, so an image does not blink.\n            keepAsyncOutputs\n          />\n        </div>\n      )),\n    [documents, render, session, scopeBase]\n  );\n}\n\n/**\n * Whether the drawing of `documents` with `render` found a placeholder, and\n * how the drawing says it did. Held for the inputs it was drawn with: new\n * documents or a new rendering (a component's definition read after the\n * panel opened) are drawn again rather than kept as the icon.\n */\nfunction useBrokenDrawing(\n  documents: readonly BlockDocument[],\n  render: MiniatureRender\n): { readonly broken: boolean; readonly broke: () => void } {\n  const [brokenFor, setBrokenFor] = React.useState<{\n    documents: readonly BlockDocument[];\n    render: MiniatureRender;\n  } | null>(null);\n  const broke = React.useCallback(\n    () => setBrokenFor({ documents, render }),\n    [documents, render]\n  );\n  const broken =\n    brokenFor !== null &&\n    brokenFor.documents === documents &&\n    brokenFor.render === render;\n  return { broken, broke };\n}\n\n/**\n * Whether the picture has come on screen, or `first`, its first document,\n * was already seen in the editor's session, which is then told it was.\n */\nfunction useSeenInSession(\n  frame: React.RefObject<HTMLSpanElement | null>,\n  first: BlockDocument | undefined,\n  session: MiniatureSession\n): boolean {\n  const seen = useFirstSeen(\n    frame,\n    first !== undefined && session.seen.has(first)\n  );\n  React.useEffect(() => {\n    if (seen && first !== undefined) session.seen.add(first);\n  }, [seen, first, session]);\n  return seen;\n}\n\n/**\n * Keeps a block that throws while React renders what it returned inside its\n * own picture: the renderer's boundary catches a block's render call, not a\n * component it returns, and an unrelated saved section must never take the\n * editor down. The picture shows its icon instead.\n */\nclass PictureBoundary extends React.Component<\n  { readonly onError: () => void; readonly children: React.ReactNode },\n  { readonly failed: boolean }\n> {\n  override state = { failed: false };\n\n  static getDerivedStateFromError(): { failed: boolean } {\n    return { failed: true };\n  }\n\n  override componentDidCatch(): void {\n    this.props.onError();\n  }\n\n  override render(): React.ReactNode {\n    return this.state.failed ? null : this.props.children;\n  }\n}\n\n/**\n * The drawing itself, mounted only once the picture has come on screen and\n * has documents to draw: measured, scaled and composed here, so a tile not\n * yet drawn costs no observer and no render beneath it.\n */\nfunction DrawnPicture({\n  frame,\n  documents,\n  render,\n  mode,\n  session,\n  renderWidth,\n  onBroken,\n}: {\n  frame: React.RefObject<HTMLSpanElement | null>;\n  documents: readonly BlockDocument[];\n  render: MiniatureRender;\n  mode: DocumentMiniatureProps[\"mode\"];\n  session: MiniatureSession;\n  renderWidth: number;\n  onBroken: () => void;\n}): React.JSX.Element {\n  const scaled = React.useRef<HTMLDivElement>(null);\n  const scale = useWidthScale(frame, renderWidth, true);\n  const composed = useDrawnLayout(scaled, true, onBroken);\n  const pages = useDrawnDocuments(documents, render, session);\n  // The site's body font and ink, named as the canvas root names them.\n  const surface =\n    typeof render.siteStyles === \"object\"\n      ? siteSurface(render, render.siteStyles)?.style\n      : undefined;\n  const boxHeight = frame.current?.clientHeight ?? 0;\n  // A document shorter than the box sits in its middle; a taller one is\n  // shown from its top.\n  const offsetTop = Math.max(0, (boxHeight - composed * scale) / 2);\n  return (\n    <MiniatureSurface\n      scaledRef={scaled}\n      renderWidth={renderWidth}\n      scale={scale}\n      previewContainer={render.styleContext?.previewContainer}\n      offsetTop={offsetTop}\n      slot=\"picture\"\n    >\n      <div\n        className=\"nx-picture__page\"\n        style={surface}\n        {...(mode === undefined ? {} : { [DARK_MODE_ATTRIBUTE]: mode })}\n      >\n        <PictureBoundary onError={onBroken}>{pages}</PictureBoundary>\n      </div>\n    </MiniatureSurface>\n  );\n}\n\nexport function DocumentMiniature({\n  documents,\n  render,\n  mode,\n  icon,\n  failed = false,\n  session,\n  renderWidth = MINIATURE_RENDER_WIDTH,\n}: DocumentMiniatureProps): React.JSX.Element {\n  const frame = React.useRef<HTMLSpanElement>(null);\n  /*\n   * The box as state as well as a ref: a picture drawn at once (seen before\n   * in the session) mounts its drawing in the same render as the box, and a\n   * child's layout effect runs before the parent's ref is set, so the drawing\n   * measures the box only once this says it exists.\n   */\n  const [box, setBox] = React.useState<HTMLSpanElement | null>(null);\n  const boxRef = React.useMemo(() => ({ current: box }), [box]);\n  const attach = React.useCallback((node: HTMLSpanElement | null) => {\n    frame.current = node;\n    setBox(node);\n  }, []);\n  const drawnDocuments = useSameDocuments(documents);\n  const { broken, broke } = useBrokenDrawing(drawnDocuments, render);\n  const state = stateOf(drawnDocuments, failed || broken);\n  const seen = useSeenInSession(frame, drawnDocuments[0], session);\n  const drawn = seen && state === \"drawn\";\n  const device = useDeviceScheme(mode === undefined);\n  const scheme = mode ?? device;\n\n  return (\n    <span\n      ref={attach}\n      className=\"nx-picture\"\n      data-state={state}\n      data-drawn={drawn ? \"true\" : undefined}\n      // The previewed scheme for the whole box, else the device's, so the\n      // ground around a short document is the page's own and not the admin's.\n      style={scheme === undefined ? undefined : { colorScheme: scheme }}\n      aria-hidden=\"true\"\n    >\n      {state === \"empty\" ? <EmptyFrameIcon /> : null}\n      {state === \"failed\" ? <BlockIconMark icon={icon} size={20} /> : null}\n      {drawn && box !== null ? (\n        <DrawnPicture\n          frame={boxRef}\n          documents={drawnDocuments}\n          render={render}\n          mode={mode}\n          session={session}\n          renderWidth={renderWidth}\n          onBroken={broke}\n        />\n      ) : null}\n    </span>\n  );\n}\n","\"use client\";\n\nimport { Button, Input, Label } from \"@nextlyhq/ui\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport { Plus, Trash2, TriangleAlert } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport {\n  BASE_BREAKPOINT,\n  BREAKPOINT_AXES,\n  storedLimitFor,\n  validateBreakpoints,\n  type BreakpointAxis,\n  type BreakpointDef,\n  type BreakpointIssue,\n  type BreakpointSet,\n} from \"../styles/breakpoints\";\n\n/** What the container axis is called, where a site uses it. */\nconst CONTAINER_TITLE = \"Container widths\";\n\n/** A new breakpoint's id, made from its name: styles are filed under it. */\nfunction idFromName(name: string): string {\n  return name\n    .trim()\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n}\n\n/** An id not already taken, numbered after the first that is. */\nfunction uniqueId(base: string, taken: ReadonlySet<string>): string {\n  if (!taken.has(base)) return base;\n  let n = 2;\n  while (taken.has(`${base}-${n}`)) n += 1;\n  return `${base}-${n}`;\n}\n\n/**\n * Where a breakpoint applies, in the device buttons' words: from just above\n * the next narrower breakpoint up to its own width.\n */\nfunction rangeOf(rows: readonly DraftRow[], row: DraftRow): string {\n  const width = Number(row.width);\n  if (row.width.trim() === \"\" || !Number.isFinite(width) || width <= 0) {\n    return \"\";\n  }\n  const narrower = rows\n    .map(other => Number(other.width))\n    .filter(other => Number.isFinite(other) && other > 0 && other < width);\n  if (narrower.length === 0) return `up to ${width}px`;\n  const below = Math.max(...narrower);\n  // A whole pixel more is where the range starts only between whole widths:\n  // a fractional width hands over just above itself, so \"481.5\" after 480.5\n  // would leave out a real stretch the wider breakpoint already covers.\n  return Number.isInteger(below) && Number.isInteger(width)\n    ? `${below + 1}–${width}px`\n    : `above ${below}px, up to ${width}px`;\n}\n\n/**\n * Props for BreakpointEditor.\n * @experimental\n */\nexport interface BreakpointEditorProps {\n  /** The site's saved breakpoints. Treated as the starting point, never mutated. */\n  value: BreakpointSet;\n  /**\n   * Leave editing: after a save that succeeded, or on Cancel. Never while a\n   * save is in flight, so a draft cannot be dropped with its write unanswered.\n   */\n  onClose: () => void;\n  /**\n   * Told when a save starts and settles, so a host that could take the editor\n   * away (closing a dialog, switching a tab) holds off until the write answers.\n   */\n  onSavingChange?: (saving: boolean) => void;\n  /**\n   * Called with the edited set when the author saves.\n   *\n   * Only ever called with a set that produces no issues, so a host does not\n   * have to re-validate before storing it.\n   *\n   * **A promise is awaited, and the editor stays open until it settles.** A host\n   * that persists over the network resolves with a message when the write was\n   * refused, and the draft is still on screen to retry or copy from. Closing on\n   * the click instead — which this did — threw away a set the author had just\n   * built by hand the moment a save failed, with nothing left to recover it\n   * from: the editor was gone, the draft with it, and the site's breakpoints\n   * unchanged.\n   *\n   * Resolving with `undefined`, or returning nothing at all, means saved. A\n   * synchronous host needs no change.\n   *\n   * Resolving with `null` means nothing was saved and there is nothing to\n   * say: the author went back from a step the host showed before saving (a\n   * confirmation, say), so the draft stays open as it was, with no refusal.\n   */\n  onSave: (next: BreakpointSet) => void | Promise<string | null | undefined>;\n  /**\n   * Why the set cannot be saved right now, when the host learns one while the\n   * editor is open (a removal started elsewhere, say): Save is disabled and\n   * the reason shown, and the draft stays on screen to save once it clears.\n   */\n  blocked?: string;\n}\n\n/**\n * Whether a value can be awaited, without asking which realm made it.\n *\n * `instanceof Promise` is a check about one global constructor, and the values\n * this has to recognise may not come from it.\n */\nfunction isThenable(\n  value: unknown\n): value is PromiseLike<string | null | undefined> {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    typeof (value as { then?: unknown }).then === \"function\"\n  );\n}\n\n/** A draft row. Width is held as TEXT while editing. */\ninterface DraftRow {\n  /**\n   * Stable across edits so React keeps focus while a field is retyped, and\n   * stable across REMOVALS because it is stored with the row rather than\n   * recomputed from its index.\n   */\n  key: string;\n  id: string;\n  label: string;\n  width: string;\n  /**\n   * Whether this row was added in this session.\n   *\n   * A saved breakpoint's id is the key every stored style is filed under, and\n   * `onSave` carries only the breakpoint set — so renaming one here would\n   * detach every style on every page that uses it, with nothing to report it.\n   */\n  isNew: boolean;\n}\n\n/**\n * Seeds the draft with keys derived from the position a row was loaded at.\n *\n * Deterministic rather than drawn from a counter: a module-level counter is\n * shared by every render on a server and starts again at zero in the browser,\n * so the same row would be keyed `row-9` in prerendered markup and `row-0` on\n * hydration — and these keys reach the DOM through the field ids.\n */\nfunction toDraft(axis: BreakpointAxis, defs: BreakpointDef[]): DraftRow[] {\n  return defs.map((def, index) => ({\n    key: `${axis}-${index}`,\n    id: def.id,\n    label: def.label,\n    width: def.maxWidth === undefined ? \"\" : String(def.maxWidth),\n    isNew: false,\n  }));\n}\n\n/**\n * A draft row as a definition.\n *\n * An empty width field means \"no bound\", which the container axis has a use\n * for. A field holding something unparseable becomes `NaN` rather than\n * `undefined`: the two are different mistakes and validation reports them\n * differently, so collapsing them here would tell the author the wrong thing.\n */\nfunction toDef(row: DraftRow): BreakpointDef {\n  const width = row.width.trim();\n  return {\n    // A SAVED id is passed through byte for byte. The engine uses it verbatim\n    // as the key stored styles are filed under, so trimming one that arrived\n    // with surrounding whitespace would re-key it on an unrelated width edit\n    // and detach those styles — the loss the field being read-only exists to\n    // prevent, reintroduced underneath it. A row added here has no styles\n    // behind it yet, so trimming what was just typed is safe and expected.\n    id: row.isNew ? row.id.trim() : row.id,\n    label: row.label.trim(),\n    ...(width === \"\" ? {} : { maxWidth: Number(width) }),\n  };\n}\n\nfunction toSet(draft: Record<BreakpointAxis, DraftRow[]>): BreakpointSet {\n  return {\n    viewport: draft.viewport.map(toDef),\n    container: draft.container.map(toDef),\n  };\n}\n\n/** The issues for one row, keyed by the field they belong to. */\nfunction issuesForRow(\n  issues: BreakpointIssue[],\n  axis: BreakpointAxis,\n  index: number\n): Partial<Record<BreakpointIssue[\"field\"], string>> {\n  const byField: Partial<Record<BreakpointIssue[\"field\"], string>> = {};\n  for (const issue of issues) {\n    if (issue.axis !== axis || issue.index !== index) continue;\n    byField[issue.field] ??= issue.message;\n  }\n  return byField;\n}\n\n/**\n * Edit the breakpoints a site's styles may respond to.\n *\n * Editing is held locally and committed on save, so a half-typed width never\n * reaches the host. Save is refused while any definition would be discarded at\n * compile time — the failure mode this exists to prevent is silent: a\n * breakpoint the compiler cannot use simply stops existing, and the styles\n * saved against it surface as stale much later.\n *\n * @experimental\n *\n * Drawn in place, as the section it edits, rather than in a dialog of its\n * own: it lives in Settings, and a dialog over a dialog splits focus and\n * Escape between two layers. The draft is seeded once, when editing starts.\n *\n * @example\n * ```tsx\n * {editing ? (\n *   <BreakpointEditor\n *     value={site.breakpoints}\n *     onSave={next => saveSettings({ breakpoints: next })}\n *     onClose={() => setEditing(false)}\n *   />\n * ) : null}\n * ```\n */\nexport function BreakpointEditor({\n  value,\n  onSave,\n  onClose,\n  onSavingChange,\n  blocked,\n}: BreakpointEditorProps): React.JSX.Element {\n  const fieldId = React.useId();\n  const [draft, setDraft] = React.useState<Record<BreakpointAxis, DraftRow[]>>(\n    () => ({\n      viewport: toDraft(\"viewport\", value.viewport),\n      container: toDraft(\"container\", value.container),\n    })\n  );\n  // Scoped to this instance, so nothing about a key depends on how many times\n  // the module has been rendered.\n  const addedRows = React.useRef(0);\n  /*\n   * Whether a save is in flight, and why the last one was refused.\n   *\n   * Derived here rather than taken as props. A `saving` prop can disagree with\n   * the promise this component is actually awaiting — a host that forgets to\n   * clear it leaves the editor permanently disabled with no way to close the\n   * loop — and the only thing that knows when THIS save settled is the promise\n   * returned to THIS click.\n   */\n  const [saving, setSavingState] = React.useState(false);\n  const setSaving = (next: boolean): void => {\n    setSavingState(next);\n    onSavingChange?.(next);\n  };\n  const [refusal, setRefusal] = React.useState<string | undefined>(undefined);\n\n  const issues = React.useMemo(\n    () => validateBreakpoints(toSet(draft)),\n    [draft]\n  );\n\n  /*\n   * Every edit is refused while a save is in flight, and the fields say so.\n   *\n   * The request carries the draft as it was at the click. Left editable, a\n   * change made in the window before the promise settles is not in that\n   * request AND is discarded by the close that follows it — the author watches\n   * their own edit vanish into a save that reported success. Freezing the form\n   * is what makes \"the set that was submitted\" and \"the set on screen\" the same\n   * thing at every moment the editor is open.\n   */\n  const updateRow = (\n    axis: BreakpointAxis,\n    key: string,\n    patch: Partial<DraftRow>\n  ): void => {\n    if (saving) return;\n    setDraft(current => ({\n      ...current,\n      [axis]: current[axis].map(row =>\n        row.key === key ? { ...row, ...patch } : row\n      ),\n    }));\n  };\n\n  /**\n   * A new name, and for a row added in this session the id made from it.\n   * Unique across both axes and never the base's, with a fallback for a name\n   * that makes no id (one with no Latin letters or digits), so any name the\n   * engine would accept can be saved without the author ever seeing the id.\n   */\n  const renameRow = (\n    axis: BreakpointAxis,\n    key: string,\n    label: string\n  ): void => {\n    if (saving) return;\n    setDraft(current => {\n      const taken = new Set(\n        BREAKPOINT_AXES.flatMap(other =>\n          current[other].filter(row => row.key !== key).map(row => row.id)\n        )\n      );\n      taken.add(BASE_BREAKPOINT);\n      return {\n        ...current,\n        [axis]: current[axis].map(row =>\n          row.key !== key\n            ? row\n            : {\n                ...row,\n                label,\n                ...(row.isNew\n                  ? { id: uniqueId(idFromName(label) || \"breakpoint\", taken) }\n                  : {}),\n              }\n        ),\n      };\n    });\n  };\n\n  const addRow = (axis: BreakpointAxis): void => {\n    if (saving) return;\n    setDraft(current => ({\n      ...current,\n      [axis]: [\n        ...current[axis],\n        {\n          key: `${axis}-added-${addedRows.current++}`,\n          id: \"\",\n          label: \"\",\n          width: \"\",\n          isNew: true,\n        },\n      ],\n    }));\n  };\n\n  const removeRow = (axis: BreakpointAxis, key: string): void => {\n    if (saving) return;\n    setDraft(current => ({\n      ...current,\n      [axis]: current[axis].filter(row => row.key !== key),\n    }));\n  };\n\n  const save = (): void => {\n    if (issues.length > 0 || saving || blocked !== undefined) return;\n    setRefusal(undefined);\n    const outcome = onSave(toSet(draft));\n    /*\n     * A THENABLE, not an `instanceof Promise`.\n     *\n     * The contract accepts a promise, and `instanceof` answers about one realm:\n     * a promise from another window or iframe, or a conforming implementation\n     * that is not the global constructor, fails the test. The editor would then\n     * close as though the write were synchronous, and a refusal or rejection\n     * arriving afterwards would be neither shown nor handled — the exact loss\n     * the await exists to prevent, restored by the check meant to detect it.\n     *\n     * A synchronous host is still finished here, and awaiting its `undefined`\n     * would cost a microtask — long enough to paint a disabled button with\n     * nothing to wait for.\n     */\n    if (!isThenable(outcome)) {\n      onClose();\n      return;\n    }\n    setSaving(true);\n    void Promise.resolve(outcome)\n      .then(message => {\n        if (message === undefined) {\n          onClose();\n          return;\n        }\n        // Kept: not saved, and nothing to report beside the draft.\n        if (message === null) return;\n        setRefusal(message);\n      })\n      .catch((reason: unknown) => {\n        /*\n         * A rejection is a refusal too, and the editor must not close on one.\n         * A host that throws rather than resolving is not following the\n         * contract, but the author's draft is not the place to make that point.\n         */\n        setRefusal(\n          reason instanceof Error\n            ? reason.message\n            : \"These breakpoints could not be saved.\"\n        );\n      })\n      .finally(() => {\n        setSaving(false);\n      });\n  };\n\n  /*\n   * Leaving is refused while a save is in flight, for the reason the frozen\n   * fields are: taken during a pending write, the editor unmounts with the\n   * draft, a refusal that lands afterwards has nowhere to be shown, and\n   * editing again seeds from a read that has not caught up, so submitting\n   * that draft overwrites the write still in flight.\n   */\n  const cancel = (): void => {\n    if (saving) return;\n    onClose();\n  };\n\n  return (\n    <div className=\"space-y-4\" data-breakpoint-editor=\"\">\n      <div className=\"space-y-6\">\n        {BREAKPOINT_AXES.filter(\n          // The container axis only on a site that already uses it: most\n          // sites style by the window's width alone.\n          axis => axis === \"viewport\" || draft[axis].length > 0\n        ).map(axis => {\n          const rows = draft[axis];\n          const left = storedLimitFor(axis) - rows.length;\n          return (\n            <section key={axis} className=\"space-y-2\">\n              {axis === \"container\" ? (\n                <h4 className=\"text-sm font-medium\">{CONTAINER_TITLE}</h4>\n              ) : null}\n              <div className=\"divide-y divide-border rounded-md border border-border\">\n                {axis === \"viewport\" ? (\n                  <div className=\"flex items-center gap-2 px-3 py-2 text-sm\">\n                    <span className=\"font-medium\">Desktop</span>\n                    <span className=\"text-muted-foreground\">\n                      the base, always applies\n                    </span>\n                  </div>\n                ) : null}\n                {rows.map((row, index) => {\n                  const rowIssues = issuesForRow(issues, axis, index);\n                  return (\n                    <div\n                      key={row.key}\n                      className=\"grid grid-cols-[1fr_8rem_7rem_auto] items-start gap-2 px-3 py-2\"\n                    >\n                      <Field\n                        id={`${fieldId}-${row.key}-label`}\n                        readOnly={saving}\n                        label=\"Name\"\n                        hideLabel\n                        value={row.label}\n                        placeholder=\"Tablet\"\n                        // The id is the name's, and shown nowhere: a clash is\n                        // said about the name, in plain words.\n                        error={rowIssues.label ?? rowIssues.id}\n                        onChange={label => renameRow(axis, row.key, label)}\n                      />\n                      <Field\n                        id={`${fieldId}-${row.key}-width`}\n                        readOnly={saving}\n                        label=\"Up to\"\n                        hideLabel\n                        value={row.width}\n                        placeholder={axis === \"container\" ? \"any\" : \"991\"}\n                        inputMode=\"numeric\"\n                        suffix=\"px\"\n                        error={rowIssues.maxWidth}\n                        onChange={width => updateRow(axis, row.key, { width })}\n                      />\n                      <span className=\"pt-2 text-sm text-muted-foreground tabular-nums\">\n                        {rangeOf(rows, row)}\n                      </span>\n                      <Button\n                        type=\"button\"\n                        variant=\"ghost\"\n                        size=\"icon\"\n                        aria-label={`Remove ${row.label.trim() || \"breakpoint\"}`}\n                        disabled={saving}\n                        onClick={() => removeRow(axis, row.key)}\n                      >\n                        <Trash2 className=\"size-4\" />\n                      </Button>\n                    </div>\n                  );\n                })}\n              </div>\n              <div className=\"flex items-center gap-3\">\n                <Button\n                  type=\"button\"\n                  variant=\"outline\"\n                  size=\"sm\"\n                  disabled={left <= 0 || saving}\n                  onClick={() => addRow(axis)}\n                >\n                  <Plus className=\"size-4\" />\n                  Add breakpoint\n                </Button>\n                <span className=\"text-xs text-muted-foreground\">\n                  {left <= 0\n                    ? \"That is as many as a site can have.\"\n                    : `You can add up to ${left} more.`}\n                </span>\n              </div>\n            </section>\n          );\n        })}\n        {draft.container.length === 0 ? (\n          // The first container width has to start somewhere: a site that has\n          // none sees this in place of the section.\n          <Button\n            type=\"button\"\n            variant=\"ghost\"\n            size=\"sm\"\n            disabled={saving}\n            onClick={() => addRow(\"container\")}\n          >\n            <Plus className=\"size-4\" />\n            Add a container width\n          </Button>\n        ) : null}\n      </div>\n      <div className=\"flex flex-wrap items-center justify-between gap-3\">\n        <p\n          className={cn(\n            \"text-xs\",\n            issues.length > 0 || refusal !== undefined\n              ? \"text-destructive\"\n              : \"text-muted-foreground\"\n          )}\n          // Announced rather than only coloured, so the reason Save is\n          // unavailable reaches a screen reader too.\n          role=\"status\"\n        >\n          {/*\n           * A REFUSAL outranks the issue count, because they answer different\n           * questions and only one of them is news. The count says what the\n           * author must fix before saving; a refusal says the save they just\n           * made did not happen. A silent line beside a failed write would\n           * read as confirmation.\n           */}\n          {/* Silent while every breakpoint is usable: the line speaks only\n              when something is wrong. Kept mounted, so what it then says is\n              announced. */}\n          {/* The host's reason next: it holds every save, a problem or not. */}\n          {refusal ??\n            blocked ??\n            (issues.length === 0\n              ? \"\"\n              : `${issues.length} ${issues.length === 1 ? \"problem\" : \"problems\"} to fix before saving.`)}\n        </p>\n        <div className=\"flex gap-2\">\n          <Button\n            type=\"button\"\n            variant=\"outline\"\n            disabled={saving}\n            onClick={cancel}\n          >\n            Cancel\n          </Button>\n          <Button\n            type=\"button\"\n            disabled={issues.length > 0 || saving || blocked !== undefined}\n            onClick={save}\n          >\n            {saving ? \"Saving…\" : \"Save breakpoints\"}\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/** One labelled field with its error, associated for assistive technology. */\nfunction Field({\n  id,\n  label,\n  hideLabel,\n  value,\n  placeholder,\n  error,\n  className,\n  inputMode,\n  suffix,\n  readOnly,\n  hint,\n  onChange,\n}: {\n  id: string;\n  label: string;\n  hideLabel?: boolean;\n  value: string;\n  placeholder?: string;\n  error?: string;\n  className?: string;\n  inputMode?: \"numeric\";\n  suffix?: string;\n  readOnly?: boolean;\n  hint?: string;\n  onChange: (value: string) => void;\n}) {\n  const errorId = `${id}-error`;\n  const hintId = `${id}-hint`;\n  return (\n    <div className=\"space-y-1\">\n      <Label htmlFor={id} className={cn(\"text-xs\", hideLabel && \"sr-only\")}>\n        {label}\n      </Label>\n      <div className=\"relative\">\n        <Input\n          id={id}\n          value={value}\n          placeholder={placeholder}\n          inputMode={inputMode}\n          readOnly={readOnly}\n          aria-invalid={error !== undefined}\n          // Only ever names elements that EXIST. Pointing at an absent id\n          // leaves the control described by nothing, which reads to a screen\n          // reader as no error and no hint at all.\n          // Names only elements that are actually RENDERED. The hint is\n          // suppressed while an error is showing, so listing its id then would\n          // point assistive technology at nothing.\n          aria-describedby={\n            [\n              error !== undefined ? errorId : null,\n              hint && error === undefined ? hintId : null,\n            ]\n              .filter(Boolean)\n              .join(\" \") || undefined\n          }\n          className={cn(\n            suffix && \"pr-8\",\n            readOnly && \"text-muted-foreground bg-muted/50\",\n            className\n          )}\n          onChange={event => onChange(event.target.value)}\n        />\n        {suffix && (\n          <span\n            aria-hidden=\"true\"\n            className=\"text-muted-foreground pointer-events-none absolute inset-y-0 right-3 flex items-center text-xs\"\n          >\n            {suffix}\n          </span>\n        )}\n      </div>\n      {error && (\n        <p id={errorId} className=\"text-destructive flex gap-1 text-xs\">\n          <TriangleAlert className=\"mt-0.5 size-3 shrink-0\" />\n          <span>{error}</span>\n        </p>\n      )}\n      {hint && !error && (\n        <p id={hintId} className=\"text-muted-foreground text-xs\">\n          {hint}\n        </p>\n      )}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The site's breakpoints, as Settings' Site tab shows and edits them.\n *\n * A list in the device buttons' own words, and an \"Edit breakpoints\" control\n * that turns the section into the editor in place. The editor is the whole of\n * editing: its rows, its validation, its cascade preview, its Save and Cancel\n * and the reason a save was refused. A breakpoint set validates as a whole, so\n * it is saved as a whole, never a row at a time.\n *\n * **In Settings rather than in the top bar.** Breakpoints are site-wide and set\n * rarely; the top bar keeps the devices that choose between them.\n *\n * @module breakpoint-manager\n */\n\nimport { Button } from \"@nextlyhq/ui\";\nimport { Check } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport {\n  authoredBreakpoints,\n  BASE_BREAKPOINT,\n  sameBreakpoints,\n  type BreakpointSet,\n} from \"../styles/breakpoints\";\n\nimport { BreakpointEditor } from \"./breakpoint-editor\";\nimport { deviceOptions, tierIcon } from \"./breakpoint-switcher\";\n\n/**\n * Props for BreakpointManager.\n * @experimental\n */\nexport interface BreakpointManagerProps {\n  /** The site's saved breakpoints, as the canvas is compiled against them. */\n  value: BreakpointSet;\n  /**\n   * Persist the edited set. See {@link BreakpointEditorProps.onSave} — a promise\n   * is awaited and a resolved string is shown as a refusal.\n   */\n  onSave: (next: BreakpointSet) => void | Promise<string | null | undefined>;\n  /**\n   * What the SAVED set's read has actually done — not merely whether it is done.\n   *\n   * Three states, because the two that are not `ready` need different words and\n   * a boolean cannot carry them. Until the read answers, `value` is the host's\n   * CONFIG DEFAULTS, so a dialog opened on it would show a set the site never\n   * chose and saving that draft would overwrite the site's real breakpoints with\n   * defaults the author never saw. That is true of a FAILED read as much as a\n   * pending one — which is why a `pending`-only gate is wrong — but the two are\n   * not the same thing to say. Told \"still loading\" after a permission denial,\n   * an author waits for a request that already finished.\n   *\n   * Disabled rather than hidden in both cases: a control that vanishes while a\n   * request is in flight moves the buttons beside it under the pointer, and an\n   * author who knows the manager exists is left wondering whether the feature\n   * was removed.\n   */\n  status: \"loading\" | \"unavailable\" | \"ready\";\n  /**\n   * Told when editing starts and ends, so a host can ask before it is left:\n   * a draft open in the editor is work not saved yet.\n   */\n  onEditingChange?: (editing: boolean) => void;\n  /** Told when a save of the set starts and settles; see the editor's. */\n  onSavingChange?: (saving: boolean) => void;\n  /**\n   * Why the breakpoints cannot be edited right now, when the host knows one\n   * the saved set's read cannot (a removal still being carried out, say):\n   * Edit breakpoints is disabled, saying why. Absent, `status` decides.\n   */\n  blocked?: string;\n  /**\n   * A short word shown beside a breakpoint, by its id: what the host has just\n   * done to it (\"put back\"), said for as long as the host passes it.\n   */\n  tags?: ReadonlyMap<string, string>;\n  /**\n   * Counted up by the host to open the editor, as Edit breakpoints does: a\n   * step that ends with editing as the way on opens it in one click.\n   */\n  editRequest?: number;\n}\n\n/**\n * Why Edit breakpoints is disabled, or `undefined` while it may be used: the\n * host's own reason first, then what the saved set's read has done.\n */\nfunction editUnavailable(\n  status: BreakpointManagerProps[\"status\"],\n  blocked: string | undefined\n): string | undefined {\n  if (blocked !== undefined) return blocked;\n  if (status === \"ready\") return undefined;\n  return status === \"loading\"\n    ? \"Available once the site's saved styles have loaded.\"\n    : \"Your site's saved styles could not be read, so editing them here could overwrite them.\";\n}\n\n/** One breakpoint in the list: its device glyph, name and range, and a tag. */\nfunction DeviceRow({\n  device,\n  tag,\n}: {\n  device: ReturnType<typeof deviceOptions>[number];\n  /** What the host says of it just now (\"put back\"), when anything. */\n  tag: string | undefined;\n}): React.JSX.Element {\n  const Glyph = tierIcon(\n    device.id === BASE_BREAKPOINT ? undefined : device.preview\n  );\n  return (\n    <li className=\"flex items-center gap-2 px-3 py-2 text-sm\">\n      <Glyph\n        className=\"size-4 shrink-0 text-muted-foreground\"\n        aria-hidden=\"true\"\n      />\n      <span className=\"font-medium\">{device.label}</span>\n      <span className=\"text-muted-foreground\">{device.range}</span>\n      {tag === undefined ? null : (\n        <span className=\"rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground\">\n          {tag}\n        </span>\n      )}\n    </li>\n  );\n}\n\n/**\n * Open the editor when the host asks (`editRequest` counted up), once per\n * request, and only when it may be opened. A request made while the set is\n * still loading (a read refetching) waits for it, so the one click is never\n * lost; one made while editing is held, or the set can't be read, is\n * answered by the disabled button's reason and not kept for later.\n */\nfunction useEditRequest(\n  editRequest: number | undefined,\n  status: BreakpointManagerProps[\"status\"],\n  ready: boolean,\n  open: () => void\n): void {\n  const asked = React.useRef(editRequest ?? 0);\n  React.useEffect(() => {\n    if (editRequest === undefined || editRequest === asked.current) return;\n    if (status === \"loading\") return;\n    asked.current = editRequest;\n    if (ready) open();\n  });\n}\n\n/**\n * The set to show and edit: `value`, or the set this surface last wrote until\n * the read catches up (see the comment inside), with `hold` to record a write.\n */\nfunction useHeldWrite(value: BreakpointSet): {\n  readonly shown: BreakpointSet;\n  readonly hold: (wrote: BreakpointSet) => void;\n} {\n  /*\n   * The set this surface last wrote, held until the read catches up.\n   *\n   * A successful write resolves before the query it invalidates has refetched,\n   * and `useSiteStyle` reports `isPending` rather than background fetching — so\n   * for a moment after saving, `value` is still the PREVIOUS set while the\n   * trigger is ready and the dialog will reopen. An author who saves and\n   * immediately reopens would be seeded from the old set, and saving that draft\n   * would overwrite the write that had just succeeded.\n   *\n   * Released by ANY change to `value`, not by `value` matching what was\n   * written. Waiting for a match cannot end if the server stored something\n   * different from what was sent — the surface would then show the submitted\n   * set forever and never the truth. Recording the value that was current at\n   * the save and yielding the moment it changes bounds this to exactly the\n   * window it exists for.\n   */\n  const [pendingWrite, setPendingWrite] = React.useState<\n    | { readonly wrote: BreakpointSet; readonly sawAtSave: BreakpointSet }\n    | undefined\n  >(undefined);\n  /*\n   * The hold survives exactly while the read has demonstrably not moved.\n   *\n   * Two earlier versions each failed in one direction, which is the tell that a\n   * third heuristic is the wrong answer. Waiting for the incoming set to MATCH\n   * what was written never ends if the server stored something else. Comparing\n   * object IDENTITY releases on any parent render that rebuilds an equal\n   * object, because the prop contract does not promise a stable reference.\n   *\n   * Both are answered by asking about CONTENT and accepting either outcome as\n   * an arrival: the read has caught up when it now equals what was written, and\n   * it has also caught up when it differs from what was there at the save. What\n   * is left — equal to the pre-save set and not to the written one — is the only\n   * state in which nothing has come back yet, so the hold cannot stick and\n   * cannot lift early.\n   */\n  const readArrived =\n    pendingWrite !== undefined &&\n    (sameBreakpoints(value, pendingWrite.wrote) ||\n      !sameBreakpoints(value, pendingWrite.sawAtSave));\n  const stillStale = pendingWrite !== undefined && !readArrived;\n  /*\n   * CLEARED once the read moves, not merely stopped being consulted.\n   *\n   * Leaving it in state makes the release temporary rather than permanent:\n   * `resolveSiteStyle` hands back the host's config OBJECT when nothing is\n   * stored, and that reference is memoised — so a site that saves a set and\n   * later has the stored section cleared through the API or an import sees\n   * `value` return to the very object it was at the save, `sawAtSave === value`\n   * become true a second time, and an optimistic write resurrect over the truth\n   * the server and canvas have both moved back to.\n   */\n  React.useEffect(() => {\n    if (readArrived) setPendingWrite(undefined);\n  }, [readArrived]);\n  return {\n    shown: stillStale ? pendingWrite.wrote : value,\n    hold: wrote => setPendingWrite({ wrote, sawAtSave: value }),\n  };\n}\n\n/**\n * The button that opens the breakpoint dialog, and the dialog.\n * @experimental\n */\nexport function BreakpointManager({\n  value,\n  onSave,\n  status,\n  onEditingChange,\n  onSavingChange,\n  blocked,\n  tags,\n  editRequest,\n}: BreakpointManagerProps): React.JSX.Element {\n  const ready = status === \"ready\" && blocked === undefined;\n  const [editing, setEditingState] = React.useState(false);\n  const setEditing = (next: boolean): void => {\n    setEditingState(next);\n    onEditingChange?.(next);\n  };\n  useEditRequest(editRequest, status, ready, () => setEditing(true));\n  // Whether this section's last save succeeded, to say so beside it.\n  const [saved, setSaved] = React.useState(false);\n  const held = useHeldWrite(value);\n  const authored = authoredBreakpoints(held.shown);\n\n  const persist = async (\n    next: BreakpointSet\n  ): Promise<string | null | undefined> => {\n    // Narrowed rather than passed through: `onSave` may return nothing at all,\n    // and `void` is not `undefined` to the checker even though it is at runtime.\n    const answered = await onSave(next);\n    const outcome =\n      typeof answered === \"string\" || answered === null ? answered : undefined;\n    // Held only on success. A refused write changed nothing, so there is no\n    // newer set for the read to catch up to.\n    if (outcome === undefined) {\n      held.hold(next);\n      setSaved(true);\n    }\n    return outcome;\n  };\n\n  const shown = held.shown;\n\n  if (editing) {\n    // Mounted only while editing, so the draft is seeded from the set at the\n    // moment the author starts, never from one that changed behind it.\n    return (\n      <BreakpointEditor\n        value={authored}\n        onSave={persist}\n        onClose={() => setEditing(false)}\n        {...(onSavingChange === undefined ? {} : { onSavingChange })}\n        // A reason that arrives while editing holds the open editor too.\n        {...(blocked === undefined ? {} : { blocked })}\n      />\n    );\n  }\n\n  return (\n    <div className=\"space-y-3\" data-breakpoint-manager=\"\">\n      <ul className=\"divide-y divide-border rounded-md border border-border\">\n        {deviceOptions(shown).map(device => (\n          <DeviceRow\n            key={device.id}\n            device={device}\n            tag={tags?.get(device.id)}\n          />\n        ))}\n      </ul>\n      <div className=\"flex items-center gap-3\">\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          disabled={!ready}\n          onClick={() => {\n            setSaved(false);\n            setEditing(true);\n          }}\n          // Disabled rather than hidden until the saved set is read: opened\n          // on the host's defaults, a save would overwrite the site's real\n          // breakpoints with a set it never chose.\n          title={editUnavailable(status, blocked)}\n        >\n          Edit breakpoints\n        </Button>\n        {/* After a save, in the save chip's word, beside what made it; a\n            refused save stays in the editor with its reason. */}\n        <span\n          role=\"status\"\n          className=\"flex items-center gap-1.5 text-sm text-muted-foreground\"\n        >\n          {saved ? (\n            <>\n              <Check className=\"size-4 text-success\" aria-hidden=\"true\" />\n              Saved\n            </>\n          ) : null}\n        </span>\n      </div>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The top bar's light and dark preview: a sun and a moon in one control,\n * beside the device buttons, that draws the canvas and the Design panel's\n * swatches with the site's dark values while it is pressed.\n *\n * One toggle button rather than a pair: there are two states, so assistive\n * technology hears one control, \"Preview in dark mode\", pressed or not. The\n * sun and the moon inside are drawn as the two halves of a segmented control,\n * the shown mode's half filled, which is how the device buttons beside it say\n * which device is shown.\n *\n * It holds nothing itself. The host keeps the mode, draws the canvas in it,\n * and decides when the switch is offered at all; the tooltip says what the\n * host guarantees, that it is a preview only.\n *\n * @module shell/dark-preview-switch\n */\nimport type { TokenMode } from \"@nextlyhq/blocks-engine\";\nimport { TooltipProvider } from \"@nextlyhq/ui\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport { Moon, Sun } from \"lucide-react\";\nimport type * as React from \"react\";\n\nimport { ChromeTooltip } from \"../chrome-tooltip\";\nimport { DARK_PREVIEW_WORDS } from \"../editor-words\";\n\n/** @experimental Settles with the canvas's mode preview. */\nexport interface DarkPreviewSwitchProps {\n  /** The mode the canvas is previewed in. */\n  mode: TokenMode;\n  /** The author asked for the other mode. */\n  onMode: (mode: TokenMode) => void;\n}\n\nconst FOCUS_RING =\n  \"focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-[color:var(--nx-builder-surface)] focus-visible:outline-none\";\n\n/**\n * The switch, one control high like the device buttons, with its border and\n * padding inside that height. It keeps its own tooltip provider, as each\n * surface of the editor's chrome does, so a host can place it anywhere.\n *\n * @experimental Settles with the canvas's mode preview.\n */\nexport function DarkPreviewSwitch({\n  mode,\n  onMode,\n}: DarkPreviewSwitchProps): React.JSX.Element {\n  const dark = mode === \"dark\";\n  return (\n    <TooltipProvider delayDuration={300}>\n      <ChromeTooltip content={DARK_PREVIEW_WORDS.tooltip}>\n        <button\n          type=\"button\"\n          aria-label={DARK_PREVIEW_WORDS.name}\n          aria-pressed={dark}\n          onClick={() => onMode(dark ? \"light\" : \"dark\")}\n          className={cn(\n            \"nx-dark-preview-switch inline-flex h-[var(--nx-builder-control-height,1.75rem)] items-center gap-0.5 rounded-md border p-0.5\",\n            FOCUS_RING\n          )}\n        >\n          <Side mode=\"light\" on={!dark} />\n          <Side mode=\"dark\" on={dark} />\n        </button>\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/** One half: the sun or the moon, filled while its mode is the one shown. */\nfunction Side({\n  mode,\n  on,\n}: {\n  mode: TokenMode;\n  on: boolean;\n}): React.JSX.Element {\n  const Icon = mode === \"dark\" ? Moon : Sun;\n  return (\n    <span\n      data-side={mode}\n      data-on={on}\n      aria-hidden=\"true\"\n      className={cn(\n        \"inline-flex h-full items-center rounded px-2\",\n        on ? \"bg-accent text-accent-foreground\" : \"text-muted-foreground\"\n      )}\n    >\n      <Icon className=\"size-3.5\" />\n    </span>\n  );\n}\n","/**\n * Copied blocks: what is put on the clipboard, how it is read back, and where\n * a paste lands.\n *\n * Pure, with no DOM and no React, so every rule here can be asserted on its\n * own; `block-clipboard-transport` moves the text on and off the clipboard and\n * `block-clipboard-verbs` wires both to the editor.\n *\n * ## The copied-blocks format\n *\n * One JSON object: `{ nextlyBlocks: 1, origin, blocks }`.\n *\n * - `nextlyBlocks` is the format's version and also what marks the text as\n *   copied blocks, so text from anywhere else is never read as blocks.\n * - `origin` is the address of the site the blocks were copied on (scheme,\n *   host and port). Blocks point at the site's own shared styles, block\n *   styles, variables, components and media by id, and those ids mean nothing\n *   on another site, so a paste whose origin differs is refused and pointed to\n *   Export / Import, which carries those items with the blocks.\n * - `blocks` are the copied blocks as the page stores them, children\n *   included. Nothing is rewritten on copy: a paste makes the fresh ids.\n *\n * @module block-clipboard\n */\n\nimport {\n  ENTRY_CONTENT_TYPE,\n  entryContentFieldOf,\n  entryContentPlacements,\n  findNode,\n  holdsEntryContent,\n  isPlainRecord,\n  nodeShapeRefusal,\n  placementTypesOf,\n  planPasteBlocks,\n  type AnyBlockDefinition,\n  type BlockDocument,\n  type BlockNode,\n  type ComponentLookup,\n  type NestingSource,\n  type PlanRefusal,\n} from \"@nextlyhq/blocks-engine\";\nimport { z } from \"zod\";\n\nimport type { BuilderOp, OpPosition } from \"../op-vocabulary\";\nimport type { SlotSource } from \"../panels/add/inserter-types\";\nimport {\n  insertionCandidates,\n  insertionFor,\n  runRole,\n} from \"../panels/add/insertion-candidates\";\n\nimport { compositionRefusalReason } from \"./composition-refusal\";\nimport {\n  ENTRY_CONTENT_ONE_REASON,\n  entryContentRefusal,\n  offeredIn,\n} from \"./entry-content-rules\";\nimport { normalizeSelection } from \"./selection\";\n\n/** The clipboard type copied blocks travel under, beside plain text. */\nexport const BLOCK_CLIPBOARD_TYPE = \"application/x-nextly-blocks+json\";\n\n/** The version of the copied-blocks format this builder writes and reads. */\nexport const BLOCK_CLIPBOARD_VERSION = 1;\n\n/** Copied blocks, as they are put on the clipboard. */\nexport interface CopiedBlocks {\n  readonly nextlyBlocks: typeof BLOCK_CLIPBOARD_VERSION;\n  /** The address of the site they were copied on. */\n  readonly origin: string;\n  readonly blocks: readonly BlockNode[];\n}\n\n/** Said when copied blocks come from another site. */\nexport const FOREIGN_SITE_REFUSAL =\n  \"These blocks were copied on another site, so they can’t be pasted here. To move blocks between sites, save them as a section, then use Export and Import on the Saved sections list.\";\n\n/** Said when copied blocks were written in a format this builder does not read. */\nexport const OTHER_VERSION_REFUSAL =\n  \"These blocks were copied from a different version of the editor, so they can’t be pasted here. Copy them again.\";\n\n/** Said when copied Entry content would land in a page that is not a template. */\nconst ENTRY_CONTENT_TEMPLATE_ONLY =\n  \"An Entry content block goes only in a template, so it can’t be pasted here.\";\n\n/** Said when copied Entry content draws a field this template's collection lacks. */\nconst ENTRY_CONTENT_FIELD_MISSING =\n  \"This Entry content block draws a field this template’s collection doesn’t have, so it can’t be pasted here.\";\n\n/**\n * Why pasted Entry content can't go in this template: a block naming a\n * blocks field the template's collection does not have, which the save would\n * refuse. `undefined` when every one names a field the collection has.\n */\nfunction foreignFieldRefusal(\n  blocks: readonly BlockNode[],\n  fields: readonly string[]\n): string | undefined {\n  // Read from the engine's own list of placements, the one the save judges\n  // a template by and the one the duplicate check counts.\n  const foreign = entryContentPlacements(blocks).some(({ node }) => {\n    const field = entryContentFieldOf(node);\n    return field === undefined || !fields.includes(field);\n  });\n  return foreign ? ENTRY_CONTENT_FIELD_MISSING : undefined;\n}\n\n/** Said when Paste finds no copied blocks on the clipboard. */\nexport const NOTHING_TO_PASTE =\n  \"There are no copied blocks to paste. Copy blocks first.\";\n\n/**\n * The selected blocks as copied blocks, or `null` with nothing selected.\n *\n * Only the outermost selected blocks, in page order: a block selected with\n * the container around it is copied once, inside that container, as Delete\n * removes it once.\n */\nexport function copyOfSelection(\n  document: BlockDocument,\n  selectedIds: readonly string[],\n  origin: string\n): CopiedBlocks | null {\n  const blocks = normalizeSelection(document, selectedIds).flatMap(id => {\n    const node = findNode(document.nodes, id);\n    return node === undefined ? [] : [node];\n  });\n  if (blocks.length === 0) return null;\n  return { nextlyBlocks: BLOCK_CLIPBOARD_VERSION, origin, blocks };\n}\n\n/** Copied blocks as the text put on the clipboard. */\nexport function serializeCopiedBlocks(copied: CopiedBlocks): string {\n  return JSON.stringify(copied);\n}\n\n/**\n * One block as the op layer would carry it.\n *\n * Any page can put text on the clipboard, so a paste claiming this site's\n * origin is not proof it came from here. What protects the page is what\n * protects every stored page: the op layer's shape rule here, the placement\n * rules the planner asks, and the renderer, which draws a type it does not\n * know as a placeholder and escapes what it draws. The op layer's own shape rule\n * decides, so a paste never accepts a block that rule would then refuse.\n */\nconst pastedNode = z.custom<BlockNode>(\n  value =>\n    isPlainRecord(value) &&\n    typeof value.id === \"string\" &&\n    typeof value.type === \"string\" &&\n    // The shape rule is what makes this value a block, so it is handed the\n    // value to judge as one; it answers with a reason for anything else.\n    nodeShapeRefusal(value as unknown as BlockNode) === undefined\n);\n\n/** The envelope, read before the blocks: version and origin first. */\nconst envelope = z.object({\n  nextlyBlocks: z.number(),\n  origin: z.string(),\n  blocks: z.array(z.unknown()),\n});\n\nconst pastedBlocks = z.array(pastedNode).min(1);\n\n/** What reading the clipboard's text found. */\nexport type ReadCopiedBlocks =\n  /** Blocks to paste. */\n  | { readonly blocks: readonly BlockNode[]; readonly refusal?: undefined }\n  /** Copied blocks that cannot be pasted here, and why, in plain words. */\n  | { readonly refusal: string; readonly blocks?: undefined }\n  /** Not copied blocks at all: the text is left to whatever reads text. */\n  | null;\n\n/**\n * Read the clipboard's text as copied blocks.\n *\n * `null` for text that is not copied blocks, so ordinary text is never taken\n * for blocks. Copied blocks from another site, or in another version of the\n * format, are refused with the reason; blocks the op layer would not carry\n * are refused as a selection that cannot be copied.\n */\nexport function readCopiedBlocks(\n  text: string,\n  origin: string\n): ReadCopiedBlocks {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(text);\n  } catch {\n    return null;\n  }\n  const read = envelope.safeParse(parsed);\n  if (!read.success) return null;\n  if (read.data.nextlyBlocks !== BLOCK_CLIPBOARD_VERSION) {\n    return { refusal: OTHER_VERSION_REFUSAL };\n  }\n  if (read.data.origin !== origin) return { refusal: FOREIGN_SITE_REFUSAL };\n  const blocks = pastedBlocks.safeParse(read.data.blocks);\n  if (!blocks.success) {\n    return {\n      refusal: compositionRefusalReason({\n        problem: read.data.blocks.length === 0 ? \"empty\" : \"invalid-node\",\n      }),\n    };\n  }\n  return { blocks: blocks.data };\n}\n\n/** What a paste needs besides the page, the selection and the blocks. */\nexport interface PasteSources {\n  /** The nesting rule, as every other insert asks it. */\n  readonly nesting: NestingSource;\n  /** The site's components, so a placed component is judged by what it draws. */\n  readonly components?: ComponentLookup;\n  /** Block definitions beyond the registry's, for a block's role. */\n  readonly definitions?: readonly AnyBlockDefinition[];\n  /** Each block type's regions, for pasting inside a container. */\n  readonly slots?: SlotSource;\n  /**\n   * In a template, its collection's blocks fields by name, which a pasted\n   * Entry content block must name one of; `undefined` while they are read.\n   */\n  readonly entryFields?: readonly string[];\n  /**\n   * The editor's lock check, phrased: why a lock refuses these ops, or\n   * `null`. A place whose lock refuses the paste is passed over for the next\n   * one, as the Add panel passes over a locked place for a clicked tile.\n   */\n  readonly lockRefusal?: (ops: readonly BuilderOp[]) => string | null;\n}\n\n/** A paste, planned: the ops and the copies' ids, or why it is refused. */\nexport type PastePlan =\n  | {\n      readonly ops: readonly BuilderOp[];\n      /** The pasted top-level blocks, in page order, for selecting them. */\n      readonly newIds: readonly string[];\n      readonly refusal?: undefined;\n    }\n  | { readonly refusal: string; readonly ops?: undefined };\n\n/**\n * Why pasted blocks carrying an Entry content block cannot go into this\n * document, or `undefined` when they may (or carry none). A template holds\n * one Entry content block, so a paste bringing a second is refused as adding\n * one is.\n */\nfunction entryContentPasteRefusal(\n  document: BlockDocument,\n  blocks: readonly BlockNode[],\n  sources: PasteSources\n): string | undefined {\n  if (!blocks.some(block => holdsEntryContent(block))) return undefined;\n  // Only a template draws an entry, so anywhere else the block is refused\n  // here rather than left for the save to refuse.\n  if (!offeredIn(document.kind, ENTRY_CONTENT_TYPE)) {\n    return ENTRY_CONTENT_TEMPLATE_ONLY;\n  }\n  // One Entry content block per template, counted in what is pasted as well\n  // as in what the template already holds.\n  // Counted from the engine's own list of placements, the one the save\n  // judges a template by.\n  if (entryContentPlacements(blocks).length > 1) {\n    return ENTRY_CONTENT_ONE_REASON;\n  }\n  const fields = sources.entryFields;\n  return (\n    entryContentRefusal(document, ENTRY_CONTENT_TYPE, fields !== undefined) ??\n    foreignFieldRefusal(blocks, fields ?? [])\n  );\n}\n\n/**\n * Plan a paste where a click on a tile adding these blocks would land.\n *\n * The places are the Add panel's (`insertionCandidates`), tried in the order\n * that panel tries them for a run of this kind (`runRole`): content goes\n * inside a selected container at its end, after a selected block that holds\n * none, and at the end of the page with nothing selected. The first place the\n * engine's paste planner accepts is taken; when none does, the paste is\n * refused with the first place's reason, in the words every other refused\n * insert uses.\n */\nexport function planPaste(\n  document: BlockDocument,\n  selectedId: string | null,\n  blocks: readonly BlockNode[],\n  sources: PasteSources\n): PastePlan {\n  const entryRefusal = entryContentPasteRefusal(document, blocks, sources);\n  if (entryRefusal !== undefined) return { refusal: entryRefusal };\n\n  const role = runRole(\n    blocks.flatMap(block => placementTypesOf(block, sources.components)),\n    sources.definitions\n  );\n  const candidates = insertionCandidates(document, selectedId, {\n    role,\n    ...(sources.slots === undefined ? {} : { slots: sources.slots }),\n  });\n  const planAt = (at: OpPosition) =>\n    planPasteBlocks(document, blocks, at, sources.nesting, sources.components);\n\n  const locked = (ops: readonly BuilderOp[]) =>\n    sources.lockRefusal?.(ops) ?? null;\n  const found = insertionFor(candidates, candidate => {\n    const plan = planAt(candidate.at);\n    if (plan.pageOps === undefined) return undefined;\n    return locked(plan.pageOps) === null ? plan.pageOps : undefined;\n  });\n  if (found === undefined) {\n    // Every place refused, so the reason is the one for where the paste was\n    // first meant to go: the planner's, or the lock's there.\n    const first = candidates[0];\n    const plan = first === undefined ? undefined : planAt(first.at);\n    if (plan?.pageOps !== undefined) {\n      return {\n        refusal:\n          locked(plan.pageOps) ??\n          compositionRefusalReason({ problem: \"destination-locked\" }),\n      };\n    }\n    const refusal: PlanRefusal = plan ?? { problem: \"invalid-position\" };\n    return { refusal: compositionRefusalReason(refusal) };\n  }\n  const ops = found.answer;\n  const newIds = ops.flatMap(op => (op.kind === \"insert\" ? [op.node.id] : []));\n  return { ops, newIds };\n}\n","/**\n * Moving copied blocks on and off the system clipboard.\n *\n * The system clipboard, so a copy in one page or browser tab pastes in\n * another. The text goes under two types: copied blocks' own type, and plain\n * text, which is the one type every browser carries between tabs and the\n * only one a menu's Paste can read back (`navigator.clipboard.readText`).\n * Plain text is read as blocks only when it is a copied-blocks object, so\n * ordinary text is never mistaken for blocks.\n *\n * The last text copied in this tab is also kept here, for a menu Paste where\n * the browser refuses to read the clipboard. A keyboard paste needs no\n * fallback: the paste event carries the clipboard's contents itself.\n *\n * @module block-clipboard-transport\n */\n\nimport { BLOCK_CLIPBOARD_TYPE } from \"./block-clipboard\";\n\n/** The last copied blocks' text in this tab, for a Paste the browser will not read for. */\nlet lastCopied: string | undefined;\n\n/**\n * Put copied blocks on a clipboard event that is being handled: the copy or\n * cut the browser is performing. Taking the event's default away is what\n * makes the browser keep this text rather than the page's selected text.\n */\nexport function putOnClipboard(event: ClipboardEvent, text: string): boolean {\n  lastCopied = text;\n  const data = event.clipboardData;\n  // Answers whether the clipboard took the text, so a Cut never removes\n  // blocks that were not copied.\n  if (data === null) return false;\n  data.setData(BLOCK_CLIPBOARD_TYPE, text);\n  data.setData(\"text/plain\", text);\n  event.preventDefault();\n  return true;\n}\n\n/**\n * Copy text from a control, such as a menu's Copy, where no clipboard event\n * is under way. Answers whether the clipboard took it, now or once the\n * asynchronous clipboard has answered.\n *\n * Asks the document for a copy (`execCommand(\"copy\")`), which the browser\n * allows during the click or keypress that chose the command, and fills the\n * copy event it raises; listened for on the window and in the capture phase,\n * so this write is the only one made. Where the browser does not run the\n * command, the asynchronous clipboard takes the plain text instead.\n */\nexport function writeToClipboard(\n  doc: Document,\n  text: string\n): boolean | Promise<boolean> {\n  lastCopied = text;\n  const view = doc.defaultView;\n  let written = false;\n  const fill = (event: Event) => {\n    if (!isClipboardEvent(event)) return;\n    event.stopImmediatePropagation();\n    written = putOnClipboard(event, text);\n  };\n  view?.addEventListener(\"copy\", fill, true);\n  try {\n    doc.execCommand(\"copy\");\n  } catch {\n    // A browser that refuses the command is answered by the fallback below.\n  } finally {\n    view?.removeEventListener(\"copy\", fill, true);\n  }\n  if (written) return true;\n  // The asynchronous clipboard answers later; a browser with none, or one\n  // that refuses, answers that nothing was written.\n  const clipboard = view?.navigator.clipboard;\n  if (clipboard === undefined) return false;\n  return clipboard.writeText(text).then(\n    () => true,\n    () => false\n  );\n}\n\n/** The text a paste event carries that may be copied blocks, or nothing. */\nexport function textOfPaste(event: ClipboardEvent): string | undefined {\n  const data = event.clipboardData;\n  if (data === null) return undefined;\n  const text = data.getData(BLOCK_CLIPBOARD_TYPE) || data.getData(\"text/plain\");\n  return text === \"\" ? undefined : text;\n}\n\n/**\n * The clipboard's text, for a menu's Paste: read from the system clipboard,\n * or the last copy made in this tab where the browser will not read it.\n */\nexport async function readClipboard(\n  doc: Document\n): Promise<string | undefined> {\n  const clipboard = doc.defaultView?.navigator.clipboard;\n  if (clipboard === undefined) return lastCopied;\n  try {\n    return await clipboard.readText();\n  } catch {\n    return lastCopied;\n  }\n}\n\n/**\n * Whether an event is a clipboard event, by its shape rather than its class:\n * a canvas frame's events are built by another window.\n */\nexport function isClipboardEvent(event: Event): event is ClipboardEvent {\n  return \"clipboardData\" in event;\n}\n","\"use client\";\n\n/**\n * ⌘C, ⌘X and ⌘V on the selected blocks, through the browser's own copy, cut\n * and paste events rather than key bindings.\n *\n * The events are what carry the clipboard: a copy or cut event takes the text\n * to put on it, and a paste event is the one place a page reads the clipboard\n * without asking the author's permission first. Heard in the editor's\n * document and in the canvas frame's, since a key pressed with focus in the\n * frame raises its event there.\n *\n * **Text keeps its keys.** A press in a text field, in a block's text being\n * edited on the canvas, or over text the author has highlighted is left to the\n * browser, so it copies, cuts and pastes text exactly as it would without the\n * editor. Only a press with no text in play acts on blocks.\n *\n * @module block-clipboard-events\n */\n\nimport { useIsomorphicLayoutEffect, type ShortcutBinding } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { useShellIsActive } from \"../shell/shell-active\";\nimport { BUILDER_CHROME_CLASS } from \"../shell-state\";\n\nimport {\n  isClipboardEvent,\n  putOnClipboard,\n  textOfPaste,\n} from \"./block-clipboard-transport\";\nimport type { BlockClipboardVerbs } from \"./block-clipboard-verbs\";\nimport { isTextEntry, modalIsOpen } from \"./canvas-escape\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { isElement } from \"./dom-kind\";\n\n/**\n * The keys, as Help lists them.\n *\n * Bindings that never fire (`when` is always false): the keys act through\n * the browser's clipboard events below, so a binding that took the keystroke\n * would stop the very event that carries the clipboard. Registered so Help,\n * which reads the editor's bindings, lists what these keys do.\n */\nexport const CLIPBOARD_KEY_HELP: readonly ShortcutBinding[] = [\n  [\"mod+c\", \"Copy the selected blocks\"],\n  [\"mod+x\", \"Cut the selected blocks\"],\n  [\"mod+v\", \"Paste copied blocks\"],\n].map(\n  ([keys = \"\", description = \"\"]): ShortcutBinding => ({\n    keys,\n    description,\n    when: () => false,\n    whenTyping: false,\n    preventDefault: false,\n    run: () => undefined,\n  })\n);\n\n/**\n * Whether a clipboard event is the editor's to answer: raised in the canvas,\n * or in the editor's own chrome, with no text in play and no dialog open.\n */\nexport function blocksTakeClipboardEvent(\n  event: Event,\n  editorDocument: Document\n): boolean {\n  // The browser raises these at the focused element, or the body with\n  // nothing focused, so the target is always an element of some document.\n  const element = event.target;\n  if (!isElement(element)) return false;\n  const doc = element.ownerDocument;\n  // A dialog over the editor owns the keyboard, Copy included.\n  if (modalIsOpen(editorDocument)) return false;\n  // A field, or a block's text being edited: the text's own copy and paste.\n  if (isTextEntry(element)) return false;\n  // Text the author highlighted is what they meant to copy or cut; a paste\n  // has nowhere to go in text that cannot be edited, so it is never held\n  // back by one. Not in Layers, whose rows select blocks: a shift-click\n  // there to select several can leave their labels highlighted.\n  const highlighted = doc.getSelection();\n  if (\n    event.type !== \"paste\" &&\n    highlighted !== null &&\n    !highlighted.isCollapsed &&\n    !inBlockTree(highlighted)\n  ) {\n    return false;\n  }\n  // In the editor's document, only from within the editor itself, or with\n  // nothing focused at all (a page just opened, before any click): a page\n  // hosting the editor keeps its own copy and paste on its own controls.\n  if (doc === editorDocument) {\n    return (\n      element === doc.body ||\n      element.closest(`.${BUILDER_CHROME_CLASS}`) !== null\n    );\n  }\n  return true;\n}\n\n/** Whether a highlight lies in a tree of blocks, such as Layers. */\nfunction inBlockTree(highlighted: Selection): boolean {\n  const anchor = highlighted.anchorNode;\n  const element = isElement(anchor) ? anchor : (anchor?.parentElement ?? null);\n  return element?.closest('[role=\"tree\"]') != null;\n}\n\n/**\n * Listen for copy, cut and paste in the editor's document and the canvas\n * frame's, and answer the ones meant for blocks. Draws nothing.\n */\nexport function BlockClipboardEvents({\n  verbs,\n  enabled,\n}: {\n  readonly verbs: BlockClipboardVerbs;\n  readonly enabled: boolean;\n}): null {\n  const canvasDocument = useCanvasFrame().document;\n  // A shell hidden for a too-narrow window keeps its selection mounted but\n  // takes no edits, and `inert` does not stop a document's own listeners.\n  const active = useShellIsActive();\n  const listening = enabled && active;\n  // The newest verbs, read when an event lands, so listeners are added once\n  // per document rather than on every render.\n  const latest = React.useRef(verbs);\n  latest.current = verbs;\n\n  useIsomorphicLayoutEffect(() => {\n    if (!listening || typeof document === \"undefined\") return;\n    const editorDocument = document;\n    const documents = new Set<Document>([editorDocument]);\n    if (canvasDocument !== null) documents.add(canvasDocument);\n\n    const onCopyOrCut = (event: Event) => {\n      if (event.defaultPrevented) return;\n      if (!isClipboardEvent(event)) return;\n      if (!blocksTakeClipboardEvent(event, editorDocument)) return;\n      const write = (text: string) => putOnClipboard(event, text);\n      if (event.type === \"cut\") latest.current.cut(write);\n      else latest.current.copy(write);\n    };\n    const onPaste = (event: Event) => {\n      if (event.defaultPrevented) return;\n      if (!isClipboardEvent(event)) return;\n      if (!blocksTakeClipboardEvent(event, editorDocument)) return;\n      const text = textOfPaste(event);\n      if (text === undefined) return;\n      // Only copied blocks are taken; any other text is the page's to handle.\n      if (latest.current.pasteText(text)) event.preventDefault();\n    };\n\n    for (const doc of documents) {\n      doc.addEventListener(\"copy\", onCopyOrCut);\n      doc.addEventListener(\"cut\", onCopyOrCut);\n      doc.addEventListener(\"paste\", onPaste);\n    }\n    return () => {\n      for (const doc of documents) {\n        doc.removeEventListener(\"copy\", onCopyOrCut);\n        doc.removeEventListener(\"cut\", onCopyOrCut);\n        doc.removeEventListener(\"paste\", onPaste);\n      }\n    };\n  }, [listening, canvasDocument]);\n\n  return null;\n}\n","/**\n * The keys a selected block is moved with, and what each keyboard action\n * says: a move's effect, a deletion and how to undo it, and why a locked\n * block would not move.\n *\n * @module keyboard-announcements\n */\n\nimport type { MoveDirection, MoveEffect } from \"../canvas/keyboard-move\";\nimport type { EditorState } from \"../editor-state\";\nimport { lockRefusalWording } from \"../lock-refusal\";\nimport { refusalAnnouncement } from \"../move-refusal\";\nimport type { BuilderOp } from \"../op-vocabulary\";\n\n/**\n * The bindings, and why these keys.\n *\n * `alt+ArrowUp`/`alt+ArrowDown` is the line-move gesture from VS Code and the\n * editors that copied it, so it arrives already known rather than needing to be\n * taught. `alt+ArrowLeft`/`alt+ArrowRight` follows the indent convention every\n * outliner and list editor shares, and it matches the axis the rule itself\n * names — `indent` and `outdent` are its own words for the effect.\n *\n * Deliberately NOT Gutenberg's `mod+shift+alt+T`/`Y`. A four-key chord for the\n * commonest structural edit in the editor is undiscoverable and awkward on a\n * laptop, and the two letters carry no relationship to the direction they move.\n */\nexport const MOVE_KEYS: ReadonlyArray<{\n  keys: string;\n  direction: MoveDirection;\n  description: string;\n}> = [\n  {\n    keys: \"alt+ArrowUp\",\n    direction: \"up\",\n    description: \"Move the selected block up\",\n  },\n  {\n    keys: \"alt+ArrowDown\",\n    direction: \"down\",\n    description: \"Move the selected block down\",\n  },\n  {\n    keys: \"alt+ArrowRight\",\n    direction: \"indent\",\n    description: \"Move the selected block into the container above it\",\n  },\n  {\n    keys: \"alt+ArrowLeft\",\n    direction: \"outdent\",\n    description: \"Move the selected block out of its container\",\n  },\n];\n\n/**\n * What each effect is announced as.\n *\n * Derived from the effect the rule already decided rather than inferred here\n * from the direction pressed. `alt+ArrowLeft` is `outdent` only when there is a\n * container to leave, and re-deriving it from the keystroke would announce a\n * move out of a group that never happened.\n *\n * Three sentences rather than one, because the three are not the same event to\n * someone who cannot see the result: reordering keeps a block among its\n * siblings, while indenting and outdenting change which block CONTAINS it.\n */\nexport const EFFECT_ANNOUNCEMENT: Readonly<Record<MoveEffect, string>> = {\n  reorder: \"Block moved\",\n  indent: \"Block moved into the container above it\",\n  outdent: \"Block moved out of its container\",\n};\n\n/**\n * How a deletion is announced.\n *\n * Names what went AND how to get it back. A screen-reader user cannot see an\n * undo control, so for them the announcement is the only place the recovery\n * path exists — and a container takes its children with it, which is invisible\n * from the block they had selected: a collapsed section looks exactly like an\n * empty one.\n *\n * The count is stated rather than prompted for. A confirmation on every delete\n * is friction people learn to click through, so it stops being a decision and\n * becomes a keystroke — protecting nobody while costing everybody. That trade\n * only holds because undo is reachable, which is why these ship together.\n */\n/**\n * @param name - what to CALL the block, already resolved by the caller.\n *\n * A resolved name rather than a type, so the one rule that decides what a block\n * is called lives in `layerLabel` and this only phrases it. Taking a type and\n * resolving here would put a second resolution in the one surface a\n * screen-reader user hears — and it would have to reach for `blockLabel`, which\n * knows nothing about the name the author gave this instance.\n */\nexport function deletionAnnouncement(\n  name: string,\n  descendants: number\n): string {\n  const what =\n    descendants === 0\n      ? `${name} deleted`\n      : `${name} deleted, with ${descendants} ${descendants === 1 ? \"block\" : \"blocks\"} inside`;\n  return `${what}. Undo with ${UNDO_KEYS_SPOKEN}.`;\n}\n\n/** How the undo shortcut is READ ALOUD, which is not how it is parsed. */\nexport const UNDO_KEYS_SPOKEN = \"Control or Command Z\";\n\n/**\n * The shared verb list, or `null` when there is no provider above.\n *\n * Deliberately NOT \"compute it for me\": a caller that handed this a fallback to\n * run would have to be told when to run it, and the honest answer — whenever\n * anything the fallback closes over changes — is exactly what this hook cannot\n * see. Written that way it memoised on the context alone, so a surface outside a\n * provider kept its FIRST answer for ever: stale availability and stale refusal\n * reasons on every later selection.\n *\n * Answering `null` hands that decision back to the caller, which is the only\n * place the inputs are known.\n */\n/**\n * The sentence for ops the editor's locks refuse, or null when they keep every\n * lock: the editor's own question, worded as every lock refusal is.\n */\nexport function lockSentence(\n  editor: Pick<EditorState, \"lockRefusalFor\">,\n  ops: readonly BuilderOp[]\n): string | null {\n  const found = editor.lockRefusalFor(ops);\n  return found === undefined\n    ? null\n    : refusalAnnouncement(lockRefusalWording(found));\n}\n","/**\n * Copy, Cut and Paste for the selected blocks, as verbs every surface shares:\n * the keys, the block toolbar's menu, the canvas's right-click menu and the\n * command palette.\n *\n * The rules are `block-clipboard`'s and the clipboard is\n * `block-clipboard-transport`'s; this joins them to the editor, through the\n * editor's own apply, so a paste is one undo step and is refused by every\n * check any other edit meets.\n *\n * @module block-clipboard-verbs\n */\n\nimport type { ComponentLookup, NestingSource } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport { registrySlotSource } from \"../panels/add/inserter\";\nimport { slotsShowingEmpty } from \"../panels/add/inserter-types\";\nimport {\n  lockSentence,\n  UNDO_KEYS_SPOKEN,\n} from \"../shell/keyboard-announcements\";\n\nimport {\n  copyOfSelection,\n  NOTHING_TO_PASTE,\n  planPaste,\n  readCopiedBlocks,\n  serializeCopiedBlocks,\n} from \"./block-clipboard\";\nimport { readClipboard, writeToClipboard } from \"./block-clipboard-transport\";\nimport { isRefusal, selectionDeletion, subjectOf } from \"./selection-ops\";\n\n/**\n * Where copied text goes: the system clipboard, or a clipboard event being\n * handled. Answers whether the text was taken, now or later.\n */\nexport type ClipboardWrite = (text: string) => boolean | Promise<boolean>;\n\n/** Said when the clipboard would not take the copied blocks. */\nconst NOT_ON_CLIPBOARD = \"The blocks couldn’t be put on the clipboard\";\n\n/** Said when the blocks being cut changed before the clipboard answered. */\nconst CHANGED_WHILE_CUTTING =\n  \"The blocks changed while they were being copied, so nothing was cut. Cut them again.\";\n\n/** Run `then` with whether a write was taken, once it has answered. */\nfunction afterWrite(\n  written: boolean | Promise<boolean>,\n  then: (ok: boolean) => void\n): void {\n  if (typeof written === \"boolean\") then(written);\n  else void written.then(then, () => then(false));\n}\n\n/** The three verbs, plus a paste of text a clipboard event already carries. */\nexport interface BlockClipboardVerbs {\n  /** Copy the selected blocks; answers whether anything was copied. */\n  readonly copy: (write?: ClipboardWrite) => boolean;\n  /** Copy then remove the selected blocks, lock permitting; answers whether it did. */\n  readonly cut: (write?: ClipboardWrite) => boolean;\n  /** Paste what the clipboard holds, read from the clipboard. */\n  readonly paste: () => void;\n  /**\n   * Paste text a paste event carries. Answers whether the text was copied\n   * blocks, pasted or refused, so other text is left to the page.\n   */\n  readonly pasteText: (text: string) => boolean;\n}\n\n/** What the verbs need from the provider that offers them. */\nexport interface BlockClipboardOptions {\n  /** The newest editor, read when a verb runs. */\n  readonly latest: React.RefObject<EditorState>;\n  /** Say something in the editor's live region. */\n  readonly announce: (message: string) => void;\n  /** Show a notice the author reads, for a paste that is refused. */\n  readonly notify: (message: string) => void;\n  readonly nesting: NestingSource;\n  readonly components?: ComponentLookup | undefined;\n  /**\n   * In a template, its collection's blocks fields by name, for a pasted\n   * Entry content block; `undefined` while they are being read.\n   */\n  readonly entryFields?: readonly string[] | undefined;\n}\n\n/**\n * The address copied blocks are marked with and checked against: this\n * site's scheme, host and port.\n */\nfunction siteOrigin(): string {\n  return globalThis.location?.origin ?? \"\";\n}\n\n/** The editor's own document, where a menu's copy is asked for. */\nfunction shellDocument(): Document | undefined {\n  return typeof document === \"undefined\" ? undefined : document;\n}\n\n/** The system clipboard, through the editor's document. */\nconst systemWrite: ClipboardWrite = text => {\n  const doc = shellDocument();\n  return doc === undefined ? false : writeToClipboard(doc, text);\n};\n\nexport function useBlockClipboardVerbs({\n  latest,\n  announce,\n  notify,\n  nesting,\n  components,\n  entryFields,\n}: BlockClipboardOptions): BlockClipboardVerbs {\n  const copy = React.useCallback(\n    (write: ClipboardWrite = systemWrite): boolean => {\n      const editorNow = latest.current;\n      const ids = editorNow.selection.ids;\n      const copied = copyOfSelection(editorNow.document, ids, siteOrigin());\n      if (copied === null) return false;\n      const subject = subjectOf(editorNow.document, ids);\n      afterWrite(write(serializeCopiedBlocks(copied)), ok => {\n        if (ok) announce(`${subject} copied.`);\n        else notify(`${NOT_ON_CLIPBOARD}.`);\n      });\n      return true;\n    },\n    [latest, announce, notify]\n  );\n\n  const cut = React.useCallback(\n    (write: ClipboardWrite = systemWrite): boolean => {\n      const editorNow = latest.current;\n      const ids = editorNow.selection.ids;\n      // The removal Delete plans, refused by the same locks in the same\n      // words, so Cut never removes what Delete would keep.\n      const plan = selectionDeletion(editorNow.document, ids);\n      const copied = copyOfSelection(editorNow.document, ids, siteOrigin());\n      if (plan === null || copied === null) return false;\n      if (isRefusal(plan)) {\n        announce(plan.reason);\n        return false;\n      }\n      const locked = lockSentence(editorNow, plan.ops);\n      if (locked !== null) {\n        announce(locked);\n        return false;\n      }\n      // Copied first, and removed only once the clipboard has taken the copy,\n      // so a cut the clipboard refuses keeps the blocks. One apply, one undo\n      // step.\n      const text = serializeCopiedBlocks(copied);\n      afterWrite(write(text), ok => {\n        if (!ok) {\n          notify(`${NOT_ON_CLIPBOARD}, so nothing was cut.`);\n          return;\n        }\n        // A clipboard that answers later leaves the author free to edit in\n        // the meantime. The removal is by id, so it would take those edits\n        // too; the blocks are removed only while they still are what was\n        // copied.\n        const now = copyOfSelection(\n          latest.current.document,\n          ids,\n          copied.origin\n        );\n        if (now === null || serializeCopiedBlocks(now) !== text) {\n          notify(CHANGED_WHILE_CUTTING);\n          return;\n        }\n        if (editorNow.applyAll(plan.ops) === null) return;\n        editorNow.select(plan.nextSelection);\n        announce(`${plan.subject} cut. Undo with ${UNDO_KEYS_SPOKEN}.`);\n      });\n      return true;\n    },\n    [latest, announce, notify]\n  );\n\n  const pasteText = React.useCallback(\n    (text: string): boolean => {\n      const read = readCopiedBlocks(text, siteOrigin());\n      if (read === null) return false;\n      if (read.refusal !== undefined) {\n        notify(read.refusal);\n        return true;\n      }\n      const editorNow = latest.current;\n      const plan = planPaste(\n        editorNow.document,\n        editorNow.selectedId,\n        read.blocks,\n        {\n          nesting,\n          ...(components === undefined ? {} : { components }),\n          // The region the canvas shows: a list previewing its empty\n          // message takes the paste there, as the Add panel's insert does.\n          slots: slotsShowingEmpty(\n            registrySlotSource(),\n            editorNow.listsShowingEmpty\n          ),\n          lockRefusal: ops => lockSentence(editorNow, ops),\n          ...(entryFields === undefined ? {} : { entryFields }),\n        }\n      );\n      if (plan.refusal !== undefined) {\n        notify(plan.refusal);\n        return true;\n      }\n      // The editor's apply judges room, placement and locks once more. It\n      // tells the author itself when a composition, placement or Layers lock\n      // refuses; a cap on the page's size it refuses without a word, as it\n      // does for every other edit.\n      const applied = editorNow.applyAll(plan.ops);\n      if (applied === null) return true;\n      // The copies are selected, as a duplicate's are, through the grammar a\n      // click uses, so a second paste lands after them.\n      const [first, ...rest] = plan.newIds;\n      if (first !== undefined) {\n        editorNow.select(first, \"replace\");\n        for (const id of rest) editorNow.select(id, \"toggle\");\n      }\n      announce(\n        `${subjectOf(applied, plan.newIds)} pasted. Undo with ${UNDO_KEYS_SPOKEN}.`\n      );\n      return true;\n    },\n    [latest, notify, announce, nesting, components, entryFields]\n  );\n\n  const paste = React.useCallback(() => {\n    const doc = shellDocument();\n    if (doc === undefined) return;\n    void readClipboard(doc).then(text => {\n      if (text === undefined || !pasteText(text)) notify(NOTHING_TO_PASTE);\n    });\n  }, [pasteText, notify]);\n\n  return React.useMemo(\n    () => ({ copy, cut, paste, pasteText }),\n    [copy, cut, paste, pasteText]\n  );\n}\n","/**\n * What \"Copy style\" takes from a block, and what a paste says.\n *\n * A copied style is the block's own values, at every state and device, and\n * the classes it wears: its block style, its text style and its shared\n * styles, as its class list holds them. Nothing else: its words, images and\n * links stay where they are. The paste itself is `batchStylePasteOps`, the\n * batch style path every multi-block edit takes, so it is one undo step.\n *\n * Kept in the editor rather than on the system clipboard, so copying a style\n * never replaces text or blocks the author copied.\n *\n * @module style-clipboard\n */\nimport {\n  findNode,\n  type AnyBlockDefinition,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { blockLabel } from \"../panels/add/inserter-catalog\";\n\nimport type { SkippedSettings, StyleSource } from \"./batch-style\";\n\n/** Said when \"Paste style\" is chosen before any style was copied. */\nexport const NOTHING_COPIED_YET =\n  \"Copy a block's style first: choose Copy style on the block that looks right.\";\n\n/**\n * The style \"Copy style\" takes from a block: a copy of its own values and\n * its class list, so a later edit of the block doesn't change what is\n * pasted. `null` for a block that is not on the page.\n */\nexport function copiedStyleOf(\n  document: BlockDocument,\n  id: string\n): StyleSource | null {\n  const node = findNode(document.nodes, id);\n  if (node === undefined) return null;\n  return {\n    styles:\n      node.styles === undefined ? undefined : structuredClone(node.styles),\n    classes: [...(node.classes ?? [])],\n  };\n}\n\n/**\n * The words for what the targets had no place for, one sentence per kind of\n * block (\"3 settings don't apply to Image.\"), or `undefined` when nothing\n * was skipped. Every block of one kind skips the same settings of one\n * source, so each kind is named once.\n */\nexport function skippedSettingsWords(\n  skipped: readonly SkippedSettings[],\n  lookup?: (type: string) => AnyBlockDefinition | undefined\n): string | undefined {\n  const byType = new Map<string, number>();\n  for (const each of skipped) {\n    if (!byType.has(each.type)) byType.set(each.type, each.count);\n  }\n  if (byType.size === 0) return undefined;\n  return [...byType]\n    .map(([type, count]) => {\n      const name = blockLabel(type, lookup);\n      return count === 1\n        ? `1 setting doesn't apply to ${name}.`\n        : `${String(count)} settings don't apply to ${name}.`;\n    })\n    .join(\" \");\n}\n","/**\n * \"Copy style\" and \"Paste style\" for the selected blocks, as verbs every\n * surface shares: the block toolbar's menu, the canvas's right-click menu and\n * the command palette.\n *\n * The copy is held here, for as long as the editor is open; the paste goes\n * through the editor's own apply as one group, so it is one undo step\n * however many blocks it reaches and is refused by every check any other\n * edit meets. It writes the blocks' own styles and classes only, never a\n * shared style, whatever the Style tab's editing bar targets: a paste that\n * changed a shared style would change every block wearing it, on every page.\n *\n * @module style-clipboard-verbs\n */\n\nimport type { AnyBlockDefinition, NamedClass } from \"@nextlyhq/blocks-engine\";\nimport { findNode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { subjectOf } from \"../canvas/selection-ops\";\nimport type { EditorState } from \"../editor-state\";\nimport { designReadOnlyReason, lockViewOf } from \"../inspector/inspector\";\nimport {\n  lockSentence,\n  UNDO_KEYS_SPOKEN,\n} from \"../shell/keyboard-announcements\";\n\nimport { batchStylePasteOps, type StyleSource } from \"./batch-style\";\nimport {\n  copiedStyleOf,\n  NOTHING_COPIED_YET,\n  skippedSettingsWords,\n} from \"./style-clipboard\";\n\n/** The two verbs. */\nexport interface StyleClipboardVerbs {\n  /** Copy the one selected block's style; answers whether it did. */\n  readonly copyStyle: () => boolean;\n  /** Give every selected block the copied style, as one undo step. */\n  readonly pasteStyle: () => void;\n}\n\n/** What the verbs need from the provider that offers them. */\nexport interface StyleClipboardOptions {\n  /** The newest editor, read when a verb runs. */\n  readonly latest: React.RefObject<EditorState>;\n  /** Say something in the editor's live region. */\n  readonly announce: (message: string) => void;\n  /** Show a notice the author reads. */\n  readonly notify: (message: string) => void;\n  /** The site's styles, to tell block styles and text styles apart. */\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\nexport function useStyleClipboardVerbs({\n  latest,\n  announce,\n  notify,\n  library,\n  definitions,\n}: StyleClipboardOptions): StyleClipboardVerbs {\n  // A ref rather than state: nothing is drawn from it, since \"Paste style\"\n  // is always offered and says what to do when nothing was copied.\n  const copied = React.useRef<StyleSource | null>(null);\n\n  const copyStyle = React.useCallback((): boolean => {\n    const editorNow = latest.current;\n    const ids = editorNow.selection.ids;\n    const [only] = ids;\n    // One block's look: with several selected, there is no one to copy.\n    if (ids.length !== 1 || only === undefined) return false;\n    const style = copiedStyleOf(editorNow.document, only);\n    if (style === null) return false;\n    copied.current = style;\n    announce(`Style copied from ${subjectOf(editorNow.document, ids)}.`);\n    return true;\n  }, [latest, announce]);\n\n  const pasteStyle = React.useCallback(() => {\n    const source = copied.current;\n    if (source === null) {\n      notify(NOTHING_COPIED_YET);\n      return;\n    }\n    const editorNow = latest.current;\n    const { document } = editorNow;\n    const ids = editorNow.selection.ids;\n    const held = heldReason(editorNow, ids);\n    if (held !== undefined) {\n      notify(held);\n      return;\n    }\n    const nodes = ids.flatMap(id => {\n      const node = findNode(document.nodes, id);\n      return node === undefined ? [] : [node];\n    });\n    if (nodes.length === 0) return;\n    const plan = batchStylePasteOps(nodes, source, {\n      library,\n      ...(definitions === undefined ? {} : { definitions }),\n    });\n    const skipped = skippedSettingsWords(plan.skipped, definitions);\n    // Shown as well as said: nothing on the page shows a setting that didn't\n    // arrive.\n    const sayExplained = (words: string): void => {\n      notify(words);\n      announce(words);\n    };\n    if (plan.ops.length === 0) {\n      if (skipped !== undefined) sayExplained(skipped);\n      else announce(alreadyWords(nodes.length));\n      return;\n    }\n    const locked = lockSentence(editorNow, plan.ops);\n    if (locked !== null) {\n      notify(locked);\n      return;\n    }\n    // The editor's apply judges the page once more; it says itself why it\n    // refuses.\n    if (editorNow.applyAll(plan.ops) === null) return;\n    if (skipped !== undefined) notify(skipped);\n    announce(pastedWords(subjectOf(document, ids), skipped));\n  }, [latest, announce, notify, library, definitions]);\n\n  return React.useMemo(\n    () => ({ copyStyle, pasteStyle }),\n    [copyStyle, pasteStyle]\n  );\n}\n\n/**\n * Why the paste is refused, from the first selected block whose design is\n * held: ONE held block refuses the whole paste, as one lock refuses a\n * delete of several, since the group is applied whole or not at all. The\n * Style tab's own reading, so the paste is refused where its fields are\n * read-only.\n */\nfunction heldReason(\n  editor: EditorState,\n  ids: readonly string[]\n): string | undefined {\n  const view = lockViewOf(editor);\n  for (const id of ids) {\n    const held = designReadOnlyReason(editor.document, id, view);\n    if (held !== undefined) return held;\n  }\n  return undefined;\n}\n\n/** Said when every target already looks like the source. */\nfunction alreadyWords(count: number): string {\n  return count === 1\n    ? \"This block already has this style.\"\n    : \"These blocks already have this style.\";\n}\n\n/** Said after a paste: what changed, what was skipped, and how to undo. */\nfunction pastedWords(subject: string, skipped: string | undefined): string {\n  return [\n    `Style pasted on ${subject}.`,\n    ...(skipped === undefined ? [] : [skipped]),\n    `Undo with ${UNDO_KEYS_SPOKEN}.`,\n  ].join(\" \");\n}\n","\"use client\";\n\n/**\n * The contexts `BlockKeyboardActions` provides and the hooks that read them:\n * the block actions the toolbar and menus run, the nesting rules to judge a\n * placement by, the selection's offer, and the toolbar's focus slot.\n *\n * Each context is exported with its type written out, as the package's\n * declaration build needs for an exported value; the values are unchanged.\n *\n * @module block-actions-context\n */\n\nimport {\n  registryNestingSource,\n  type BlockDocument,\n  type NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { MoveDirection } from \"../canvas/keyboard-move\";\nimport type { SelectionOffer } from \"../canvas/selection-offer\";\nimport type { TurnIntoOffer } from \"../canvas/turn-into-verb\";\n\n/**\n * The structural verbs, as callables.\n *\n * Published so a POINTER surface can press exactly what a keystroke presses.\n * The floating toolbar offers the same five actions, and a toolbar that applied\n * its own ops would be a second answer to \"what does duplicate do\" — which an\n * author meets as two buttons that disagree, months after the second one was\n * written.\n *\n * Every one is silent when it has no subject, so a caller may press any of them\n * without first asking whether it applies. `toolbarActions` answers that\n * separately, for drawing a control as unavailable rather than for guarding the\n * call.\n */\nexport interface BlockActions {\n  /** Move the selection one step in `direction`, lock permitting. */\n  readonly move: (direction: MoveDirection) => void;\n  /** Delete the selection and everything inside it, lock permitting. */\n  readonly delete: () => void;\n  /** Copy the selection in beside itself and select the copy. */\n  readonly duplicate: () => void;\n  /** Put the selection on the clipboard, to paste on this page or another. */\n  readonly copy: () => void;\n  /** Put the selection on the clipboard and remove it, lock permitting. */\n  readonly cut: () => void;\n  /** Paste copied blocks where a clicked block would land. */\n  readonly paste: () => void;\n  /**\n   * Take the one selected block's look: its own values and the styles it\n   * wears. Optional, so a host built before it keeps compiling.\n   */\n  readonly copyStyle?: () => void;\n  /** Give every selected block the copied look, as one undo step. */\n  readonly pasteStyle?: () => void;\n  /** Select the container holding the selection. */\n  readonly selectParent: () => void;\n  /**\n   * Begin storing the selection in the pattern library.\n   *\n   * Unlike the four above it this runs NO op: it hands the gesture back to the\n   * host, which owns the library, the form that names what is saved and the\n   * write that stores it. It travels with the others because every surface over\n   * these verbs — toolbar, context menu, palette — must reach it the same way,\n   * and a second channel for one verb is how one surface comes to offer what\n   * another cannot run.\n   *\n   * No keystroke is bound to it here. The others are direct manipulations of a\n   * selection an author is looking at; this opens a form, and a shortcut that\n   * opens a modal belongs to the host's own key map rather than to the canvas.\n   */\n  readonly saveAsPattern: () => void;\n  /**\n   * Begin saving the block's look as a shared style, handed to the host as\n   * the pattern save is. Absent where the host offers no shared styles.\n   */\n  readonly saveAsSharedStyle?: () => void;\n  /**\n   * Open the selected placement's component in its own view, through the\n   * host. Like Save as pattern it runs no op: where the component opens, and\n   * whether this author may, are the host's. Silent for any other selection.\n   * Optional, so a host built before it keeps compiling.\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. Like `saveAsPattern`, this\n   * hands the gesture to the host, which owns the form and the write. Absent\n   * where the host offers no components.\n   */\n  readonly turnIntoComponent?: () => void;\n  /** Detach the selected placement, duplicate its component, update a pattern. */\n  readonly detachComponent?: () => void;\n  readonly duplicateComponent?: () => void;\n  readonly updatePattern?: () => void;\n  /** Put the selected blocks in a new Box at their place, as one step. */\n  readonly wrapInBox?: () => void;\n  /** Replace the selected container by its blocks, as one step. */\n  readonly unwrap?: () => void;\n  /**\n   * Turn the selected block into another type (`\"core/heading\"`), as one undo\n   * step, saying what it removes or why it cannot. Optional, so a host built\n   * before it keeps compiling.\n   */\n  readonly turnInto?: (to: string) => void;\n  /**\n   * \"Turn into\" for a block in a page the caller holds rather than the\n   * selection: the format bar's, which writes the words typed first and turns\n   * the block in the page that left. The same judging and words as\n   * {@link turnInto}.\n   */\n  readonly turnIntoIn?: {\n    readonly choices: (\n      document: BlockDocument,\n      id: string\n    ) => readonly TurnIntoOffer[];\n    readonly run: (document: BlockDocument, id: string, to: string) => void;\n  };\n}\n\n/**\n * The verbs, for a surface rendered under {@link BlockKeyboardActions}.\n *\n * `null` until a provider is above it, which {@link useBlockActionsContext}\n * turns into a thrown error rather than a silently inert toolbar.\n */\nexport const BlockActionsContext: React.Context<BlockActions | null> =\n  React.createContext<BlockActions | null>(null);\n\n/**\n * The nesting rules the editor is judging placements by, for surfaces below it.\n *\n * A SECOND context rather than a field on {@link BlockActions}, because the two\n * are different kinds of thing: those are verbs to run, this is a rule source to\n * ask. Folding it in would make every consumer of the verbs re-render when a\n * host swapped its rules, and would put a non-verb in a type whose name promises\n * verbs.\n *\n * `null` means no provider, which {@link useNestingSource} answers with the\n * registry — the same default every surface here already applies.\n */\nexport const NestingContext: React.Context<NestingSource | null> =\n  React.createContext<NestingSource | null>(null);\n\n/**\n * The verbs for the current selection, computed once for every surface.\n *\n * The bar, the right-click menu and the palette each need the same list, and\n * `toolbarActions` is not a cheap read: deciding whether a selection can be\n * saved BUILDS the document a save would store — it clones the selected forest,\n * re-identifies it and surveys the result — because that is what makes the\n * answer exact. Asked three times, an ordinary edit copies and walks a large\n * selection three times before anything is drawn.\n *\n * Published from here because this is the one place above all three that\n * already holds the editor and the rules they must agree about.\n */\nexport const SelectionActionsContext: React.Context<SelectionOffer | null> =\n  React.createContext<SelectionOffer | null>(null);\n\nexport function useSelectionActionsContext(): SelectionOffer | null {\n  return React.useContext(SelectionActionsContext);\n}\n\nexport const ToolbarFocusContext: React.Context<ToolbarFocusSlot | null> =\n  React.createContext<ToolbarFocusSlot | null>(null);\n\n/**\n * The nearest provider's toolbar focus slot, or `null` outside one: the\n * block toolbar puts its focus call here for Alt+F10.\n */\nexport function useToolbarFocusSlot(): ToolbarFocusSlot | null {\n  return React.useContext(ToolbarFocusContext);\n}\n\n/**\n * The verbs from the nearest {@link BlockKeyboardActions}.\n *\n * Throws when there is none. A toolbar without them would render its buttons\n * and do nothing on every press, which looks like a broken editor rather than\n * like a missing wrapper — and it would reach a person before it reached a\n * developer.\n */\nexport function useBlockActionsContext(): BlockActions {\n  const actions = React.useContext(BlockActionsContext);\n  if (actions === null) {\n    throw new Error(\n      \"[@nextlyhq/builder] Block actions are only available inside \" +\n        \"<BlockKeyboardActions>. Render it as an ancestor of whatever uses them.\"\n    );\n  }\n  return actions;\n}\n\n/**\n * The nesting rules to judge a placement by, from the nearest provider.\n *\n * Falls back to the registry, which is what the canvas, the insert panel and the\n * keyboard route all default to — so a surface outside a provider answers the\n * way it did before this existed.\n *\n * It exists because a host MAY supply its own rules, and until this a surface\n * had no way to reach them: `BlockKeyboardActions` took a `nesting` option and\n * kept it, so the keyboard enforced the host's rules while the toolbar and the\n * context menu consulted the registry. One selection could then be offered on\n * one surface and refused on another, for the same document.\n */\nexport function useNestingSource(): NestingSource {\n  const supplied = React.useContext(NestingContext);\n  // Memoised on the supplied value so a surface that depends on the identity —\n  // `toolbarActions` is called inside a memo keyed on its arguments — is not\n  // handed a new object every render.\n  return React.useMemo(() => supplied ?? registryNestingSource(), [supplied]);\n}\n\n/**\n * Holds the call that finds an editor's block toolbar's tab stop, which\n * answers `null` while no bar is drawn.\n */\nexport type ToolbarFocusSlot = React.MutableRefObject<\n  (() => HTMLElement | null) | null\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 * What `useBlockKeyboardActions` takes and returns: the verbs shared with the\n * toolbar, the host's shared-style and component verbs, the options, the\n * result, and the slot the canvas frame is read into.\n *\n * @module keyboard-actions-options\n */\n\nimport type { ComponentLookup, NestingSource } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { BlockClipboardVerbs } from \"../canvas/block-clipboard-verbs\";\nimport type { OfferSignal, SelectionOffer } from \"../canvas/selection-offer\";\nimport type {\n  ComponentVerbsOffer,\n  ToolbarAction,\n  ToolbarActionId,\n  TurnIntoChoice,\n} from \"../canvas/toolbar-actions\";\nimport type { EditorState } from \"../editor-state\";\nimport type { SharedStyleOffer } from \"../styles/shared-style-target\";\n\nimport type { BlockActions, ToolbarFocusSlot } from \"./block-actions-context\";\n\n/**\n * The verbs for the current selection, as a surface OUTSIDE the provider is\n * handed them: which are offered and why not, and a way to run one.\n *\n * The inspector is drawn beside the canvas rather than under this provider,\n * and its card offers Duplicate and Delete. Handing it these is what keeps\n * that menu to the toolbar's verdicts and verbs rather than a second copy.\n */\nexport interface SharedBlockVerbs {\n  /** What to show while no menu is open: the locks are not asked. */\n  readonly actions: readonly ToolbarAction[];\n  /** The same verbs with the locks asked, for a menu as it opens. */\n  readonly withLocks: () => readonly ToolbarAction[];\n  /** Listen for a change to what `withLocks` would answer; optional. */\n  readonly subscribe?: OfferSignal[\"subscribe\"];\n  readonly run: (id: ToolbarActionId) => void;\n}\n\nexport interface BlockKeyboardActionsOptions {\n  /**\n   * The editor whose document these move blocks in.\n   *\n   * The whole state rather than a document and an `apply` separately: the move\n   * is computed against a document and applied through a store, and passing\n   * them apart lets a caller hand a document from one render to an `apply`\n   * bound to another.\n   */\n  editor: EditorState;\n  /**\n   * The nesting rule source, for explaining a refused move.\n   *\n   * Optional, defaulting to the registry — which is what the canvas asks, so a\n   * refusal reads the same whether the author dragged the block or moved it\n   * with the keyboard. Present as an option only so a test can supply a rule\n   * set without registering blocks globally.\n   */\n  nesting?: NestingSource;\n  /**\n   * The component definitions the canvas draws, for judging a moved instance.\n   *\n   * An instance node's own type is not a registered block, so the nesting\n   * rule restricts it nowhere; a move is judged by the ROOTS of the definition\n   * it draws instead, resolved through this map as a drop of the same instance\n   * is (`placementTypesOf`). Optional, because a host whose library has not\n   * loaded has nothing to resolve against — an unresolvable instance is judged\n   * by its own type, which is how a placeholder stays movable.\n   */\n  definitions?: ComponentLookup;\n  /**\n   * Begin storing the selection in the library, when the author asks to.\n   *\n   * Supplied by the host because everything the gesture needs is the host's:\n   * which collection a pattern goes in, what it is called, and the route that\n   * writes it. Nothing here can do any of that, and a builder that guessed would\n   * be guessing about somebody else's schema.\n   */\n  onSaveAsPattern: () => void;\n  /**\n   * Whether the author may create a pattern at all. Defaults to true.\n   *\n   * Supplied by the host for the same reason `onSaveAsPattern` is: the grant is\n   * held against the collection a pattern goes in, a site may have renamed it,\n   * and nothing here can know either. A builder that guessed would be guessing\n   * about somebody else's schema.\n   *\n   * Permissive while unknown — see `toolbarActions`, which explains why this one\n   * refusal defaults the opposite way to the rest.\n   */\n  mayCreatePattern?: boolean;\n  /**\n   * Open a placed component in its own view, given its id and the\n   * placement's node id. Supplied by the host, which knows where that view is\n   * and whether this author may update components; omitted, \"Edit component\"\n   * is not offered anywhere.\n   */\n  onEditComponent?: (componentId: string, nodeId: string) => void;\n  /**\n   * Whether the bindings are live. Defaults to true.\n   *\n   * A host that mounts the canvas inside something modal turns them off rather\n   * than unmounting the canvas, so the selection survives whatever is over it.\n   */\n  enabled?: boolean;\n  /**\n   * Begin typing the selected block's text in place, reporting whether it\n   * could be.\n   *\n   * The keyboard route to the gesture a double-click performs. A pointer-only\n   * way into editing would leave the text of every block unreachable without a\n   * mouse, which is the plainest kind of WCAG 2.1.1 failure — and it is a real\n   * one here, because the canvas is where the text is.\n   *\n   * Optional: a host that has not wired inline editing registers no binding at\n   * all, rather than one that presses and does nothing.\n   */\n  onEditText?: (nodeId: string) => boolean;\n  /**\n   * Making components from a selection, where the host has a component\n   * library: whether the author may, and the gestures that open the host's\n   * forms. Absent, neither verb is offered.\n   */\n  components?: ComponentVerbsHost;\n  /**\n   * Saving a block's look as a shared style, where the host has the site's\n   * shared styles: what it knows of them and the author's right, and the\n   * gesture that opens its form. Absent, the verb is not offered.\n   */\n  sharedStyles?: SharedStyleVerbHost;\n  /**\n   * Esc pressed with no block selected, which otherwise does nothing: a host\n   * editing a look on its own leaves it, back to editing blocks.\n   *\n   * @experimental Settles with the Design panel's Block looks group.\n   */\n  onEscapeWithoutSelection?: () => void;\n  /**\n   * The header or footer selected on the canvas, while one is: Delete and\n   * Backspace then remove nothing and announce `refusal`, the host's words\n   * for where it is changed (\"The site header isn't part of this page.\n   * Change it in Page settings.\"). The other block keys have no subject.\n   */\n  selectedRegion?: { readonly refusal: string };\n  /**\n   * \"/\" pressed with a block selected, or with nothing selected, while no\n   * text is being typed: the host opens its in-place picker there, adding\n   * by the placement rule. Absent, \"/\" is left to the browser and Help does\n   * not list it.\n   *\n   * @experimental Settles with the in-place picker.\n   */\n  onAddBlockHere?: () => void;\n}\n\n/**\n * The host's side of \"Save as shared style…\".\n *\n * @experimental Settles with the shared-styles editor.\n */\nexport interface SharedStyleVerbHost extends SharedStyleOffer {\n  readonly onSaveAsSharedStyle: () => void;\n}\n\n/**\n * The host's side of \"Turn into component…\".\n *\n * @experimental Settles when the composition API ships.\n */\nexport interface ComponentVerbsHost extends ComponentVerbsOffer {\n  /**\n   * Open the form, told which way is open: replacing the selection with a\n   * placement, keeping it and saving a copy, or both, with the reason for a\n   * way that is not.\n   */\n  readonly onTurnIntoComponent: (choice: TurnIntoChoice) => void;\n  /** Detach the selected placement. Absent, with no definitions, Detach is not offered. */\n  readonly onDetachComponent?: () => void;\n  readonly onDuplicateComponent?: () => void;\n  /** Update a pattern. Absent, with no `mayUpdatePattern`, it is not offered. */\n  readonly onUpdatePattern?: () => void;\n}\n\n/** The verbs the host runs for the menu's component group. */\nexport type ComponentVerbId =\n  | \"turn-into-component\"\n  | \"detach-component\"\n  | \"duplicate-component\"\n  | \"update-pattern\";\n\n/** The host's gesture for one component verb, if it offers it. */\nexport function componentVerbRunner(\n  host: ComponentVerbsHost,\n  id: ComponentVerbId,\n  /** Which way \"Turn into component…\" may go, asked when it was pressed. */\n  choice: () => TurnIntoChoice\n): (() => void) | undefined {\n  const runners: Record<ComponentVerbId, (() => void) | undefined> = {\n    \"turn-into-component\": () => host.onTurnIntoComponent(choice()),\n    \"detach-component\": host.onDetachComponent,\n    \"duplicate-component\": host.onDuplicateComponent,\n    \"update-pattern\": host.onUpdatePattern,\n  };\n  return runners[id];\n}\n\n/** What the hook hands back: the region's text, and the verbs behind the keys. */\nexport interface BlockKeyboardActionsResult {\n  /** The live region's current text. Owned by one region and one only. */\n  readonly announcement: string;\n  /** The same verbs the keystrokes run, for a pointer surface to press. */\n  readonly actions: BlockActions;\n  /**\n   * The rules this resolved placements by: the host's, or the registry.\n   *\n   * Returned so the provider can publish the SAME source it enforced, rather\n   * than every surface below resolving the default again and a host-supplied\n   * one reaching only the keyboard.\n   */\n  readonly nesting: NestingSource;\n  /**\n   * What to OFFER for the current selection, computed once for every surface.\n   *\n   * Told apart from {@link BlockKeyboardActionsResult.actions} by the question\n   * each answers: those are verbs to RUN, this is the list of what may be run\n   * and why not. Returned so the provider publishes the same list it built\n   * rather than each surface rebuilding it — and rebuilding it is not cheap,\n   * because deciding whether a selection can be saved builds the document a\n   * save would store. Its depth moves are judged with the position function\n   * the move verb itself runs; its locks are asked only by a menu that opens.\n   */\n  readonly offer: SelectionOffer;\n  /** `offer.actions`, as this result has always carried it. */\n  readonly selectionActions: ToolbarAction[];\n  /** `offer.depthMoves`, as this result has always carried it. */\n  readonly depthMoves: SelectionOffer[\"depthMoves\"];\n  /**\n   * Where this editor's block toolbar puts the call that finds its tab stop,\n   * for Alt+F10 to focus. Held per editor rather than looked up in the\n   * document, which may hold another editor's toolbar first.\n   */\n  readonly toolbarFocus: ToolbarFocusSlot;\n  /**\n   * Where the canvas's frame is put for Escape to send focus back to, filled\n   * by {@link BlockKeyboardActions}. Empty, Escape moves the selection from\n   * wherever it is pressed.\n   */\n  readonly canvasFrame: CanvasFrameSlot;\n  /**\n   * Copy, Cut and Paste, for the clipboard events {@link BlockKeyboardActions}\n   * listens for: the same verbs the menus run, writing to the event in hand.\n   */\n  readonly clipboard: BlockClipboardVerbs;\n}\n\n/**\n * Holds the canvas's frame, or `null` while there is none.\n *\n * A slot rather than a context read inside the hook: the canvas frame's\n * context changes with every zoom and resize the canvas reports, and the\n * Escape binding needs only the frame, when the key lands. Filled by a child\n * of its own, so a resize re-renders that child alone.\n */\nexport type CanvasFrameSlot = React.MutableRefObject<HTMLIFrameElement | null>;\n","\"use client\";\n\n/**\n * Moving the selected block with the keyboard.\n *\n * **This is not a convenience over dragging; it is the accessible way to do the\n * same job.** WCAG 2.2 adds SC 2.5.7 *Dragging Movements* (AA), which requires\n * any function operated by a drag to be achievable without one, and SC 2.1.1\n * *Keyboard* (A) requires it to be operable from a keyboard at all. A canvas\n * that can only reorder by pointer fails both. Building this first means the\n * drag path arrives as an enhancement over a working baseline rather than as\n * the only way in.\n *\n * **The rule lives in `keyboard-move`; this is the wiring.** That module decides\n * where a block lands, what the move means, and which slot it may vacate. Every\n * decision worth asserting is already made there, without React and without a\n * DOM. What is only true here is which keys ask for it, when they are allowed\n * to, and that the answer reaches the one place a document changes.\n *\n * This module is the hook and its provider, and the entry for the rest: the\n * keys and what each action says are in `keyboard-announcements.ts`, the\n * contexts the toolbar and menus read in `block-actions-context.ts`, and what\n * the hook takes and returns in `keyboard-actions-options.ts`.\n *\n * @module keyboard-actions\n */\n\nimport {\n  registryNestingSource,\n  type BlockDocument,\n  type NamedClass,\n  type NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport { useIsomorphicLayoutEffect, useShortcuts } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  BlockClipboardEvents,\n  CLIPBOARD_KEY_HELP,\n} from \"../canvas/block-clipboard-events\";\nimport { useBlockClipboardVerbs } from \"../canvas/block-clipboard-verbs\";\nimport {\n  CANVAS_ESCAPE_PRIORITY,\n  escapeOutcome,\n  modalIsOpen,\n  pressOrigin,\n  returnFocusToCanvas,\n} from \"../canvas/canvas-escape\";\nimport { useCanvasFrame } from \"../canvas/canvas-frame-context\";\nimport {\n  keyboardMovePosition,\n  type MoveDirection,\n} from \"../canvas/keyboard-move\";\nimport { usePreviewedCollection } from \"../canvas/previewed-entry\";\nimport { offerSignal, useSelectionOffer } from \"../canvas/selection-offer\";\nimport {\n  isRefusal,\n  selectionDeletion,\n  selectionDuplication,\n  selectionMove,\n} from \"../canvas/selection-ops\";\nimport { planUnwrap, planWrap } from \"../canvas/selection-wrap\";\nimport {\n  patternSaveRefusal,\n  SAVE_PATTERN_GRANT_REFUSAL,\n  toolbarActions,\n  turnIntoChoice,\n  type MoveJudge,\n  type MovePosition,\n} from \"../canvas/toolbar-actions\";\nimport { runTurnInto, turnIntoOffers } from \"../canvas/turn-into-verb\";\nimport type { EditorState } from \"../editor-state\";\nimport { escapeFieldEdit } from \"../field-edit\";\nimport { lockViewOf } from \"../inspector/inspector\";\nimport { placedComponentId } from \"../inspector/instance-inspector\";\nimport { lockedBlockWording, lockRefusalWording } from \"../lock-refusal\";\nimport { lockBlockingMove } from \"../locking\";\nimport {\n  nestingRefusalForMove,\n  refusalAnnouncement,\n  unmovedAnnouncement,\n} from \"../move-refusal\";\nimport { pathTo } from \"../panels/layers/layers\";\nimport { useStyleClipboardVerbs } from \"../styles/style-clipboard-verbs\";\n\nimport {\n  type BlockActions,\n  BlockActionsContext,\n  NestingContext,\n  SelectionActionsContext,\n  ToolbarFocusContext,\n  type ToolbarFocusSlot,\n} from \"./block-actions-context\";\nimport { blockActionRunners } from \"./builder-commands\";\nimport { useNoticeSink } from \"./builder-notices\";\nimport {\n  type BlockKeyboardActionsOptions,\n  type BlockKeyboardActionsResult,\n  type CanvasFrameSlot,\n  type ComponentVerbId,\n  componentVerbRunner,\n  type SharedBlockVerbs,\n} from \"./keyboard-actions-options\";\nimport {\n  deletionAnnouncement,\n  EFFECT_ANNOUNCEMENT,\n  lockSentence,\n  MOVE_KEYS,\n  UNDO_KEYS_SPOKEN,\n} from \"./keyboard-announcements\";\n\n// The keys and what is announced, the contexts the toolbar and menus read,\n// and what the hook takes and returns live in modules of their own beside\n// it; every name this module exported still is.\n// Part of this module's exported names; no importer in the package reads it.\n// fallow-ignore-next-line unused-type\nexport type { ToolbarFocusSlot } from \"./block-actions-context\";\nexport {\n  type BlockActions,\n  useBlockActionsContext,\n  useNestingSource,\n  useSelectionActionsContext,\n  useToolbarFocusSlot,\n} from \"./block-actions-context\";\nexport type {\n  BlockKeyboardActionsOptions,\n  BlockKeyboardActionsResult,\n  ComponentVerbsHost,\n  SharedBlockVerbs,\n  SharedStyleVerbHost,\n} from \"./keyboard-actions-options\";\nexport { MOVE_KEYS } from \"./keyboard-announcements\";\n\n/**\n * Register the move bindings for as long as the caller is mounted.\n *\n * The verbs come back as well as the announcement, and the reason is the one\n * this hook's earlier note argued against: a returned handler could be bound to\n * a second set of keys. What settles it is that the alternative is worse. The\n * toolbar needs the same five verbs AND the same live region, and a surface\n * that reimplemented either would produce two answers to one gesture — a second\n * region that talks over the first, or a button whose op drifts from its\n * keystroke's. Sharing them is what keeps there being one of each.\n *\n * The keys stay this module's alone: nothing here is bindable by a caller, and\n * {@link BlockKeyboardActions} is the only supported way to reach the verbs.\n */\nexport function useBlockKeyboardActions({\n  mayCreatePattern = true,\n  editor,\n  enabled = true,\n  onEditText,\n  nesting,\n  definitions,\n  onSaveAsPattern,\n  onEditComponent,\n  components,\n  sharedStyles,\n  onEscapeWithoutSelection,\n  onAddBlockHere,\n  selectedRegion,\n}: BlockKeyboardActionsOptions): BlockKeyboardActionsResult {\n  // Read when the key lands, so a host's newest callback is the one called.\n  const escapeWithoutSelection = React.useRef(onEscapeWithoutSelection);\n  escapeWithoutSelection.current = onEscapeWithoutSelection;\n  // The header or footer selected, read when Delete lands for the same reason.\n  const latestRegion = React.useRef(selectedRegion);\n  latestRegion.current = selectedRegion;\n  /*\n   * The same rule source the pointer route asks, defaulted the way the insert\n   * panel defaults it. Taken as an option rather than resolved here only so a\n   * test can supply one; a host passing nothing gets the registry, which is\n   * what the canvas passes too — two surfaces asking one source, so a refusal\n   * cannot be explained one way on a drag and another on a keypress.\n   */\n  const nestingSource = React.useMemo(\n    () => nesting ?? registryNestingSource(),\n    [nesting]\n  );\n  // The message a live region reads out. Held as state rather than written to\n  // the DOM directly so React owns the node — a region mutated behind React's\n  // back is reverted by the next render, silently and only sometimes.\n  const [announcement, setAnnouncement] = React.useState(\"\");\n\n  // A move can repeat the previous effect — two presses of alt+ArrowDown are\n  // both \"Block moved\" — and a live region does not re-announce text that did\n  // not change. The zero-width space alternates the string so each press is a\n  // new value, without changing what is read aloud.\n  const announce = React.useCallback((message: string) => {\n    setAnnouncement(previous =>\n      previous.replace(/\\u200b$/, \"\") === message ? `${message}\\u200b` : message\n    );\n  }, []);\n\n  // The newest editor, reachable from a binding registered once. The shortcut\n  // layer is deliberately not rebuilt when its bindings change — rebuilding\n  // moves the layer to the top of its depth and silently changes precedence —\n  // so a closure captured at registration would go on applying moves against\n  // the document from that render.\n  const latest = React.useRef(editor);\n  latest.current = editor;\n  // The canvas's frame, read when Escape lands for the same reason: it is\n  // where focus goes back to from a panel, and the frame is registered after\n  // the bindings are. See `CanvasFrameSlot` for who fills it.\n  const latestFrame: CanvasFrameSlot = React.useRef<HTMLIFrameElement | null>(\n    null\n  );\n  const toolbarFocus: ToolbarFocusSlot = React.useRef<\n    (() => HTMLElement | null) | null\n  >(null);\n\n  const deleteSelected = React.useCallback(() => {\n    const editorNow = latest.current;\n    // A header or footer selected: nothing of the page's is, so nothing is\n    // removed, and the host's words say where it is changed instead.\n    const region = latestRegion.current;\n    if (editorNow.selectedId === null && region !== undefined) {\n      announce(region.refusal);\n      return;\n    }\n    const plan = selectionDeletion(editorNow.document, editorNow.selection.ids);\n    // `null` means there is nothing to delete — no selection, or ids an undo\n    // has since removed. Nothing is applied and nothing is said, because there\n    // is no event to report.\n    if (plan === null) return;\n\n    /*\n     * A lock is a POLICY refusal, so it is announced where a structural one is\n     * not. Nothing about the page explains why the key did nothing, the remedy\n     * is one the author can act on, and a keyboard user has no badge to look\n     * at. ONE lock refuses the whole group, because the group is atomic and\n     * there is no half-done delete to fall back to.\n     */\n    if (isRefusal(plan)) {\n      announce(plan.reason);\n      return;\n    }\n    const locked = lockSentence(editorNow, plan.ops);\n    if (locked !== null) {\n      announce(locked);\n      return;\n    }\n\n    if (editorNow.applyAll(plan.ops) === null) return;\n\n    // Moved only after the store accepted the removal. Moving it first would\n    // leave the author pointed at a neighbour while the blocks they asked to\n    // delete are still there.\n    editorNow.select(plan.nextSelection);\n    announce(deletionAnnouncement(plan.subject, plan.descendants));\n  }, [announce]);\n\n  /*\n   * Copy, Cut and Paste, through the clipboard. A refused paste is shown as\n   * a notice as well as said, since a paste from the keys has no control to\n   * dim beside it and nothing on the page says why nothing arrived.\n   */\n  const notify = useNoticeSink();\n  // In a template, the fields a pasted Entry content block may name.\n  const blocksFields = usePreviewedCollection()?.blocksFields;\n  const entryFields = React.useMemo(\n    () => blocksFields?.map(field => field.name),\n    [blocksFields]\n  );\n  const clipboard = useBlockClipboardVerbs({\n    latest,\n    announce,\n    notify,\n    nesting: nestingSource,\n    components: definitions,\n    entryFields,\n  });\n\n  const duplicateSelected = React.useCallback(() => {\n    const editorNow = latest.current;\n    const plan = selectionDuplication(\n      editorNow.document,\n      editorNow.selection.ids\n    );\n    // `null` means there is nothing to duplicate, or a position the op\n    // vocabulary cannot express. Nothing is applied and nothing is said.\n    if (plan === null) return;\n\n    /*\n     * A lock does NOT stop a duplication. The command layer must not let an\n     * author move or delete a locked node, and duplicating does neither — the\n     * originals stay exactly where they are. Refusing would mean an author\n     * could not take copies of the blocks they had most deliberately protected.\n     *\n     * A slot's lock is another matter: a copy placed in a slot whose blocks\n     * are fixed changes what that slot holds, so the slot's lock refuses it.\n     */\n    const locked = lockSentence(editorNow, plan.ops);\n    if (locked !== null) {\n      announce(locked);\n      return;\n    }\n    if (editorNow.applyAll(plan.ops) === null) return;\n\n    /*\n     * Selection follows the copies: they are what the author is now working on,\n     * and leaving the originals selected would send the next edit to the wrong\n     * half of two identical runs.\n     *\n     * Built through the same grammar a click uses — one replace then toggles —\n     * rather than by writing a selection object directly, so there is no second\n     * way to construct one and no second place that has to remember the\n     * outermost rule.\n     */\n    const [first, ...rest] = plan.newIds;\n    if (first !== undefined) {\n      editorNow.select(first, \"replace\");\n      for (const id of rest) editorNow.select(id, \"toggle\");\n    }\n    announce(`${plan.subject} duplicated. Undo with ${UNDO_KEYS_SPOKEN}.`);\n  }, [announce]);\n\n  /**\n   * Wrapping the selection in a Box, or unwrapping the selected container,\n   * as ONE step: refused with its reason, where the placement rules forbid\n   * the result or a lock holds a block it moves, and said either way.\n   * Selection follows what was made: the new Box, or the unwrapped blocks.\n   */\n  const runWrap = React.useCallback(\n    (kind: \"wrap\" | \"unwrap\") => {\n      const editorNow = latest.current;\n      const [only] = editorNow.selection.ids;\n      const plan =\n        kind === \"wrap\"\n          ? planWrap(editorNow.document, editorNow.selection.ids, nestingSource)\n          : only === undefined\n            ? null\n            : planUnwrap(editorNow.document, only, nestingSource);\n      if (plan === null) return;\n      if (isRefusal(plan)) {\n        announce(plan.reason);\n        return;\n      }\n      const locked = lockSentence(editorNow, plan.ops);\n      if (locked !== null) {\n        announce(locked);\n        return;\n      }\n      if (editorNow.applyAll(plan.ops) === null) return;\n      const [first, ...rest] = plan.select;\n      if (first !== undefined) {\n        editorNow.select(first, \"replace\");\n        for (const id of rest) editorNow.select(id, \"toggle\");\n      }\n      announce(\n        `${kind === \"wrap\" ? \"Wrapped in a box\" : \"Unwrapped\"}. Undo with ${UNDO_KEYS_SPOKEN}.`\n      );\n    },\n    [announce, nestingSource]\n  );\n\n  /**\n   * Reordering a selection that holds more than one block.\n   *\n   * Only `up` and `down`. Depth is the other axis, and a set does not have one\n   * answer for it: `indent` appends to the container above, so two blocks\n   * indenting together would arrive in an order neither of them was in.\n   *\n   * Returns whether it handled the press, so the single-block path below stays\n   * exactly as it was for the case it already served.\n   */\n  const moveSet = React.useCallback(\n    (direction: MoveDirection): boolean => {\n      const editorNow = latest.current;\n      const ids = editorNow.selection.ids;\n      if (ids.length <= 1 || (direction !== \"up\" && direction !== \"down\")) {\n        return false;\n      }\n\n      const plan = selectionMove(editorNow.document, ids, direction);\n      // A set at the edge of its container, exactly as one block there: the\n      // press did nothing and that is the answer. Handled either way, because\n      // falling through would move the PRIMARY alone and break the set apart.\n      if (plan === null) return true;\n\n      /*\n       * A lock and a split selection are both POLICY refusals, so both are\n       * announced where a structural one is not. Nothing on the page explains\n       * why the key did nothing, and a keyboard author has no dimmed button to\n       * look at.\n       */\n      if (isRefusal(plan)) {\n        announce(plan.reason);\n        return true;\n      }\n      const locked = lockSentence(editorNow, plan.ops);\n      if (locked !== null) {\n        announce(locked);\n        return true;\n      }\n\n      if (editorNow.applyAll(plan.ops) !== null) {\n        announce(`${plan.subject} moved.`);\n      }\n      // The selection deliberately does not change, for the same reason it does\n      // not for one block: a run of presses walks the same set across the list.\n      return true;\n    },\n    [announce]\n  );\n\n  /*\n   * Where a block's move goes, with the component definitions this provider\n   * was given. ONE function for the verb below and for the menu's Move in and\n   * Move out availability, so the menu never offers a move the verb, asked\n   * with other inputs, would find nowhere to make.\n   */\n  const movePosition = React.useCallback<MovePosition>(\n    (document, id, direction) =>\n      keyboardMovePosition(document.nodes, id, direction, definitions),\n    [definitions]\n  );\n\n  /*\n   * Whether the placement rule refuses a move, and its words: the one call\n   * the verb below refuses by and the menu's Move in and Move out are dimmed\n   * by, with the same rules and component definitions.\n   */\n  const placementRefusal = React.useCallback<MoveJudge>(\n    (document, id, to) =>\n      nestingRefusalForMove(document, id, to, nestingSource, definitions),\n    [nestingSource, definitions]\n  );\n\n  const moveSelected = React.useCallback(\n    (direction: MoveDirection) => {\n      if (moveSet(direction)) return;\n\n      const editorNow = latest.current;\n      const selectedId = editorNow.selectedId;\n      if (selectedId === null) return;\n\n      // Only the node itself, never its subtree: moving a container leaves\n      // a locked child in the same slot at the same index, so the lock is\n      // not violated and refusing would let one locked caption freeze the\n      // whole section around it.\n      const lockedNode = lockBlockingMove(editorNow.document, selectedId);\n      if (lockedNode !== undefined) {\n        announce(\n          refusalAnnouncement(lockedBlockWording(lockedNode, selectedId))\n        );\n        return;\n      }\n\n      // The component definitions go with it so an indent into a component\n      // instance enters a slot the component exposes.\n      const move = movePosition(editorNow.document, selectedId, direction);\n      // `null` is an ordinary answer: the first block cannot move up, and a\n      // top-level block cannot outdent. Refusing quietly is right — a block\n      // at the end of its container has nowhere to go, and saying so would\n      // be an error message for pressing a key that did nothing.\n      if (move === null) return;\n\n      /*\n       * Asked BEFORE the move, because the op store does not consult the\n       * nesting rule — `ops.ts` holds no reference to it — so a placement the\n       * rule forbids is applied rather than refused.\n       *\n       * This is the keyboard route's half of the decision `drop-targets` makes\n       * for the pointer, of the same function, so the two surfaces cannot\n       * disagree about where a block may go. A keyboard author who could not\n       * be refused here would build documents a pointer author cannot.\n       */\n      const refusal = placementRefusal(editorNow.document, selectedId, move.to);\n      if (refusal !== null) {\n        announce(refusalAnnouncement(refusal));\n        return;\n      }\n\n      const op = {\n        kind: \"move\" as const,\n        id: selectedId,\n        to: move.to,\n        dropSlotIfEmpty: move.dropSlotIfEmpty,\n      };\n      // The locks' half, asked of the editor's own question so the sentence a\n      // keyboard author hears is the one the pointer's notice shows.\n      const lockBreak = editorNow.lockRefusalFor([op]);\n      if (lockBreak !== undefined) {\n        announce(refusalAnnouncement(lockRefusalWording(lockBreak)));\n        return;\n      }\n\n      const applied = editorNow.apply(op);\n      // Announced only once the store has accepted it. A keyboard author\n      // cannot see the result, and announcing before it answered would report\n      // a move that did not happen, which is worse than silence because it\n      // cannot be told from one that did.\n      if (applied !== null) {\n        announce(EFFECT_ANNOUNCEMENT[move.effect]);\n        return;\n      }\n      /*\n       * The store refused something the nesting rule permits — a byte cap, a\n       * depth limit, an op the forest rejects. The sentence names no cause,\n       * because none was established: naming a nesting one here would send an\n       * author to change a container that was never the problem.\n       *\n       * Still spoken rather than silent. `move === null` above is a boundary\n       * with nowhere to go and is correctly quiet; reaching HERE means a move\n       * was attempted and did not happen, which a keyboard author cannot see.\n       */\n      announce(unmovedAnnouncement(editorNow.document, selectedId));\n      // The selection deliberately does NOT change. The block that moved is\n      // the block still selected, so a second press continues moving the\n      // same block — which is what makes a run of presses walk it across the\n    },\n    [announce, moveSet, movePosition, placementRefusal]\n  );\n\n  /**\n   * Select the container holding the selection.\n   *\n   * Reads the same trail the breadcrumb draws, so \"the parent\" cannot mean one\n   * block here and another there. Silent when there is no container: a\n   * top-level block has none, and saying so on every press would be an error\n   * message for a control that is already disabled.\n   */\n  const selectParent = React.useCallback(() => {\n    const editorNow = latest.current;\n    const parent = parentOf(editorNow.document, editorNow.selectedId);\n    if (parent === undefined) return;\n    editorNow.select(parent);\n  }, []);\n\n  const bindings = React.useMemo(\n    () =>\n      MOVE_KEYS.map(({ keys, direction, description }) => ({\n        keys,\n        description,\n        // Checked at press time rather than by toggling `enabled`: with nothing\n        // selected the keystroke has no subject, and passing it on lets the\n        // browser do whatever it would have done — which on a text field is\n        // move the caret by word.\n        when: () => latest.current.selectedId !== null,\n        // Not while typing. Alt carries a non-shift modifier, so the manager\n        // would otherwise fire these inside a field, where alt+Arrow is\n        // word-wise caret movement on every platform that has it. An author\n        // editing a heading must be able to move the caret through it.\n        whenTyping: false,\n        run: () => moveSelected(direction),\n      })),\n    [moveSelected]\n  );\n\n  // Whether Delete has a subject: a block, or a header or footer, which it\n  // refuses aloud.\n  const deletes = React.useCallback(\n    (): boolean =>\n      latest.current.selectedId !== null || latestRegion.current !== undefined,\n    []\n  );\n  const editing = React.useMemo(\n    () => [\n      {\n        // Both keys. Delete is the explicit one; Backspace is what most people\n        // reach for, and binding only one leaves half the authors pressing a\n        // key that does nothing.\n        keys: \"Delete\",\n        description: \"Delete the selected block\",\n        when: () => deletes(),\n        // Not while typing, and for a sharper reason than the moves: alt+Arrow\n        // in a field is caret movement, but Backspace is the most destructive\n        // key a text field has. A binding that fired there would eat the\n        // author's characters instead of their block.\n        whenTyping: false,\n        run: () => deleteSelected(),\n      },\n      {\n        /*\n         * `mod+d`, which is what a duplicating editor binds nearly everywhere —\n         * Figma, Sketch and every canvas tool an author is likely to arrive\n         * from. The browser's own `mod+d` bookmarks the page, and taking it is\n         * the deliberate trade: inside a full-screen editor a bookmark is not\n         * what the keystroke means, and the shortcut manager prevents the\n         * default so the dialog does not appear over the canvas.\n         */\n        keys: \"mod+d\",\n        description: \"Duplicate the selected block\",\n        when: () => latest.current.selectedId !== null,\n        // Not while typing. `mod+d` in a text field is a browser action rather\n        // than an editing one, but an author mid-sentence is not asking for a\n        // block, and the manager cannot tell the two apart without this.\n        whenTyping: false,\n        run: () => duplicateSelected(),\n      },\n      {\n        keys: \"Backspace\",\n        description: \"Delete the selected block\",\n        when: () => deletes(),\n        whenTyping: false,\n        run: () => deleteSelected(),\n      },\n      {\n        /*\n         * `alt+F10`, the editor convention for reaching a block's toolbar\n         * from the keyboard: from the canvas, or from text being edited inside\n         * the block, which is why it also runs while typing.\n         */\n        keys: \"alt+F10\",\n        description: \"Move focus to the selected block's toolbar\",\n        // Only while a bar is drawn to take focus: a host may render the\n        // keystrokes alone, and the bar goes while a block is dragged. The key\n        // is then left to the browser rather than taken to do nothing.\n        when: () =>\n          latest.current.selectedId !== null &&\n          (toolbarFocus.current?.() ?? null) !== null,\n        whenTyping: true,\n        run: () => toolbarFocus.current?.()?.focus(),\n      },\n      {\n        keys: \"mod+z\",\n        description: \"Undo the last change\",\n        // Not while the caret is in a block's text.\n        //\n        // `whenTyping` defaults to TRUE for any binding opening on a modifier,\n        // and `preventDefault` to true with it — so without this the canvas\n        // SWALLOWS the author's undo mid-sentence and rewinds the DOCUMENT\n        // instead. They lose a block move they had finished with and keep the\n        // words they wanted back: both halves wrong at once.\n        //\n        // Declining leaves the keystroke to the element, which is what an\n        // uncontrolled `contentEditable` wants — inline editing hands the DOM\n        // over for the duration precisely so the browser's own history serves\n        // the caret. The document's history resumes owning `mod+z` the moment\n        // the edit commits, which is also when there is a document change worth\n        // undoing.\n        whenTyping: false,\n        // No selection required: undo acts on the document's history, not on\n        // whatever happens to be selected — and the commonest thing to undo is\n        // a deletion, which leaves a different block selected than the one the\n        // edit touched.\n        when: () => latest.current.canUndo,\n        run: () => {\n          // Said once the step has taken effect: a shared style change is\n          // undone by a write, which can be refused.\n          void Promise.resolve(latest.current.undo()).then(done => {\n            if (done) announce(\"Undone\");\n          });\n        },\n      },\n      {\n        // Both spellings: `mod+shift+z` is the convention on macOS and in most\n        // editors, `mod+y` is the Windows one. Neither is wrong and authors\n        // arrive with whichever they learned.\n        keys: \"mod+shift+z\",\n        description: \"Redo the last undone change\",\n        // Same reason as `mod+z` above: a redo taken from the caret rewinds the\n        // wrong history. `mod+shift+z` opens on a modifier too, so it inherits\n        // the same firing default and needs the same refusal.\n        whenTyping: false,\n        when: () => latest.current.canRedo,\n        run: () => {\n          void Promise.resolve(latest.current.redo()).then(done => {\n            if (done) announce(\"Redone\");\n          });\n        },\n      },\n      {\n        keys: \"mod+y\",\n        description: \"Redo the last undone change\",\n        whenTyping: false,\n        when: () => latest.current.canRedo,\n        run: () => {\n          void Promise.resolve(latest.current.redo()).then(done => {\n            if (done) announce(\"Redone\");\n          });\n        },\n      },\n    ],\n    [announce, deleteSelected, deletes, duplicateSelected]\n  );\n\n  /*\n   * Enter opens the selected block's text for typing, which is the keyboard\n   * route to what a double-click does on the canvas.\n   *\n   * Registered only when a host supplied the verb: a binding that presses and\n   * does nothing is worse than no binding, because it teaches an author the key\n   * is broken rather than absent.\n   *\n   * `whenTyping: false` is what stops it firing again once the caret is in.\n   * The shortcut manager counts a `contentEditable` element as a typing target,\n   * so an author pressing Enter inside a paragraph gets a line break from the\n   * element rather than a second attempt to begin an edit that is already open.\n   */\n  const inlineEditing = React.useMemo(\n    () =>\n      onEditText === undefined\n        ? []\n        : [\n            {\n              keys: \"Enter\",\n              description: \"Edit the selected block's text\",\n              when: () => latest.current.selectedId !== null,\n              whenTyping: false,\n              run: () => {\n                const id = latest.current.selectedId;\n                if (id !== null) onEditText(id);\n              },\n            },\n          ],\n    [onEditText]\n  );\n\n  /*\n   * \"/\" opens the host's in-place picker where the author is, the key Notion\n   * and Gutenberg taught for adding a block. Registered only when the host\n   * has a picker, so Help lists it only then.\n   *\n   * Not while typing: in a block's text or a field, \"/\" is a character. With\n   * or without a selection, since nothing selected adds at the end of the\n   * page. Read through a ref so the host's newest callback is the one run.\n   */\n  const addBlockHere = React.useRef(onAddBlockHere);\n  addBlockHere.current = onAddBlockHere;\n  const hasAddBlockHere = onAddBlockHere !== undefined;\n  const adding = React.useMemo(\n    () =>\n      hasAddBlockHere\n        ? [\n            {\n              keys: \"/\",\n              description: \"Add a block here\",\n              whenTyping: false,\n              run: () => addBlockHere.current?.(),\n            },\n          ]\n        : [],\n    [hasAddBlockHere]\n  );\n\n  useShortcuts(\n    [\n      ...bindings,\n      ...editing,\n      ...inlineEditing,\n      ...adding,\n      ...CLIPBOARD_KEY_HELP,\n    ],\n    {\n      name: \"builder-block-actions\",\n      enabled,\n    }\n  );\n\n  /*\n   * Escape, claimed for the editor and registered as its OWN layer.\n   *\n   * Separate from the block actions above because it needs a precedence they\n   * must not have. The host page binds Escape to \"cancel and go back\", and both\n   * sets are in one stack — so without a claim here the form's binding took the\n   * key and navigated away from the entry, discarding every uncommitted block\n   * edit. Raising the whole block-actions layer instead would put Delete and\n   * `mod+d` above the command palette's modal hold, so a keystroke aimed at the\n   * palette would edit the canvas behind it.\n   *\n   * `whenTyping` is left at its default, which is TRUE for Escape. That is not\n   * incidental: standing down inside a field would drop the key straight back\n   * to the form's cancel, and the inspector is full of fields. What focus in a\n   * field changes is what the key DOES, never who consumes it — see\n   * `canvas-escape`.\n   */\n  useShortcuts(\n    [\n      {\n        keys: \"Escape\",\n        description:\n          \"Select the block holding this one, or clear the selection\",\n        // The one case the editor declines. `when` rather than a branch in\n        // `run`, because declining has to leave the key UNCONSUMED for the\n        // dialog to receive it, and a binding that runs has already taken it.\n        // The modal test alone, which is the first thing `escapeOutcome`\n        // asks: the rest of the rule needs the event, and `when` is not given\n        // one.\n        when: () =>\n          !modalIsOpen(typeof document === \"undefined\" ? undefined : document),\n        run: event => {\n          const editorNow = latest.current;\n          // A field being edited: the press puts back the value from before\n          // the edit, recording nothing, and does nothing else. Pressed again\n          // in that field, it leaves the field for the canvas, the block\n          // still selected: one thing per press, innermost first.\n          const field = escapeFieldEdit(pressOrigin(event));\n          if (field === \"put-back\") return;\n          if (field === \"leave-field\") {\n            const frame = latestFrame.current;\n            if (frame !== null) returnFocusToCanvas(frame);\n            return;\n          }\n          // Where the press began, from the keystroke itself: a layer that\n          // closed on this same key has already moved focus by now.\n          const outcome = escapeOutcome(\n            typeof document === \"undefined\" ? undefined : document,\n            { origin: pressOrigin(event), canvasFrame: latestFrame.current }\n          );\n          if (outcome === \"return-to-canvas\") {\n            // The frame, where the page's own keys land: the selected block\n            // is still outlined in it, and Delete, Alt+F10, Enter and Escape\n            // act on it from there.\n            const frame = latestFrame.current;\n            if (frame !== null) returnFocusToCanvas(frame);\n            return;\n          }\n          if (outcome !== \"navigate-selection\") return;\n          if (editorNow.selectedId === null) {\n            escapeWithoutSelection.current?.();\n            return;\n          }\n          // Up a level: the block holding the selection, the same answer\n          // \"Select parent\" gives, or nothing once the selection is at the top.\n          editorNow.select(\n            parentOf(editorNow.document, editorNow.selectedId) ?? null\n          );\n        },\n      },\n    ],\n    {\n      name: \"builder-canvas-escape\",\n      enabled,\n      priority: CANVAS_ESCAPE_PRIORITY,\n    }\n  );\n\n  /*\n   * The planner's verdict, honoured HERE rather than left to each surface.\n   *\n   * The toolbar keeps an unavailable verb focusable and still calls its runner,\n   * deliberately, so the verb can announce its own refusal — that is how the\n   * existing verbs behave, and a bare pass-through would instead open a form\n   * and post a selection the planner has already rejected.\n   *\n   * Announced rather than merely refused, for the same reason: an author who\n   * pressed a dimmed control is owed the reason, and the live region is where\n   * every other refusal here is said.\n   *\n   * The host is asked only once the verdict is yes, so the form never opens\n   * over a selection that cannot be saved.\n   */\n  const saveSelectionAsPattern = React.useCallback(() => {\n    // The GRANT before the planner, matching the order the action list uses:\n    // an author who may not save at all is owed that reason rather than a\n    // critique of the blocks they chose. Checked HERE and not only there\n    // because the toolbar keeps an unavailable verb focusable and still calls\n    // this runner — so a refusal that lived only in the description would dim\n    // the control and open the form anyway, for exactly the authors this\n    // exists to stop.\n    if (!mayCreatePattern) {\n      announce(SAVE_PATTERN_GRANT_REFUSAL);\n      return;\n    }\n    // The words the menu dims the verb with, Entry content's among them.\n    const refusal = patternSaveRefusal(\n      editor.document,\n      editor.selection.ids,\n      nestingSource\n    );\n    if (refusal !== undefined) {\n      announce(refusal);\n      return;\n    }\n    onSaveAsPattern();\n  }, [\n    mayCreatePattern,\n    editor.document,\n    editor.selection.ids,\n    nestingSource,\n    announce,\n    onSaveAsPattern,\n  ]);\n\n  /*\n   * The component verbs, refused in words before the host is asked: the\n   * toolbar keeps a dimmed verb focusable, so a press of one still lands here.\n   * The reason is the one the action list carries, so the two cannot differ.\n   */\n  const componentOffer = React.useMemo(\n    () =>\n      components === undefined\n        ? undefined\n        : {\n            mayCreate: components.mayCreate,\n            ...(components.definitions === undefined\n              ? {}\n              : { definitions: components.definitions }),\n            ...(components.mayUpdatePattern === undefined\n              ? {}\n              : { mayUpdatePattern: components.mayUpdatePattern }),\n          },\n    [components]\n  );\n  const runComponentVerb = React.useCallback(\n    (id: ComponentVerbId) => {\n      if (components === undefined) return;\n      const offered = toolbarActions(\n        editor.document,\n        editor.selectedId,\n        editor.selection.ids,\n        nestingSource,\n        mayCreatePattern,\n        editor.lockRefusalFor,\n        componentOffer\n      ).find(action => action.id === id);\n      if (offered === undefined) return;\n      if (!offered.enabled) {\n        if (offered.reason !== undefined) announce(offered.reason);\n        return;\n      }\n      componentVerbRunner(components, id, () =>\n        turnIntoChoice(\n          editor.document,\n          editor.selection.ids,\n          nestingSource,\n          editor.lockRefusalFor\n        )\n      )?.();\n    },\n    [\n      components,\n      componentOffer,\n      editor.document,\n      editor.selectedId,\n      editor.selection.ids,\n      editor.lockRefusalFor,\n      nestingSource,\n      mayCreatePattern,\n      announce,\n    ]\n  );\n\n  /*\n   * What the host knows of the site's shared styles, kept by its two values\n   * so a host building a fresh object each render does not rebuild the list.\n   */\n  const sharedLibrary = sharedStyles?.library;\n  const sharedMayChange = sharedStyles?.mayChange;\n  const sharedOffer = React.useMemo(\n    () =>\n      sharedMayChange === undefined\n        ? undefined\n        : { library: sharedLibrary, mayChange: sharedMayChange },\n    [sharedLibrary, sharedMayChange]\n  );\n\n  // What the lock view is read from, so the offer depends on them alone.\n  const { composed, lockDefinitions } = editor;\n  // With the editor's lock view, the source the save dialog judges by, so an\n  // area locked to its content dims the verb here too.\n  const sharedStyleOffer = React.useMemo(\n    () =>\n      sharedOffer === undefined\n        ? undefined\n        : { ...sharedOffer, view: lockViewOf({ composed, lockDefinitions }) },\n    [sharedOffer, composed, lockDefinitions]\n  );\n\n  /*\n   * The verb list, computed ONCE for every surface below, without asking the\n   * locks; a menu asks them as it opens (`selection-offer`). See\n   * {@link SelectionActionsContext}.\n   */\n  const offer = useSelectionOffer({\n    document: editor.document,\n    selectedId: editor.selectedId,\n    selectedIds: editor.selection.ids,\n    nesting: nestingSource,\n    mayCreatePattern,\n    lockRefusalFor: editor.lockRefusalFor,\n    components: componentOffer,\n    offersEditComponent: onEditComponent !== undefined,\n    sharedStyles: sharedStyleOffer,\n    movePosition,\n    placementRefusal,\n    limits: editor.limits,\n  });\n  const selectionActions = offer.actions;\n  /*\n   * \"Save as shared style…\", refused in words before the host is asked, as\n   * the component verbs are: a dimmed verb stays focusable in the toolbar.\n   */\n  const onSaveAsSharedStyle = sharedStyles?.onSaveAsSharedStyle;\n  const saveAsSharedStyle = React.useCallback(() => {\n    const offered = selectionActions.find(\n      action => action.id === \"save-as-shared-style\"\n    );\n    if (offered === undefined) return;\n    if (!offered.enabled) {\n      if (offered.reason !== undefined) announce(offered.reason);\n      return;\n    }\n    onSaveAsSharedStyle?.();\n  }, [selectionActions, onSaveAsSharedStyle, announce]);\n  const editSelectedComponent = useEditComponentVerb(editor, onEditComponent);\n  const turnVerbs = useTurnIntoVerbs(\n    editor,\n    nestingSource,\n    sharedLibrary,\n    announce\n  );\n  // Copy style and Paste style: the blocks' own looks, never a shared style.\n  const styleClipboard = useStyleClipboardVerbs({\n    latest,\n    announce,\n    notify,\n    library: sharedLibrary,\n  });\n\n  const actions = React.useMemo<BlockActions>(\n    () => ({\n      move: moveSelected,\n      delete: deleteSelected,\n      duplicate: duplicateSelected,\n      // Run from a menu, where no clipboard event is under way: Copy and Cut\n      // write to the system clipboard themselves.\n      copy: () => {\n        clipboard.copy();\n      },\n      cut: () => {\n        clipboard.cut();\n      },\n      paste: clipboard.paste,\n      copyStyle: () => {\n        styleClipboard.copyStyle();\n      },\n      pasteStyle: styleClipboard.pasteStyle,\n      selectParent,\n      saveAsPattern: saveSelectionAsPattern,\n      editComponent: editSelectedComponent,\n      turnIntoComponent: () => runComponentVerb(\"turn-into-component\"),\n      detachComponent: () => runComponentVerb(\"detach-component\"),\n      duplicateComponent: () => runComponentVerb(\"duplicate-component\"),\n      updatePattern: () => runComponentVerb(\"update-pattern\"),\n      wrapInBox: () => runWrap(\"wrap\"),\n      unwrap: () => runWrap(\"unwrap\"),\n      saveAsSharedStyle,\n      ...turnVerbs,\n    }),\n    [\n      runWrap,\n      saveAsSharedStyle,\n      turnVerbs,\n      moveSelected,\n      deleteSelected,\n      duplicateSelected,\n      clipboard,\n      styleClipboard,\n      selectParent,\n      saveSelectionAsPattern,\n      editSelectedComponent,\n      runComponentVerb,\n    ]\n  );\n\n  return {\n    announcement,\n    actions,\n    nesting: nestingSource,\n    offer,\n    selectionActions: offer.actions,\n    depthMoves: offer.depthMoves,\n    toolbarFocus,\n    canvasFrame: latestFrame,\n    clipboard,\n  };\n}\n\n/**\n * Keeps an editor's canvas frame slot pointing at the frame the canvas has\n * registered, and draws nothing. Its own component so that the canvas\n * reporting a new zoom or size re-renders this and not the editor's bindings.\n */\nfunction CanvasFrameReader({ into }: { into: CanvasFrameSlot }): null {\n  const frame = useCanvasFrame().frame;\n  useIsomorphicLayoutEffect(() => {\n    into.current = frame;\n    return () => {\n      // Cleared with the frame, so a slot never points at a frame that has\n      // left the page.\n      if (into.current === frame) into.current = null;\n    };\n  }, [into, frame]);\n  return null;\n}\n\n/**\n * The \"Turn into\" verbs: the one selected block turned into another type as\n * one undo step, saying what it removed or why it could not (`runTurnInto`),\n * and the same for a block in a page a caller holds (the format bar's). Each\n * is judged with the site's styles, so a block style the new type cannot wear\n * is kept as its own styles. Silent for a selection of more than one block,\n * which is offered no turn.\n */\nfunction useTurnIntoVerbs(\n  editor: EditorState,\n  nesting: NestingSource,\n  library: readonly NamedClass[] | undefined,\n  announce: (words: string) => void\n): Pick<BlockActions, \"turnInto\" | \"turnIntoIn\"> {\n  const { document, selectedId, selection, apply, lockRefusalFor, limits } =\n    editor;\n  const turnIntoIn = React.useMemo(() => {\n    // Judged as the editor's own apply judges: its placement rules, its size\n    // limits, and the site's styles for a block style that cannot come along.\n    const judging = {\n      nesting,\n      limits,\n      ...(library === undefined ? {} : { library }),\n    };\n    return {\n      choices: (page: BlockDocument, id: string) =>\n        turnIntoOffers(page, id, {\n          ...judging,\n          ask: lockRefusalFor,\n          planned: true,\n        }),\n      run: (page: BlockDocument, id: string, to: string) => {\n        runTurnInto(\n          { document: page, apply, lockRefusalFor },\n          id,\n          to,\n          announce,\n          judging\n        );\n      },\n    };\n  }, [apply, lockRefusalFor, nesting, limits, library, announce]);\n  const turnInto = React.useCallback(\n    (to: string) => {\n      if (selectedId === null || selection.ids.length !== 1) return;\n      turnIntoIn.run(document, selectedId, to);\n    },\n    [document, selectedId, selection.ids, turnIntoIn]\n  );\n  return React.useMemo(\n    () => ({ turnInto, turnIntoIn }),\n    [turnInto, turnIntoIn]\n  );\n}\n\n/**\n * The \"Edit component\" verb: hands the selected placement's component to the\n * host, or does nothing for any other selection, or where no host answers.\n */\nfunction useEditComponentVerb(\n  editor: EditorState,\n  onEditComponent: BlockKeyboardActionsOptions[\"onEditComponent\"]\n): () => void {\n  return React.useCallback(() => {\n    if (onEditComponent === undefined) return;\n    const ids = editor.selection.ids;\n    if (ids.length !== 1) return;\n    const nodeId = ids[0];\n    if (nodeId === undefined) return;\n    const componentId = placedComponentId(editor.document, nodeId);\n    if (componentId !== undefined) onEditComponent(componentId, nodeId);\n  }, [editor.document, editor.selection.ids, onEditComponent]);\n}\n\n/**\n * The block holding `id`, read from the same trail the breadcrumb draws, or\n * nothing for a top-level block or a selection the document no longer holds.\n * \"Select parent\" and Escape both ask this, so they cannot name two parents.\n */\nfunction parentOf(\n  document: EditorState[\"document\"],\n  id: string | null\n): string | undefined {\n  const path = pathTo(document, id);\n  return path[path.length - 2]?.id;\n}\n\n/**\n * The bindings as a component, for mounting inside the shell.\n *\n * `BuilderShell` provides the shortcut context, so the hook cannot be called by\n * whatever RENDERS the shell — only by something inside it. A host would\n * otherwise have to invent a null-returning wrapper of its own, and every host\n * would invent a slightly different one.\n *\n * Renders the live region, and publishes the verbs to whatever it wraps. Both\n * belong to the same mount deliberately: a toolbar reachable without the region\n * could act without announcing, and a keyboard author would meet a button that\n * changes the page and says nothing.\n *\n * `children` is optional. A host that wants only the keystrokes passes none and\n * gets exactly what this rendered before.\n */\nexport function BlockKeyboardActions({\n  onShareVerbs,\n  children,\n  // Handed on whole, so an option the host left out stays out.\n  ...options\n}: BlockKeyboardActionsOptions & {\n  readonly children?: React.ReactNode;\n  /**\n   * Called with the verbs whenever they change, and with `undefined` when this\n   * provider goes, for a surface drawn outside it.\n   */\n  readonly onShareVerbs?: (verbs: SharedBlockVerbs | undefined) => void;\n}): React.JSX.Element {\n  const {\n    announcement,\n    actions,\n    nesting: rules,\n    offer,\n    toolbarFocus,\n    canvasFrame,\n    clipboard,\n  } = useBlockKeyboardActions(options);\n\n  /*\n   * Shared from a layout effect, so a surface outside sees the verbs for the\n   * selection it is drawing in the same frame.\n   *\n   * Shared again only when what is OFFERED changes — which verbs, whether each\n   * may run, and why not — and never merely because a render made new\n   * objects. A host keeps the shared value in its own state, so sharing on\n   * every render re-renders the host, which re-renders this, which shares\n   * again: an infinite update. `run` reads the latest verbs through a ref, so\n   * a value shared earlier still runs what this render would, whatever the\n   * verbs close over beside the editor (they already read the live editor).\n   */\n  const latestVerbs = React.useRef(actions);\n  const latestOffer = React.useRef(offer);\n  const [offerChanged] = React.useState(offerSignal);\n  const sharedOffer = React.useRef<string | null>(null);\n  useIsomorphicLayoutEffect(() => {\n    latestVerbs.current = actions;\n    latestOffer.current = offer;\n    offerChanged.notify();\n    if (onShareVerbs === undefined) return;\n    const offered = offer.actions\n      .map(each => `${each.id}:${each.enabled}:${each.reason ?? \"\"}`)\n      .join(\"|\");\n    if (offered === sharedOffer.current) return;\n    sharedOffer.current = offered;\n    onShareVerbs({\n      actions: offer.actions,\n      // Through the ref, as `run`: a menu opened later asks of that moment.\n      withLocks: () => latestOffer.current.withLocks().actions,\n      subscribe: offerChanged.subscribe,\n      run: id => blockActionRunners(latestVerbs.current)[id](),\n    });\n  }, [onShareVerbs, actions, offer, offerChanged]);\n  useIsomorphicLayoutEffect(\n    () => () => {\n      sharedOffer.current = null;\n      onShareVerbs?.(undefined);\n    },\n    [onShareVerbs]\n  );\n\n  // `polite`, not `assertive`: a move is the author's own action and its result\n  // can wait for a pause. Assertive interrupts whatever is being read, which for\n  // a run of presses means talking over itself.\n  //\n  // The region is present from the first render rather than appearing with its\n  // first message. A live region added to the page at the same moment it gains\n  // text is frequently not announced at all, because the assistive technology\n  // has nothing it was already watching.\n  return (\n    <NestingContext.Provider value={rules}>\n      <SelectionActionsContext.Provider value={offer}>\n        <BlockActionsContext.Provider value={actions}>\n          <ToolbarFocusContext.Provider value={toolbarFocus}>\n            <CanvasFrameReader into={canvasFrame} />\n            <BlockClipboardEvents\n              verbs={clipboard}\n              enabled={options.enabled ?? true}\n            />\n            <p aria-live=\"polite\" role=\"status\" className=\"nx-sr-only\">\n              {announcement}\n            </p>\n            {children}\n          </ToolbarFocusContext.Provider>\n        </BlockActionsContext.Provider>\n      </SelectionActionsContext.Provider>\n    </NestingContext.Provider>\n  );\n}\n","/**\n * The verbs for the current selection, as every pointer surface asks for them.\n *\n * The bar and the right-click menu draw different things and decide nothing:\n * both take the list from `toolbarActions`, and both have to ask it the same\n * question — the whole selection, judged by the rules the host supplied. Written\n * out at each of them, that question was four lines duplicated, and duplicated\n * lines are how one surface came to ask a narrower question than the other in\n * the first place.\n *\n * A hook rather than a helper, because two thirds of the question are context: a\n * surface cannot ask about the host's rules without reading them, and cannot\n * memoise the answer without a hook to memoise in.\n *\n * @module selection-actions\n */\n\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport {\n  useNestingSource,\n  useSelectionActionsContext,\n} from \"../shell/keyboard-actions\";\n\nimport type { SelectionVerbs } from \"./selection-offer\";\nimport { toolbarActions, type ToolbarAction } from \"./toolbar-actions\";\n\n/**\n * What to offer for this editor's selection, recomputed only when it changes.\n *\n * `locks` says whether to ask the locks too: false for what a surface shows\n * as the selection changes, true for a menu that is opening, whose items an\n * author is about to choose between. Asking them means trying each verb's\n * edit on a copy of the page, so it is asked only where its answer is read.\n *\n * Memoised on the parts rather than on `editor`, which is a fresh object every\n * render: depending on it would rebuild the list on every frame of a drag, and\n * the menu keys its rows on identity.\n */\nexport function useSelectionActions(\n  editor: EditorState,\n  locks: boolean = false\n): ToolbarAction[] {\n  return useSelectionVerbs(editor, locks).actions;\n}\n\n/**\n * The verbs and the block menu's depth moves, as {@link useSelectionActions}\n * decides them.\n */\nexport function useSelectionVerbs(\n  editor: EditorState,\n  locks: boolean\n): SelectionVerbs {\n  const { document, selectedId } = editor;\n  const selectedIds = editor.selection.ids;\n  const nesting = useNestingSource();\n  const shared = useSelectionActionsContext();\n  const ask = locks ? editor.lockRefusalFor : undefined;\n\n  /*\n   * The provider's answer where there is one, and this surface's own where\n   * there is not — decided INSIDE the memo, which is what makes it both lazy\n   * and correct.\n   *\n   * Lazy, because with a provider above, `toolbarActions` is never called\n   * here at all. That is the point — deciding whether a selection can be\n   * SAVED builds the document a save would store, so three surfaces computing\n   * it separately made an ordinary edit clone and walk a large selection three\n   * times. The provider also keeps its lock answers, so a second menu reads\n   * the first one's.\n   *\n   * Correct, because every input the fallback reads is a dependency. Written as\n   * a thunk memoised on the context alone, a surface with no provider kept its\n   * first answer for ever, and the suppression that made that compile was\n   * hiding it.\n   *\n   * Outside a provider there is no move verb to judge depth moves with, so\n   * none are offered.\n   */\n  return React.useMemo(() => {\n    if (shared !== null) return locks ? shared.withLocks() : shared;\n    return {\n      actions: toolbarActions(\n        document,\n        selectedId,\n        selectedIds,\n        nesting,\n        undefined,\n        ask,\n        undefined,\n        false,\n        undefined,\n        locks\n      ),\n      depthMoves: [],\n    };\n  }, [shared, locks, document, selectedId, selectedIds, nesting, ask]);\n}\n","\"use client\";\n\n/**\n * The editor's command palette, assembled and mounted.\n *\n * `CommandPalette` is the surface and `builderCommands` is the list; this is\n * the one piece that knows both, and it exists so a host does not have to.\n * Mounting the palette otherwise means reaching into the verbs context,\n * rebuilding the command array on the right renders, and knowing that the\n * palette must sit inside `BlockKeyboardActions` — three things every host\n * would have to get right, and would get right differently.\n *\n * **It was the missing piece.** `CommandPalette` shipped and was tested and was\n * exported, and no host ever mounted it — so the editor advertised a command\n * palette that no author could open. Pressing `mod+k` in the admin opens\n * `@nextlyhq/admin`'s palette instead, which is the reason the gap survived a\n * browser check: something opens, so the feature looks present.\n *\n * @module editor-command-palette\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../block-icon\";\nimport { useSelectionActions } from \"../canvas/selection-actions\";\nimport type { EditorState } from \"../editor-state\";\nimport {\n  InsertAnnouncement,\n  placementWords,\n  useInsertOffers,\n  type InsertOffers,\n  type InsertOffersInputs,\n} from \"../panels/add/insert-panel\";\nimport { blockLabel, filterEntries } from \"../panels/add/inserter\";\nimport {\n  layersOf,\n  UNNAMED_COMPONENT,\n  type ComponentTitleOf,\n  type LayerNode,\n} from \"../panels/layers/layers\";\n\nimport { builderCommands } from \"./builder-commands\";\nimport {\n  CommandPalette,\n  type BuilderCommand,\n  type CommandGroupOptions,\n} from \"./command-palette\";\nimport { useBlockActionsContext } from \"./keyboard-actions\";\n\n/** The groups a search shows, in the order an author reads them. */\nconst ADD_GROUP = \"Add\";\nconst PAGE_GROUP = \"On this page\";\n/** How many of each kind a search shows: enough to choose from at a glance. */\nconst SEARCH_LIMIT = 5;\n\n/**\n * Results the host finds elsewhere, such as the site's other pages, shown as\n * one more group between the page's blocks and the commands.\n *\n * @experimental\n */\nexport interface EditorSearchResults {\n  /** The group's heading, and what it says while its search runs or fails. */\n  group: Omit<CommandGroupOptions, \"matched\">;\n  /** What the host found for the current search, best first. */\n  commands: readonly BuilderCommand[];\n}\n\nexport interface EditorCommandPaletteProps {\n  /** The editor whose state the commands read and change. */\n  editor: EditorState;\n  /**\n   * Leaving the editor, when the host has somewhere to go.\n   *\n   * Omitted where there is nowhere — the editor embedded in a form that is\n   * already on screen — and the palette then offers no way out rather than a\n   * command that does nothing. Passed to `builderCommands`, which makes the\n   * same distinction the shell's exit affordance does.\n   */\n  onExit?: () => void;\n  /**\n   * What the Add panel adds from, so a search offers the same blocks and adds\n   * each where the panel would. Without it, search adds nothing.\n   */\n  insert?: Omit<InsertOffersInputs, \"editor\" | \"enabled\">;\n  /** Bring a block into view on the canvas once a search has selected it. */\n  revealBlock?: (id: string) => void;\n  /** Results the host searches for itself: the site's other pages. */\n  results?: EditorSearchResults;\n  /** Told the search as the author types it, for the host's own results. */\n  onSearchChange?: (query: string) => void;\n  /**\n   * A component's title by id, so a placed component is found and named by\n   * what the author placed, as Layers names it.\n   */\n  componentTitle?: ComponentTitleOf;\n  /** Controls the palette, for a host that also opens it from a button. */\n  open?: boolean;\n  onOpenChange?: (open: boolean) => void;\n}\n\nexport function EditorCommandPalette({\n  editor,\n  onExit,\n  insert,\n  revealBlock,\n  results,\n  onSearchChange,\n  componentTitle,\n  open,\n  onOpenChange,\n}: EditorCommandPaletteProps): React.JSX.Element {\n  const verbs = useBlockActionsContext();\n  // Whether the palette is open, followed whoever opens it: its verbs ask the\n  // locks only while an author can choose between them. Handed to the palette\n  // as its open state, so a palette the shell closes tells this as it closes.\n  const [shown, setShown] = React.useState(false);\n  const isOpen = open ?? shown;\n  const actions = useSelectionActions(editor, isOpen);\n  // Taken out of `editor` so the list below depends on these two functions\n  // rather than on the store object, for the reason given there.\n  const { undo, redo } = editor;\n\n  /*\n   * Rebuilt when what it OFFERS could have changed, which is the document, the\n   * selection and the history's two flags.\n   *\n   * `editor` as a whole would be the obvious dependency and is the wrong one:\n   * the store hands back a fresh object on every render, so the list would be\n   * rebuilt on every frame of a panel drag — and `CommandPalette` keys its rows\n   * on identity, so a list rebuilt mid-search is a list that loses the row the\n   * author had highlighted.\n   */\n  const commands = React.useMemo(\n    () =>\n      builderCommands({\n        // The SAME list the bar and the menu are drawing, not a second call\n        // that could be given a narrower question — which is how this surface\n        // came to offer a verb the bar refused.\n        actions,\n        verbs,\n        // Undo and redo answer as a promise for a recorded step. The palette\n        // only runs them, and that promise settles on its own (a failed step\n        // answers `false` rather than rejecting), so the answer is let go here\n        // rather than handed to a command whose `run` returns nothing.\n        undo: () => {\n          void undo();\n        },\n        redo: () => {\n          void redo();\n        },\n        canUndo: editor.canUndo,\n        canRedo: editor.canRedo,\n        onExit,\n      }),\n    [actions, undo, redo, editor.canUndo, editor.canRedo, verbs, onExit]\n  );\n\n  // What is being searched for, so the blocks to add are matched as the Add\n  // panel matches them and the page's blocks are listed only while searching.\n  const [query, setQuery] = React.useState(\"\");\n  const offers = useInsertOffers({\n    editor,\n    ...insert,\n    // Judged only while a search could show them.\n    enabled: insert !== undefined && query !== \"\",\n  });\n  const found = [\n    ...(insert === undefined ? [] : addCommands(offers, editor, query)),\n    ...pageCommands(\n      editor,\n      query,\n      revealBlock,\n      iconsOf(offers.catalog),\n      componentTitle\n    ),\n    ...(results?.commands ?? []),\n    ...commands,\n  ];\n\n  return (\n    <>\n      {/* Outside the dialog, which closes as a row runs, so the sentence an\n          insert from search is announced with is still there to be read. */}\n      <InsertAnnouncement text={offers.announcement} afterClose />\n      <CommandPalette\n        commands={found}\n        groups={[\n          // Already matched, by the Add panel's own rule.\n          { name: ADD_GROUP, limit: SEARCH_LIMIT, matched: true },\n          { name: PAGE_GROUP, limit: SEARCH_LIMIT },\n          ...(results === undefined\n            ? []\n            : [{ ...results.group, matched: true }]),\n        ]}\n        onSearchChange={next => {\n          setQuery(next);\n          onSearchChange?.(next);\n        }}\n        placeholder=\"Search blocks, this page, pages and commands…\"\n        emptyMessage={searched => (\n          <>\n            <p className=\"text-foreground\">Nothing matches “{searched}”.</p>\n            <p className=\"mt-1\">\n              Search finds blocks to add, blocks on this page, your pages and\n              commands.\n            </p>\n          </>\n        )}\n        open={isOpen}\n        onOpenChange={next => {\n          setShown(next);\n          onOpenChange?.(next);\n        }}\n      />\n    </>\n  );\n}\n\n/**\n * The blocks and components the Add panel would offer for this search, each\n * saying where it will go and added there.\n *\n * Matched by the panel's own filter, so search and the panel agree on what a\n * word finds. Saved sections stay in the panel, and a block with nowhere to go\n * is left out: a search row is there to be chosen, and the panel is where the\n * reason is explained.\n */\nfunction addCommands(\n  { catalog, offers, insert }: InsertOffers,\n  editor: Pick<EditorState, \"document\">,\n  query: string\n): BuilderCommand[] {\n  if (query === \"\") return [];\n  return byLabelFirst(filterEntries(catalog, query), query).flatMap(entry => {\n    const offer = offers.get(entry.id);\n    if (entry.kind === \"pattern\" || offer?.place === undefined) return [];\n    return [\n      {\n        id: `add:${entry.id}`,\n        label: entry.label,\n        group: ADD_GROUP,\n        icon: <BlockIconMark icon={entry.icon} size={16} />,\n        // The panel's words: \"Adding after Hero\", or, when this block can't\n        // go there, where it goes instead.\n        detail: placementWords(\n          offer.climbed ? \"Goes\" : \"Adding\",\n          editor.document,\n          offer.place\n        ),\n        verb: \"Add\",\n        run: () => insert(offer),\n      },\n    ];\n  });\n}\n\n/**\n * The page's blocks, by the names Layers shows, each saying what it is and\n * where it sits. Listed only while searching: the whole page is what Layers\n * is for.\n */\nfunction pageCommands(\n  editor: Pick<EditorState, \"document\" | \"select\">,\n  query: string,\n  revealBlock: ((id: string) => void) | undefined,\n  icons: ReadonlyMap<string, string | undefined>,\n  componentTitle: ComponentTitleOf | undefined\n): BuilderCommand[] {\n  if (query === \"\") return [];\n  return blocksOnPage(editor.document, componentTitle).map(\n    ({ layer, parent }) => {\n      // A placement is a component, in the word and the mark Layers uses, rather\n      // than the engine's name for its node type.\n      const kind = layer.component ? UNNAMED_COMPONENT : blockLabel(layer.type);\n      return {\n        id: `block:${layer.id}`,\n        label: layer.label,\n        // The same mark the Add panel draws for this kind of block.\n        icon: (\n          <BlockIconMark\n            icon={layer.component ? \"component\" : icons.get(layer.type)}\n            size={16}\n          />\n        ),\n        // Found by what it is as well as by its name: \"heading\" finds them all.\n        keywords: [kind],\n        group: PAGE_GROUP,\n        // The kind only where the name doesn't already say it.\n        detail: [\n          ...(layer.label === kind ? [] : [kind]),\n          ...(parent === undefined ? [] : [`in ${parent.label}`]),\n        ].join(\" · \"),\n        verb: \"Select\",\n        run: () => {\n          editor.select(layer.id);\n          revealBlock?.(layer.id);\n        },\n      };\n    }\n  );\n}\n\n/**\n * The panel's matches, those whose NAME the search begins a word of first,\n * then those whose name holds it, then the rest (a match in a description or\n * a keyword). Stable, so the panel's order holds within each.\n */\nfunction byLabelFirst<TEntry extends { label: string }>(\n  entries: readonly TEntry[],\n  query: string\n): TEntry[] {\n  const wanted = query.toLowerCase();\n  const rank = (label: string): number => {\n    const lower = label.toLowerCase();\n    if (lower.startsWith(wanted) || lower.includes(` ${wanted}`)) return 0;\n    return lower.includes(wanted) ? 1 : 2;\n  };\n  return entries\n    .map((entry, index) => ({ entry, index, rank: rank(entry.label) }))\n    .sort((a, b) => a.rank - b.rank || a.index - b.index)\n    .map(ranked => ranked.entry);\n}\n\n/** Each block type's mark, as the Add panel's catalogue names it. */\nfunction iconsOf(\n  catalog: InsertOffers[\"catalog\"]\n): ReadonlyMap<string, string | undefined> {\n  const icons = new Map<string, string | undefined>();\n  for (const entry of catalog) {\n    if (entry.kind === \"block\" && !icons.has(entry.blockName)) {\n      icons.set(entry.blockName, entry.icon);\n    }\n  }\n  return icons;\n}\n\n/** Every block on the page, in document order, with the block it sits in. */\nfunction blocksOnPage(\n  document: BlockDocument,\n  componentTitle: ComponentTitleOf | undefined\n): { layer: LayerNode; parent?: LayerNode }[] {\n  const out: { layer: LayerNode; parent?: LayerNode }[] = [];\n  // Bounded by the document's size: each node is visited once.\n  const walk = (nodes: readonly LayerNode[], parent?: LayerNode): void => {\n    for (const layer of nodes) {\n      out.push(parent === undefined ? { layer } : { layer, parent });\n      walk(layer.children, layer);\n    }\n  };\n  walk(layersOf(document, componentTitle));\n  return out;\n}\n","\"use client\";\n\n/**\n * The right-click menu over the canvas, and the fourth surface over the block\n * verbs.\n *\n * The keystrokes, the floating toolbar and the command palette were the first\n * three. This one exists because it is where an author looks first — Webflow,\n * Framer, Figma and Gutenberg all put the block verbs on a secondary click, so\n * an editor without one reads as broken rather than as minimal.\n *\n * ## It derives; it does not decide\n *\n * Every question this menu could ask is already answered somewhere:\n *\n * - WHICH verbs, and whether each is available, comes from `toolbarActions` —\n *   the same call the floating bar makes, with the same order and the same\n *   reasons. `builder-commands` states the rule for the palette and it is the\n *   same one here: asking a second time is how a menu comes to offer a verb the\n *   button beside it shows as unavailable.\n * - WHAT each one runs comes from `blockActionRunners`, shared with the palette\n *   so the two cannot bind the same label to different verbs.\n * - WHICH block it acts on is the canvas's selection, which the canvas itself\n *   moves to the block under the pointer before this ever opens.\n *\n * What is left is presentation, which is this module's whole job.\n *\n * ## Labels come from the toolbar, not the palette\n *\n * The palette deliberately says \"Duplicate block\", because a palette row is\n * read in a list with no context. A context menu is drawn AT the block, like\n * the toolbar, so it takes the toolbar's shorter \"Duplicate\" for the same\n * reason the toolbar does.\n *\n * ## A disabled verb stays, and says why IN THE MENU\n *\n * The reason is VISIBLE text inside the item, not a `title`. The toolbar can\n * use a tooltip because its buttons stay hoverable; a disabled menu item does\n * not, since the shared item style sets `data-[disabled]:pointer-events-none`\n * — and Radix skips disabled items in keyboard navigation, so there is no\n * route to a tooltip by either input. A `title` there is an explanation that\n * exists in the markup and reaches nobody.\n *\n * `toolbarActions` sets `reason` only for a cause an author can act on — a lock\n * — and leaves self-evident ones unsaid. So an unavailable verb is drawn\n * disabled with its reason rather than removed: a menu that silently omits\n * Delete answers \"why can I not delete this\" with nothing at all, and the\n * remedy for the one reason it does report is one field away.\n *\n * ## Why the trigger generates no box\n *\n * Radix's trigger renders a `span`, and a span wrapped around the canvas is an\n * inline box holding a block one — it would change the layout of the thing it\n * is meant to be transparent over. `display: contents` makes the wrapper\n * generate no box at all while leaving it in the DOM, which is all this needs:\n * events bubble along the tree rather than along the layout, and Radix anchors\n * a context menu to the pointer's own coordinates rather than to the trigger's\n * rect.\n *\n * Keeping it ABOVE the canvas root, rather than on it, is also what keeps the\n * canvas's drag handlers intact. Radix binds its own pointer handlers for the\n * touch long-press, and the canvas root already carries a full set for\n * dragging; on one element the two would overwrite each other.\n *\n * ## Touch and pen open it by a different route, and act on the same subject\n *\n * Radix opens a long-press from its own 700ms `pointerdown` timer and never\n * dispatches a `contextmenu` event, so the canvas's filtering — which runs on\n * that event — does not see it at all. Left alone, a long press on a block that\n * was not selected opens the PREVIOUS selection's verbs, and Delete among them\n * acts on a block the author is not looking at.\n *\n * The press is therefore NOTED and nothing more. Acting on it would be acting\n * on a contact that has not yet become anything: a press becomes a long press\n * only after 700ms, and most never do — selecting there retargets the\n * inspector and the toolbar every time the author scrolls the canvas with a\n * finger, and Radix's own cancellation on `pointermove` would not put it back.\n *\n * The selection moves when the menu actually OPENS, which is the first moment\n * a long press is known to be one. For a mouse the canvas has already selected\n * by then, on the context event, and the check below makes that a no-op.\n *\n * Rejecting a press aimed at chrome or at text is the canvas's job rather than\n * this one's, and it does it by withholding the event — see its pointer-down\n * rule for why `preventDefault` here would be the wrong instrument.\n *\n * ## What opens it, and what is known about the keyboard\n *\n * Measured in a real browser: a right-click opens it at the pointer, both at\n * scale 1 and under the canvas's CSS `zoom`, and a touch long-press opens it\n * through Radix's own timer.\n *\n * The platform's context-menu key sends a `contextmenu` event from whatever\n * holds focus, so it reaches this by the same path a right-click does —\n * PROVIDED focus is on something inside a block. A block that renders a\n * focusable control is: `core/button` draws an anchor carrying the node marker\n * itself. Focus on the canvas REGION is not, and cannot be: that region is an\n * ancestor of this trigger, so an event from it travels away rather than into\n * it, and there is no block under it to act on either way.\n *\n * That keyboard path is reasoned, not measured. The automation available here\n * cannot generate the event — a synthesised `Shift+F10` produces no\n * `contextmenu` event at all, measured with a capture listener, so it can\n * neither confirm nor refute the behaviour and no claim is made from it.\n *\n * What does not depend on any of it: every verb here is reachable without a\n * pointer regardless, through the keystrokes, the block toolbar's roving tab\n * stop, and the command palette. This is one more route to them, never the\n * only one — which is why blocks that carry no focusable control cost nothing\n * by being unable to open it.\n *\n * @module block-context-menu\n */\n\nimport {\n  ContextMenu,\n  ContextMenuContent,\n  ContextMenuItem,\n  ContextMenuSeparator,\n  ContextMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport { blockActionRunners } from \"../shell/builder-commands\";\nimport {\n  useBlockActionsContext,\n  type BlockActions,\n} from \"../shell/keyboard-actions\";\n\nimport { CANVAS_ROOT_CLASS, contextMenuTargetOf } from \"./canvas\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { isElement } from \"./dom-kind\";\nimport { useSelectionVerbs } from \"./selection-actions\";\nimport { isTurnIntoAction } from \"./turn-into-verb\";\n\n/**\n * The wrapper's style, hoisted so it is one object rather than one per render.\n *\n * A fresh literal here would give the wrapper a new `style` prop on every\n * render of the canvas, which React writes back to the DOM each time.\n */\nconst TRANSPARENT_WRAPPER: React.CSSProperties = { display: \"contents\" };\n\n/** Where the menu's own verbs end and the editor-wide ones would begin. */\nconst DESTRUCTIVE: ReadonlySet<string> = new Set([\"delete\"]);\n\n/**\n * Which group a verb is drawn in: \"Turn into\" Text, Rich text or Heading on\n * their own, so they read apart from \"Turn into component…\"; the other\n * menu-only verbs (the component verbs); and the structural ones.\n */\nfunction groupOf(action: {\n  readonly id: string;\n  readonly inMenu?: true;\n}): \"turn-into\" | \"menu\" | \"structure\" {\n  if (isTurnIntoAction(action.id)) return \"turn-into\";\n  return action.inMenu === true ? \"menu\" : \"structure\";\n}\n\n/**\n * Whether the verb at `index` opens a group: the menu-only verbs after the\n * structural ones, and the \"Turn into\" verbs, before and after them.\n */\nfunction startsMenuGroup(\n  actions: readonly { readonly id: string; readonly inMenu?: true }[],\n  index: number\n): boolean {\n  const here = actions[index];\n  const before = actions[index - 1];\n  if (here === undefined || before === undefined) return false;\n  const [now, then] = [groupOf(here), groupOf(before)];\n  if (now === then) return false;\n  return now !== \"structure\" || then === \"turn-into\";\n}\n\nexport interface BlockContextMenuProps {\n  /** The editor whose selection the verbs act on. */\n  editor: EditorState;\n  /** The canvas this menu opens over. */\n  children: React.ReactNode;\n}\n\nexport function BlockContextMenu({\n  editor,\n  children,\n}: BlockContextMenuProps): React.JSX.Element {\n  const verbs = useBlockActionsContext();\n  // Still read directly: what the menu does on OPEN depends on what was clicked\n  // relative to the selection, which is a different use from deciding which\n  // verbs to offer.\n  const { selectedId } = editor;\n  const selectedIds = editor.selection.ids;\n\n  const select = editor.select;\n  /*\n   * What the last press was aimed at, remembered rather than acted on.\n   *\n   * A ref because nothing renders from it and because the value has to survive\n   * from the press to the open without causing a render in between — a state\n   * update here would rerender the canvas on every contact.\n   */\n  const pressedTarget = React.useRef<string | null>(null);\n  const canvas = useCanvasFrame();\n  const noteTarget = React.useCallback(\n    (event: React.MouseEvent<HTMLDivElement>) => {\n      /*\n       * This wrapper's OWN canvas, which is the outermost one beneath it. A\n       * canvas nested inside a block of that canvas is deeper, so it is not\n       * what `querySelector` returns — and a block belonging to it is refused\n       * here rather than answered for by this menu.\n       *\n       * A canvas in a frame is not beneath the wrapper in the DOM, only in\n       * the component tree, which is how its events reach this handler; it\n       * is the outermost canvas in the frame's document.\n       */\n      const root =\n        event.currentTarget.querySelector(`.${CANVAS_ROOT_CLASS}`) ??\n        (canvas.frame === null\n          ? null\n          : (canvas.document?.querySelector(`.${CANVAS_ROOT_CLASS}`) ?? null));\n      pressedTarget.current =\n        root === null ? null : contextMenuTargetOf(event.target, root);\n      /*\n       * The menu opens where the press was, read from this event's client\n       * coordinates. A press inside the frame reports them in the FRAME's\n       * viewport while the menu is drawn in the editor's, so they are carried\n       * across here, before the trigger's own handler reads them.\n       */\n      if (\n        canvas.frame !== null &&\n        isElement(event.target) &&\n        event.target.ownerDocument !== event.currentTarget.ownerDocument\n      ) {\n        const at = canvas.toHost({ x: event.clientX, y: event.clientY });\n        Object.assign(event, { clientX: at.x, clientY: at.y });\n      }\n    },\n    [canvas]\n  );\n  const opened = React.useCallback(\n    (open: boolean) => {\n      // CONSUMED, whether or not this is an opening. A value left behind is a\n      // value some later opening can read: a keyboard menu key arrives as a\n      // context event with no press before it, and would otherwise be answered\n      // with whatever the last press happened to be pointing at.\n      const id = pressedTarget.current;\n      pressedTarget.current = null;\n      if (!open || id === null) return;\n      // Already chosen means already correct — every route selects through the\n      // canvas first — and replacing would drop the rest of a multiple\n      // selection the gesture was meant to act on.\n      if (selectedIds.includes(id)) return;\n      select(id, \"replace\");\n    },\n    [select, selectedIds]\n  );\n\n  return (\n    // Not modal: a modal menu marks the editor around it aria-hidden while its\n    // controls stay focusable (axe: aria-hidden-focus). Escape, a click\n    // outside and Tab still close it.\n    <ContextMenu modal={false} onOpenChange={opened}>\n      <ContextMenuTrigger asChild>\n        <div\n          style={TRANSPARENT_WRAPPER}\n          onPointerDown={noteTarget}\n          onContextMenu={noteTarget}\n        >\n          {children}\n        </div>\n      </ContextMenuTrigger>\n      {/*\n        Nothing to act on means nothing to draw. The canvas stops the event\n        before it reaches the trigger when the pointer was over the background,\n        so this is the other route to the same state: a selection that was\n        cleared while the menu's own markup still existed.\n      */}\n      {selectedId === null ? null : (\n        <ContextMenuContent aria-label=\"Block actions\">\n          <BlockMenuItems editor={editor} verbs={verbs} />\n        </ContextMenuContent>\n      )}\n    </ContextMenu>\n  );\n}\n\n/**\n * The menu's items, drawn only while it is open: so the locks are asked about\n * its verbs when it opens, and never merely because a block was selected.\n */\nfunction BlockMenuItems({\n  editor,\n  verbs,\n}: {\n  editor: EditorState;\n  verbs: BlockActions;\n}): React.JSX.Element {\n  // The same question the bar asks, asked once, with the locks asked too:\n  // the author is about to choose between these, so each is dimmed with the\n  // lock's reason where a lock refuses it.\n  const { actions, depthMoves } = useSelectionVerbs(editor, true);\n  const run = React.useMemo(() => blockActionRunners(verbs), [verbs]);\n\n  /*\n   * Move in and Move out, after Move down: the menu's way to every move a\n   * Layers drag makes, for an author who does not drag. Run through the same\n   * verb as Alt+ArrowRight and Alt+ArrowLeft, which judges the move by the\n   * placement rule and the locks and says why when it refuses. Judged by the\n   * provider with the position function the move verb runs, component\n   * definitions included, so an item is offered exactly when pressing it\n   * would move.\n   */\n  const entries = React.useMemo(\n    () =>\n      actions.flatMap(action => {\n        const own = { ...action, run: run[action.id] };\n        return action.id !== \"move-down\"\n          ? [own]\n          : [\n              own,\n              ...depthMoves.map(move => ({\n                ...move,\n                run: () => verbs.move(move.direction),\n              })),\n            ];\n      }),\n    [actions, run, verbs, depthMoves]\n  );\n\n  return (\n    <>\n      {entries.map((action, index) => (\n        <React.Fragment key={action.id}>\n          {DESTRUCTIVE.has(action.id) || startsMenuGroup(entries, index) ? (\n            <ContextMenuSeparator />\n          ) : null}\n          <ContextMenuItem\n            disabled={!action.enabled}\n            // Stacked once there is a reason, so the explanation sits under\n            // the verb rather than running on from it.\n            className={\n              action.reason === undefined && action.note === undefined\n                ? undefined\n                : \"flex-col items-start gap-0.5\"\n            }\n            onSelect={() => {\n              action.run();\n            }}\n          >\n            <span>{action.label}</span>\n            {action.reason === undefined ? null : (\n              // Part of the item's own content, so it is both on screen and\n              // in the name the item is announced by. Nothing here stays\n              // hoverable or focusable once disabled, so an explanation\n              // carried outside the content would reach nobody.\n              <span className=\"text-xs opacity-80\">{action.reason}</span>\n            )}\n            {action.note === undefined || action.reason !== undefined ? null : (\n              // What the verb removes, said before it is chosen, where its\n              // reason would go: an open verb has no reason to show.\n              <span className=\"text-xs opacity-80\">{action.note}</span>\n            )}\n          </ContextMenuItem>\n        </React.Fragment>\n      ))}\n    </>\n  );\n}\n","\"use client\";\n\n/**\n * The floating format bar: bold, italic and a link for the words selected in\n * a passage being edited on the canvas, drawn just above them.\n *\n * ## One bar, configured per block\n *\n * It draws the actions the passage it serves was opened with\n * ({@link FormatTarget.actions}): a Text is offered \"B\", \"I\", \"Link\" and\n * \"Turn into\"; a Rich text adds \"H2\", \"H3\", bullets, numbers and quote, each\n * making the caret's block that one and, pressed again, a paragraph. The\n * verbs are the editor's own — the same ⌘B and ⌘I the keys press — so a\n * button and its shortcut cannot disagree.\n *\n * ## \"Turn into\" opens its choices in the bar\n *\n * The types the block can become, each with what it would remove, or dimmed\n * with why not, read from the same offer the block menu reads. Choosing one\n * finishes the edit, so the words typed are what is turned.\n *\n * ## It never takes the caret away by pointer\n *\n * A press on the bar keeps the focus in the passage (`mousedown` is not\n * allowed to move it), so the selection the button acts on is still there.\n * The keyboard reaches it with Alt+F10, as it reaches every toolbar in the\n * builder; Escape goes back to the words. While the focus is in the bar on the\n * passage's behalf, the passage's blur does not finish the edit\n * ({@link FormatBarStore.holdsFocus}); leaving the bar for anywhere else does.\n *\n * ## Drawn in the canvas overlay, kept clear of the block bar\n *\n * Placed in the overlay's coordinates over the selected words, above them,\n * or below them where there is no room above on screen or the block bar is\n * there, so the two bars never cover each other.\n *\n * @module format-bar\n */\n\nimport * as React from \"react\";\n\nimport type { Rect } from \"../geometry\";\nimport { BlockActionsContext } from \"../shell/block-actions-context\";\n\nimport { CANVAS_ROOT_CLASS, CHROME_ATTRIBUTE } from \"./canvas\";\nimport { BLOCK_TOOLBAR_CLASS } from \"./canvas-chrome\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport { overlaps } from \"./canvas-tab-places\";\nimport { isElement, isHTMLElement } from \"./dom-kind\";\nimport {\n  BLOCK_BUTTON_FACES,\n  blockIsOn,\n  FORMAT_BAR_WORDS,\n  linkTo,\n} from \"./format-actions\";\nimport {\n  formatBar,\n  formatBarShown,\n  isBlockAction,\n  type FormatAction,\n  type FormatBarSnapshot,\n  type FormatBlockAction,\n  type FormatTarget,\n} from \"./format-bar-state\";\nimport {\n  canvasContentRect,\n  overlaySpaceOf,\n  selectedWordsRect,\n} from \"./geometry-dom\";\nimport { TURN_INTO_TARGETS, type TurnIntoOffer } from \"./turn-into-verb\";\n\n// The bar's words, where the tests and the bar's users have always read them.\nexport { FORMAT_BAR_WORDS } from \"./format-actions\";\n\n/** The bar's class, and the notice's. */\nconst FORMAT_BAR_CLASS = \"nx-format-bar\";\nconst FORMAT_NOTICE_CLASS = \"nx-format-notice\";\n\n/** How far the bar sits from the words it acts on, in overlay pixels. */\nconst GAP_PX = 6;\n\n/** Where the bar is drawn, in the overlay's coordinates. */\ninterface Placed {\n  readonly x: number;\n  readonly y: number;\n}\n\n/**\n * Where the block bar is drawn in the same layer, from the place it was\n * given and its size, or `undefined` while it is not drawn.\n */\nfunction blockBarBox(\n  bar: HTMLElement,\n  sizeOf: (element: HTMLElement) => { width: number; height: number }\n): Rect | undefined {\n  const blockBar = bar.parentElement?.querySelector(`.${BLOCK_TOOLBAR_CLASS}`);\n  if (!isHTMLElement(blockBar)) return undefined;\n  const x = Number.parseFloat(blockBar.style.left);\n  const y = Number.parseFloat(blockBar.style.top);\n  if (!Number.isFinite(x) || !Number.isFinite(y)) return undefined;\n  return { x, y, ...sizeOf(blockBar) };\n}\n\n/**\n * Where the bar goes for the words in `target`: above them, or below where\n * the space above is off screen or under the block bar. `null` when the\n * passage is not in this overlay's canvas.\n */\nfunction placeBar(bar: HTMLElement, target: FormatTarget): Placed | null {\n  const space = overlaySpaceOf(bar, CANVAS_ROOT_CLASS);\n  if (space === null || !space.root.contains(target.element)) return null;\n  const words = space.place(selectedWordsRect(target.element, space.root));\n  const size = space.sizeOf(bar);\n  const width = space.place(canvasContentRect(space.root, space.root)).width;\n  const x = Math.max(0, Math.min(words.x, width - size.width));\n  const above = { x, y: words.y - size.height - GAP_PX };\n  const below = { x, y: words.y + words.height + GAP_PX };\n  const blockBar = blockBarBox(bar, space.sizeOf);\n  const blocked =\n    blockBar !== undefined && overlaps({ ...above, ...size }, blockBar);\n  return above.y < 0 || blocked ? below : above;\n}\n\n/** \"Turn into\" for the passage the bar serves: its choices, and the turn. */\ninterface TurnIntoAt {\n  readonly choices: () => readonly TurnIntoOffer[];\n  readonly run: (to: string) => void;\n}\n\n/**\n * The editor's \"Turn into\" verbs for the passage, where both the passage and\n * the editor offer them: judged on the words as typed, and run on the page\n * the edit leaves once it is finished.\n */\nfunction useTurnInto(target: FormatTarget): TurnIntoAt | undefined {\n  const verbs = React.useContext(BlockActionsContext)?.turnIntoIn;\n  const at = target.turnInto;\n  return React.useMemo(\n    () =>\n      verbs === undefined || at === undefined\n        ? undefined\n        : {\n            choices: () => verbs.choices(at.typedPage(), at.nodeId),\n            run: (to: string) => {\n              const page = at.finish();\n              if (page !== null) verbs.run(page, at.nodeId, to);\n            },\n          },\n    [verbs, at]\n  );\n}\n\n/**\n * The bar's buttons, in order, for the passage it serves: \"Turn into\" where\n * the block can be turned, and the block buttons where the editor can change\n * a block.\n */\nfunction drawnActions(\n  target: FormatTarget,\n  turnInto: TurnIntoAt | undefined\n): readonly FormatAction[] {\n  return target.actions.filter(action =>\n    action === \"turnInto\"\n      ? turnInto !== undefined\n      : !isBlockAction(action) || target.session.block !== undefined\n  );\n}\n\n/** Keep a press on the bar from taking the focus out of the passage. */\nfunction keepFocus(event: React.MouseEvent): void {\n  event.preventDefault();\n}\n\n/**\n * Give the words back their caret, then let the passage finish on its own\n * blur again: in that order, so the move back is not read as leaving.\n */\nfunction backToWords(target: FormatTarget): void {\n  target.session.focus();\n  formatBar.setHoldsFocus(false);\n}\n\n/** Arrow keys move between the \"Turn into\" choices, wrapping. */\nfunction moveAmongChoices(event: React.KeyboardEvent): void {\n  if (event.key !== \"ArrowDown\" && event.key !== \"ArrowUp\") return;\n  const list = event.currentTarget;\n  const items = [\n    ...list.querySelectorAll<HTMLElement>(\"[role='menuitem']:not([disabled])\"),\n  ];\n  if (items.length === 0) return;\n  event.preventDefault();\n  event.stopPropagation();\n  const at = items.indexOf(list.ownerDocument.activeElement as HTMLElement);\n  const step = event.key === \"ArrowDown\" ? 1 : -1;\n  items[(at + step + items.length) % items.length]?.focus();\n}\n\n/**\n * The \"Turn into\" choices: each type the block can become, with what it would\n * remove, or dimmed with why not. Choosing one turns the block; Escape goes\n * back to the words.\n */\nfunction TurnChoices({\n  target,\n  turnInto,\n}: {\n  target: FormatTarget;\n  turnInto: TurnIntoAt;\n}): React.JSX.Element {\n  const choices = React.useMemo(() => turnInto.choices(), [turnInto]);\n  const list = React.useRef<HTMLDivElement>(null);\n  React.useEffect(() => {\n    formatBar.setHoldsFocus(true);\n    // The first open choice, or the list itself when none is open, so the\n    // focus stays in the bar and Escape still goes back to the words.\n    const first = list.current?.querySelector<HTMLElement>(\n      \"[role='menuitem']:not([disabled])\"\n    );\n    (first ?? list.current)?.focus();\n  }, []);\n  const close = (): void => {\n    formatBar.setTurning(false);\n    backToWords(target);\n  };\n  return (\n    <div\n      ref={list}\n      role=\"menu\"\n      aria-label={FORMAT_BAR_WORDS.turnInto}\n      tabIndex={-1}\n      className={`${FORMAT_BAR_CLASS}__choices`}\n      onKeyDown={event => {\n        escapeCloses(event, close);\n        moveAmongChoices(event);\n      }}\n    >\n      {choices.map(choice => {\n        const said = choice.reason ?? choice.note;\n        return (\n          <button\n            key={choice.to}\n            type=\"button\"\n            role=\"menuitem\"\n            className={`${FORMAT_BAR_CLASS}__choice`}\n            disabled={!choice.enabled}\n            onMouseDown={keepFocus}\n            onClick={() => {\n              formatBar.setTurning(false);\n              turnInto.run(choice.to);\n            }}\n          >\n            <span>{choice.name}</span>\n            {said === undefined ? null : (\n              <span className={`${FORMAT_BAR_CLASS}__choice-note`}>{said}</span>\n            )}\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\n/** Escape in the address field closes it, and goes no further. */\nfunction escapeCloses(event: React.KeyboardEvent, close: () => void): void {\n  if (event.key !== \"Escape\") return;\n  event.preventDefault();\n  event.stopPropagation();\n  close();\n}\n\n/** \"Remove link\", offered while the selected words are a link. */\nfunction RemoveLink({\n  shown,\n  target,\n  close,\n}: {\n  shown: boolean;\n  target: FormatTarget;\n  close: () => void;\n}): React.JSX.Element | null {\n  if (!shown) return null;\n  return (\n    <button\n      type=\"button\"\n      className={`${FORMAT_BAR_CLASS}__button`}\n      onClick={() => {\n        target.session.link(null);\n        close();\n      }}\n    >\n      {FORMAT_BAR_WORDS.removeLink}\n    </button>\n  );\n}\n\n/** Why an address was refused, read out as it is said. */\nfunction RefusedAddress({\n  id,\n  shown,\n}: {\n  id: string;\n  shown: boolean;\n}): React.JSX.Element | null {\n  if (!shown) return null;\n  return (\n    <p id={id} className={`${FORMAT_BAR_CLASS}__error`} role=\"alert\">\n      {FORMAT_BAR_WORDS.badAddress}\n    </p>\n  );\n}\n\n/** The address field: where a link goes, and whether it opens a new tab. */\nfunction LinkField({\n  state,\n  target,\n}: {\n  state: FormatBarSnapshot;\n  target: FormatTarget;\n}): React.JSX.Element {\n  const current = state.selection?.link ?? null;\n  const [address, setAddress] = React.useState(current?.url ?? \"\");\n  const [newTab, setNewTab] = React.useState(current?.newTab ?? false);\n  const [refused, setRefused] = React.useState(false);\n  const input = React.useRef<HTMLInputElement>(null);\n  const errorId = React.useId();\n  React.useEffect(() => {\n    formatBar.setHoldsFocus(true);\n    input.current?.focus();\n  }, []);\n  const close = (): void => {\n    formatBar.setLinking(false);\n    backToWords(target);\n  };\n  const apply = (): void => {\n    if (linkTo(target.session, address, newTab, current !== null)) close();\n    else setRefused(true);\n  };\n  return (\n    <form\n      className={`${FORMAT_BAR_CLASS}__link`}\n      onSubmit={event => {\n        event.preventDefault();\n        apply();\n      }}\n      onKeyDown={event => escapeCloses(event, close)}\n    >\n      <input\n        ref={input}\n        className={`${FORMAT_BAR_CLASS}__address`}\n        // Text, not `url`: the browser's own check refuses an address on this\n        // site (\"/about\", \"#team\"), which a link may hold; the address is\n        // judged by the format's own rule (`isLinkableUrl`) when applied.\n        type=\"text\"\n        inputMode=\"url\"\n        aria-label={FORMAT_BAR_WORDS.address}\n        placeholder={FORMAT_BAR_WORDS.addressHint}\n        value={address}\n        aria-invalid={refused}\n        {...(refused ? { \"aria-describedby\": errorId } : {})}\n        onChange={event => {\n          setAddress(event.target.value);\n          setRefused(false);\n        }}\n      />\n      <label className={`${FORMAT_BAR_CLASS}__new-tab`}>\n        <input\n          type=\"checkbox\"\n          checked={newTab}\n          onChange={event => setNewTab(event.target.checked)}\n        />\n        {FORMAT_BAR_WORDS.newTab}\n      </label>\n      <button type=\"submit\" className={`${FORMAT_BAR_CLASS}__button`}>\n        {FORMAT_BAR_WORDS.apply}\n      </button>\n      <RemoveLink shown={current !== null} target={target} close={close} />\n      <RefusedAddress id={errorId} shown={refused} />\n    </form>\n  );\n}\n\n/** What every button of the bar shares. */\ninterface ButtonProps {\n  readonly action: FormatAction;\n  readonly state: FormatBarSnapshot;\n  readonly target: FormatTarget;\n  readonly tabbable: boolean;\n  readonly onFocusHere: () => void;\n}\n\n/** The attributes every button of the bar carries. */\nfunction commonOf(props: ButtonProps) {\n  return {\n    type: \"button\" as const,\n    className: `${FORMAT_BAR_CLASS}__button`,\n    tabIndex: props.tabbable ? 0 : -1,\n    onMouseDown: keepFocus,\n    onFocus: props.onFocusHere,\n    \"data-format-action\": props.action,\n  };\n}\n\n/** B or I: a mark, said on when the selected words carry it. */\nfunction MarkButton(\n  props: ButtonProps & { readonly mark: \"bold\" | \"italic\" }\n): React.JSX.Element {\n  const { mark, state, target } = props;\n  const bold = mark === \"bold\";\n  return (\n    <button\n      {...commonOf(props)}\n      aria-label={\n        bold ? FORMAT_BAR_WORDS.boldName : FORMAT_BAR_WORDS.italicName\n      }\n      aria-pressed={state.selection?.[mark] === true}\n      aria-keyshortcuts={bold ? \"Meta+B Control+B\" : \"Meta+I Control+I\"}\n      data-mark={mark}\n      onClick={() => target.session.format(mark)}\n    >\n      {bold ? FORMAT_BAR_WORDS.bold : FORMAT_BAR_WORDS.italic}\n    </button>\n  );\n}\n\n/** Link: opens the address field, said on when the words are a link. */\nfunction LinkButton(props: ButtonProps): React.JSX.Element {\n  return (\n    <button\n      {...commonOf(props)}\n      aria-pressed={props.state.selection?.link != null}\n      aria-keyshortcuts=\"Meta+K Control+K\"\n      onClick={() => formatBar.setLinking(true)}\n    >\n      {FORMAT_BAR_WORDS.link}\n    </button>\n  );\n}\n\n/**\n * H2, H3, bullets, numbers or quote: makes the caret's block that one, said\n * on while it is; pressed again, back to a paragraph.\n */\nfunction BlockButton(\n  props: ButtonProps & { readonly block: FormatBlockAction }\n): React.JSX.Element {\n  const { block, state, target } = props;\n  const { face, name } = BLOCK_BUTTON_FACES[block];\n  return (\n    <button\n      {...commonOf(props)}\n      aria-label={name}\n      aria-pressed={blockIsOn(state.selection, block)}\n      onClick={() => target.session.block?.(block)}\n    >\n      {face}\n    </button>\n  );\n}\n\n/** One button of the bar. */\nfunction ActionButton(props: ButtonProps): React.JSX.Element {\n  const { action } = props;\n  if (action === \"bold\" || action === \"italic\") {\n    return <MarkButton {...props} mark={action} />;\n  }\n  if (action === \"link\") return <LinkButton {...props} />;\n  if (isBlockAction(action)) return <BlockButton {...props} block={action} />;\n  return (\n    <button\n      {...commonOf(props)}\n      aria-haspopup=\"menu\"\n      aria-expanded={props.state.turning}\n      onClick={() => formatBar.setTurning(true)}\n    >\n      {FORMAT_BAR_WORDS.turnInto}\n    </button>\n  );\n}\n\n/**\n * The notice a change that lost formatting leaves under the passage: what a\n * Text keeps, and the way to Rich text where the host offers it.\n */\nfunction DroppedNotice({\n  target,\n}: {\n  target: FormatTarget;\n}): React.JSX.Element {\n  const turnInto = useTurnInto(target);\n  return (\n    <div\n      className={FORMAT_NOTICE_CLASS}\n      role=\"status\"\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n      onMouseDown={keepFocus}\n    >\n      <span>{FORMAT_BAR_WORDS.dropped}</span>\n      {turnInto === undefined ? null : (\n        <button\n          type=\"button\"\n          className={`${FORMAT_NOTICE_CLASS}__action`}\n          onClick={() => turnInto.run(TURN_INTO_TARGETS[\"turn-into-rich-text\"])}\n        >\n          {FORMAT_BAR_WORDS.toRichText}\n        </button>\n      )}\n      <button\n        type=\"button\"\n        className={`${FORMAT_NOTICE_CLASS}__action`}\n        onClick={() => formatBar.setDropped(false)}\n      >\n        {FORMAT_BAR_WORDS.dismiss}\n      </button>\n    </div>\n  );\n}\n\n/** The notice's place: just under the passage, in the overlay. */\nfunction useNoticePlace(\n  notice: React.RefObject<HTMLDivElement | null>,\n  target: FormatTarget | null,\n  shown: boolean\n): Placed | null {\n  const [place, setPlace] = React.useState<Placed | null>(null);\n  const measure = React.useCallback(() => {\n    const element = notice.current;\n    setPlace(\n      !shown || element === null || target === null\n        ? null\n        : placeUnder(element, target)\n    );\n  }, [notice, target, shown]);\n  React.useLayoutEffect(measure, [measure]);\n  React.useEffect(() => {\n    if (!shown) return;\n    return watchCanvasFor(() => notice.current, measure);\n  }, [shown, measure, notice]);\n  return place;\n}\n\n/** Just under the passage, in the overlay; `null` outside this canvas. */\nfunction placeUnder(element: HTMLElement, target: FormatTarget): Placed | null {\n  const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n  if (space === null || !space.root.contains(target.element)) return null;\n  const box = space.place(canvasContentRect(target.element, space.root));\n  return { x: box.x, y: box.y + box.height + GAP_PX };\n}\n\n/**\n * Whether Alt+F10 asked for the bar and it has not taken the focus yet. The\n * bar is drawn while it is asked, so a caret with nothing selected can still\n * reach it.\n */\nfunction useFocusRequest(request: number): {\n  readonly asked: boolean;\n  readonly done: () => void;\n} {\n  const seen = React.useRef(request);\n  const [asked, setAsked] = React.useState(false);\n  React.useEffect(() => {\n    if (request === seen.current) return;\n    seen.current = request;\n    setAsked(true);\n  }, [request]);\n  const done = React.useCallback(() => setAsked(false), []);\n  return React.useMemo(() => ({ asked, done }), [asked, done]);\n}\n\n/**\n * Take the focus to the bar's tab stop. The words' blur is told first that\n * the bar holds the focus, as moving there is still editing; and told again\n * that it does not when the focus did not arrive.\n */\nfunction focusBar(element: HTMLElement | null): void {\n  const stop = element?.querySelector<HTMLElement>('[tabindex=\"0\"]');\n  if (element === null || stop === null || stop === undefined) return;\n  formatBar.setHoldsFocus(true);\n  stop.focus();\n  if (!element.contains(element.ownerDocument.activeElement))\n    formatBar.setHoldsFocus(false);\n}\n\n/**\n * The bar, and the notice, for the passage being edited, drawn in the canvas\n * overlay it is mounted in. Draws nothing while no passage it serves is open.\n */\nexport function FormatBar(): React.JSX.Element | null {\n  const state = React.useSyncExternalStore(\n    formatBar.subscribe,\n    formatBar.get,\n    formatBar.get\n  );\n  const { target } = state;\n  if (target === null) return null;\n  return (\n    <>\n      <OpenBar state={state} target={target} />\n      {state.dropped ? <NoticeLayer target={target} /> : null}\n    </>\n  );\n}\n\n/**\n * Where the bar is drawn while it is shown, measured again whenever the\n * canvas moves under the words: an image above them loading, the canvas\n * resized, a recompiled sheet, as the block bar re-measures.\n */\nfunction useBarPlace(\n  bar: React.RefObject<HTMLDivElement | null>,\n  shown: boolean,\n  target: FormatTarget,\n  state: FormatBarSnapshot\n): Placed | null {\n  const [placed, setPlaced] = React.useState<Placed | null>(null);\n  const measure = React.useCallback(() => {\n    const element = bar.current;\n    setPlaced(shown && element !== null ? placeBar(element, target) : null);\n  }, [bar, shown, target]);\n  // Again when the address field or the \"Turn into\" choices open or close,\n  // which change the bar's size.\n  React.useLayoutEffect(measure, [\n    measure,\n    state.selection,\n    state.linking,\n    state.turning,\n  ]);\n  React.useEffect(() => {\n    if (!shown) return;\n    return watchCanvasFor(() => bar.current, measure);\n  }, [bar, shown, measure]);\n  return placed;\n}\n\n/**\n * The focus leaving the bar. For another element of the editor's own page it\n * is known at once; across into the canvas frame it is read once it has\n * landed: back in the words is still editing; anywhere else finishes the\n * edit, as leaving the words does.\n */\nfunction leaveBar(\n  bar: HTMLElement | null,\n  target: FormatTarget,\n  next: EventTarget | null\n): void {\n  const passage = target.element;\n  // Moving to another field of the editor: finished NOW, before that field can\n  // take the shared editor and supersede the words still unwritten in it.\n  if (isElement(next) && next !== passage) {\n    formatBar.setHoldsFocus(false);\n    target.finish();\n    return;\n  }\n  setTimeout(() => {\n    if (bar?.contains(bar.ownerDocument.activeElement)) return;\n    const inWords =\n      passage.ownerDocument.activeElement === passage &&\n      passage.ownerDocument.hasFocus();\n    formatBar.setHoldsFocus(false);\n    if (!inWords) target.finish();\n  }, 0);\n}\n\n/** Where an arrow, Home or End moves the bar's focus, or `undefined`. */\nfunction movedTo(key: string, stop: number, count: number): number | undefined {\n  const moves: Record<string, number> = {\n    ArrowRight: stop + 1,\n    ArrowLeft: stop - 1,\n    Home: 0,\n    End: count - 1,\n  };\n  return moves[key];\n}\n\n/** Focus the bar's button at `index`, wrapping, and answer where it landed. */\nfunction focusButton(bar: HTMLElement | null, index: number): number | null {\n  const buttons = bar?.querySelectorAll<HTMLElement>(\n    `.${FORMAT_BAR_CLASS}__button`\n  );\n  const count = buttons?.length ?? 0;\n  if (count === 0) return null;\n  const next = ((index % count) + count) % count;\n  buttons?.[next]?.focus();\n  return next;\n}\n\n/** The bar itself, for a passage being edited. */\nfunction OpenBar({\n  state,\n  target,\n}: {\n  state: FormatBarSnapshot;\n  target: FormatTarget;\n}): React.JSX.Element {\n  const bar = React.useRef<HTMLDivElement>(null);\n  const [stop, setStop] = React.useState(0);\n  const [focused, setFocused] = React.useState(false);\n  const wanted = useFocusRequest(state.focusRequest);\n  const shown = formatBarShown(state) || focused || wanted.asked;\n  const turnInto = useTurnInto(target);\n  const actions = drawnActions(target, turnInto);\n  const placed = useBarPlace(bar, shown, target, state);\n\n  // Alt+F10 from the words: drawn first, even over a caret with nothing\n  // selected, then focused once placed.\n  React.useEffect(() => {\n    if (!wanted.asked || placed === null) return;\n    wanted.done();\n    focusBar(bar.current);\n  }, [wanted, placed]);\n\n  const onKeyDown = (event: React.KeyboardEvent): void => {\n    if (state.linking || state.turning) return;\n    if (event.key === \"Escape\") {\n      event.preventDefault();\n      event.stopPropagation();\n      backToWords(target);\n      return;\n    }\n    const to = movedTo(event.key, stop, actions.length);\n    if (to === undefined) return;\n    event.preventDefault();\n    const landed = focusButton(bar.current, to);\n    if (landed !== null) setStop(landed);\n  };\n\n  return (\n    <div\n      ref={bar}\n      className={FORMAT_BAR_CLASS}\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n      role=\"toolbar\"\n      aria-orientation=\"horizontal\"\n      aria-label={FORMAT_BAR_WORDS.bar}\n      hidden={!shown}\n      data-linking={state.linking ? \"\" : undefined}\n      style={placedStyle(placed)}\n      onFocus={() => {\n        formatBar.setHoldsFocus(true);\n        setFocused(true);\n      }}\n      onBlur={event => {\n        const next = event.relatedTarget;\n        if (isElement(next) && bar.current?.contains(next)) return;\n        setFocused(false);\n        leaveBar(bar.current, target, next);\n      }}\n      onKeyDown={onKeyDown}\n    >\n      {state.linking ? (\n        <LinkField state={state} target={target} />\n      ) : state.turning && turnInto !== undefined ? (\n        <TurnChoices target={target} turnInto={turnInto} />\n      ) : (\n        actions.map((action, index) => (\n          <ActionButton\n            key={action}\n            action={action}\n            state={state}\n            target={target}\n            tabbable={index === Math.min(stop, actions.length - 1)}\n            onFocusHere={() => setStop(index)}\n          />\n        ))\n      )}\n    </div>\n  );\n}\n\n/** A placed layer's style: kept out of sight until it has a place. */\nfunction placedStyle(placed: Placed | null): React.CSSProperties {\n  return {\n    left: placed?.x ?? 0,\n    top: placed?.y ?? 0,\n    visibility: placed === null ? \"hidden\" : undefined,\n  };\n}\n\n/** The paste notice's layer, just under the passage. */\nfunction NoticeLayer({ target }: { target: FormatTarget }): React.JSX.Element {\n  const notice = React.useRef<HTMLDivElement>(null);\n  const place = useNoticePlace(notice, target, true);\n  return (\n    <div\n      ref={notice}\n      className={`${FORMAT_NOTICE_CLASS}__place`}\n      style={placedStyle(place)}\n    >\n      <DroppedNotice target={target} />\n    </div>\n  );\n}\n","/**\n * How much of a scroller's top the block toolbar keeps clear.\n *\n * @module scroll-clearance\n */\n\n/**\n * The `scroll-padding-top` that keeps both the scroller's own clearance and\n * the bar's `height` pixels clear. Pixels are compared here; anything else —\n * a percentage of the scroller, a `calc()` — is not a number of pixels this\n * can read, so the browser is asked for the larger of the two with `max()`.\n */\nexport function clearanceWith(own: string, height: number): string {\n  const bar = `${String(height)}px`;\n  const value = own.trim();\n  if (value === \"\" || value === \"auto\") return bar;\n  const pixels = /^(-?[\\d.]+)px$/.exec(value)?.[1];\n  if (pixels !== undefined) {\n    return `${String(Math.max(Number(pixels), height))}px`;\n  }\n  return `max(${value}, ${bar})`;\n}\n","\"use client\";\n\n/**\n * The floating toolbar: the structural verbs, at the block they act on.\n *\n * Every action here already existed and was reachable only by keystroke —\n * alt+Arrow to move, mod+D to duplicate, Delete to remove. An author who has\n * not read a shortcut list has no way to discover that this editor can\n * duplicate a block at all, so for most of the people using it those verbs were\n * effectively absent. This is B-16's pointer half; the breadcrumb in the bottom\n * bar is the other.\n *\n * ## It presses the SAME verbs the keys do\n *\n * The callbacks come from `useBlockActionsContext`, which is the set\n * `BlockKeyboardActions` binds. Nothing here applies an op. A toolbar with its\n * own ops would be a second answer to \"what does duplicate do\", and the two\n * would drift — the author meets that as a button and a keystroke that disagree,\n * long after either was written. It is also why the announcements are right\n * without this module containing one: the verbs announce into the single live\n * region that component owns.\n *\n * ## Why it is drawn in the canvas overlay\n *\n * The bar is positioned in the canvas's own CONTENT coordinates, which means\n * scrolling the canvas carries it along with the block at no cost — there is no\n * scroll listener here, and there is no frame on which the bar and the block it\n * names disagree. That is the same reason the drop indicator lives there.\n *\n * ## Disabled, not hidden; and still focusable\n *\n * A bar whose buttons come and go changes width and order as the selection\n * moves, so the control an author is aiming at has moved by the time they\n * arrive. Unavailable actions stay in place, dimmed.\n *\n * They also stay REACHABLE, through `aria-disabled` rather than the `disabled`\n * attribute. A disabled button is removed from the tab sequence, and the reason\n * it is disabled — \"Caption inside this block is locked\" — is precisely what a\n * keyboard or screen-reader author needs and would then never receive. The\n * press is refused in the handler instead.\n *\n * @module block-toolbar\n */\n\nimport {\n  COMPONENT_INSTANCE_TYPE,\n  componentLayersLocks,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport {\n  ArrowDown,\n  ArrowUp,\n  ClipboardCopy,\n  ClipboardPaste,\n  Component,\n  Copy,\n  CopyPlus,\n  CornerLeftUp,\n  Ellipsis,\n  FileText,\n  Group,\n  Heading,\n  LayoutTemplate,\n  Lock,\n  LockOpen,\n  Paintbrush,\n  PaintRoller,\n  Palette,\n  RefreshCw,\n  Scissors,\n  SquarePen,\n  Trash2,\n  Type,\n  Ungroup,\n  Unlink,\n  type LucideIcon,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Rect } from \"../geometry\";\nimport {\n  layersLockChangeable,\n  lockOp,\n  lockStatusOf,\n  lockViewOf,\n} from \"../inspector/inspector\";\nimport { lockRefusalWording } from \"../lock-refusal\";\nimport { lockBlockingEdit } from \"../locking\";\nimport { refusalAnnouncement } from \"../move-refusal\";\nimport { layerLabel, pathTo } from \"../panels/layers/layers\";\nimport { blockActionRunners } from \"../shell/builder-commands\";\nimport {\n  useBlockActionsContext,\n  useToolbarFocusSlot,\n} from \"../shell/keyboard-actions\";\n\nimport {\n  CANVAS_ROOT_CLASS,\n  CHROME_ATTRIBUTE,\n  outermostElementsOf,\n} from \"./canvas\";\nimport { nodeAddressOf } from \"./canvas-addressing\";\nimport { BLOCK_TOOLBAR_CLASS } from \"./canvas-chrome\";\nimport { useCanvasFrame, type CanvasFrame } from \"./canvas-frame-context\";\nimport { watchScreenBand } from \"./canvas-geometry-watch\";\nimport { useTabPost } from \"./canvas-tab-places\";\nimport { isHTMLElement } from \"./dom-kind\";\nimport { FormatBar } from \"./format-bar\";\nimport {\n  canvasContentRect,\n  canvasScroller,\n  drawnBoxes,\n  onScreenOf,\n  overlaySpaceOf,\n} from \"./geometry-dom\";\nimport { useHoveredBlock } from \"./hovered-block\";\nimport { clearanceWith } from \"./scroll-clearance\";\nimport { useSelectionActions } from \"./selection-actions\";\nimport {\n  TOOLBAR_GAP_PX,\n  type ToolbarAction,\n  type ToolbarActionId,\n  toolbarPlacement,\n  type ToolbarPlacement,\n  type ToolbarScreen,\n  unionRect,\n} from \"./toolbar-actions\";\nimport { isTurnIntoAction } from \"./turn-into-verb\";\nimport { EDITING_ATTRIBUTE } from \"./use-inline-text\";\n\n/** A rectangle on screen as the top and bottom a toolbar keeps to. */\nfunction screenBand(rect: Rect): ToolbarScreen {\n  return {\n    top: rect.y,\n    bottom: rect.y + rect.height,\n    left: rect.x,\n    right: rect.x + rect.width,\n  };\n}\n\n/**\n * The bar's stops: the lock, where one holds the block, leads the bar (on a\n * locked block it is what an author meets first), then the buttons, then\n * \"More\" where it holds any verbs.\n */\nfunction barStopsOf(\n  lock: BarLock | undefined,\n  buttons: number,\n  menu: number\n): { lock: BarLock | undefined; lead: number; stops: number } {\n  const lead = lock === undefined ? 0 : 1;\n  return { lock, lead, stops: lead + buttons + (menu > 0 ? 1 : 0) };\n}\n\n/** The bar's stepped-aside marker: present while it steps aside for typing. */\nfunction typingMark(aside: boolean): { \"data-typing\"?: \"\" } {\n  return aside ? { \"data-typing\": \"\" } : {};\n}\n\n/**\n * The bar's fade marker: present while the pointer is over a block that is\n * not selected.\n *\n * Not over a block inside the selection when the bar is drawn inside it:\n * there the bar sits over what it names, and pointing under it is pointing\n * at the selected block's own content, so it stays, and stays pressable.\n */\nfunction fadedAside(\n  hovered: string | null,\n  selectedIds: readonly string[],\n  over: { inside: boolean; document: EditorState[\"document\"] }\n): { \"data-faded\"?: \"\" } {\n  if (hovered === null || selectedIds.includes(hovered)) return {};\n  const within =\n    over.inside &&\n    pathTo(over.document, hovered).some(node => selectedIds.includes(node.id));\n  return within ? {} : { \"data-faded\": \"\" };\n}\n\n/**\n * `scroll-padding-top` on the canvas's scroller, the bar's height and gap,\n * while the bar is drawn: a block scrolled or focused into view then stops\n * below the bar rather than under it (WCAG 2.4.11), or the scroller's own\n * clearance where that is larger. In the root's coordinates,\n * the scroller's, the bar being drawn at its own size over a frame painted at\n * another. The scroller's own value comes back after.\n */\n/**\n * The elements the bar is placed against for the selected blocks: every\n * outermost element each one draws, not its first — a placement whose\n * definition draws a headline and an intro is both, and a bar placed under the\n * headline alone would sit over the intro's line. Only those that draw a box\n * (`drawnBoxes`), so a part hidden on this device adds no zero rectangle at\n * the canvas origin; a block none of whose elements draws one keeps its\n * elements, as it had before. One list for the measurement and for what is\n * watched for a change of size, so the two cannot disagree.\n */\nfunction measuredPartsOf(\n  root: HTMLElement,\n  selectedIds: readonly string[]\n): Element[] {\n  const parts: Element[] = [];\n  for (const elements of outermostElementsOf(\n    root,\n    new Set(selectedIds)\n  ).values()) {\n    const drawn = elements.flatMap(drawnBoxes);\n    parts.push(...(drawn.length > 0 ? drawn : elements));\n  }\n  return parts;\n}\n\nfunction useScrollClearance(\n  bar: React.RefObject<HTMLDivElement | null>,\n  hidden: boolean,\n  placement: ToolbarPlacement | null,\n  canvasFrame: CanvasFrame\n): void {\n  const drawn = !hidden && placement !== null;\n  React.useEffect(() => {\n    const element = bar.current;\n    if (!drawn || element === null) return;\n    const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) return;\n    const scroller = canvasScroller(space.root, space.frame !== null);\n    if (!isHTMLElement(scroller)) return;\n    const height = space.sizeOf(element).height / space.scale + TOOLBAR_GAP_PX;\n    const before = scroller.style.scrollPaddingTop;\n    // The larger of the bar's and what the scroller already keeps clear: a\n    // site keeping focused blocks below its sticky header sets its own, and\n    // the bar must not shrink that to the bar alone.\n    scroller.style.scrollPaddingTop = clearanceWith(\n      scroller.ownerDocument.defaultView?.getComputedStyle(scroller)\n        .scrollPaddingTop ?? \"\",\n      height\n    );\n    return () => {\n      scroller.style.scrollPaddingTop = before;\n    };\n  }, [bar, drawn, canvasFrame]);\n}\n\n/**\n * The selected block's Layers lock, its own or one around it, as the bar says\n * it: the canvas draws nothing else that tells a locked block from any other,\n * and the dimmed buttons only say why one at a time. Nothing for a set of\n * blocks, or a block no lock holds.\n *\n * - `unlock`: the block's own lock, which whoever edits the page may lift, so\n *   the bar offers to lift it where the author is looking.\n * - `held`: its own lock, pinned where it sits (a `contentOnly` area fixes it\n *   with the block's design), so the bar says Locked and why.\n * - `around`: the lock of a block it sits inside. Unlock acts on a block's own\n *   lock only, so the bar names that block and offers to select it, where its\n *   own bar offers Unlock.\n */\ntype BarLock =\n  | { readonly kind: \"unlock\"; readonly id: string }\n  | { readonly kind: \"held\"; readonly reason: string }\n  | { readonly kind: \"around\"; readonly id: string; readonly name: string };\n\n/** What a pinned lock says where the area it sits in gives no reason. */\nconst HELD_REASON = \"The area it sits in fixes this.\";\n\n/**\n * What a placed component's Layers lock says: the lock refusal's own words\n * for it, as an edit the component holds is refused.\n */\nconst COMPONENT_HELD_REASON = refusalAnnouncement(\n  lockRefusalWording({\n    code: \"layers-locked\",\n    label: \"\",\n    relation: \"component\",\n    verb: \"change\",\n  })\n);\n\n/**\n * Whether the block sits inside a component the page places: in the slot the\n * placement exposes, which the page fills. Only there can a component's own\n * lock hold one of the page's blocks.\n */\nfunction insidePlacement(nodes: readonly BlockNode[], id: string): boolean {\n  const search = (list: readonly BlockNode[], placed: boolean): boolean => {\n    for (const node of list) {\n      const within = placed || node.type === COMPONENT_INSTANCE_TYPE;\n      if (node.id === id) return placed;\n      for (const children of Object.values(node.slots ?? {})) {\n        if (search(children, within)) return true;\n      }\n    }\n    return false;\n  };\n  return search(nodes, false);\n}\n\n/**\n * Whether a component the page places locks the block in Layers. Only the\n * composed page shows it: the lock is in the component's own nodes, which a\n * page reaches through its placement. Composed only for a block inside a\n * placement, so selecting any other block composes nothing.\n */\nfunction lockedByComponent(editor: EditorState, id: string): boolean {\n  if (!insidePlacement(editor.document.nodes, id)) return false;\n  const composed = editor.composed();\n  return composed !== undefined && componentLayersLocks(composed.nodes).has(id);\n}\n\nfunction barLockOf(\n  editor: EditorState,\n  selectedId: string | null,\n  selectedIds: readonly string[]\n): BarLock | undefined {\n  if (selectedId === null || selectedIds.length > 1) return undefined;\n  // A placed component's own lock holds first: the page may lift only its\n  // own, which would leave the block held all the same.\n  if (lockedByComponent(editor, selectedId)) {\n    return { kind: \"held\", reason: COMPONENT_HELD_REASON };\n  }\n  const holder = lockBlockingEdit(editor.document, selectedId);\n  if (holder === undefined) return undefined;\n  if (holder.id !== selectedId) {\n    return { kind: \"around\", id: holder.id, name: layerLabel(holder) };\n  }\n  // Asked only of a block locked itself, so a click on any other block reads\n  // no slot locks.\n  const status = lockStatusOf(editor.document, selectedId, lockViewOf(editor));\n  return layersLockChangeable(status)\n    ? { kind: \"unlock\", id: selectedId }\n    : { kind: \"held\", reason: status.slot?.reason ?? HELD_REASON };\n}\n\n/**\n * Hidden while the author types in the selected block, where the bar is drawn\n * inside it: there it sits over the block's first line, which is what is\n * being typed. Back as soon as the pointer moves, the editing ends, or focus\n * comes to the bar (Alt+F10 from the text being edited).\n */\nfunction useTypingAside(\n  bar: React.RefObject<HTMLDivElement | null>,\n  inside: boolean,\n  selectedIds: readonly string[],\n  canvasFrame: CanvasFrame,\n  /**\n   * Whether the bar is drawn. A bar hidden for a drag is drawn again as a new\n   * element, which the listeners have to move to.\n   */\n  drawn: boolean\n): boolean {\n  const [aside, setAside] = React.useState(false);\n  // Keyed on the ids, not the array, which a render may hand over afresh:\n  // re-listening would bring the bar back mid-word.\n  const selected = selectedIds.join(\"\\n\");\n  // The canvas's document, held by the frame's provider: a frame that loads\n  // another page replaces it, and the listeners move to the new one.\n  const canvas = canvasFrame.document;\n  React.useEffect(() => {\n    setAside(false);\n    const element = bar.current;\n    if (!inside || !drawn || element === null) return;\n    return listenForTyping(\n      canvas ?? element.ownerDocument,\n      element,\n      selected.split(\"\\n\"),\n      setAside\n    );\n  }, [bar, inside, selected, canvas, drawn]);\n  return aside;\n}\n\n/**\n * Whether a key press writes into the text: a character, or a key that\n * removes one or breaks the line. Not a shortcut held with a modifier, nor a\n * key such as F10 or Escape, so Alt+F10 still reaches the bar.\n */\nfunction writesText(event: KeyboardEvent): boolean {\n  if (event.altKey || event.ctrlKey || event.metaKey) return false;\n  return (\n    event.key.length === 1 ||\n    event.key === \"Backspace\" ||\n    event.key === \"Delete\" ||\n    event.key === \"Enter\"\n  );\n}\n\n/**\n * Listen for typing in the selected blocks' text, telling `aside` when the\n * bar should step aside and when it should come back; returns the way to stop.\n *\n * The typing is heard in the canvas's own document, the pointer in both that\n * one and the bar's, which differ when the canvas is in a frame. The end of\n * the editing is the element being typed into losing its editing mark, so\n * that element is watched, and the watch moves with the typing.\n */\nfunction listenForTyping(\n  canvas: Document,\n  bar: HTMLElement,\n  ids: readonly string[],\n  aside: (value: boolean) => void\n): () => void {\n  const documents = new Set([canvas, bar.ownerDocument]);\n  let watched: { element: Element; observer: MutationObserver } | null = null;\n  const back = (): void => {\n    watched?.observer.disconnect();\n    watched = null;\n    aside(false);\n  };\n  const watch = (typing: Element): void => {\n    if (watched?.element === typing) return;\n    watched?.observer.disconnect();\n    watched = null;\n    const Watch = canvas.defaultView?.MutationObserver;\n    if (typeof Watch !== \"function\") return;\n    const observer = new Watch(() => {\n      if (!typing.hasAttribute(EDITING_ATTRIBUTE)) back();\n    });\n    observer.observe(typing, { attributeFilter: [EDITING_ATTRIBUTE] });\n    watched = { element: typing, observer };\n  };\n  // A key that writes, or text put in some other way: an input method's\n  // composition or a software keyboard sends `beforeinput` with no key a\n  // `keydown` names.\n  const typed = (event: Event): void => {\n    if (event.type === \"keydown\" && !writesText(event as KeyboardEvent)) {\n      return;\n    }\n    // The root as it is now, which a page loaded into the frame replaces.\n    const root = overlaySpaceOf(bar, CANVAS_ROOT_CLASS)?.root;\n    if (root === undefined) return;\n    const typing = typingIn(event.target, root, ids);\n    if (typing === null) return;\n    aside(true);\n    watch(typing);\n  };\n  canvas.addEventListener(\"keydown\", typed, true);\n  canvas.addEventListener(\"beforeinput\", typed, true);\n  bar.addEventListener(\"focusin\", back);\n  for (const each of documents) each.addEventListener(\"pointermove\", back);\n  return () => {\n    watched?.observer.disconnect();\n    canvas.removeEventListener(\"keydown\", typed, true);\n    canvas.removeEventListener(\"beforeinput\", typed, true);\n    bar.removeEventListener(\"focusin\", back);\n    for (const each of documents) each.removeEventListener(\"pointermove\", back);\n  };\n}\n\n/**\n * The element being typed into inside one of the selected blocks, or `null`\n * when the key was pressed anywhere else.\n */\nfunction typingIn(\n  target: EventTarget | null,\n  root: HTMLElement,\n  selectedIds: readonly string[]\n): Element | null {\n  if (!isHTMLElement(target) || !root.contains(target)) return null;\n  const editing = target.closest(`[${EDITING_ATTRIBUTE}]`);\n  const owner = editing?.closest(`[${NODE_ID_ATTRIBUTE}]`);\n  // The canvas's address of the element: a component's text answers with\n  // its placement, which is what is selected.\n  const id = owner == null ? null : nodeAddressOf(owner);\n  return editing !== null && id !== null && selectedIds.includes(id)\n    ? editing\n    : null;\n}\n\nconst ICONS: Record<ToolbarActionId, LucideIcon> = {\n  \"select-parent\": CornerLeftUp,\n  \"move-up\": ArrowUp,\n  \"move-down\": ArrowDown,\n  duplicate: Copy,\n  // The clipboard's own glyphs, as every editor's Edit menu draws them.\n  copy: ClipboardCopy,\n  cut: Scissors,\n  paste: ClipboardPaste,\n  // A brush picks a look up and puts it down, as a format painter does.\n  \"copy-style\": Paintbrush,\n  \"paste-style\": PaintRoller,\n  // The marks the Add panel draws for the three blocks, so a verb shows what\n  // the block becomes.\n  \"turn-into-text\": Type,\n  \"turn-into-rich-text\": FileText,\n  \"turn-into-heading\": Heading,\n  // A page outline rather than a bookmark or a star: what is stored is a piece\n  // of layout, and the same glyph names the Patterns tier in the insert panel.\n  \"save-as-pattern\": LayoutTemplate,\n  // A palette: what is saved is a look, which other blocks can wear.\n  \"save-as-shared-style\": Palette,\n  // A pen on a square, the editing glyph: the component opens to be edited.\n  \"edit-component\": SquarePen,\n  // The component mark: the selection becomes one.\n  \"turn-into-component\": Component,\n  \"detach-component\": Unlink,\n  \"duplicate-component\": CopyPlus,\n  \"update-pattern\": RefreshCw,\n  // The grouping marks: blocks gathered into one, and one let go.\n  \"wrap-in-box\": Group,\n  unwrap: Ungroup,\n  delete: Trash2,\n};\n\n/**\n * The roving stop kept on the focused button when the bar gains or loses its\n * lock control around it: a keyboard press of Select parent onto a locked\n * block keeps focus on that button while every index after the lock moves\n * by one.\n */\nfunction useStopFollowsFocus(\n  bar: React.RefObject<HTMLDivElement | null>,\n  lead: number,\n  stops: number,\n  setActiveIndex: (index: number) => void\n): void {\n  React.useEffect(() => {\n    const element = bar.current;\n    if (element === null) return;\n    const focused = element.ownerDocument.activeElement;\n    const index = [...element.querySelectorAll(\"button\")].findIndex(\n      button => button === focused\n    );\n    if (index >= 0) setActiveIndex(index);\n  }, [bar, lead, stops, setActiveIndex]);\n}\n\nexport interface BlockToolbarProps {\n  /** The editor whose selection this acts on. */\n  editor: EditorState;\n  /**\n   * Suppress the bar, for a host that is mid-gesture.\n   *\n   * A drag is the case this exists for: the bar would sit over the canvas while\n   * the author is aiming at it, and it names a block that is in the middle of\n   * moving. Rendering nothing is right rather than hiding with CSS, because a\n   * hidden bar would still be in the tab order.\n   */\n  hidden?: boolean;\n}\n\nexport function BlockToolbar({\n  editor,\n  hidden = false,\n}: BlockToolbarProps): React.JSX.Element | null {\n  const verbs = useBlockActionsContext();\n  const bar = React.useRef<HTMLDivElement | null>(null);\n\n  /*\n   * Alt+F10's way to the bar, put in this editor's slot while it is mounted:\n   * the bar's tab stop, the one button of its roving set that holds\n   * `tabindex=\"0\"`, or `null` while no bar is drawn. Through the editor's own\n   * slot rather than a search of the document, which may hold another\n   * editor's bar first.\n   */\n  const focusSlot = useToolbarFocusSlot();\n  React.useEffect(() => {\n    if (focusSlot === null) return;\n    const stop = (): HTMLElement | null =>\n      bar.current?.querySelector<HTMLElement>('[tabindex=\"0\"]') ?? null;\n    focusSlot.current = stop;\n    return () => {\n      if (focusSlot.current === stop) focusSlot.current = null;\n    };\n  }, [focusSlot]);\n  const [placement, setPlacement] = React.useState<ToolbarPlacement | null>(\n    null\n  );\n  // Where the bar is drawn, posted to the board the canvas's tabs are placed\n  // by (`canvas-tab-places.ts`): a tab or badge on the selected block's top\n  // edge, or a neighbour's, takes its next place rather than sit under the\n  // bar. The bar keeps its place; the tabs move.\n  const postBox = useTabPost(\"toolbar\");\n\n  // Still read directly: the bar MEASURES against these and re-measures when\n  // the document changes, which is a different use from deciding which verbs to\n  // offer. `document` in particular has to stay bound — dropping it does not\n  // fail, it silently resolves to the window's own.\n  const { document, selectedId } = editor;\n  const selectedIds = editor.selection.ids;\n  const actions = useSelectionActions(editor);\n  // The verbs drawn as buttons, and those kept behind \"More\". One stop in the\n  // bar's roving order stands for the whole menu.\n  const buttons = React.useMemo(\n    () => actions.filter(action => action.inMenu !== true),\n    [actions]\n  );\n  const menu = React.useMemo(\n    () => actions.filter(action => action.inMenu === true),\n    [actions]\n  );\n  const { lock, lead, stops } = barStopsOf(\n    barLockOf(editor, selectedId, selectedIds),\n    buttons.length,\n    menu.length\n  );\n\n  /*\n   * Which button holds the tab stop, per the WAI-ARIA toolbar pattern: one stop\n   * for the whole bar, arrows to move within it.\n   *\n   * Held as an index rather than an id so it survives a selection change to a\n   * block whose actions differ, and reset below when the selection moves —\n   * otherwise the stop would sit on whichever button happened to be there for\n   * the last block.\n   */\n  const [activeIndex, setActiveIndex] = React.useState(0);\n  React.useEffect(() => {\n    /*\n     * Only when focus is elsewhere.\n     *\n     * Duplicate and Select parent both CHANGE the selection, and an author who\n     * pressed one of them with the keyboard still has focus on that button.\n     * Resetting the stop to 0 there would leave the roving index and the caret\n     * on different buttons, so the next arrow press would jump backwards from\n     * where the author is looking. When the bar holds focus, `onFocus` has\n     * already put the index where the caret is.\n     */\n    const element = bar.current;\n    // Asked of the bar's OWN document, which is the one whose focused element\n    // it can contain: the window's would report an iframe around the bar\n    // whenever the bar is drawn inside a frame.\n    if (\n      element !== null &&\n      element.contains(element.ownerDocument.activeElement)\n    ) {\n      return;\n    }\n    setActiveIndex(0);\n  }, [selectedId]);\n  useStopFollowsFocus(bar, lead, stops, setActiveIndex);\n  // Kept inside the bar when it loses a stop, as when Unlock leaves it with\n  // the stop on its last button: an index past the end holds no tab stop,\n  // and the bar would be out of reach.\n  const stop = Math.min(activeIndex, Math.max(stops - 1, 0));\n\n  /*\n   * Measure after the DOM has the block but before the browser paints, so the\n   * bar never appears at a stale position first.\n   *\n   * Re-run on the document as well as the selection: an edit can resize the\n   * selected block — that is most of what the inspector does — and a bar keyed\n   * on the selection alone would stay where the block used to end.\n   */\n  const measure = React.useCallback(() => {\n    const element = bar.current;\n    if (element === null || selectedId === null) {\n      postBox(null);\n      setPlacement(null);\n      return;\n    }\n    /*\n     * The canvas the bar is drawn over, and the space it is drawn in: inside\n     * the root when the canvas shares the editor's document, or in the layer\n     * over the canvas's frame, where the root's coordinates are scaled to the\n     * frame's zoom and the bar keeps its own size.\n     */\n    const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) {\n      postBox(null);\n      setPlacement(null);\n      return;\n    }\n    const { root } = space;\n    /*\n     * Anchored to the UNION of everything selected, not to the primary.\n     *\n     * With two blocks selected at opposite ends of a page, a bar drawn at one\n     * of them describes an action about to happen to the other, which the\n     * author cannot see. The union is the shape the selection occupies.\n     */\n    const rects = measuredPartsOf(root, selectedIds).map(part =>\n      space.place(canvasContentRect(part, root))\n    );\n    const block = unionRect(rects);\n    if (block === undefined) {\n      postBox(null);\n      setPlacement(null);\n      return;\n    }\n    // The bar's own size, through the same measurement the block goes through.\n    // Its position is discarded — what is wanted is width and height — but a\n    // second way of reading a rectangle is exactly what `geometry-dom` exists\n    // to prevent, and a bar measured one way against a block measured another\n    // is a disagreement that only shows up at a scroll offset.\n    const size = space.sizeOf(element);\n    const placed = toolbarPlacement(\n      block,\n      size,\n      // The root's own box rather than its scroll extent. `scrollWidth` and\n      // `scrollHeight` are the CONTENT's size, so a long page would report a\n      // height of several thousand and the clamp would let the bar sit far\n      // outside what the author can see.\n      space.place(canvasContentRect(root, root)),\n      TOOLBAR_GAP_PX,\n      // Kept to what is on screen: room above is room above on screen, and\n      // a tall block scrolled past its top keeps its bar in view.\n      screenBand(onScreenOf(space)),\n      // Each selected block, so the bar is kept to the screen sideways only\n      // where one of them is on it.\n      rects\n    );\n    postBox(root, {\n      tabs: [],\n      taken: [{ x: placed.x, y: placed.y, ...size }],\n    });\n    setPlacement(placed);\n  }, [selectedId, selectedIds, postBox]);\n\n  /*\n   * The frame's reading as well — its scale, page and viewport: a zoom moves\n   * every block on screen while nothing inside the frame changes size, and a\n   * page that has just loaded into the frame is a root the bar has not\n   * measured against.\n   */\n  const canvasFrame = useCanvasFrame();\n  React.useLayoutEffect(() => {\n    // Hidden, the bar is not drawn, so no tab keeps clear of it.\n    if (hidden) {\n      postBox(null);\n      return;\n    }\n    measure();\n  }, [measure, hidden, document, actions, canvasFrame, postBox]);\n\n  /*\n   * Re-measure when the block changes size for a reason no render reports — an\n   * image finishing, a webfont swapping, the panels being resized around the\n   * canvas. Without this the bar sits at the position the block had while it\n   * was still loading, which is the state most pages spend their first second\n   * in.\n   */\n  React.useEffect(() => {\n    if (hidden || selectedId === null) return;\n    const element = bar.current;\n    const root =\n      element === null\n        ? null\n        : (overlaySpaceOf(element, CANVAS_ROOT_CLASS)?.root ?? null);\n    if (root === null) return;\n    // Absent in jsdom unless a test supplies one, and absent in older browsers.\n    // A missing observer costs a re-measure, not correctness — every render\n    // path above still measures. Built from the canvas root's window, the\n    // realm of the blocks it observes, which is a frame's when the canvas is in\n    // one.\n    const Sizes = root.ownerDocument.defaultView?.ResizeObserver;\n    if (typeof Sizes !== \"function\") return;\n    const observer = new Sizes(() => measure());\n\n    /*\n     * EVERY selected block, not only the primary.\n     *\n     * The bar is anchored to the union of them all, so any one of them changing\n     * size moves where it belongs. Watching the primary alone would leave the\n     * bar stale whenever a secondary block reflowed — which is most of what\n     * happens while an image loads or a webfont swaps.\n     */\n    // The very elements the bar is placed against, so a placement's later\n    // part resizing on its own (an image arriving, a font swapping) is heard.\n    for (const part of measuredPartsOf(root, selectedIds)) {\n      observer.observe(part);\n    }\n    observer.observe(root);\n    return () => observer.disconnect();\n  }, [measure, hidden, selectedId, selectedIds, document, canvasFrame]);\n\n  /*\n   * And when the canvas scrolls, or the part of it on screen resizes. The\n   * block does not move in the canvas's own coordinates, but what of it is on\n   * screen does, and the bar keeps to that: a tall block scrolled past its top\n   * takes its bar to the screen's top, and a window made too short for the\n   * bar under a block moves it there too. The scrolls heard are the ones the\n   * screen band is read from (`watchScreenBand`), the host's scroller\n   * around a zoomed frame among them, so what is heard and what is measured\n   * cannot be two different sets.\n   */\n  React.useEffect(() => {\n    if (hidden || selectedId === null) return;\n    const element = bar.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) return;\n    return watchScreenBand(space.root, space.frame, measure);\n  }, [measure, hidden, selectedId, canvasFrame]);\n\n  const hovered = useHoveredBlock();\n\n  useScrollClearance(bar, hidden, placement, canvasFrame);\n  const typingAside = useTypingAside(\n    bar,\n    placement?.side === \"inside\",\n    selectedIds,\n    canvasFrame,\n    !hidden && actions.length > 0\n  );\n\n  /*\n   * After a press that takes its own button away (Unlock, Select it), focus\n   * goes to the bar's stop rather than to nothing, so a keyboard author keeps\n   * their place in the bar.\n   */\n  const keepFocus = React.useCallback(() => {\n    const element = bar.current;\n    if (element === null) return;\n    if (!element.contains(element.ownerDocument.activeElement)) return;\n    element.ownerDocument.defaultView?.requestAnimationFrame(() => {\n      bar.current?.querySelector<HTMLElement>('[tabindex=\"0\"]')?.focus();\n    });\n  }, []);\n  const unlock = React.useCallback(\n    (id: string) => {\n      keepFocus();\n      // The op Layers' padlock applies, through the store's one apply, so it\n      // is one edit undo takes back.\n      editor.apply(lockOp(id, false));\n    },\n    [editor, keepFocus]\n  );\n  const selectHolder = React.useCallback(\n    (id: string) => {\n      keepFocus();\n      editor.select(id);\n    },\n    [editor, keepFocus]\n  );\n\n  const focusAt = React.useCallback((index: number) => {\n    setActiveIndex(index);\n    const buttons = bar.current?.querySelectorAll(\"button\");\n    const target = buttons?.[index];\n    if (isHTMLElement(target)) target.focus();\n  }, []);\n\n  const onKeyDown = React.useCallback(\n    (event: React.KeyboardEvent<HTMLDivElement>) => {\n      const count = stops;\n      if (count === 0) return;\n      // Wrapping, which the toolbar pattern lists as the common choice: the bar\n      // is five buttons, and stopping at the ends makes reaching Delete from\n      // Select parent four presses instead of one.\n      if (event.key === \"ArrowRight\") {\n        focusAt((stop + 1) % count);\n      } else if (event.key === \"ArrowLeft\") {\n        focusAt((stop - 1 + count) % count);\n      } else if (event.key === \"Home\") {\n        focusAt(0);\n      } else if (event.key === \"End\") {\n        focusAt(count - 1);\n      } else {\n        return;\n      }\n      // Only for the keys handled above. Returning first leaves Tab, Escape and\n      // every shortcut the shell binds to reach their own handlers.\n      event.preventDefault();\n    },\n    [stops, stop, focusAt]\n  );\n\n  /*\n   * A press is passed on WHATEVER the action's availability says.\n   *\n   * Every verb already refuses what it cannot do — a first block will not move\n   * up, a locked one will not be deleted — so a guard here would refuse a\n   * second time and could only ever disagree with the first. It would also cost\n   * something real: a lock refusal ANNOUNCES itself, so a dimmed Delete pressed\n   * by a keyboard author says \"Caption is locked. Unlock it to delete it.\"\n   * rather than nothing at all. That sentence is the reason the button stays\n   * pressable, and swallowing the press here would take it away.\n   */\n  // The SHARED runner map, not a second one.\n  //\n  // 🔴 The dispatch here was a chain of `else if` ending in a bare `else\n  // verbs.delete()`, so a verb added to `ToolbarActionId` and not wired did not\n  // fail to compile — it fell through and DELETED the block the author had\n  // selected. Measured: adding an id makes `ICONS` fail with TS2741 and left\n  // the dispatch silent, so the compiler pointed at the icon, a developer\n  // supplied one, and the new button then deleted things.\n  //\n  // Taken from `blockActionRunners` rather than written again here. A second\n  // exhaustive record makes the compiler demand an entry in BOTH and prove\n  // nothing about the two agreeing — this bar could be wired to a different\n  // verb than the palette and the context menu, which is the drift the\n  // exhaustiveness was added to prevent, one level up.\n  const perform = React.useMemo(() => blockActionRunners(verbs), [verbs]);\n\n  const run = React.useCallback(\n    (action: ToolbarAction) => {\n      perform[action.id]();\n    },\n    [perform]\n  );\n\n  if (hidden) return null;\n  /*\n   * The format bar for words being edited is drawn beside this bar, in the\n   * same layer, so the two are placed knowing of each other and never cover\n   * each other; it draws nothing while no passage it serves is open.\n   */\n  if (actions.length === 0) return <FormatBar />;\n\n  // Faded while the pointer is over another block: the bar sits over the\n  // block above the selection, which would otherwise be covered while the\n  // author points at it. Faded, not removed, so a pointer heading for the bar\n  // still reaches its buttons, and reaching them is pointing at chrome, which\n  // lets the hovered block go.\n  const faded = fadedAside(hovered, selectedIds, {\n    inside: placement?.side === \"inside\",\n    document,\n  });\n\n  return (\n    <>\n      <FormatBar />\n      <div\n        ref={bar}\n        className={BLOCK_TOOLBAR_CLASS}\n        // Marked as chrome so a press here is not read as a click on the page\n        // background, which would clear the very selection this bar acts on.\n        {...{ [CHROME_ATTRIBUTE]: \"\" }}\n        role=\"toolbar\"\n        aria-orientation=\"horizontal\"\n        aria-label=\"Block actions\"\n        data-side={placement?.side}\n        {...faded}\n        {...typingMark(typingAside)}\n        // Kept out of sight rather than unmounted until the first measurement.\n        // The bar has to be in the DOM to be measured at all, and mounting it at\n        // a default position would show it in the wrong place for one frame.\n        style={\n          placement === null\n            ? { visibility: \"hidden\" }\n            : { left: placement.x, top: placement.y }\n        }\n        onKeyDown={onKeyDown}\n      >\n        <BarLockControl\n          lock={lock}\n          active={stop === 0}\n          onFocus={() => setActiveIndex(0)}\n          onUnlock={unlock}\n          onSelect={selectHolder}\n        />\n        {buttons.map((action, index) => {\n          const Icon = ICONS[action.id];\n          const describedBy =\n            action.reason === undefined\n              ? undefined\n              : `nx-toolbar-reason-${action.id}`;\n          return (\n            <button\n              key={action.id}\n              type=\"button\"\n              className=\"nx-block-toolbar__button\"\n              // The name is the verb alone. Voice control activates a control by\n              // its name, so folding the reason into it would make \"click delete\"\n              // stop matching the button called Delete.\n              aria-label={action.label}\n              aria-disabled={action.enabled ? undefined : true}\n              aria-describedby={describedBy}\n              /*\n               * The description twice over: `title` for a pointer, and a hidden\n               * span for anything that reads the accessible description. `title`\n               * alone never reaches a keyboard author, who is exactly the person\n               * the reason is for.\n               *\n               * No keystroke hint here yet. A binding spelled `mod` resolves to\n               * Command on Apple platforms and Control everywhere else, so any\n               * fixed string is wrong on one of them and \"Ctrl+D\" on a Mac\n               * teaches a keystroke that does nothing.\n               *\n               * That is answerable now — `detectApplePlatform` is on\n               * `@nextlyhq/ui`'s public entry, and `key-hint.ts` spells a binding\n               * for the platform in hand. What is missing is the other half: the\n               * bar knows an action id, and the id alone does not say which\n               * binding runs it. The moves come from one table and the rest from\n               * the keystroke registrations, so a hint here needs those joined\n               * without writing a third list that can disagree with both.\n               */\n              title={action.reason ?? action.label}\n              tabIndex={lead + index === stop ? 0 : -1}\n              onFocus={() => setActiveIndex(lead + index)}\n              onClick={() => run(action)}\n            >\n              <Icon size={16} aria-hidden=\"true\" />\n              {describedBy === undefined ? null : (\n                <span id={describedBy} className=\"nx-sr-only\">\n                  {action.reason}\n                </span>\n              )}\n            </button>\n          );\n        })}\n        {menu.length === 0 ? null : (\n          <MoreMenu\n            editor={editor}\n            actions={menu}\n            index={lead + buttons.length}\n            activeIndex={stop}\n            onFocus={setActiveIndex}\n            run={run}\n          />\n        )}\n      </div>\n    </>\n  );\n}\n\n/**\n * The bar's first stop on a locked block: Unlock where the author may lift\n * the lock; Locked, dimmed with the reason, where they may not; and for a\n * block inside a locked one, the block that holds it with \"Select it\".\n */\nfunction BarLockControl({\n  lock,\n  active,\n  onFocus,\n  onUnlock,\n  onSelect,\n}: {\n  lock: BarLock | undefined;\n  active: boolean;\n  onFocus: () => void;\n  onUnlock: (id: string) => void;\n  onSelect: (id: string) => void;\n}): React.JSX.Element | null {\n  const stop = { tabIndex: active ? 0 : -1, onFocus };\n  // One editor's reason apart from another's, where two are on one page.\n  const reasonId = React.useId();\n  if (lock === undefined) return null;\n  if (lock.kind === \"unlock\") {\n    return (\n      <button\n        type=\"button\"\n        className=\"nx-block-toolbar__lock-button\"\n        {...stop}\n        onClick={() => onUnlock(lock.id)}\n      >\n        <LockOpen size={14} aria-hidden=\"true\" />\n        Unlock\n      </button>\n    );\n  }\n  if (lock.kind === \"held\") {\n    // Dimmed but reachable, as the bar's other unavailable verbs are, so the\n    // reason reaches a keyboard author as well as a pointer.\n    return (\n      <button\n        type=\"button\"\n        className=\"nx-block-toolbar__lock-button\"\n        // The name is the word alone, as the other buttons' are; the reason\n        // is the description.\n        aria-label=\"Locked\"\n        aria-disabled={true}\n        aria-describedby={reasonId}\n        title={lock.reason}\n        {...stop}\n      >\n        <Lock size={14} aria-hidden=\"true\" />\n        Locked\n        <span id={reasonId} className=\"nx-sr-only\">\n          {lock.reason}\n        </span>\n      </button>\n    );\n  }\n  return (\n    <span className=\"nx-block-toolbar__lock\" data-lock-note=\"\">\n      <Lock size={12} aria-hidden=\"true\" />\n      Locked by {lock.name}\n      {\" · \"}\n      <button\n        type=\"button\"\n        className=\"nx-block-toolbar__lock-select\"\n        title={`Select ${lock.name}`}\n        {...stop}\n        onClick={() => onSelect(lock.id)}\n      >\n        Select it\n      </button>\n    </span>\n  );\n}\n\n/**\n * The bar's last stop: the verbs kept behind \"More\", each with its reason\n * when it may not run. The reason is visible text, as in the context menu,\n * since a disabled menu item takes no focus and a tooltip would reach nobody.\n *\n * `actions` are the bar's, which ask the locks nothing; the items are drawn\n * from the same verbs with the locks asked, once the menu opens.\n */\nfunction MoreMenu({\n  editor,\n  actions,\n  index,\n  activeIndex,\n  onFocus,\n  run,\n}: {\n  editor: EditorState;\n  actions: readonly ToolbarAction[];\n  index: number;\n  activeIndex: number;\n  onFocus: (index: number) => void;\n  run: (action: ToolbarAction) => void;\n}): React.JSX.Element {\n  return (\n    // Not modal, as the block's other menus: a modal menu marks the editor\n    // around it aria-hidden while its controls stay focusable.\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild>\n        <button\n          type=\"button\"\n          className=\"nx-block-toolbar__button\"\n          aria-label=\"More actions\"\n          title=\"More actions\"\n          tabIndex={index === activeIndex ? 0 : -1}\n          onFocus={() => onFocus(index)}\n        >\n          <Ellipsis size={16} aria-hidden=\"true\" />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align=\"start\"\n        className=\"nx-block-toolbar__menu\"\n        // Chrome, so a press inside is not read as a click on the page.\n        {...{ [CHROME_ATTRIBUTE]: \"\" }}\n      >\n        <MoreMenuItems editor={editor} shown={actions} run={run} />\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/**\n * The \"More\" menu's items, drawn only while it is open: each of the bar's\n * menu verbs as the locks answer it, so a lock is asked when the author can\n * act on its answer and not on every selection.\n */\nfunction MoreMenuItems({\n  editor,\n  shown,\n  run,\n}: {\n  editor: EditorState;\n  shown: readonly ToolbarAction[];\n  run: (action: ToolbarAction) => void;\n}): React.JSX.Element {\n  const asked = useSelectionActions(editor, true);\n  const items = React.useMemo(\n    () => asked.filter(action => shown.some(each => each.id === action.id)),\n    [asked, shown]\n  );\n  return (\n    <>\n      {items.map((action, index) => {\n        const Icon = ICONS[action.id];\n        // \"Turn into\" Text, Rich text or Heading, drawn as a group of their\n        // own so they read apart from \"Turn into component…\".\n        const after = items[index - 1];\n        const parted =\n          after !== undefined &&\n          isTurnIntoAction(after.id) !== isTurnIntoAction(action.id);\n        const said = action.reason ?? action.note;\n        return (\n          <React.Fragment key={action.id}>\n            {parted ? <DropdownMenuSeparator /> : null}\n            <DropdownMenuItem\n              disabled={!action.enabled}\n              className=\"nx-block-toolbar__menu-item\"\n              onSelect={() => run(action)}\n            >\n              <Icon size={16} aria-hidden=\"true\" />\n              <span className=\"nx-block-toolbar__menu-text\">\n                <span>{action.label}</span>\n                {said === undefined ? null : (\n                  <span className=\"nx-block-toolbar__menu-reason\">{said}</span>\n                )}\n              </span>\n            </DropdownMenuItem>\n          </React.Fragment>\n        );\n      })}\n    </>\n  );\n}\n","/**\n * Where a node's spacing bands land, as arithmetic over plain numbers.\n *\n * The canvas draws an author's margin and padding as coloured bands with the\n * value written on them. Deciding WHERE each band goes is geometry, and it is\n * kept here — away from the DOM — for the reason `geometry.ts` gives about\n * itself: jsdom lays nothing out and reports every element as zero-sized, so a\n * placement rule written against live elements can only be exercised in a\n * browser. Written against numbers it can be exercised anywhere, and the browser\n * is left to certify the one thing only it can: that the numbers handed in\n * describe the element they claim to.\n *\n * ## Two coordinate spaces meet here, and they are not the same space\n *\n * `border` arrives from `canvasContentRect`, which reads `getBoundingClientRect`\n * — a POST-transform measurement, so an element drawn at half size reports half\n * the pixels. The edge lengths arrive from `getComputedStyle`, which reports\n * UNSCALED CSS pixels and knows nothing about a transform on the element or on\n * anything above it.\n *\n * `scale` is what reconciles them, and it is required rather than defaulted\n * because the mismatch is reachable TODAY: `transform` is a catalog property, so\n * an author can scale a block and every band would otherwise be wrong by exactly\n * that factor with nothing failing. It is per-axis because `scale(2, 0.5)` is\n * one value, and a single factor would be right on one axis and wrong on the\n * other.\n *\n * The LABEL never moves with it. The author typed sixteen pixels; drawing the\n * block at half size did not change what they typed, and a band reading `8`\n * would name a value that appears nowhere in their document.\n *\n * @module spacing-bands\n */\n\nimport type { EdgeLengths, Rect, Scale } from \"../geometry\";\n\nimport type { CornerRadii, RoundedShape } from \"./border-radii\";\nimport {\n  insetCornerRadii,\n  isSquare,\n  roundedShapeIn,\n  scaleCornerRadii,\n} from \"./border-radii\";\n\n/*\n * Re-exported rather than moved outright because both are the vocabulary this\n * module's callers already speak, while `border-radii.ts` needs them too and a\n * type imported FROM here would make the two modules import each other.\n */\nexport type { EdgeLengths, Scale } from \"../geometry\";\n\n/** The four physical sides, in the order a CSS shorthand writes them. */\nexport type SpacingSide = \"top\" | \"right\" | \"bottom\" | \"left\";\n\n/**\n * Which box of the CSS model a band belongs to.\n *\n * Border is measured but never drawn: it is a different catalog group, and the\n * padding box cannot be located without it.\n */\nexport type SpacingBox = \"margin\" | \"padding\";\n\n/** One band to draw, with the text that goes on it. */\nexport interface SpacingBand {\n  readonly box: SpacingBox;\n  readonly side: SpacingSide;\n  /** In the same space as the `border` rectangle it was derived from. */\n  readonly rect: Rect;\n  /** The CSS-pixel value, unscaled, as the author would recognise it. */\n  readonly label: string;\n  /**\n   * A margin that pulls the element toward the side rather than away from it.\n   *\n   * Kept as a flag rather than a negative extent because a rectangle with a\n   * negative height draws nothing: the band is laid out INSIDE the border edge\n   * instead, which is where the margin box genuinely is, and the caller styles\n   * it differently so it cannot be mistaken for padding.\n   */\n  readonly negative: boolean;\n  /**\n   * The rounded box this band's FILL has to be cut to, when one is smaller than\n   * the band.\n   *\n   * Absent on the ordinary square block, and absent on every band that lies\n   * wholly outside the block: a positive margin sits beyond the border edge,\n   * where the margin box is a plain rectangle whatever the corners do, so\n   * nothing there is drawn over ground the block does not occupy.\n   *\n   * Stated in the BAND's own coordinates, because that is what a `clip-path` on\n   * the band is resolved against.\n   */\n  readonly clip?: RoundedShape;\n  /**\n   * The container this margin is the gap OF, by name, when it is not the\n   * block's own: a container spaces every child after the first, and the\n   * child's computed margin reports that space. Absent on a margin the block\n   * carries itself, and on every padding band.\n   */\n  readonly gapFrom?: string;\n}\n\n/** Everything the placement needs, and nothing that has to be read from a DOM. */\nexport interface SpacingGeometry {\n  /** The node's border box, in canvas content coordinates, post-transform. */\n  readonly border: Rect;\n  /** Border widths, needed because padding is measured from the padding box. */\n  readonly borderWidths: EdgeLengths;\n  readonly margin: EdgeLengths;\n  readonly padding: EdgeLengths;\n  /** The scale `border` was measured at. See the module docblock. */\n  readonly scale: Scale;\n  /**\n   * The scale a MARGIN renders at, which is not always the one above.\n   *\n   * Padding and border widths lie inside the element's own transform and render\n   * scaled with it, so `scale` is right for them. A margin does not: it is laid\n   * out in the PARENT's coordinates, and the element's own transform moves only\n   * its own rendering. Measured — a 100px block with `margin-top: 28px` under a\n   * transform that pins its top edge leaves a real gap of 28 rendered pixels,\n   * while the composed scale would draw the band 14 high and name the space\n   * beside it wrongly by half.\n   *\n   * Equal to {@link scale} for the ordinary element that carries no transform of\n   * its own, which is why this is easy to miss.\n   */\n  readonly marginScale: Scale;\n  /**\n   * The border box's USED corner radii, unscaled, already resolved and reduced.\n   *\n   * Resolved by the caller because a percentage resolves against the border\n   * box's own size in LAYOUT pixels, and `border` has already been through the\n   * transform by the time it arrives here. See `border-radii.ts` for why the\n   * computed value is not the used one.\n   */\n  readonly radii: CornerRadii;\n}\n\nconst SIDES: readonly SpacingSide[] = [\"top\", \"right\", \"bottom\", \"left\"];\n\n/**\n * The value as the author would write it, to two decimals.\n *\n * A computed length is frequently fractional — a percentage, a `rem` against a\n * non-integer root, a flex remainder — and the full expansion is noise on a\n * band a few pixels tall. `String` drops the trailing zeros that `toFixed`\n * keeps, so a whole number reads as `16` rather than `16.00`, and it renders\n * negative zero as `0`.\n */\nfunction labelFor(value: number): string {\n  return String(Math.round(value * 100) / 100);\n}\n\n/**\n * Whether a side has anything to report, decided FROM the label.\n *\n * A band drawn beside the text `0` is worse than no band: eight of them appear\n * on every selection and train the author to stop reading the overlay. Asking\n * the label rather than the raw value keeps the two answers from disagreeing —\n * a length of `0.001` rounds to `0`, and the version that tests the raw value\n * draws a band that says nothing.\n */\nfunction reports(label: string): boolean {\n  return label !== \"0\";\n}\n\n/**\n * The bands for one node, in paint order.\n *\n * Margin first so padding paints over it. The two only overlap where a margin\n * is negative — that band lies inside the border edge, across the same pixels\n * padding occupies — and there the padding is the more useful of the two.\n */\nexport function spacingBands(\n  geometry: SpacingGeometry\n): readonly SpacingBand[] {\n  const { border, scale } = geometry;\n  /*\n   * Each edge scales by the axis it runs along: a left margin is a horizontal\n   * distance and a top margin a vertical one. Scaling both by one factor is\n   * right only while the transform is uniform, and `scale(2, 0.5)` is a single\n   * legal value that makes it wrong on one axis.\n   */\n  const scaledBy =\n    (by: Scale) =>\n    (edges: EdgeLengths): EdgeLengths => ({\n      top: edges.top * by.y,\n      right: edges.right * by.x,\n      bottom: edges.bottom * by.y,\n      left: edges.left * by.x,\n    });\n  const scaled = scaledBy(scale);\n\n  // Margins take the ancestors' scale alone. See `marginScale`: the element's\n  // own transform renders its box smaller without touching the space its margin\n  // reserves, so the two boxes genuinely scale differently.\n  const margin = scaledBy(geometry.marginScale)(geometry.margin);\n  const padding = scaled(geometry.padding);\n  const bands: SpacingBand[] = [];\n\n  const inward = inwardExtents(margin, border);\n  /*\n   * Two rounded shapes, because the two kinds of band sit in different boxes. A\n   * negative margin is drawn INSIDE the border edge, so it is the border box's\n   * own curve that decides where it may paint; padding is drawn inside the\n   * border, where the curve is that much tighter.\n   *\n   * Both are scaled AFTER the border widths come off, which is the order the\n   * lengths are in: a radius and a border width are both unscaled CSS pixels\n   * until the transform is applied to their difference.\n   */\n  const outerRadii = scaleCornerRadii(geometry.radii, scale);\n  const innerRadii = scaleCornerRadii(\n    insetCornerRadii(geometry.radii, geometry.borderWidths),\n    scale\n  );\n\n  for (const side of SIDES) {\n    const value = geometry.margin[side];\n    const label = labelFor(value);\n    if (!reports(label)) continue;\n    const rect = marginRect(border, side, margin, inward);\n    const negative = value < 0;\n    bands.push({\n      box: \"margin\",\n      side,\n      rect,\n      label,\n      negative,\n      // Only the negative one, which is the only margin band laid inside the\n      // border edge and so the only one a corner can cut.\n      clip: negative ? clipWithin(rect, border, outerRadii) : undefined,\n    });\n  }\n\n  /*\n   * Padding is measured from the padding box, which is the border box inset by\n   * the border. Insetting by nothing is the common case and the general form\n   * costs the same, so there is no branch for it — a block that does carry a\n   * border would otherwise draw every padding band offset by its width.\n   */\n  const inner = inset(border, scaled(geometry.borderWidths));\n\n  for (const side of SIDES) {\n    const value = geometry.padding[side];\n    const label = labelFor(value);\n    if (!reports(label)) continue;\n    const rect = paddingRect(inner, side, padding);\n    bands.push({\n      box: \"padding\",\n      side,\n      rect,\n      label,\n      negative: false,\n      clip: clipWithin(rect, inner, innerRadii),\n    });\n  }\n\n  return bands;\n}\n\n/**\n * The clip a band's fill needs, or nothing when the box it sits in has square\n * corners.\n *\n * Nothing is the answer for nearly every block, and it is worth distinguishing:\n * a `clip-path` that happens to cut nothing still puts the fill on its own\n * compositing path, and an absent clip lets the ordinary case stay ordinary.\n */\nfunction clipWithin(\n  band: Rect,\n  shape: Rect,\n  radii: CornerRadii\n): RoundedShape | undefined {\n  if (isSquare(radii)) return undefined;\n  return roundedShapeIn(band, shape, radii);\n}\n\n/** A rectangle reduced on each side, never past zero in either dimension. */\nfunction inset(rect: Rect, by: EdgeLengths): Rect {\n  return {\n    x: rect.x + by.left,\n    y: rect.y + by.top,\n    width: Math.max(0, rect.width - by.left - by.right),\n    height: Math.max(0, rect.height - by.top - by.bottom),\n  };\n}\n\n/**\n * How far each negative margin reaches INTO the border box.\n *\n * A negative margin has no bound in CSS: `margin-top: -100px` on a twenty-pixel\n * block is legal, and pulling an element further than its own size is the usual\n * way an overlap is authored. Drawn unbounded the band runs past the opposite\n * edge and colours a neighbour's pixels as this block's margin — the one thing\n * the overlay exists to answer, answered wrongly.\n *\n * Opposite sides are bounded TOGETHER, not one at a time. Clamping each to the\n * border dimension on its own still lets a pair overlap in the middle, and the\n * fills are translucent, so the contested strip darkens and reads as a third\n * value that nobody wrote. Sharing the dimension in proportion keeps each side's\n * band the larger of the two exactly when its margin is the larger, and lets\n * them meet without either crossing.\n *\n * The bound moves the band, never the number: the label is taken from the\n * authored value, so a margin clamped for want of room still reports what the\n * author typed.\n */\nfunction inwardExtents(margin: EdgeLengths, border: Rect): EdgeLengths {\n  const inwardPair = (\n    near: number,\n    far: number,\n    size: number\n  ): { near: number; far: number } => {\n    const total = near + far;\n    if (total <= size) return { near, far };\n    // `total` exceeds `size` and `size` is never negative, so `total` is\n    // positive here and the division is safe.\n    const share = size / total;\n    return { near: near * share, far: far * share };\n  };\n\n  const vertical = inwardPair(\n    Math.max(0, -margin.top),\n    Math.max(0, -margin.bottom),\n    border.height\n  );\n  const horizontal = inwardPair(\n    Math.max(0, -margin.left),\n    Math.max(0, -margin.right),\n    border.width\n  );\n  return {\n    top: vertical.near,\n    bottom: vertical.far,\n    left: horizontal.near,\n    right: horizontal.far,\n  };\n}\n\n/**\n * Where one margin band sits relative to the border box.\n *\n * A positive margin lies OUTSIDE the border edge, which is the case the box\n * model makes obvious. A negative one lies inside it: the margin box is smaller\n * than the border box on that side, because that is what pulling an element\n * toward its neighbour means. Drawing a negative margin outward would put the\n * band exactly where the space it removes is not.\n *\n * `inward` carries every side's bounded inward reach, not just this one's,\n * because a band has to know where its neighbours stop — see\n * {@link inwardExtents}.\n *\n * The two axes are separate functions rather than four arms of one switch: they\n * follow DIFFERENT rules about the corners, and writing them together meant a\n * reader had to hold both to be sure which applied.\n */\nfunction marginRect(\n  border: Rect,\n  side: SpacingSide,\n  margin: EdgeLengths,\n  inward: EdgeLengths\n): Rect {\n  const value = margin[side];\n  const outward = value >= 0;\n  const extent = outward ? value : inward[side];\n  return side === \"top\" || side === \"bottom\"\n    ? horizontalMarginRect(border, side, { extent, outward, margin })\n    : verticalMarginRect(border, side, { extent, outward, inward });\n}\n\n/**\n * The TOP or BOTTOM band, which runs across the box.\n *\n * Outward, it spans the whole MARGIN box rather than the border box. Spanning\n * the border box leaves the outer corners painted by nothing: with a top and a\n * left margin, the rectangle above-and-left of the border box belongs to the\n * margin area and no band reached it. Extending the horizontal bands over the\n * vertical margins assigns each corner exactly once — the side bands still stop\n * at the border height, so nothing is painted twice and no translucent overlap\n * darkens a corner.\n *\n * Only OUTWARD neighbours extend it. A negative margin makes the margin box\n * smaller on that side, so there is no corner out there to fill.\n */\nfunction horizontalMarginRect(\n  border: Rect,\n  side: \"top\" | \"bottom\",\n  {\n    extent,\n    outward,\n    margin,\n  }: { extent: number; outward: boolean; margin: EdgeLengths }\n): Rect {\n  const leftOut = Math.max(0, margin.left);\n  const rightOut = Math.max(0, margin.right);\n  const span = outward\n    ? { x: border.x - leftOut, width: border.width + leftOut + rightOut }\n    : { x: border.x, width: border.width };\n\n  const top = border.y;\n  const bottom = border.y + border.height;\n  let y: number;\n  if (side === \"top\") y = outward ? top - extent : top;\n  else y = outward ? bottom : bottom - extent;\n\n  return { ...span, y, height: extent };\n}\n\n/**\n * The LEFT or RIGHT band, which runs down the box.\n *\n * An INWARD one yields the corners to the horizontal bands, mirroring what\n * {@link horizontalMarginRect} does outward: there the top and bottom bands\n * span the margin box's full width and the side bands stop at the border\n * height, so each corner is painted exactly once. Inward, the horizontal bands\n * lie INSIDE the border box, and a side band spanning the full height would\n * cross them — the fills are translucent, so the corner darkens and reads as a\n * value nobody wrote.\n *\n * An outward side band needs no such inset: it sits beyond the border edge,\n * where no inward band reaches.\n */\nfunction verticalMarginRect(\n  border: Rect,\n  side: \"left\" | \"right\",\n  {\n    extent,\n    outward,\n    inward,\n  }: { extent: number; outward: boolean; inward: EdgeLengths }\n): Rect {\n  const y = outward ? border.y : border.y + inward.top;\n  const height = outward\n    ? border.height\n    : Math.max(0, border.height - inward.top - inward.bottom);\n\n  const left = border.x;\n  const right = border.x + border.width;\n  let x: number;\n  if (side === \"left\") x = outward ? left - extent : left;\n  else x = outward ? right : right - extent;\n\n  return { x, y, width: extent, height };\n}\n\n/**\n * Where one padding band sits inside the padding box.\n *\n * Top and bottom take the full width; left and right take what is left between\n * them. The alternative — all four spanning fully — draws the corners twice,\n * and padding bands are translucent, so a doubled corner reads as a heavier\n * colour that means nothing.\n *\n * Clamped at zero because padding can exceed the box it is measured in: a\n * fixed-height element with more padding than height is legal, and the\n * remainder between top and bottom is then negative.\n */\nfunction paddingRect(inner: Rect, side: SpacingSide, by: EdgeLengths): Rect {\n  /*\n   * Every extent is clamped to the box, not only the remainder between two\n   * sides. Padding can exceed the box it is measured in — `box-sizing:\n   * border-box` with a fixed height and a larger padding keeps the computed\n   * padding and collapses the content — and an unclamped band then runs past the\n   * border edge and is drawn over the neighbouring block, which is worse than\n   * drawing nothing because it names another block's space as this one's.\n   */\n  const top = Math.min(by.top, inner.height);\n  const bottom = Math.min(by.bottom, inner.height);\n  const left = Math.min(by.left, inner.width);\n  const right = Math.min(by.right, inner.width);\n  const middle = Math.max(0, inner.height - top - bottom);\n  switch (side) {\n    case \"top\":\n      return { x: inner.x, y: inner.y, width: inner.width, height: top };\n    case \"bottom\":\n      return {\n        x: inner.x,\n        y: inner.y + inner.height - bottom,\n        width: inner.width,\n        height: bottom,\n      };\n    case \"left\":\n      return { x: inner.x, y: inner.y + top, width: left, height: middle };\n    case \"right\":\n      return {\n        x: inner.x + inner.width - right,\n        y: inner.y + top,\n        width: right,\n        height: middle,\n      };\n  }\n}\n\n/**\n * Whether two band lists say the same thing, by VALUE.\n *\n * The overlay re-measures whenever the canvas moves or mutates, which on a page\n * being typed into is often. Handing React a fresh array each time re-renders\n * the whole overlay for a layout that did not move, so the caller keeps the\n * array it already has when the answer is unchanged.\n *\n * Every field is compared, not a subset. A rectangle that moved without changing\n * size, or a label that changed while the geometry held, are both real changes\n * an author must see — and a comparison that skipped either would freeze the\n * overlay in exactly the case it exists to report.\n */\nexport function sameBands(\n  left: readonly SpacingBand[],\n  right: readonly SpacingBand[]\n): boolean {\n  if (left.length !== right.length) return false;\n  return left.every((one, index) => {\n    const other = right[index];\n    return other !== undefined && sameBand(one, other);\n  });\n}\n\n/**\n * Whether two bands describe the same thing.\n *\n * Every field, not a subset. A band that MOVED without resizing, a label that\n * changed while the geometry held, and a curve that changed while both held are\n * all real changes an author has to see, and a comparison skipping any of them\n * freezes the overlay in exactly the case it exists to report.\n */\nfunction sameBand(one: SpacingBand, other: SpacingBand): boolean {\n  return (\n    one.box === other.box &&\n    one.side === other.side &&\n    one.label === other.label &&\n    one.negative === other.negative &&\n    one.gapFrom === other.gapFrom &&\n    sameRect(one.rect, other.rect) &&\n    sameClip(one.clip, other.clip)\n  );\n}\n\n/** Whether two rectangles are the same rectangle. */\nfunction sameRect(one: Rect, other: Rect): boolean {\n  return (\n    one.x === other.x &&\n    one.y === other.y &&\n    one.width === other.width &&\n    one.height === other.height\n  );\n}\n\n/**\n * Whether two bands are cut to the same shape.\n *\n * Compared because NOTHING else here changes when only the radius does. An\n * author dragging `border-radius` moves no band rectangle, no label and no\n * sign, so a comparison over those fields alone reports the bands equal, the\n * caller keeps the array it already had, and the fill stays cut to the curve the\n * block used to have — which is the case this clip exists for.\n */\nfunction sameClip(\n  left: RoundedShape | undefined,\n  right: RoundedShape | undefined\n): boolean {\n  if (left === undefined || right === undefined) return left === right;\n  return (\n    left.x === right.x &&\n    left.y === right.y &&\n    left.width === right.width &&\n    left.height === right.height &&\n    CLIP_CORNERS.every(\n      corner =>\n        left.radii[corner].x === right.radii[corner].x &&\n        left.radii[corner].y === right.radii[corner].y\n    )\n  );\n}\n\n/** The four corners, named so the comparison above cannot silently skip one. */\nconst CLIP_CORNERS = [\n  \"topLeft\",\n  \"topRight\",\n  \"bottomRight\",\n  \"bottomLeft\",\n] as const satisfies readonly (keyof CornerRadii)[];\n\n/**\n * Boxes that CSS gives no margin, whatever the computed style reports.\n *\n * `getComputedStyle` answers with the declared computed length for a property\n * that does not apply to the generated box, so an author who sets a margin on a\n * `table-row` gets a number back from a box that has none. Drawing it names\n * space that does not exist and cannot be made to exist by changing the value.\n *\n * The internal table boxes and the internal ruby boxes, both of which the\n * catalog's `display` keyword list ships. `table-caption` is deliberately absent\n * — it is not an internal table box and its margins apply normally.\n */\nconst MARGINLESS: ReadonlySet<string> = new Set([\n  \"table-row-group\",\n  \"table-header-group\",\n  \"table-footer-group\",\n  \"table-row\",\n  \"table-cell\",\n  \"table-column-group\",\n  \"table-column\",\n  \"ruby-base\",\n  \"ruby-text\",\n  \"ruby-base-container\",\n  \"ruby-text-container\",\n]);\n\n/**\n * Boxes that CSS gives no padding.\n *\n * The same set MINUS `table-cell`, which is the one internal table box padding\n * does apply to — and the distinction is the point, because a cell's padding is\n * the common case an author actually sets.\n */\nconst PADDINGLESS: ReadonlySet<string> = new Set(\n  [...MARGINLESS].filter(display => display !== \"table-cell\")\n);\n\n/**\n * Computed displays that generate a NON-ATOMIC inline box.\n *\n * These are the boxes whose block-axis margins do not affect layout. An ATOMIC\n * inline — `inline-block`, `inline-flex`, `inline-table`, `inline flow-root\n * list-item` — is inline-level too, and its margins DO apply, so the question\n * is not whether a box is inline-level but whether it is atomic.\n *\n * A set rather than an equality test, because `display` is a two-part value and\n * the catalog ships the multi-keyword forms: `inline list-item` is authorable\n * eight different ways, and `ruby` is inline-level without the word appearing in\n * it at all. Matching `\"inline\"` exactly misses both.\n *\n * Written against the COMPUTED value, which is what makes a set sufficient. The\n * browser normalises order and shorthand — every one of `list-item inline`,\n * `flow inline list-item` and `inline flow list-item` computes to `inline\n * list-item` — so the fifty-nine spellings the catalog ships collapse to\n * twenty-seven computed values, and these are the three of them that are\n * inline and non-atomic.\n *\n * Measured, every catalog display value at once, by declaring fifty pixels of\n * margin above and below and reading how far the following content moved: these\n * three moved it by zero. `contents` and `none` did too and are deliberately\n * absent — they generate no box at all, which the caller refuses outright\n * before asking this.\n */\nconst NON_ATOMIC_INLINE: ReadonlySet<string> = new Set([\n  \"inline\",\n  \"inline list-item\",\n  \"ruby\",\n]);\n\n/** Whether each physical side of one box can carry spacing at all. */\nexport interface EdgeApplicability {\n  readonly top: boolean;\n  readonly right: boolean;\n  readonly bottom: boolean;\n  readonly left: boolean;\n}\n\nconst ALL_SIDES: EdgeApplicability = {\n  top: true,\n  right: true,\n  bottom: true,\n  left: true,\n};\nconst NO_SIDES: EdgeApplicability = {\n  top: false,\n  right: false,\n  bottom: false,\n  left: false,\n};\n\n/**\n * Whether the writing mode puts the BLOCK axis vertically on screen.\n *\n * `horizontal-tb` and anything unrecognised count as horizontal, which is the\n * initial value and the overwhelming case; every `vertical-*` and `sideways-*`\n * mode turns the block axis sideways.\n */\nfunction blockAxisIsVertical(writingMode: string): boolean {\n  return (\n    !writingMode.startsWith(\"vertical\") && !writingMode.startsWith(\"sideways\")\n  );\n}\n\n/**\n * Which spacing a generated box of this display type can actually have.\n *\n * PER SIDE rather than per box, because an inline box is not all-or-nothing: a\n * non-replaced, non-atomic one takes its INLINE-axis margins and ignores its\n * BLOCK-axis ones entirely, while `getComputedStyle` reports whatever the author\n * declared on all four. A blanket answer draws top and bottom bands for space an\n * inline box does not create.\n *\n * Which displays those are is {@link NON_ATOMIC_INLINE}, and it is more than the\n * `inline` keyword: the catalog ships the multi-keyword forms, so `inline\n * list-item` and `ruby` reach here as well.\n *\n * Which physical sides those are depends on the writing mode: the block axis is\n * vertical in `horizontal-tb` and horizontal in every `vertical-*` mode. Padding\n * is left alone — an inline box's block-axis padding does not affect layout, but\n * it DOES render, and this overlay reports what renders.\n *\n * `replaced` is the exception that makes the inline branch conditional, and it\n * is not a detail of an obscure element: `core/image` renders a bare `<img>`\n * whenever it has no caption, so the most ordinary image on a page IS an inline\n * replaced root. A replaced box is sized by its own content rather than by the\n * line, and its block-axis margins are part of what the line box has to make\n * room for — measured in Chromium, fifty pixels above and below an inline\n * `<img>` moves the following content by exactly a hundred, and the same\n * declaration on a `<span>` moves it by nothing. It cannot be read off the\n * computed style, which is why the caller passes it.\n */\nexport function spacingApplies(\n  display: string,\n  writingMode: string,\n  replaced: boolean\n): { margin: EdgeApplicability; padding: EdgeApplicability } {\n  const padding = PADDINGLESS.has(display) ? NO_SIDES : ALL_SIDES;\n  if (MARGINLESS.has(display)) return { margin: NO_SIDES, padding };\n  if (!NON_ATOMIC_INLINE.has(display) || replaced)\n    return { margin: ALL_SIDES, padding };\n\n  const acrossBlock = blockAxisIsVertical(writingMode);\n  return {\n    margin: {\n      top: !acrossBlock,\n      bottom: !acrossBlock,\n      left: acrossBlock,\n      right: acrossBlock,\n    },\n    padding,\n  };\n}\n\n/** Zero the edges a generated box cannot have, keeping the ones it can. */\nexport function applicableEdges(\n  edges: EdgeLengths,\n  applies: EdgeApplicability\n): EdgeLengths {\n  return {\n    top: applies.top ? edges.top : 0,\n    right: applies.right ? edges.right : 0,\n    bottom: applies.bottom ? edges.bottom : 0,\n    left: applies.left ? edges.left : 0,\n  };\n}\n\n/**\n * How far outside its own box the overlay layer must be allowed to paint.\n *\n * A band can legitimately sit outside the canvas. The first block's top margin\n * collapses through the page wrapper and the root — neither establishes a\n * formatting context — so its band is placed above the layer entirely; a\n * negative margin or an edge-flush block can do the same on any side.\n *\n * A FIXED allowance is the wrong shape and was the first attempt: any constant\n * is too small for some legal value, and `2rem` clipped an ordinary `64px`\n * spacing step. This measures what the bands actually need instead, so the clip\n * is exactly as loose as the content requires and no looser.\n *\n * `chip` is added unconditionally because the value chip is CENTRED on its band\n * and deliberately unclipped, so a band flush with an edge overflows by its own\n * half-height even when the band itself escapes by nothing. It is bounded by the\n * chip's own size, which this package controls.\n */\nexport function overlayEscape(\n  bands: readonly SpacingBand[],\n  layer: { readonly width: number; readonly height: number },\n  chip: number\n): number {\n  let escape = 0;\n  for (const band of bands) {\n    escape = Math.max(\n      escape,\n      -band.rect.y,\n      -band.rect.x,\n      band.rect.y + band.rect.height - layer.height,\n      band.rect.x + band.rect.width - layer.width\n    );\n  }\n  return Math.max(0, escape) + chip;\n}\n","/**\n * Whose space a block's block-start margin is: the block's own, or the gap of\n * the container holding it.\n *\n * A block carries no outer margin of its own. A container that declares a\n * `childGap` spaces every child after the first with a top margin, so the\n * computed style of that child reports the gap AS its margin, and a band\n * labelled with the number alone tells the author the child carries spacing it\n * does not. The overlay names the container instead: \"Gap · from Section\".\n *\n * Decided by which rule WINS, not by what the value is. Every rule the gap\n * decides is keyed on {@link CHILD_GAP_CLASS}, which the element holding it\n * wears, so taking that one class off for a synchronous read takes the gap out\n * of the cascade and changes nothing else: the container keeps its padding,\n * font size and every other default, so a margin an author wrote in `%` or `em`\n * resolves exactly as before. If the child's margin changes, the gap was the\n * rule applying; an author's margin outranks the gap and survives unchanged,\n * even when it is the same length or reads the same token. The attribute is\n * restored inside the same task, so nothing paints and the canvas's mutation\n * watch sees no net change.\n *\n * The element holding the rule is the block's parent. It is usually the\n * container's own element; inside a configured collection loop it is the\n * entry wrapper the loop draws around each repetition, which is no node of\n * its own, so the OWNER named is the nearest enclosing node: the loop.\n *\n * @module spacing-gap\n */\n\nimport {\n  CHILD_GAP_CLASS,\n  findNode,\n  type AnyBlockDefinition,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\nimport { NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport { layerLabel } from \"../panels/layers/layers\";\n\nimport type { SpacingSide } from \"./spacing-bands\";\n\n/** The physical side a block's `margin-block-start` lands on. */\nexport function blockStartSide(writingMode: string): SpacingSide {\n  if (writingMode.startsWith(\"vertical-rl\") || writingMode === \"sideways-rl\") {\n    return \"right\";\n  }\n  if (writingMode.startsWith(\"vertical-lr\") || writingMode === \"sideways-lr\") {\n    return \"left\";\n  }\n  return \"top\";\n}\n\n/** The computed margin on one physical side, as the browser reports it. */\nfunction marginOn(style: CSSStyleDeclaration, side: SpacingSide): string {\n  switch (side) {\n    case \"top\":\n      return style.marginTop;\n    case \"right\":\n      return style.marginRight;\n    case \"bottom\":\n      return style.marginBottom;\n    case \"left\":\n      return style.marginLeft;\n  }\n}\n\n/** Whether a computed `display` lays its children out with `gap`. */\nfunction spacesWithGap(display: string): boolean {\n  return /\\b(?:flex|grid)\\b/.test(display);\n}\n\n/**\n * The name of the container whose gap this block's block-start margin is, or\n * `undefined` when the margin is the block's own (or there is none to name).\n *\n * Whether the container HAS a gap is read from the compiled page alone: the\n * marker its element wears and the probe below. The compiler marks a container\n * for whichever source declared its gap, the block definition or the compile\n * context, so asking the definition again here would miss a gap only the\n * context declares. `lookup` is the resolver the canvas renders with, used\n * only to name the container.\n */\nexport function gapOwnerOf(\n  block: Element,\n  document: BlockDocument,\n  lookup: (type: string) => AnyBlockDefinition | undefined\n): string | undefined {\n  // `> * + *`: the first child is never spaced by its container.\n  if (block.previousElementSibling === null) return undefined;\n  // The element the gap rule is keyed on, which must wear the marker.\n  const holder = block.parentElement;\n  if (holder === null || !holder.classList.contains(CHILD_GAP_CLASS)) {\n    return undefined;\n  }\n  // The node that owns it: the holder itself, or the nearest node around it.\n  const ownerId = holder\n    .closest(`[${NODE_ID_ATTRIBUTE}]`)\n    ?.getAttribute(NODE_ID_ATTRIBUTE);\n  if (ownerId === null || ownerId === undefined) return undefined;\n  const container = findNode(document.nodes, ownerId);\n  if (container === undefined) return undefined;\n  const view = block.ownerDocument.defaultView;\n  if (view === null) return undefined;\n  // A flex or grid holder spaces with `gap`, and its children's flow margin\n  // is taken off; a margin there is the child's own.\n  if (spacesWithGap(view.getComputedStyle(holder).display)) return undefined;\n\n  const style = view.getComputedStyle(block);\n  const side = blockStartSide(style.writingMode);\n  const shown = marginOn(style, side);\n  holder.classList.remove(CHILD_GAP_CLASS);\n  let withoutGap: string;\n  try {\n    withoutGap = marginOn(view.getComputedStyle(block), side);\n  } finally {\n    holder.classList.add(CHILD_GAP_CLASS);\n  }\n  return withoutGap === shown ? undefined : layerLabel(container, lookup);\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 * Turning a pointer gesture on a spacing band into a style edit.\n *\n * The bands `spacing-bands.ts` draws are PHYSICAL — a rectangle above the block\n * is its top margin — while the catalog stores spacing LOGICALLY, as block and\n * inline start and end. Everything in this module exists on the seam between\n * those two vocabularies, plus the arithmetic that turns pointer travel into a\n * number an author would recognise.\n *\n * Deliberately free of React and of the DOM. The gesture that drives it lives\n * in `spacing-handles.tsx`, which is where capture, frames and focus belong; a\n * mapping from a side to an address is a pure question and testing it through a\n * rendered component would mean pointer plumbing standing between a wrong edge\n * and the test that is supposed to name it.\n *\n * ## Why the mapping is spelled out here and not asked of CSS\n *\n * `side-orientation.ts` says a hand-written map from a logical side to a\n * physical edge \"would be a second implementation of something CSS already\n * does\", and for the inspector's box that is right: it puts `writing-mode` on a\n * grid and lets the browser place four controls. That works because the box\n * only has to LOOK right. A drag has to WRITE, and no CSS property answers\n * \"which logical side is the edge under this pointer\" — the question runs the\n * other way, from a physical edge back to the name of the value to store. So\n * the table is stated, and the tests that hold it are the whole guard.\n *\n * ## Unresolved orientation refuses, and does not fall back to left-to-right\n *\n * `orientationOfElement` reports absence rather than guessing, for the reason\n * its docblock gives: an unread element and a left-to-right one are\n * indistinguishable, and the confident wrong answer is the expensive one. A\n * handle inherits that. Absent orientation means no handles at all — a drag\n * that edited `inlineStart` on an element whose inline start is the other edge\n * moves the block the wrong way and leaves an author no way to see why.\n *\n * @module spacing-drag\n */\n\nimport type { StyleValue } from \"@nextlyhq/blocks-engine\";\n\nimport type { Scale } from \"../geometry\";\nimport type { SideOrientation } from \"../styles/side-orientation\";\nimport { measurementOf } from \"../styles/style-numeric\";\nimport type { LogicalSide } from \"../styles/style-sides\";\nimport type { StyleAddress } from \"../styles/style-values\";\n\nimport type { SpacingBox, SpacingSide } from \"./spacing-bands\";\n\n/** How much one arrow key moves a value, in CSS pixels. */\nexport const SPACING_STEP_PX = 1;\n\n/**\n * How much `PageUp` / `PageDown` moves a value.\n *\n * The coarse step is on Page rather than on `Shift`+arrow, which is where an\n * author would first reach for it. `Shift` already means \"every side\" for this\n * gesture, and it has to keep meaning that on the keyboard: WCAG 2.5.7 is\n * satisfied by a path that reaches the same VALUES as the pointer, so a\n * modifier that selected sides with one hand and step sizes with the other\n * would leave the all-sides edit reachable only by dragging.\n */\nexport const SPACING_PAGE_PX = 10;\n\n/** The four physical sides, in the order a CSS shorthand writes them. */\nconst SIDES: readonly SpacingSide[] = [\"top\", \"right\", \"bottom\", \"left\"];\n\n/** The side across the box from each one. */\nconst OPPOSITE: Record<SpacingSide, SpacingSide> = {\n  top: \"bottom\",\n  bottom: \"top\",\n  left: \"right\",\n  right: \"left\",\n};\n\n/**\n * Which physical edge the block axis starts at, and which the inline axis does\n * when the direction is left-to-right.\n *\n * Read from the CSS Writing Modes model, one row per `writing-mode` keyword:\n *\n * | mode | block start | inline start (ltr) |\n * | --- | --- | --- |\n * | `horizontal-tb` | top | left |\n * | `vertical-rl` | right | top |\n * | `vertical-lr` | left | top |\n * | `sideways-rl` | right | top |\n * | `sideways-lr` | left | **bottom** |\n *\n * `sideways-lr` is the row that is not a rotation of its neighbour and the one\n * a table built by symmetry gets wrong. Its text is turned 90° ANTI-clockwise\n * while every other vertical mode turns it clockwise, so its inline axis runs\n * up the screen and its left-to-right start is the BOTTOM edge. Reasoned from\n * the spec and then verified in a browser, because a mapping nobody can check\n * by looking at it is exactly the kind that stays wrong.\n */\nconst AXIS_STARTS = new Map<\n  string,\n  { readonly block: SpacingSide; readonly inline: SpacingSide }\n>([\n  [\"horizontal-tb\", { block: \"top\", inline: \"left\" }],\n  [\"vertical-rl\", { block: \"right\", inline: \"top\" }],\n  [\"vertical-lr\", { block: \"left\", inline: \"top\" }],\n  [\"sideways-rl\", { block: \"right\", inline: \"top\" }],\n  [\"sideways-lr\", { block: \"left\", inline: \"bottom\" }],\n]);\n\n/** The horizontal, left-to-right axes, which every unknown mode falls back to. */\nconst DEFAULT_AXES = { block: \"top\", inline: \"left\" } as const;\n\n/**\n * The logical side a physical edge of this element is.\n *\n * An unrecognised `writing-mode` is read as `horizontal-tb`, which is the\n * initial value and what `spacingApplies` already does with one. A computed\n * style answers with a keyword, so this arm is reached only by a caller\n * synthesising an orientation — and horizontal is the answer that is right\n * unless the site went out of its way.\n *\n * `direction` decides only which END of the inline axis starts, and anything\n * that is not `rtl` is read as left-to-right for the same reason.\n *\n * @param side - the physical edge the handle sits on\n * @param orientation - the edited element's writing mode and direction\n * @returns the catalog's name for that side\n */\nexport function logicalSideFor(\n  side: SpacingSide,\n  orientation: SideOrientation\n): LogicalSide {\n  /*\n   * A `Map`, so a writing mode named `constructor` or `toString` is a mode this\n   * table does not have rather than a hit on `Object.prototype`. A plain object\n   * answers those with a function, and `axes.block` is then `undefined` — which\n   * reaches none of the branches below and silently reports every edge as the\n   * inline end.\n   */\n  const axes = AXIS_STARTS.get(orientation.writingMode) ?? DEFAULT_AXES;\n  const inlineStart =\n    orientation.direction === \"rtl\" ? OPPOSITE[axes.inline] : axes.inline;\n  if (side === axes.block) return \"blockStart\";\n  if (side === OPPOSITE[axes.block]) return \"blockEnd\";\n  return side === inlineStart ? \"inlineStart\" : \"inlineEnd\";\n}\n\n/** What the author is holding down while dragging or pressing a key. */\nexport interface SpacingModifiers {\n  /** Every side of this box moves together. */\n  readonly shift: boolean;\n  /** This side and the one across from it move together. */\n  readonly alt: boolean;\n}\n\n/**\n * The physical sides one gesture edits.\n *\n * `Shift` wins over `Alt` when both are held: it is the larger set, and the\n * opposite pair is contained in it, so there is no reading of \"all four AND\n * this pair\" that is not just all four.\n *\n * Returned in shorthand order rather than in the order the modifiers imply, so\n * the ops a commit builds are in one order whatever edge the drag started from\n * — two documents that differ only in which handle was grabbed would otherwise\n * compare unequal.\n *\n * @param side - the side the handle belongs to\n * @param modifiers - what is held down\n * @returns every physical side this gesture writes\n */\nexport function spacingSidesFor(\n  side: SpacingSide,\n  modifiers: SpacingModifiers\n): readonly SpacingSide[] {\n  if (modifiers.shift) return SIDES;\n  if (modifiers.alt) {\n    const pair = new Set<SpacingSide>([side, OPPOSITE[side]]);\n    return SIDES.filter(one => pair.has(one));\n  }\n  return [side];\n}\n\n/** The two scales a band was drawn at. See `SpacingGeometry` for why there are two. */\nexport interface SpacingScales {\n  /** The scale padding and border widths render at: the block's own transform included. */\n  readonly scale: Scale;\n  /** The scale a margin renders at: the ancestors' transform only. */\n  readonly marginScale: Scale;\n}\n\n/**\n * How many CSS pixels of value one pointer movement is worth.\n *\n * ## The sign is \"thicker\", not \"up\" or \"outward\"\n *\n * A margin band lies outside the border edge and grows AWAY from the block; a\n * padding band lies inside it and grows TOWARD the middle. Dragging the top\n * margin's handle upward and the top padding's handle downward both make the\n * band under the pointer thicker, which is the one description that fits every\n * edge of both boxes — and it is what an author sees, because the handle sits\n * on the edge that moves.\n *\n * Stated as \"outward for margin, inward for padding\" it is the same table; a\n * single `outward` sign per side negated for padding is how it is written, so\n * the eight cases cannot disagree with each other.\n *\n * ## The scale is the band's own, and the caller does not choose it\n *\n * Padding renders inside the element's transform and a margin does not, so the\n * two are drawn at different scales — `SpacingGeometry` carries both for that\n * reason. Both go in here and this picks, rather than the caller passing \"the\"\n * scale: a handle that divided a margin by the composed scale is wrong by\n * exactly the block's own transform, which is invisible until someone scales a\n * block and then reports that dragging its margin moves twice as far as it\n * should.\n *\n * @param box - which box the band belongs to\n * @param side - the physical edge being dragged\n * @param movement - pointer travel in CLIENT pixels\n * @param scales - the scales the bands were measured at\n * @param outward - whether the responding edge moves AWAY from the block, which\n *   is the measured answer as it comes: NOT mirrored for a negative band, since\n *   the sign changes where the rectangle is drawn and not which edge responds\n * @returns the value change in CSS pixels, or `undefined` at an unusable scale\n */\nexport function spacingDelta(\n  box: SpacingBox,\n  side: SpacingSide,\n  movement: { readonly dx: number; readonly dy: number },\n  scales: SpacingScales,\n  outward: boolean\n): number | undefined {\n  const scale = box === \"margin\" ? scales.marginScale : scales.scale;\n  const vertical = side === \"top\" || side === \"bottom\";\n  const factor = vertical ? scale.y : scale.x;\n  /*\n   * A zero or unreadable scale has no pixels to divide by. `describable`\n   * already refuses a block collapsed to nothing, so this is the second guard\n   * rather than the only one — but dividing here would produce `Infinity` and\n   * commit it, and a refusal is the honest answer for a gesture whose distance\n   * cannot be measured.\n   */\n  if (!Number.isFinite(factor) || factor === 0) return undefined;\n  const travel = vertical ? movement.dy : movement.dx;\n  // Positive where the band grows toward the pointer's direction of travel.\n  const away = side === \"top\" || side === \"left\" ? -1 : 1;\n  const sign = outward ? away : -away;\n  const delta = (sign * travel) / factor;\n  /*\n   * `-0` normalised away. Negating a zero travel produces it, and it compares\n   * equal to zero everywhere while printing as `-0` — so it passes every guard\n   * and then appears in a serialised op, or in a message read to an author, as\n   * a value nobody wrote.\n   */\n  return delta === 0 ? 0 : delta;\n}\n\n/**\n * Where a drag on this side starts from, or why it cannot start.\n *\n * `ok: false` is a real outcome and not an error path. The band shows a number\n * for every side, so every side LOOKS draggable, and the two cases below are\n * ones where the number on screen is not something a pixel edit can move\n * without destroying what produced it.\n */\nexport type SpacingStart =\n  | { readonly ok: true; readonly px: number }\n  | { readonly ok: false; readonly reason: string };\n\n/** A stored value that is a token reference rather than a literal. */\nfunction isTokenRef(value: StyleValue): value is { $token: string } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    typeof (value as { $token?: unknown }).$token === \"string\"\n  );\n}\n\n/**\n * The pixel number a stored value holds, or `undefined`.\n *\n * DERIVED from `style-numeric`'s grammar rather than matched with a pattern of\n * this module's own. A second parser here omitted a leading `+`, a leading-dot\n * fraction and an exponent — all of them valid CSS the catalog and the compiler\n * accept — so `+10px`, `.5px` and `1e2px` rendered normally while the handle\n * beside them refused to move, with nothing on screen to explain it. The\n * numeric affordance in the inspector already asks this question; asking it the\n * same way is what keeps the two surfaces agreeing about which values are\n * draggable.\n */\nfunction pixelsOf(value: StyleValue): number | undefined {\n  const measured = measurementOf(value);\n  if (measured === undefined) return undefined;\n  /*\n   * A stored NUMBER carries no unit, and is read as pixels. `StyleValue` admits\n   * one at a length position, and the alternative — refusing it — would make a\n   * side undraggable for holding a quantity this gesture can express perfectly\n   * well. Every other unit is refused: see the docblock above on why a `rem` or\n   * a percentage must not be quietly replaced with the pixels it resolves to.\n   */\n  return measured.unit === \"px\" || measured.unit === \"\"\n    ? measured.number\n    : undefined;\n}\n\n/**\n * The pixel value a drag on this side begins at, or the reason it may not.\n *\n * ## A token is refused, not overwritten\n *\n * A side set to `{ $token: \"space-4\" }` renders whatever the token says and\n * follows it when the token moves. Committing `24px` over that severs the link\n * silently: the page looks identical at the instant of the drag and stops\n * tracking the design system forever after, which is the failure an author\n * cannot see. Refusing says so and leaves the inspector — where a token is\n * chosen deliberately — as the way to change it.\n *\n * ## So is any other unit, and `auto` most of all\n *\n * `margin` accepts `auto`, percentages and every CSS length, and the drag can\n * only speak pixels. `auto` is the one that matters: it is how a block is\n * centred, and replacing it with the pixel value it happens to resolve to\n * today un-centres the block the next time the container changes width. A\n * percentage and a `rem` are the same argument more quietly.\n *\n * ## Nothing stored is the ordinary case and is allowed\n *\n * A side with no value of its own inherits from a class, a block default or\n * nothing at all, and the band already shows the USED number. Starting there\n * and writing a pixel value is what an author asking to drag it means — the\n * first commit is an override, which is what the inspector's own fields do too.\n *\n * Rounded on the way in, so a used value of `10.5px` gives both the pointer and\n * the arrow keys the same integers to move between. Two paths that must reach\n * the same values cannot start half a pixel apart.\n *\n * @param stored - the node's OWN value at this address, if it has one\n * @param usedPx - the value the browser resolved, as the band reports it\n * @returns the starting pixel value, or the reason there is not one\n */\nexport function spacingStart(\n  stored: StyleValue | undefined,\n  usedPx: number\n): SpacingStart {\n  if (stored === undefined) {\n    return Number.isFinite(usedPx)\n      ? { ok: true, px: Math.round(usedPx) }\n      : { ok: false, reason: \"This spacing has no measured value to drag.\" };\n  }\n  if (isTokenRef(stored)) {\n    return {\n      ok: false,\n      reason: \"This side is set to a token. Change it in the Style panel.\",\n    };\n  }\n  const px = pixelsOf(stored);\n  if (px !== undefined) return { ok: true, px: Math.round(px) };\n  if (typeof stored === \"string\") {\n    return {\n      ok: false,\n      reason: `This side is set to ${stored.trim()}. Change it in the Style panel.`,\n    };\n  }\n  return {\n    ok: false,\n    reason: \"This side is not a length. Change it in the Style panel.\",\n  };\n}\n\n/**\n * The value a side lands on, given where it started and how far the drag went.\n *\n * Padding is clamped at zero because CSS has no negative padding: without the\n * clamp a drag past the edge would build `-4px`, the catalog would refuse it,\n * and the handle would appear to stick for the rest of the gesture with nothing\n * said. A margin is not clamped — `allowNegative` is in the catalog and pulling\n * a block over its neighbour is a real thing authors do.\n *\n * Rounded, matching `spacingStart`: an author dragging reads whole pixels off\n * the band, and a stored `23.7003px` is a value nobody asked for.\n *\n * @param startPx - the value the gesture began at\n * @param delta - the change so far, in CSS pixels\n * @param box - which box, since only one of them may go below zero\n * @returns the value to preview or commit\n */\nexport function spacingValue(\n  startPx: number,\n  delta: number,\n  box: SpacingBox\n): number {\n  const next = Math.round(startPx + delta);\n  return box === \"padding\" ? Math.max(0, next) : next;\n}\n\n/**\n * What one arrow key means as a pointer movement, in CSS pixels.\n *\n * Only the two keys along the band's own axis. A left arrow on a top handle is\n * left alone rather than treated as zero, so it keeps whatever meaning the\n * surrounding editor gives it instead of being swallowed by a control it does\n * not address.\n */\nconst ARROW_MOVES = new Map<\n  string,\n  { readonly dx: number; readonly dy: number }\n>([\n  [\"ArrowUp\", { dx: 0, dy: -SPACING_STEP_PX }],\n  [\"ArrowDown\", { dx: 0, dy: SPACING_STEP_PX }],\n  [\"ArrowLeft\", { dx: -SPACING_STEP_PX, dy: 0 }],\n  [\"ArrowRight\", { dx: SPACING_STEP_PX, dy: 0 }],\n]);\n\n/**\n * How far one key press moves this side's value, or `undefined` for a key that\n * means nothing here.\n *\n * ## The arrows go through the DRAG's own sign table\n *\n * An arrow is treated as a one-pixel pointer movement and put through\n * {@link spacingDelta}, rather than being given directions of its own. The two\n * paths have to agree — WCAG 2.5.7 is satisfied by a keyboard route that reaches\n * the same VALUES as the pointer, not merely by one that exists — and a second\n * table would be free to disagree about, say, whether Up grows a bottom padding.\n * That disagreement is invisible until someone compares the two by hand.\n *\n * The unit scale is passed because a key press is already a number of CSS\n * pixels: there is no canvas zoom to divide out of it.\n *\n * ## Page steps are a size, not a direction\n *\n * `PageUp` means \"more\" and `PageDown` means \"less\" whichever edge is focused,\n * so they take the sign table out of the question entirely. They carry the\n * coarse step because `Shift` is spoken for: it selects SIDES on both paths, and\n * a modifier that chose sides with the pointer and step sizes with the keyboard\n * would leave the all-sides edit reachable only by dragging.\n *\n * @param key - the `KeyboardEvent.key` that was pressed\n * @param box - which box the focused band belongs to\n * @param side - the physical edge the focused handle sits on\n * @param outward - whether the responding edge moves AWAY from the block, taken\n *   unmirrored exactly as {@link spacingDelta} takes it\n * @returns the value change in CSS pixels, or `undefined` to ignore the key\n */\nexport function spacingKeyDelta(\n  key: string,\n  box: SpacingBox,\n  side: SpacingSide,\n  outward: boolean\n): number | undefined {\n  if (key === \"PageUp\") return SPACING_PAGE_PX;\n  if (key === \"PageDown\") return -SPACING_PAGE_PX;\n  /*\n   * Up MEANS MORE on every handle, and Down means less.\n   *\n   * The handles are spinbuttons, and Up and Down are that role's own keys: a\n   * screen-reader user told they have an adjustable number expects them to work\n   * the same way on all eight, whichever edge is focused. Read spatially they\n   * would do nothing on a left or right handle at all, and would run backwards\n   * on a bottom margin and a top padding — where moving DOWN is what grows the\n   * value.\n   *\n   * The spatial reading survives beside it, on the axis each band actually runs\n   * along, because a pointer user reaches for the arrow that points the way the\n   * edge moves. The two only disagree where a numeric answer exists, and there\n   * the numeric one wins: a vertical band takes its meaning from this table,\n   * and a horizontal band keeps Left and Right as travel.\n   */\n  if (key === \"ArrowUp\") return SPACING_STEP_PX;\n  if (key === \"ArrowDown\") return -SPACING_STEP_PX;\n  /*\n   * A `Map` rather than an object literal, and it is not defensive dressing:\n   * `KeyboardEvent.key` is an arbitrary string, and an object lookup answers\n   * `constructor` with a function. Measured before this changed — a\n   * `constructor` press on a LEFT handle read `.dx` off that function, got\n   * `undefined`, and returned `NaN` as the distance to move.\n   */\n  const move = ARROW_MOVES.get(key);\n  if (move === undefined) return undefined;\n  // Across the band's own axis this key addresses nothing.\n  const vertical = side === \"top\" || side === \"bottom\";\n  if (vertical !== (move.dx === 0)) return undefined;\n  return spacingDelta(\n    box,\n    side,\n    move,\n    { scale: { x: 1, y: 1 }, marginScale: { x: 1, y: 1 } },\n    outward\n  );\n}\n\n/**\n * Whether the drawn BAND thickens away from the block, which is where its\n * handle goes.\n *\n * The box does not decide this, though a margin can look as though it settles\n * the question: lying outside the border box, growing one seems unable to move\n * it. Measured, that is false for `margin-top`, for `margin-left`, and for\n * `margin-right` on an auto-width block — `spacing-response.ts` carries the\n * table and answers for both boxes.\n *\n * A NEGATIVE band mirrors it, and this is the only question it mirrors.\n * `spacingBands` lays a negative margin INSIDE the border edge, reflected\n * across it, so the rectangle's two edges swap which of them is the far one.\n *\n * THIS IS NOT THE DRAG DIRECTION. Where the handle sits and which way the\n * NUMBER grows are separate questions, and a negative band answers them\n * differently: the value of a\n * `margin-top` rising from `-20px` to `-10px` moves the border edge DOWN, the\n * same direction it moves for a positive one, because the physical edge that\n * responds does not care about the sign. Only the rectangle is mirrored, so\n * only this is. `spacingDelta` takes the measured answer unmirrored.\n *\n * @param negative - whether a margin band is a negative one\n * @param measured - whether the band's OUTER edge was seen to respond\n */\nexport function spacingBandDrawnOutward(\n  negative: boolean,\n  measured: boolean\n): boolean {\n  return measured !== negative;\n}\n\n/** The address one side of one box occupies at the tier being edited. */\nexport function spacingAddress(\n  box: SpacingBox,\n  side: LogicalSide,\n  tier: { readonly state: StyleAddress[\"state\"]; readonly breakpoint: string }\n): StyleAddress {\n  return {\n    state: tier.state,\n    breakpoint: tier.breakpoint,\n    // The catalog's key IS the box name for both boxes, so there is no table\n    // here to fall out of step with `catalog.ts`.\n    property: box,\n    path: [side],\n  };\n}\n\n/** The value a style write carries for a pixel length. */\nexport function spacingCssValue(px: number): string {\n  return `${String(px)}px`;\n}\n","\"use client\";\n\n/**\n * The interactive half of the spacing overlay.\n *\n * Stage 1 draws bands that report. This turns each one into something an author\n * can move: a handle on the edge that grows, a scrub preview while the pointer\n * is down, and ONE op when it comes up.\n *\n * ## Why this is not inside `spacing-overlay.tsx`\n *\n * The bands are `aria-hidden`, deliberately — the same numbers are in the\n * inspector with real labels, and announcing eight of them on every arrow-key\n * move through the layer tree would bury that surface. A handle is the exact\n * opposite: it is focusable, and a focusable element inside an `aria-hidden`\n * subtree is a defect in every audit tool that exists, because a keyboard user\n * can reach something a screen reader is told is not there. So the bands keep\n * their `aria-hidden` and the handles sit beside them rather than within.\n *\n * ## One gesture, one entry in the history\n *\n * The document is written exactly once per gesture, on release. Everything\n * during the drag is a stylesheet this component mounts and throws away, which\n * is what `style-scrub.ts` was built for and what makes fifty pointer moves\n * cost one undo rather than fifty. The multi-side cases go through\n * `styleWriteOps`, which folds them into a single op — four `styleWriteOp`\n * calls would each carry a whole `styles` envelope and the last would win.\n *\n * ## The keyboard and the pointer are the SAME edit\n *\n * WCAG 2.5.7 asks for a non-drag path to anything reachable by dragging, and a\n * second implementation of \"what does this gesture write\" would satisfy the\n * letter of that while drifting from the pointer within a release. So both\n * paths call one `commit`, and both derive their direction from\n * `spacingDelta` — an arrow key is a one-pixel pointer movement, run through\n * the same sign table. The modifiers mean the same thing on both, which is why\n * the coarse keyboard step is on `PageUp`/`PageDown` rather than on `Shift`.\n *\n * ## A side showing nothing has no handle, and that is not a 2.5.7 gap\n *\n * `spacingBands` draws no band for a side that reports `0`, so there is nothing\n * to put a handle on. Such a side cannot be dragged either, so there is no drag\n * path needing an equivalent; the inspector's own fields are how a value starts\n * from nothing, and they are the click path this row's acceptance names.\n *\n * ## The preview's known edge, stated rather than hidden\n *\n * `scrubPreviewCss` warns that a rule mounted after the WHOLE compiled sheet\n * outranks the interaction states as well as the base one. This mounts after\n * the sheet, so while a BASE-state drag is in flight on a node that also\n * declares the same property for `hover`, hovering the block shows the scrubbed\n * base value instead of the hover value. It lasts only as long as the gesture,\n * the commit is unaffected, and placing the element beside the rules for its\n * own state needs the provenance trace the host does not pass here.\n *\n * @module spacing-handles\n */\n\nimport {\n  getBlock,\n  nodeClassNames,\n  stylePropertiesForSupports,\n  walkNodes,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Rect } from \"../geometry\";\nimport {\n  followScrub,\n  scrubModifiersOf,\n  type ScrubSession,\n  type ScrubTravel,\n} from \"../scrub-gesture\";\nimport type { SideOrientation } from \"../styles/side-orientation\";\nimport {\n  scrubCommitOps,\n  scrubPreviewCss,\n  type ScrubTarget,\n} from \"../styles/style-scrub\";\nimport {\n  readStyleValue,\n  type StyleAddress,\n  type StyleWrite,\n} from \"../styles/style-values\";\n\nimport { CANVAS_ROOT_CLASS, CHROME_ATTRIBUTE } from \"./canvas\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\n// The one test of two rectangles sharing pixels the canvas's chrome uses.\nimport { overlaps } from \"./canvas-tab-places\";\nimport { canvasPointerPoints, overlaySpaceOf } from \"./geometry-dom\";\nimport type {\n  EdgeLengths,\n  SpacingBand,\n  SpacingBox,\n  SpacingSide,\n} from \"./spacing-bands\";\nimport {\n  logicalSideFor,\n  spacingAddress,\n  spacingCssValue,\n  spacingDelta,\n  spacingBandDrawnOutward,\n  spacingKeyDelta,\n  spacingSidesFor,\n  spacingStart,\n  spacingValue,\n  type SpacingModifiers,\n  type SpacingScales,\n} from \"./spacing-drag\";\n\n/** Everything about the measured block a gesture needs, taken once. */\nexport interface SpacingSubject {\n  readonly nodeId: string;\n  /** The used margins, in unscaled CSS pixels, as the bands report them. */\n  readonly margin: EdgeLengths;\n  /** The used paddings, in unscaled CSS pixels. */\n  readonly padding: EdgeLengths;\n  readonly scales: SpacingScales;\n  /**\n   * How the element runs, or `undefined` when it could not be read.\n   *\n   * Absent means NO handles. See `spacing-drag.ts`: a physical edge cannot be\n   * turned into a logical address without it, and guessing left-to-right edits\n   * the opposite side of every right-to-left block.\n   */\n  readonly orientation: SideOrientation | undefined;\n  /**\n   * Whether each band thickens AWAY from the block, per box and side.\n   *\n   * MEASURED rather than assumed, for both boxes. Which edge moves depends on\n   * the layout: a block whose height fits its content grows its border edge\n   * outward when its padding grows, one with a fixed height moves the content\n   * edge inward — and a `margin-top` in normal flow moves the border edge down\n   * while its outer edge stays pinned by whatever precedes it, which is the\n   * opposite of what `margin-bottom` does. See `spacing-response.ts`. A handle\n   * placed on the wrong edge sits still while the block moves away from it, and\n   * the drag runs backwards.\n   */\n  readonly outward: Readonly<\n    Record<SpacingBox, Readonly<Record<SpacingSide, boolean>>>\n  >;\n}\n\n/** The tier a scrub writes to, and what the canvas compiled it with. */\nexport interface SpacingScrubContext {\n  readonly address: Pick<StyleAddress, \"state\" | \"breakpoint\">;\n  readonly breakpoints?: ScrubTarget[\"breakpoints\"];\n  readonly previewContainer?: string;\n  readonly tokenPrefix?: string;\n  readonly policy?: ScrubTarget[\"policy\"];\n  readonly scope?: string;\n}\n\nexport interface SpacingHandlesProps {\n  readonly editor: EditorState;\n  readonly bands: readonly SpacingBand[];\n  readonly subject: SpacingSubject;\n  readonly context: SpacingScrubContext;\n  /**\n   * Re-measure the bands, because a preview has changed what they describe.\n   *\n   * Asked for EXPLICITLY rather than left to the overlay's own observers, and\n   * the reason is in `canvas-geometry-watch.ts`: the style mutation watcher\n   * ignores every record inside the overlay's own layer, so that drawing the\n   * bands cannot schedule the next measurement. The scrub preview is a `<style>`\n   * inside that layer, so it is invisible to the watcher by the same rule — and\n   * `ResizeObserver` reports size, never position, so a margin preview that\n   * moves a fixed-size block reports nothing either. Without this the block\n   * slides under a band and a value chip that stay where the gesture started.\n   */\n  readonly onPreviewChange?: () => void;\n  /**\n   * Whether a gesture is in flight, so the host can keep this mounted.\n   *\n   * A preview can make its own block undescribable, and the measurement that\n   * follows then has nothing to draw. Unmounting on that removes the control the\n   * pointer is holding: the listeners detach, the preview goes, and the drag\n   * ends without committing and without a word. The host keeps the subject\n   * alive while this is true.\n   */\n  readonly onGestureChange?: (held: boolean) => void;\n}\n\n/**\n * How thick a handle's hit area is, in the author's pixels: 24, the minimum\n * target WCAG 2.2 asks of a pointer control, where its band has the room.\n */\nconst HANDLE_SCREEN_PX = 24;\n\n/**\n * The least a handle's hit area is, in the author's pixels, on a band thinner\n * than this: centred on the band, so it reaches past it by a few pixels at\n * most. The Style panel's spacing fields edit the same values at full size.\n */\nconst HANDLE_FLOOR_PX = 9;\n\n/** A gesture in flight. */\ninterface Gesture {\n  readonly band: SpacingBand;\n  /**\n   * Which way the value grows, frozen at the press.\n   *\n   * A drag must not reverse under the hand. The answer is MEASURED, so it can\n   * change while the pointer is down — the drag's own preview resizes the block,\n   * and a block that gains a settled width answers the opposite way — and a\n   * gesture that read it fresh would send the pointer one way and the number the\n   * other, mid-stroke. Frozen for the same reason as the scale and the starting\n   * values above it: these are properties OF the gesture.\n   */\n  readonly valueOutward: boolean;\n  /** Every side of this box that has a usable starting value. */\n  readonly starts: ReadonlyMap<SpacingSide, number>;\n  /** Why each remaining side has none. See `commit`. */\n  readonly refusals: ReadonlyMap<SpacingSide, string>;\n  /** The pointer's part: threshold, capture and listeners. See `onPointerDown`. */\n  readonly session: ScrubSession;\n  /**\n   * The modifiers the last preview was drawn with.\n   *\n   * The commit reads THIS rather than the release event. Letting go of Shift\n   * before letting go of the button is an ordinary way to end a gesture, and\n   * the two events then disagree: the canvas last showed four sides moving and\n   * the release would write one. Whatever the author last SAW is what they\n   * asked for.\n   */\n  shown: SpacingModifiers;\n}\n\n/**\n * A band that has been measured away, at the edge it collapsed to.\n *\n * `spacingBands` omits a side reporting `0`, and the band is only missing\n * because the drag took it there — so the honest picture is not the geometry it\n * had when the gesture began. Kept at its starting rectangle the handle sits\n * wherever the old value put it, which for a large padding is visibly far from\n * the pointer, and reports that old number to assistive technology for the rest\n * of the drag.\n *\n * The FIXED edge is the one that does not move: a band collapses onto it. Which\n * that is follows from the same table `handleRect` uses, read the other way\n * round.\n */\nfunction collapsed(band: SpacingBand, outward: boolean): SpacingBand {\n  const { rect, side } = band;\n  const far = side === \"bottom\" || side === \"right\";\n  const atMax = far === outward;\n  const vertical = side === \"top\" || side === \"bottom\";\n  // The moving edge has met the fixed one, so the band has no extent left.\n  const anchored = atMax\n    ? { ...rect, ...(vertical ? { height: 0 } : { width: 0 }) }\n    : {\n        ...rect,\n        ...(vertical\n          ? { y: rect.y + rect.height, height: 0 }\n          : { x: rect.x + rect.width, width: 0 }),\n      };\n  return { ...band, rect: anchored, label: \"0\" };\n}\n\n/**\n * Apply a settled write, answering with the reason it did not land.\n *\n * The two `null`s here mean opposite things and only one of them is a refusal.\n * From the VALUE layer, `op: null` says the document already holds this — the\n * ordinary end of a drag that came back to where it started. From\n * `editor.apply`, `null` says the op was REJECTED, a document limit being the\n * likely cause, and nothing moved. Announcing the new value there tells a\n * screen-reader user an edit landed while the canvas snaps back to what it was.\n */\nfunction applied(editor: EditorState, result: StyleWrite): string | undefined {\n  if (!result.ok) {\n    return (\n      result.issues[0]?.message ?? \"That spacing value cannot be used here.\"\n    );\n  }\n  if (result.op === null) return undefined;\n  return editor.apply(result.op) === null\n    ? \"That spacing change was not applied.\"\n    : undefined;\n}\n\n/**\n * Where every band's handle sits, in the bands' order.\n *\n * Each is placed alone first, and a handle whose strip would overlap another\n * on its side is placed again, splitting the stretch the two share. Both\n * passes at the one `scale`: at a zoom the least size grows in the bands'\n * units, so two strips that clear each other at 100% can overlap at 50%, and\n * a check made at another scale than the placement would miss it.\n *\n * @param edgeOf - whether a band's moving edge is its outward one\n * @param scale - the canvas's painted zoom, 1 outside a frame\n * @internal\n */\nexport function placeHandles(\n  bands: readonly SpacingBand[],\n  edgeOf: (band: SpacingBand) => boolean,\n  scale: number\n): Rect[] {\n  const alone = bands.map(band =>\n    handleRect(band, edgeOf(band), undefined, scale)\n  );\n  return bands.map((band, index) => {\n    const own = alone[index];\n    if (own === undefined) throw new Error(\"a band without a handle\");\n    const partner = bands.findIndex((other, at) => {\n      const theirs = alone[at];\n      return (\n        at !== index &&\n        other.side === band.side &&\n        theirs !== undefined &&\n        overlaps(own, theirs)\n      );\n    });\n    const other = bands[partner];\n    return other === undefined\n      ? own\n      : handleRect(band, edgeOf(band), shareWith(band, other), scale);\n  });\n}\n\n/**\n * The stretch two overlapping handles split between them: the union of their\n * bands along the side's axis, and which half this one takes.\n */\ninterface HandleShare {\n  readonly low: number;\n  readonly room: number;\n  /** This handle takes the half at the block's outside: the margin's. */\n  readonly outer: boolean;\n}\n\n/** The share of `band`'s handle beside `other`'s, which it overlaps. */\nfunction shareWith(band: SpacingBand, other: SpacingBand): HandleShare {\n  const across = band.side === \"top\" || band.side === \"bottom\";\n  const from = (rect: Rect) => (across ? rect.y : rect.x);\n  const to = (rect: Rect) =>\n    across ? rect.y + rect.height : rect.x + rect.width;\n  const low = Math.min(from(band.rect), from(other.rect));\n  const high = Math.max(to(band.rect), to(other.rect));\n  return { low, room: high - low, outer: band.box === \"margin\" };\n}\n\n/**\n * Where a handle's strip sits on its band.\n *\n * INSIDE the band, flush with the edge that moves. The band is the one place a\n * press can only mean this control: past its outer edge is the neighbour the\n * margin spaces the block from, and past its inner edge are the block's own\n * children, and a press on either has to select what is there. A centred\n * strip reached half its thickness into both.\n *\n * A band thinner than the strip is the strip, all of it; one thinner than\n * {@link HANDLE_FLOOR_PX} gets that much, centred on it.\n *\n * `share` splits the stretch two handles would overlap on. A negative\n * margin's band is laid inside the border edge, where padding's is, so the two\n * start at one edge; the padding's, drawn later, would otherwise take every\n * press there. The margin takes the half at the block's outside and the\n * padding the half inside it, the order the two boxes have, so both strips\n * take pointer events.\n */\nfunction handleRect(\n  band: SpacingBand,\n  outward: boolean,\n  share?: HandleShare,\n  scale = 1\n): Rect {\n  const { rect, side } = band;\n  const across = side === \"top\" || side === \"bottom\";\n  const far = side === \"bottom\" || side === \"right\";\n  const size = HANDLE_SCREEN_PX / scale;\n  const floor = HANDLE_FLOOR_PX / scale;\n  const at = (from: number, thickness: number): Rect =>\n    across\n      ? { x: rect.x, y: from, width: rect.width, height: thickness }\n      : { x: from, y: rect.y, width: thickness, height: rect.height };\n\n  if (share !== undefined) {\n    const { low, room } = share;\n    const thickness = Math.max(Math.min(size, room / 2), floor);\n    // Centred as a pair where the two need more room than there is.\n    const centring = thickness * 2 > room ? (room - thickness * 2) / 2 : 0;\n    // The block's outside is the low end on the top and left, the high end on\n    // the bottom and right.\n    const offset = centring + (share.outer ? 0 : thickness);\n    return at(far ? low + room - offset - thickness : low + offset, thickness);\n  }\n\n  /*\n   * The edge that MOVES when the value grows, which is where the control\n   * belongs. `outward` says which one that is, and it is a property of neither\n   * the box nor the side: both boxes depend on the block's sizing model, so both\n   * are measured. See `spacingBandDrawnOutward` and `spacing-response.ts`.\n   */\n  const atMax = far === outward;\n  const low = across ? rect.y : rect.x;\n  const room = across ? rect.height : rect.width;\n  const thickness = Math.max(Math.min(size, room), floor);\n  // A band thinner than the floor: the strip centred on it.\n  const inset = thickness > room ? (room - thickness) / 2 : 0;\n  return at(atMax ? low + room - inset - thickness : low + inset, thickness);\n}\n\n/** The words an author reads for one side of one box. */\nfunction handleLabel(band: SpacingBand): string {\n  return `${band.side} ${band.box}`;\n}\n\n/** One side's settled value, as both the preview and the commit read it. */\ninterface SpacingWrite {\n  readonly address: StyleAddress;\n  readonly value: string;\n  readonly side: SpacingSide;\n  readonly px: number;\n}\n\n/**\n * What the live region says once a gesture has landed.\n *\n * A single side names itself, because that is what the author grabbed. A\n * multi-side gesture names the BOX and lists the values rather than repeating\n * four side names, which is a sentence nobody finishes listening to.\n */\nfunction committedMessage(\n  band: SpacingBand,\n  writes: readonly SpacingWrite[]\n): string {\n  const [only] = writes;\n  if (writes.length === 1 && only !== undefined) {\n    return `${handleLabel(band)} ${String(only.px)} pixels`;\n  }\n  return `${band.box} ${writes.map(write => String(write.px)).join(\", \")} pixels`;\n}\n\n/**\n * Only the sides this gesture actually MOVED.\n *\n * A drag that wanders and comes back, or one whose travel rounds to no pixels,\n * would otherwise write every side the value it already has — which the value\n * layer turns into a real op wherever the node held nothing of its own, because\n * `undefined` and `10px` are a genuine difference to it. The author's reward for\n * a gesture they abandoned would be an undo entry and four explicit overrides\n * they never asked for.\n *\n * Filtered per SIDE rather than on the delta as a whole, so a Shift drag that\n * pushes one padding against its floor still writes the three that moved.\n */\nfunction movedWrites(\n  writes: readonly SpacingWrite[],\n  starts: ReadonlyMap<SpacingSide, number>\n): readonly SpacingWrite[] {\n  return writes.filter(write => write.px !== starts.get(write.side));\n}\n\n/**\n * Why this gesture cannot be written, or `undefined` when it can.\n *\n * A side the gesture ASKED for and cannot write refuses the whole thing. Shift\n * and Alt promise every side, or the pair across; writing only the subset that\n * happens to be plain pixels would honour that promise partially and silently —\n * an author holding Shift over a box whose left margin is a token would get\n * three sides moved and nothing to say the fourth stayed put.\n *\n * Asked per COMMIT rather than at the press, because the modifier is read live:\n * which sides are being requested changes under the hand, so which refusals\n * matter changes with it.\n */\nfunction blockingRefusal(\n  band: SpacingBand,\n  refusals: ReadonlyMap<SpacingSide, string>,\n  modifiers: SpacingModifiers\n): string | undefined {\n  for (const side of spacingSidesFor(band.side, modifiers)) {\n    const reason = refusals.get(side);\n    if (reason !== undefined) return reason;\n  }\n  return undefined;\n}\n\nexport function SpacingHandles({\n  editor,\n  bands,\n  subject,\n  context,\n  onPreviewChange,\n  onGestureChange,\n}: SpacingHandlesProps): React.JSX.Element | null {\n  const gesture = React.useRef<Gesture | null>(null);\n  /**\n   * What the current render knows, readable from a listener installed earlier.\n   *\n   * A gesture's document listeners are created once, at the press, and close\n   * over the values of that render. Most of them are properties OF the gesture\n   * and are right to freeze — the scale it is measured in, the values it\n   * started from. The node's styles are not: the document can move while the\n   * pointer is down, and a whole-envelope patch built from a stale snapshot\n   * un-does whatever happened in between. The canvas keeps a `latest` ref for\n   * the same reason.\n   */\n  const latest = React.useRef<{\n    styles: BlockNode[\"styles\"];\n    nodeId: string;\n    /** The tier the surface is editing, so a gesture can notice it moved. */\n    tier: string;\n    /** The canvas scale it is painted at, for the same reason. */\n    scale: string;\n  }>({ styles: undefined, nodeId: \"\", tier: \"\", scale: \"\" });\n  const [preview, setPreview] = React.useState<string | null>(null);\n  /*\n   * Over a frame the handles are drawn in the editor's document, scaled with\n   * the page, while the preview has to reach the page in the frame's.\n   */\n  const canvas = useCanvasFrame();\n  const handleScale = canvas.frame === null ? 1 : canvas.scale;\n  const previewHost =\n    canvas.frame === null ? null : (canvas.document?.head ?? null);\n  /**\n   * The band a gesture is holding, kept alive for the gesture's lifetime.\n   *\n   * `spacingBands` draws nothing for a side reporting `0`, so dragging a\n   * padding down to its floor makes the preview re-measure, drops that band,\n   * and unmounts the very handle the pointer is captured on. The browser then\n   * releases capture and the gesture is stranded: preview live, nothing\n   * committed, no listener able to clean it up. Held in STATE rather than read\n   * off the gesture ref, because keeping an element mounted is a rendering\n   * decision and has to survive the re-render the measurement causes.\n   */\n  const [held, setHeld] = React.useState<SpacingBand | null>(null);\n  /**\n   * The MEASURED response a pointer gesture began with, before any mirroring.\n   *\n   * Unmirrored on purpose. Which edge of the drawn rectangle carries the handle\n   * depends on the band's sign as well, and a drag can change that sign by\n   * carrying a margin through zero — so the sign is applied where the handle is\n   * placed rather than baked in here.\n   *\n   * `null` whenever no pointer gesture is live, which includes a band merely\n   * held by focus: each key press is an edit of its own and reads the current\n   * measurement, so freezing there would pin the handle to an answer the block\n   * has stopped giving.\n   */\n  const [draggedResponse, setDraggedResponse] = React.useState<boolean | null>(\n    null\n  );\n  const [message, setMessage] = React.useState(\"\");\n\n  const { document: doc } = editor;\n  const { nodeId, orientation } = subject;\n\n  /*\n   * The class the compiler emitted for this node, read from the WHOLE document.\n   * `nodeClassName` on the id alone cannot see a hash collision, and on a\n   * document where the compiler had already disambiguated one the preview would\n   * be written against another node's class — so the drag would move a\n   * different block, or nothing at all.\n   */\n  const nodeClass = React.useMemo(() => {\n    const ids: string[] = [];\n    walkNodes(doc.nodes, node => ids.push(node.id));\n    return nodeClassNames(ids).get(nodeId);\n  }, [doc, nodeId]);\n\n  /** The node as the document currently holds it. */\n  const node = React.useMemo(() => {\n    let found: (typeof doc.nodes)[number] | undefined;\n    walkNodes(doc.nodes, one => {\n      if (one.id === nodeId) found = one;\n    });\n    return found;\n  }, [doc, nodeId]);\n\n  /**\n   * Which spacing boxes this block's author allows to be written.\n   *\n   * ASKED of the engine, exactly as `style-inspector.ts` asks it. `supports` is\n   * a capability declaration whose meaning belongs to the registry, and a\n   * handle that ignored it would offer an edit the Style panel deliberately\n   * withholds — a block that renders a heading's native margin without opting\n   * into margin support would gain a writable control on the canvas and none in\n   * the inspector.\n   *\n   * A block the registry does not know offers nothing, which is the same answer\n   * the panel gives: it can still CLEAR what is stored, and clearing is not\n   * something a drag does.\n   */\n  const writable = React.useMemo(() => {\n    const type = node?.type;\n    const definition = type === undefined ? undefined : getBlock(type);\n    if (definition === undefined) return new Set<string>();\n    return new Set(\n      stylePropertiesForSupports(definition.supports).map(\n        entry => entry.property\n      )\n    );\n  }, [node?.type]);\n\n  /** The tier this render is editing, as one comparable value. */\n  const tier = `${context.address.state}\\u0000${context.address.breakpoint}`;\n\n  /** The scale this render measures in, as one comparable value. */\n  const scaleKey = `${String(subject.scales.scale.x)},${String(\n    subject.scales.scale.y\n  )},${String(subject.scales.marginScale.x)},${String(\n    subject.scales.marginScale.y\n  )}`;\n\n  // Refreshed on every render, so a listener from an earlier one reads today's\n  // document rather than the one the gesture began in.\n  latest.current.styles = node?.styles;\n  latest.current.nodeId = nodeId;\n  latest.current.tier = `${context.address.state}\\u0000${context.address.breakpoint}`;\n  latest.current.scale = scaleKey;\n\n  /**\n   * Which edge of the drawn band carries its handle, and ONLY that.\n   *\n   * Not the direction a drag grows the value: `valueOutwardOf` below answers\n   * that, unmirrored, and the two disagree for a negative band — which is drawn\n   * reflected across the border edge while the edge the layout moves stays\n   * where it was. Reading placement as direction runs those drags backwards.\n   *\n   * MEASURED for both boxes, a margin no less than a padding. The reasoning that\n   * makes a margin look structural — that it lies outside the border box and so\n   * cannot move it — is one the element disagrees with: growing `margin-top`\n   * drives the border edge down while the outer edge stays pinned by whatever\n   * precedes it. See `spacing-response.ts`, which asks rather than assumes.\n   */\n  const drawnOutwardOf = React.useCallback(\n    (band: SpacingBand): boolean =>\n      spacingBandDrawnOutward(\n        band.negative,\n        subject.outward[band.box][band.side]\n      ),\n    [subject.outward]\n  );\n\n  /**\n   * Which way the VALUE grows, which is a different question from where the\n   * handle sits.\n   *\n   * The measured answer, taken unmirrored. A negative band is drawn reflected\n   * across the border edge, so its rectangle's far edge swaps — but the\n   * physical edge that responds does not, and neither does the arithmetic:\n   * raising a `margin-top` from `-20px` to `-10px` moves the border edge down,\n   * exactly as raising a positive one does. Feeding the mirrored answer to\n   * `spacingDelta` made a drag on the correctly placed handle commit `-30px`\n   * and run the block away from the pointer.\n   */\n  const valueOutwardOf = React.useCallback(\n    (band: SpacingBand): boolean => subject.outward[band.box][band.side],\n    [subject.outward]\n  );\n\n  /**\n   * Where this band's handle sits, holding still for the band being dragged.\n   *\n   * Everything else takes the current measurement. The band under a pointer\n   * takes the one its gesture began with, because the alternative is a handle\n   * that jumps to the opposite edge of its own band mid-stroke: the drag's\n   * preview resizes the block, a block that gains a settled width answers the\n   * other way, and the arithmetic is frozen at the press regardless. Reading the\n   * two from different moments is what puts the pointer and the number in\n   * disagreement.\n   */\n  const drawnEdgeOf = React.useCallback(\n    (band: SpacingBand): boolean => {\n      const dragging =\n        held !== null && held.box === band.box && held.side === band.side;\n      /*\n       * Mirrored against the band as it is drawn NOW, not as it was drawn at\n       * the press. A drag can carry a margin through zero, and `spacingBands`\n       * reflects a negative one across the border edge — so the rectangle's far\n       * edge swaps while the measurement that decides which edge responds does\n       * not. Freezing the mirrored answer would leave the handle on the edge the\n       * old sign put it, and it would stop following the pointer there.\n       */\n      return dragging && draggedResponse !== null\n        ? spacingBandDrawnOutward(band.negative, draggedResponse)\n        : drawnOutwardOf(band);\n    },\n    [draggedResponse, drawnOutwardOf, held]\n  );\n\n  const targetFor = React.useCallback(\n    (address: StyleAddress): ScrubTarget | undefined =>\n      nodeClass === undefined\n        ? undefined\n        : {\n            nodeId,\n            nodeClass,\n            address,\n            ...(context.breakpoints === undefined\n              ? {}\n              : { breakpoints: context.breakpoints }),\n            ...(context.previewContainer === undefined\n              ? {}\n              : { previewContainer: context.previewContainer }),\n            ...(context.tokenPrefix === undefined\n              ? {}\n              : { tokenPrefix: context.tokenPrefix }),\n            ...(context.policy === undefined ? {} : { policy: context.policy }),\n            ...(context.scope === undefined ? {} : { scope: context.scope }),\n            /*\n             * What else this node declares, so a preview for one state does not\n             * outrank another. See `ScrubTarget.styles`: every state compiles at\n             * equal specificity and later wins on order, so a base-state drag\n             * would otherwise repaint the block's hover value for as long as the\n             * pointer was over it.\n             */\n            ...(node?.styles === undefined ? {} : { styles: node.styles }),\n          },\n    [context, node?.styles, nodeClass, nodeId]\n  );\n\n  /**\n   * The address one physical side of this box writes to.\n   *\n   * `undefined` when the element's orientation could not be read, which is the\n   * refusal the whole feature inherits rather than a case to paper over.\n   */\n  const addressFor = React.useCallback(\n    (band: SpacingBand, side: SpacingSide): StyleAddress | undefined =>\n      orientation === undefined\n        ? undefined\n        : spacingAddress(band.box, logicalSideFor(side, orientation), {\n            state: context.address.state,\n            breakpoint: context.address.breakpoint,\n          }),\n    [context.address.breakpoint, context.address.state, orientation]\n  );\n\n  /**\n   * Where every side of this box would start from, and why one cannot.\n   *\n   * Taken once at the START of a gesture rather than per move, so that holding\n   * Shift halfway through a drag picks up the other sides from where they were\n   * when the hand went down — not from wherever the preview has since implied.\n   */\n  const startsFor = React.useCallback(\n    (\n      band: SpacingBand\n    ): {\n      starts: Map<SpacingSide, number>;\n      refusals: Map<SpacingSide, string>;\n    } => {\n      const used = band.box === \"margin\" ? subject.margin : subject.padding;\n      const starts = new Map<SpacingSide, number>();\n      const refusals = new Map<SpacingSide, string>();\n      for (const side of [\"top\", \"right\", \"bottom\", \"left\"] as const) {\n        const address = addressFor(band, side);\n        if (address === undefined) continue;\n        const stored =\n          node === undefined ? undefined : readStyleValue(node.styles, address);\n        const start = spacingStart(stored, used[side]);\n        if (start.ok) starts.set(side, start.px);\n        else refusals.set(side, start.reason);\n      }\n      return { starts, refusals };\n    },\n    [addressFor, node, subject.margin, subject.padding]\n  );\n\n  /**\n   * The values one gesture would write, keyed by side.\n   *\n   * Shared by the preview and the commit so the two cannot disagree about what\n   * the drag means: a preview computed one way and a commit another is exactly\n   * the snap-back on release that `style-scrub` warns about.\n   */\n  const valuesFor = React.useCallback(\n    (\n      band: SpacingBand,\n      starts: ReadonlyMap<SpacingSide, number>,\n      delta: number,\n      modifiers: SpacingModifiers\n    ): SpacingWrite[] =>\n      spacingSidesFor(band.side, modifiers).flatMap(side => {\n        const start = starts.get(side);\n        const address = addressFor(band, side);\n        if (start === undefined || address === undefined) return [];\n        const px = spacingValue(start, delta, band.box);\n        return [{ address, value: spacingCssValue(px), side, px }];\n      }),\n    [addressFor]\n  );\n\n  /** Write the gesture's result to the document, as ONE op. */\n\n  const commit = React.useCallback(\n    (\n      band: SpacingBand,\n      starts: ReadonlyMap<SpacingSide, number>,\n      refusals: ReadonlyMap<SpacingSide, string>,\n      delta: number,\n      modifiers: SpacingModifiers\n    ): void => {\n      const blocked = blockingRefusal(band, refusals, modifiers);\n      if (blocked !== undefined) {\n        setMessage(blocked);\n        return;\n      }\n      /*\n       * Only the sides this gesture actually MOVED.\n       *\n       * A drag that wanders and comes back, or one whose travel rounds to no\n       * pixels, would otherwise write every side its value already has — which\n       * the value layer turns into an op wherever the node held nothing of its\n       * own, because `undefined` and `10px` are a real difference to it. The\n       * author's reward for a gesture they abandoned is an undo entry and four\n       * explicit overrides they never asked for.\n       *\n       * Filtered per SIDE rather than on the delta as a whole, so a Shift drag\n       * that pushes one padding against its floor still writes the three sides\n       * that moved.\n       */\n      const writes = movedWrites(\n        valuesFor(band, starts, delta, modifiers),\n        starts\n      );\n      const first = writes[0];\n      if (first === undefined) return;\n      const target = targetFor(first.address);\n      if (target === undefined) return;\n      /*\n       * The gesture must still be about the block it started on.\n       *\n       * This component is not keyed on the node, so selecting another block\n       * mid-drag — from the Layers panel, say — re-renders it in place with a\n       * new subject while the listeners installed at the press keep running.\n       * The styles read above would then be the NEW block's whole envelope, and\n       * the op names the OLD one: releasing would copy one block's styling over\n       * another's. A gesture whose subject moved is abandoned, not committed.\n       */\n      if (latest.current.nodeId !== nodeId) return;\n      /*\n       * And it must still be about the tier it started in.\n       *\n       * The state switcher and the canvas width are outside this component, so\n       * either can move while the pointer is down — a second pointer on the\n       * switcher, or a panel resize that changes the edited breakpoint. The\n       * addresses this gesture carries were built at the press and name the OLD\n       * tier, so releasing would commit into a tier the canvas and the inspector\n       * have both stopped showing: an edit an author cannot see landing\n       * somewhere they are not looking.\n       */\n      if (latest.current.tier !== tier) return;\n      /*\n       * And the canvas must still be painted at the scale the gesture began in.\n       *\n       * A shell panel resizing, or the window changing, can alter fit zoom\n       * without crossing a breakpoint — so the tier guard above does not see it.\n       * The origin was converted to content coordinates at the OLD scale while\n       * every later point is converted at the new one, so their subtraction\n       * reports a large movement for a pointer that never moved, and the result\n       * is then divided by the frozen old scale before it is committed.\n       */\n      if (latest.current.scale !== scaleKey) return;\n      const result = scrubCommitOps(\n        target,\n        /*\n         * Read NOW, not closed over at the press.\n         *\n         * A style op patches the whole envelope, and the document can move\n         * while the pointer is down — the editor's own undo shortcut is enough.\n         * Built from the snapshot the gesture began with, the patch would carry\n         * every declaration that snapshot held, so releasing would restore an\n         * undone value or erase an edit made mid-drag. The gesture's own sides\n         * are folded into whatever the node holds at the moment of release.\n         */\n        latest.current.styles,\n        writes.map(write => ({ address: write.address, value: write.value }))\n      );\n      setMessage(applied(editor, result) ?? committedMessage(band, writes));\n    },\n    // `node.styles` is deliberately absent: the commit reads the LATEST styles\n    // through a ref, so rebuilding this callback per edit would only replace the\n    // listeners of a gesture already in flight.\n    [editor, nodeId, scaleKey, targetFor, tier, valuesFor]\n  );\n\n  /** Draw the gesture's result without touching the document. */\n  const showPreview = React.useCallback(\n    (\n      band: SpacingBand,\n      starts: ReadonlyMap<SpacingSide, number>,\n      refusals: ReadonlyMap<SpacingSide, string>,\n      delta: number,\n      modifiers: SpacingModifiers\n    ): void => {\n      /*\n       * The SAME gate the commit applies. Without it, holding Shift over a box\n       * whose left margin is a token previews the three sides that can move and\n       * then refuses everything on release — the canvas showing an edit that\n       * was never available, and taking it back at the moment the author let\n       * go. A refusal the preview does not honour is a promise the commit\n       * breaks.\n       */\n      if (blockingRefusal(band, refusals, modifiers) !== undefined) {\n        setPreview(null);\n        return;\n      }\n      const rules: string[] = [];\n      for (const write of valuesFor(band, starts, delta, modifiers)) {\n        const target = targetFor(write.address);\n        if (target === undefined) continue;\n        const css = scrubPreviewCss(target, write.value);\n        // A refused value draws nothing rather than drawing the last accepted\n        // one: a preview that lags the pointer reads as the drag having stuck.\n        if (css.ok) rules.push(css.css);\n      }\n      setPreview(rules.length === 0 ? null : rules.join(\"\\n\"));\n    },\n    [targetFor, valuesFor]\n  );\n\n  const endGesture = React.useCallback((): void => {\n    const live = gesture.current;\n    gesture.current = null;\n    setPreview(null);\n    setHeld(null);\n    setDraggedResponse(null);\n    // Ends the session too; a session ending itself comes back here, once.\n    live?.session.end();\n  }, []);\n\n  /**\n   * Begin a gesture, and follow it on the DOCUMENT rather than on the handle.\n   *\n   * The handle is a nine-pixel strip, and the activation threshold is four: a\n   * pointer that has travelled far enough to mean a drag has usually left the\n   * strip already. Listening on the handle alone therefore cannot work, and it\n   * fails by DEADLOCK rather than by dropping the occasional event — capture is\n   * what keeps later moves coming back to the element, capture waits for\n   * activation, and activation needs the very moves that stopped arriving. The\n   * gesture simply never starts, and the handle reads as inert.\n   *\n   * Measured in a browser, which is the only place it shows: a test that fires\n   * `pointermove` AT the handle delivers events the real DOM would have sent to\n   * whatever the pointer is over, and passes against exactly this.\n   *\n   * The handlers close over the gesture's own inputs at the moment of the press.\n   * That is the intended reading rather than a limitation: the scale a drag is\n   * measured in and the styles it starts from are properties of when the hand\n   * went down, and nothing writes the document until it comes up.\n   */\n  const onPointerDown = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>, band: SpacingBand): void => {\n      // Only the primary button starts an edit; a context-menu press must not.\n      if (event.button !== 0) return;\n      /*\n       * One gesture at a time. A second finger, or a pen alongside a touch,\n       * also arrives with `button === 0`: accepted, it would replace the live\n       * gesture's band and starts while the first pointer's document listeners\n       * stayed installed, so the first pointer would go on driving — writing\n       * the second gesture's side — and one listener set would leak.\n       */\n      if (gesture.current !== null) return;\n      const { starts, refusals } = startsFor(band);\n      const refusal = refusals.get(band.side);\n      if (refusal !== undefined) {\n        setMessage(refusal);\n        return;\n      }\n      if (!starts.has(band.side)) return;\n      event.preventDefault();\n\n      const host = event.currentTarget;\n      const originX = event.clientX;\n      const originY = event.clientY;\n\n      /*\n       * The canvas root, so pointer travel can be expressed in the SAME space\n       * the bands were measured in.\n       */\n      const space = overlaySpaceOf(host, CANVAS_ROOT_CLASS);\n      const root = space?.root ?? null;\n      /*\n       * A pointer on a handle drawn over a frame is reported in the EDITOR's\n       * client coordinates, and the root's rectangles are read in the frame's:\n       * carried across first, through the one mapping every gesture uses.\n       */\n      const inCanvas = (x: number, y: number): { x: number; y: number } =>\n        space === null ? { x, y } : space.pointInCanvas({ x, y });\n      const pressed = inCanvas(originX, originY);\n      const origin =\n        root === null ? null : canvasPointerPoints(pressed.x, pressed.y, root);\n\n      /**\n       * How far the pointer has moved in the root's own CONTENT space, which is\n       * what the VALUE comes from. The activation threshold is the shared\n       * gesture's, in client pixels: whether a press was meant as a drag is a\n       * property of the hand, and measured in canvas pixels it would shrink\n       * with the zoom.\n       *\n       * The two differ by the root's painted scale, which `renderedScale`\n       * deliberately stops below — the bands are children of the root and are\n       * drawn through its transform already, so their rectangles need no such\n       * factor. A pointer does: its coordinates come from the screen with the\n       * root's zoom baked in. Left unconverted, a canvas painted at half size\n       * moves the value half as far as the handle under the hand — and it is\n       * invisible at 100%, which is where a drag is usually tried.\n       *\n       * Converted through `canvasPointerPoints`, which is what `canvas-drag`\n       * aims with. A subtraction of its own here would be a second mapping,\n       * free to disagree with the one every other gesture on this canvas uses.\n       */\n      const travelled = (\n        moved: PointerEvent,\n        hand: ScrubTravel\n      ): { readonly dx: number; readonly dy: number } => {\n        if (root === null || origin === null) return hand;\n        const at = inCanvas(moved.clientX, moved.clientY);\n        const now = canvasPointerPoints(at.x, at.y, root);\n        return {\n          dx: now.content.x - origin.content.x,\n          dy: now.content.y - origin.content.y,\n        };\n      };\n\n      /*\n       * The press, its threshold, capture, Escape and the document listeners\n       * are the shared scrub gesture's, which the inspector's labels use too:\n       * see `scrub-gesture.ts` for why each is where it is.\n       */\n      const session = followScrub(\n        {\n          pointerId: event.pointerId,\n          clientX: originX,\n          clientY: originY,\n          host,\n        },\n        {\n          onMove: (moved, hand) => {\n            const live = gesture.current;\n            if (live === null) return;\n            const delta = spacingDelta(\n              live.band.box,\n              live.band.side,\n              travelled(moved, hand),\n              subject.scales,\n              live.valueOutward\n            );\n            if (delta === undefined) return;\n            const shown = scrubModifiersOf(moved);\n            live.shown = shown;\n            showPreview(live.band, live.starts, live.refusals, delta, shown);\n          },\n          onRelease: (lifted, hand) => {\n            const live = gesture.current;\n            if (live === null) return;\n            const delta = spacingDelta(\n              live.band.box,\n              live.band.side,\n              travelled(lifted, hand),\n              subject.scales,\n              live.valueOutward\n            );\n            if (delta === undefined) return;\n            /*\n             * `live.shown`, not the release event's modifiers. See `shown`:\n             * releasing Shift before the button is ordinary, and reading the\n             * release would commit a different edit from the one on screen.\n             */\n            commit(live.band, live.starts, live.refusals, delta, live.shown);\n          },\n          onEscape: () => setMessage(\"Spacing drag cancelled.\"),\n          onEnd: endGesture,\n        }\n      );\n\n      setHeld(band);\n      /*\n       * Frozen together, from one reading, so the edge the handle sits on and\n       * the direction the number moves cannot come from different measurements.\n       */\n      setDraggedResponse(valueOutwardOf(band));\n      gesture.current = {\n        band,\n        valueOutward: valueOutwardOf(band),\n        starts,\n        refusals,\n        shown: scrubModifiersOf(event),\n        session,\n      };\n    },\n    [commit, endGesture, showPreview, startsFor, subject.scales, valueOutwardOf]\n  );\n\n  /*\n   * After the browser has applied the preview, ask for a fresh measurement.\n   *\n   * A LAYOUT effect, so the bands are re-read before the frame is painted and\n   * never appear a step behind the block they describe. Keyed on the preview\n   * text: an unchanged preview re-measures nothing, and clearing it on release\n   * measures once more against the committed document.\n   */\n  React.useLayoutEffect(() => {\n    onPreviewChange?.();\n  }, [onPreviewChange, preview]);\n\n  // Reported from `held`, which is set for a pointer gesture and for a focused\n  // keyboard one alike — both need the control to outlive a vanished band.\n  React.useEffect(() => {\n    onGestureChange?.(held !== null);\n  }, [held, onGestureChange]);\n\n  /*\n   * A gesture does not outlive the handles. The overlay unmounts them whenever\n   * the selection changes or a canvas drag starts, and listeners left on the\n   * document would then commit against a node nobody is editing — or leak one\n   * pair per press for the life of the editor.\n   */\n  React.useEffect(() => () => gesture.current?.session.end(), []);\n\n  const onKeyDown = React.useCallback(\n    (event: React.KeyboardEvent<HTMLElement>, band: SpacingBand): void => {\n      /*\n       * Escape is handled on the document for the life of a gesture, not here:\n       * a drag started on an unfocused handle never gives this element the key.\n       */\n      /*\n       * The direction lives in `spacing-drag.ts` and runs through the same sign\n       * table the pointer does, so the two paths cannot come to disagree about\n       * which way a key grows a value. A key this band does not answer to is\n       * left alone rather than swallowed.\n       */\n      const delta = spacingKeyDelta(\n        event.key,\n        band.box,\n        band.side,\n        valueOutwardOf(band)\n      );\n      if (delta === undefined) return;\n      /*\n       * A pointer gesture owns the value until it is released.\n       *\n       * The handle can hold focus while a drag is in flight, so an arrow key\n       * pressed mid-drag would commit immediately — and the release, built from\n       * the starts taken at the PRESS, would then overwrite it. The author's key\n       * edit disappears and the history keeps an entry for it, which is the\n       * worst of both. Escape is already filtered this way on the document\n       * listener; this is the same rule for the keys that write.\n       */\n      if (gesture.current !== null) return;\n\n      event.preventDefault();\n      const { starts, refusals } = startsFor(band);\n      /*\n       * The band this key is about is held for as long as the handle has focus.\n       *\n       * Stepping a 1px padding down to zero makes `spacingBands` stop drawing\n       * it, and the focused control would unmount underneath the author — focus\n       * falls back to the body, and the next press goes nowhere. A margin can\n       * legitimately continue through zero into negative values, so losing the\n       * handle there loses half the range as well.\n       */\n      setHeld(band);\n      commit(band, starts, refusals, delta, scrubModifiersOf(event));\n    },\n    [commit, startsFor, valueOutwardOf]\n  );\n\n  /*\n   * The live region is ALWAYS mounted and only its text changes. A polite\n   * region inserted already carrying its message is not reliably announced, so\n   * a keyboard author would miss the value they just set — the same reason\n   * `BuilderNoticeRegion` keeps its container permanently.\n   */\n  const region = (\n    <div\n      className=\"nx-spacing-handles__status\"\n      role=\"status\"\n      aria-live=\"polite\"\n      aria-atomic=\"true\"\n    >\n      {message}\n    </div>\n  );\n\n  /**\n   * The bands that get a handle: the measured ones, plus the one being held.\n   *\n   * A gesture outlives its own band whenever the value it is dragging reaches\n   * zero, and the handle has to outlive it too — see `held`. Matched by box and\n   * side rather than by identity, since every measurement builds fresh objects.\n   */\n  const drawn =\n    held === null ||\n    bands.some(band => band.box === held.box && band.side === held.side)\n      ? bands\n      : [...bands, collapsed(held, drawnEdgeOf(held))];\n\n  if (orientation === undefined || nodeClass === undefined) {\n    /*\n     * No handles at all. Without an orientation a physical edge cannot be\n     * turned into a logical address, and without the emitted class a preview\n     * cannot be aimed — both are cases where the honest thing is to offer\n     * nothing rather than to edit a side the author did not grab.\n     */\n    return region;\n  }\n\n  /*\n   * Split with another handle where the two would overlap.\n   *\n   * A negative margin's band is laid inside the border edge, where padding's\n   * is — so `margin-top: -16px` beside `padding-top: 20px` gives two bands\n   * from one edge. Padding is drawn later, so its handle would take every\n   * press there and the margin's control would be advertised and unreachable.\n   */\n  /*\n   * No handle where the block's author did not offer the property. The band\n   * still draws — it reports what the page renders, which is true either way —\n   * but a control that wrote it would bypass a capability declaration the\n   * Style panel honours. Left out BEFORE the handles are placed, so a handle\n   * with no partner drawn beside it keeps its whole band.\n   */\n  const handled = drawn.filter(band => writable.has(band.box));\n  const placed = placeHandles(handled, drawnEdgeOf, handleScale);\n\n  return (\n    <>\n      {handled.map((band, index) => {\n        const rect = placed[index];\n        if (rect === undefined) return null;\n        return (\n          <div\n            key={`${band.box}-${band.side}`}\n            className=\"nx-spacing-handles__handle\"\n            data-box={band.box}\n            data-side={band.side}\n            /*\n             * Marked as chrome so the canvas does not resolve a press on it to\n             * the block underneath. The bands themselves are not marked, and\n             * must not be: they take no pointer events at all.\n             */\n            {...{ [CHROME_ATTRIBUTE]: \"\" }}\n            /*\n             * Deliberately NOT `role=\"slider\"`.\n             *\n             * A slider's `aria-valuemin` and `aria-valuemax` default to 0 and\n             * 100 when omitted, so the role asserts a range whether or not one\n             * is given. This control has no such range: the catalog lets a\n             * margin go negative and neither box has a ceiling, so every\n             * negative margin and every value above 100 would be reported to\n             * assistive technology as outside its own control's bounds. Stating\n             * bounds instead would mean inventing two numbers the catalog does\n             * not have, which misreports the control in the other direction.\n             *\n             * So the value goes in the NAME, where it needs no range to be\n             * meaningful and is read on focus, and every change is announced\n             * through the live region below. A focusable element with an\n             * accurate name and a spoken result describes this control honestly;\n             * a slider with a fabricated range does not.\n             */\n            /*\n             * `spinbutton`, not `slider` and not a bare `div`.\n             *\n             * A `div` keeps the generic role, and naming a generic role is\n             * prohibited — so `aria-label` on one is not exposed, and a\n             * keyboard user reaches an unnamed element with nothing to say that\n             * arrows adjust it. `slider` names itself but defaults\n             * `aria-valuemin`/`aria-valuemax` to 0 and 100 when they are\n             * omitted, which would report every negative margin and every value\n             * over a hundred as outside its own range, and there are no honest\n             * bounds to state instead.\n             *\n             * A spinbutton is the adjustable-number role whose bounds are\n             * OPTIONAL: absent, it simply has none, which is the truth here.\n             * Arrow keys are its native interaction, which is what this is.\n             */\n            role=\"spinbutton\"\n            tabIndex={0}\n            aria-label={handleLabel(band)}\n            aria-valuenow={Number(band.label)}\n            aria-valuetext={`${band.label} pixels`}\n            /*\n             * Only the press is bound here. Everything after it is followed on\n             * the document, because a pointer that has travelled far enough to\n             * mean a drag has already left this nine-pixel strip.\n             */\n            onPointerDown={event => onPointerDown(event, band)}\n            onKeyDown={event => onKeyDown(event, band)}\n            /*\n             * The keyboard's claim on a band ends when focus does. A pointer\n             * gesture still in flight keeps its own claim: it is the one that\n             * has to survive to its release.\n             */\n            onBlur={() => {\n              if (gesture.current === null) setHeld(null);\n            }}\n            style={{\n              left: `${String(rect.x)}px`,\n              top: `${String(rect.y)}px`,\n              width: `${String(rect.width)}px`,\n              height: `${String(rect.height)}px`,\n            }}\n          />\n        );\n      })}\n      {preview === null ? null : previewHost === null ? (\n        <style>{preview}</style>\n      ) : (\n        createPortal(<style>{preview}</style>, previewHost)\n      )}\n      {region}\n    </>\n  );\n}\n","\"use client\";\n\n/**\n * The selected block's spacing, drawn on the page it applies to.\n *\n * An author setting margin or padding in the inspector is looking at the\n * canvas, not at the panel, and until now the only way to see what a value did\n * was to change it and watch the layout move. This draws the space itself:\n * a band over each side that has one, with the value written on it.\n *\n * ## The values come from the RENDERED page, not from the document\n *\n * `getComputedStyle` is the source, and the alternative — reading the stored\n * style tier the inspector edits — is wrong here in four separate ways, any one\n * of which is enough:\n *\n * - The catalog stores spacing per LOGICAL side (`margin-inline-start`), and a\n *   band is drawn on a PHYSICAL one. Which physical edge an inline side lands on\n *   depends on the element's inherited `direction` and `writing-mode`, so\n *   deriving it from the document means reimplementing a resolution rule the\n *   browser has already applied correctly.\n * - `auto` is a legal margin and has no value at all until layout runs — it is\n *   what centres a block.\n * - A percentage resolves against the containing block, which the document\n *   cannot see.\n * - The tier the inspector edits is not the whole cascade. A named class, a\n *   block-type default or a breakpoint override can win, and an overlay reading\n *   one tier would confidently name a value the page does not use.\n *\n * So the page is asked what it is doing, rather than a second opinion being\n * computed alongside it and drifting.\n *\n * ## The PRIMARY selection only\n *\n * Spacing belongs to a node; a multi-block selection has no margin of its own,\n * and drawing a set of bands per member leaves the numbers ambiguous about which\n * block each describes. The primary is the one the inspector answers for, so the\n * two surfaces agree about whose value is on screen.\n *\n * ## When it re-measures, and the one case it cannot see\n *\n * A re-measure happens when the selection changes, when the document changes,\n * and whenever `watchCanvasFor` reports that a rectangle may have moved.\n * Between them those cover an edit, an image or webfont arriving, the panels\n * moving, a scroller carrying the block, a transition settling, a recompiled\n * site sheet, and a breakpoint changing — a breakpoint is driven by the\n * canvas's own width, so the root's resize is the event that reports it.\n *\n * Which mechanisms the second of those owns is deliberately not restated here:\n * that list belongs to `canvas-geometry-watch.ts`, and a copy of it in this\n * docblock would be a second answer to fall out of step.\n *\n * What is NOT covered is a spacing change driven purely by a CSS STATE: a\n * `:hover` or `:focus-visible` rule altering a margin repaints without mutating\n * the DOM and without resizing anything, so there is no event for an observer to\n * receive — a `MutationObserver` sees nothing either, because nothing mutates.\n * Reaching it would mean re-measuring on pointer traffic across the canvas or\n * polling every frame, and both cost more than the staleness they remove. Stated\n * here rather than left to be discovered: while the pointer rests on a block\n * whose hover rule moves it, the bands describe its resting state.\n *\n * @module spacing-overlay\n */\n\nimport { registeredBlocks, type BlockResolver } from \"@nextlyhq/blocks-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Scale } from \"../geometry\";\nimport { designIsWritable, lockViewOf } from \"../inspector/inspector\";\nimport { BASE_BREAKPOINT } from \"../styles/breakpoints\";\nimport {\n  orientationOfElement,\n  type SideOrientation,\n} from \"../styles/side-orientation\";\n\nimport { clipPathOf, scaleCornerRadii } from \"./border-radii\";\nimport { CANVAS_ROOT_CLASS, nodeElement } from \"./canvas\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport {\n  canvasContentRect,\n  canvasPaintedScale,\n  clippedByAncestor,\n  hasScrollbarGutter,\n  layoutFragments,\n  overlaySpaceOf,\n  renderedScale,\n  usedRadiiOf,\n  viewportPositioned,\n  type RenderedScale,\n} from \"./geometry-dom\";\nimport {\n  applicableEdges,\n  overlayEscape,\n  sameBands,\n  spacingApplies,\n  spacingBands,\n  type EdgeApplicability,\n  type EdgeLengths,\n  type SpacingBand,\n  type SpacingBox,\n  type SpacingSide,\n} from \"./spacing-bands\";\nimport { blockStartSide, gapOwnerOf } from \"./spacing-gap\";\nimport {\n  SpacingHandles,\n  type SpacingScrubContext,\n  type SpacingSubject,\n} from \"./spacing-handles\";\nimport { spacingRespondsOutward, styleCapable } from \"./spacing-response\";\n\n/** The root's size and the frame's scale, for bands drawn over a frame. */\ninterface FramedLayer {\n  readonly width: number;\n  readonly height: number;\n  readonly scale: number;\n}\n\nfunction sameFramedLayer(\n  a: FramedLayer | null,\n  b: FramedLayer | null\n): boolean {\n  if (a === null || b === null) return a === b;\n  return a.width === b.width && a.height === b.height && a.scale === b.scale;\n}\n\n/**\n * The layer's own style: how far its clip may extend, and over a frame, the\n * root's box scaled to the frame's zoom.\n *\n * Over a frame the layer is laid out at the root's size in the root's own\n * coordinates and scaled as a whole, so every band, its clip and its rounded\n * corners stay in the units they were measured in. `--nx-spacing-scale` is\n * what the chips and handles undo to keep their own size.\n */\nfunction framedLayerStyle(\n  escape: number,\n  framed: FramedLayer | null\n): React.CSSProperties {\n  const clip = { \"--nx-spacing-escape\": `${String(escape)}px` };\n  if (framed === null) return clip as React.CSSProperties;\n  return {\n    ...clip,\n    \"--nx-spacing-scale\": String(framed.scale),\n    inset: \"auto\",\n    left: 0,\n    top: 0,\n    width: framed.width,\n    height: framed.height,\n    transform: `scale(${String(framed.scale)})`,\n    transformOrigin: \"0 0\",\n  } as React.CSSProperties;\n}\n\nexport interface SpacingOverlayProps {\n  /** The editor whose primary selection is measured. */\n  editor: EditorState;\n  /**\n   * Suppress the bands, for a host that is mid-gesture.\n   *\n   * A drag is the case this exists for: the bands describe a layout that is in\n   * the middle of changing, so every value on screen is about to be wrong.\n   */\n  hidden?: boolean;\n  /**\n   * The tier a handle writes to, and what the canvas compiled this page with.\n   *\n   * OPTIONAL, and its absence is not a neutral default. Omitted, a handle\n   * writes the base breakpoint of the resting state through an unscoped,\n   * default-prefixed preview — correct for an unscoped page at base, and wrong\n   * in a way the author can see for anything else: `scrubPreviewCss` refuses a\n   * non-base breakpoint it was given no set for, so the drag shows nothing\n   * moving. A host that draws tiers or scopes must pass this.\n   */\n  scrub?: SpacingScrubContext;\n  /**\n   * The block resolver the canvas renders with, which is what decides whether a\n   * container spaces its children. The renderer's own default when omitted,\n   * the process registry, so the overlay asks the same source the page was\n   * drawn from.\n   */\n  blocks?: BlockResolver;\n}\n\n/**\n * A computed length in pixels, or zero where the browser reports no number.\n *\n * `auto` is the case that reaches this. A computed margin is normally the used\n * value — a number even where the author wrote `auto` — but an element that is\n * not laid out has nothing to resolve against, and the string comes back\n * unresolved. Zero is the honest reading: there is no space to draw.\n */\nfunction lengthOf(value: string): number {\n  const parsed = Number.parseFloat(value);\n  return Number.isFinite(parsed) ? parsed : 0;\n}\n\n/**\n * The four physical margins, paddings and border widths of one element.\n *\n * PHYSICAL longhands rather than the logical ones the catalog stores, because a\n * band is drawn on a physical edge — and letting the browser resolve\n * `inline-start` to a side is the point, not an oversight.\n *\n * Spelled out one property at a time rather than assembled from a side name.\n * The computed style is a typed interface, and a name built at runtime turns\n * every one of these reads into an index lookup the checker cannot verify.\n */\nfunction boxesOf(style: CSSStyleDeclaration): {\n  margin: EdgeLengths;\n  padding: EdgeLengths;\n  borderWidths: EdgeLengths;\n} {\n  return {\n    margin: {\n      top: lengthOf(style.marginTop),\n      right: lengthOf(style.marginRight),\n      bottom: lengthOf(style.marginBottom),\n      left: lengthOf(style.marginLeft),\n    },\n    padding: {\n      top: lengthOf(style.paddingTop),\n      right: lengthOf(style.paddingRight),\n      bottom: lengthOf(style.paddingBottom),\n      left: lengthOf(style.paddingLeft),\n    },\n    borderWidths: {\n      top: lengthOf(style.borderTopWidth),\n      right: lengthOf(style.borderRightWidth),\n      bottom: lengthOf(style.borderBottomWidth),\n      left: lengthOf(style.borderLeftWidth),\n    },\n  };\n}\n\n/**\n * The band's box, plus the clip its FILL takes when the block is rounded.\n *\n * The clip travels as a custom property rather than as this element's own\n * `clip-path` because the band carries the value chip, and the chip\n * deliberately overflows the band it names — the case where a number is hardest\n * to guess is the case where the space is too small to hold it. Clipping the\n * element would take the number with it, so the stylesheet applies the property\n * to the fill alone.\n */\nfunction bandStyle(band: SpacingBand): React.CSSProperties {\n  const box: React.CSSProperties = {\n    left: band.rect.x,\n    top: band.rect.y,\n    width: band.rect.width,\n    height: band.rect.height,\n  };\n  if (band.clip === undefined) return box;\n  return {\n    ...box,\n    \"--nx-spacing-clip\": clipPathOf(band.clip),\n  } as React.CSSProperties;\n}\n\n/**\n * Elements whose box is REPLACED by content the CSS box model does not lay out.\n *\n * Asked because a replaced inline box keeps its block-axis margins where a\n * non-replaced one drops them, and nothing in the computed style says which\n * kind a box is — `display` answers `inline` for both. It is the element type\n * that decides, so the element type is what this asks.\n *\n * Every member was measured, not assumed: forced to `display: inline` and given\n * a top and bottom margin, each one below moves the content after it by the\n * full amount, and `span`, `div` and `math` move it by nothing. `math` is the\n * surprise — MathML Core lays its box out like any other, so it is deliberately\n * absent rather than forgotten.\n *\n * A replaced element that is not currently rendering anything — an `<audio>`\n * with no controls, an `<embed>` with no type — generates no replaced box and\n * takes no block-axis margin, and this still calls it replaced. That is the\n * safer of the two errors: it draws a band for spacing the box takes the moment\n * it has something to show, where the other omits spacing that is in effect\n * right now.\n */\nconst REPLACED_TAGS: ReadonlySet<string> = new Set([\n  \"img\",\n  \"iframe\",\n  \"embed\",\n  \"object\",\n  \"video\",\n  \"audio\",\n  \"canvas\",\n  \"svg\",\n  \"input\",\n  \"select\",\n  \"textarea\",\n  \"button\",\n  \"progress\",\n  \"meter\",\n]);\n\n/** Whether this element's box is replaced. See {@link REPLACED_TAGS}. */\nexport function isReplaced(element: Element): boolean {\n  /*\n   * `localName` rather than `tagName`, which upper-cases an HTML element's name\n   * but leaves an SVG one alone — so `<svg>` inside HTML answers `svg` to one\n   * and `svg` to the other while `<img>` answers `img` and `IMG`. Comparing the\n   * lower-cased local name is the spelling that holds for both.\n   */\n  return REPLACED_TAGS.has(element.localName.toLowerCase());\n}\n\n/**\n * The physical margins the cascade left at `auto`.\n *\n * An `auto` margin is space the browser works out, usually to centre a block,\n * not a value an author or a default set. The panel shows such a margin as\n * unset, so the canvas draws no band and writes no number for it either: a\n * \"32\" there would name a value nobody can find to change.\n *\n * Asked of the COMPUTED value rather than the used one. `getComputedStyle`\n * answers margins with the used value, so a centred block's `auto` comes back\n * as pixels and cannot be told from a set margin. Typed OM's\n * `computedStyleMap()` keeps the keyword. A browser without it (Firefox, at the\n * time of writing) reads every margin as set, as before: the bands there still\n * describe the space, only the `auto` ones keep a number.\n */\nfunction autoMargins(block: Element): EdgeApplicability {\n  if (!(\"computedStyleMap\" in block)) {\n    return { top: false, right: false, bottom: false, left: false };\n  }\n  const computed = block.computedStyleMap();\n  const isAuto = (property: string): boolean =>\n    computed.get(property)?.toString() === \"auto\";\n  return {\n    top: isAuto(\"margin-top\"),\n    right: isAuto(\"margin-right\"),\n    bottom: isAuto(\"margin-bottom\"),\n    left: isAuto(\"margin-left\"),\n  };\n}\n\n/**\n * The spacing this block can actually be drawn with, on each side.\n *\n * Two separate reasons zero a side, and they are both here so that no caller\n * can apply one and forget the other.\n *\n * The first is what CSS gives the generated box. `display: table-row` and the\n * internal ruby boxes take no margin, everything internal to a table except a\n * cell takes no padding, and a non-replaced inline box takes no block-axis\n * margin — while the computed style answers with whatever the author declared,\n * so reading it unconditionally draws bands for space that does not exist.\n *\n * The second is whether a band could be PUT there. A transform does not affect\n * layout: an ancestor's transform scales the subtree it lays out, gaps\n * included, so a margin inside one really does render smaller and `scale` is\n * right to apply it — but the block's OWN transform moves only its rendering,\n * while the space its margin reserves stays where the untransformed box left\n * it. Measured, a 100px block with `margin-bottom: 20px` under `scale(2)`\n * leaves a gap of MINUS eighty pixels, drawn over the neighbour that margin is\n * holding away, so no rectangle beside the rendered border edge describes it.\n *\n * That second reason is applied PER EDGE, because the sides are independent and\n * so are the two ends of one axis: `translateY(-4px)` — an ordinary hover lift —\n * moves the top and bottom margins and leaves left and right where they were,\n * while `translateY(-25px) scaleY(0.5)` pins the TOP edge and moves only the\n * bottom. See `selfMoved`, which asks whether each edge renders where it lays\n * out rather than inspecting the declaration.\n *\n * Padding is subject only to the first reason. It lies INSIDE the transform and\n * renders scaled with the box, so those bands stay correct on both axes.\n */\nfunction drawableBoxes(\n  style: CSSStyleDeclaration,\n  block: Element,\n  scale: RenderedScale\n): { margin: EdgeLengths; padding: EdgeLengths; borderWidths: EdgeLengths } {\n  const applies = spacingApplies(\n    style.display,\n    style.writingMode,\n    isReplaced(block)\n  );\n  const auto = autoMargins(block);\n  const margin: EdgeApplicability = {\n    top: applies.margin.top && !scale.selfMoved.top && !auto.top,\n    bottom: applies.margin.bottom && !scale.selfMoved.bottom && !auto.bottom,\n    left: applies.margin.left && !scale.selfMoved.left && !auto.left,\n    right: applies.margin.right && !scale.selfMoved.right && !auto.right,\n  };\n  const measured = boxesOf(style);\n  return {\n    borderWidths: measured.borderWidths,\n    margin: applicableEdges(measured.margin, margin),\n    padding: applicableEdges(measured.padding, applies.padding),\n  };\n}\n\n/**\n * How far a value chip can overflow the band it is centred on.\n *\n * Bounded by the chip's own size, which this package sets: `0.6875rem` text on a\n * `1.4` line box with two pixels of padding, so a little over twenty pixels tall\n * and wider than that only for a value nobody authors. Twenty-four covers it\n * with room and keeps the clip allowance small.\n */\nconst CHIP_OVERFLOW_PX = 24;\n\n/** One array identity for every empty result, so React can bail out of a render. */\nconst NO_BANDS: readonly SpacingBand[] = [];\n\n/**\n * Whether axis-aligned bands can describe this block at all.\n *\n * One predicate rather than a guard per case, because every entry is the same\n * property: the rendered box is not a single upright rectangle sitting in the\n * canvas's own coordinates, so no rectangle pinned to a physical side describes\n * it and no scale factor rescues one that tries.\n *\n * Drawing nothing is the right answer for all of them. A band is read as a\n * MEASUREMENT, so one drawn in the wrong place is worse than an overlay that\n * declines to draw.\n */\nfunction describable(\n  fragments: number,\n  viewportPositioned: boolean,\n  gutter: boolean,\n  clipped: boolean,\n  scale: RenderedScale\n): boolean {\n  // No box at all — `display: none`, `display: contents`.\n  if (fragments === 0) return false;\n  /*\n   * An inline box wrapped across lines. Its padding and margins belong to the\n   * individual fragments while the bounding rectangle is their union, so bands\n   * drawn from that union run through the whitespace between lines.\n   */\n  if (fragments > 1) return false;\n  /*\n   * Positioned against the viewport rather than the page. A sticky or fixed\n   * block stops moving with the canvas content the bands are drawn in, so they\n   * slide away from it on the first scroll — and scrolling emits no resize, so\n   * nothing re-measures.\n   *\n   * Decided by `viewportPositioned` in `geometry-dom.ts` rather than by reading\n   * `position` here, because it is a property of the coordinate space\n   * `canvasContentRect` measures in and not of bands: every overlay drawn in\n   * that space refuses the same elements, and a second copy of the test would\n   * go on accepting a value the shared one had learned to refuse.\n   */\n  if (viewportPositioned) return false;\n  /*\n   * A classic scrollbar takes its width between the padding box and the border,\n   * so a padding box derived from the borders alone is too wide by the gutter\n   * and the band lands on the scrollbar. Which side it takes depends on the\n   * writing direction.\n   */\n  if (gutter) return false;\n  /*\n   * Cut off by an ancestor. The block's own rectangle is reported unclipped and\n   * the overlay draws outside that container, so bands taken from it would paint\n   * over ground where the block is not rendered.\n   */\n  if (clipped) return false;\n  // A rotation, skew, reflection, perspective, or a collapse to zero.\n  return scale.describable;\n}\n\n/** The tier a handle writes to when the host names none. See `scrub`. */\nconst RESTING_BASE: SpacingScrubContext = {\n  address: { state: \"base\", breakpoint: BASE_BREAKPOINT },\n};\n\n/**\n * Whether two measurements of the block describe the same gesture inputs.\n *\n * Compared by VALUE so a re-measure that found nothing moved does not hand the\n * handles a new object and restart every gesture they hold. `sameBands` already\n * does this for the bands; a subject compared by identity would defeat it.\n */\n/** The four sides, for comparisons that must cover all of them. */\nconst SIDES: readonly SpacingSide[] = [\"top\", \"right\", \"bottom\", \"left\"];\n\nfunction sameEdges(one: EdgeLengths, other: EdgeLengths): boolean {\n  return (\n    one.top === other.top &&\n    one.right === other.right &&\n    one.bottom === other.bottom &&\n    one.left === other.left\n  );\n}\n\nfunction sameScales(\n  one: SpacingSubject[\"scales\"],\n  other: SpacingSubject[\"scales\"]\n): boolean {\n  return (\n    one.scale.x === other.scale.x &&\n    one.scale.y === other.scale.y &&\n    one.marginScale.x === other.marginScale.x &&\n    one.marginScale.y === other.marginScale.y\n  );\n}\n\n/**\n * Both unread, or both reading the same way.\n *\n * Optional chaining rather than a null branch: an unread orientation compares\n * equal to another unread one, which is right — neither draws a handle, so\n * nothing about the gesture layer differs between them.\n */\nfunction sameOrientation(\n  one: SideOrientation | undefined,\n  other: SideOrientation | undefined\n): boolean {\n  return (\n    one?.writingMode === other?.writingMode &&\n    one?.direction === other?.direction\n  );\n}\n\nfunction sameSubject(\n  one: SpacingSubject | null,\n  other: SpacingSubject | null\n): boolean {\n  if (one === null || other === null) return one === other;\n  return (\n    one.nodeId === other.nodeId &&\n    sameEdges(one.margin, other.margin) &&\n    sameEdges(one.padding, other.padding) &&\n    sameScales(one.scales, other.scales) &&\n    sameOrientation(one.orientation, other.orientation) &&\n    /*\n     * The probed answer is part of what a handle IS, so it belongs in this\n     * comparison. An edit can turn a block from content-sized to fixed-sized\n     * without changing a single measured length — the cache is re-probed and\n     * answers differently, and a comparison blind to it would keep the old\n     * subject: the handle stays on the edge that has stopped moving and the drag\n     * keeps the direction that has stopped being right, until some unrelated\n     * margin or scale change happens to force a replacement.\n     *\n     * NOT covered by a test of its own, and said here rather than left to be\n     * discovered. What `outward` DOES once it reaches the handles is\n     * covered — `spacing-handles.test.tsx` asserts both the edge it places the\n     * control on and the direction it drags in. What is untested is this\n     * propagation step: reaching it needs a measurement whose probe answers\n     * differently while every other length holds still, and every attempt to\n     * stage that in jsdom broke the measurement chain it was standing on. A\n     * test that fights its harness is worth less than a note that does not.\n     */\n    ([\"margin\", \"padding\"] as const).every(box =>\n      SIDES.every(side => one.outward[box][side] === other.outward[box][side])\n    )\n  );\n}\n\n/**\n * The scale the probe's movement will be SEEN at, for one box on one side.\n *\n * A margin takes the ANCESTOR scale and a padding the composed one, and what\n * separates them is the element's OWN transform: a padding renders inside that\n * transform and scales with it, while a margin displaces the box in the\n * PARENT's coordinates, which the element's own transform never touches.\n * Measured in Chromium — under `scale(0.5)` on the block itself, a ten-pixel\n * margin probe still moves the edge ten pixels while a ten-pixel padding probe\n * moves it five.\n *\n * `renderedScale` already separates the two and says why, and `spacingDelta`\n * already divides by the matching one of the pair. Reading the composed scale\n * for both asks a question this package has answered and takes the wrong half\n * of the answer: on a transformed block the margin threshold then wants twice\n * the movement there is, reads a moving edge as pinned, and inverts the\n * handle.\n *\n * The root's own painted scale composes either way, because it is above the\n * element and applies to both boxes alike.\n */\nexport function probeScale(\n  box: SpacingBox,\n  side: SpacingSide,\n  scale: RenderedScale,\n  rootPainted: Scale\n): number {\n  const vertical = side === \"top\" || side === \"bottom\";\n  const laidOutIn = box === \"margin\" ? scale.ancestor : scale;\n  return (\n    (vertical ? laidOutIn.y : laidOutIn.x) *\n    (vertical ? rootPainted.y : rootPainted.x)\n  );\n}\n\nexport function SpacingOverlay({\n  editor,\n  hidden = false,\n  scrub = RESTING_BASE,\n  blocks,\n}: SpacingOverlayProps): React.JSX.Element | null {\n  // The renderer's default when the host names none, so a canvas drawn with\n  // the process registry is asked about through that same registry.\n  const resolver = React.useMemo(() => blocks ?? registeredBlocks(), [blocks]);\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const [bands, setBands] = React.useState<readonly SpacingBand[]>([]);\n  /*\n   * What the gesture layer needs about the measured block, taken in the SAME\n   * measurement the bands come from. Read separately it could disagree with\n   * them — a drag scaled by one reading against bands drawn from another.\n   */\n  const [subject, setSubject] = React.useState<SpacingSubject | null>(null);\n  /**\n   * Whether the handles are holding a gesture that has not been released.\n   *\n   * A preview can make its own block undescribable — a margin can push it\n   * partly behind an `overflow: hidden` ancestor, a padding can bring on a\n   * classic scrollbar — and the measurement that follows then legitimately has\n   * no bands to draw. Clearing the subject there unmounts the handles mid-drag:\n   * the listeners detach, the preview disappears, and the gesture ends without\n   * committing and without saying anything. The author sees the drag evaporate.\n   *\n   * So the SUBJECT survives while a gesture is live. The bands still go, which\n   * is honest — nothing is measurable to report — but the control the pointer\n   * is holding stays until it is let go.\n   */\n  const gestureLive = React.useRef(false);\n  /*\n   * How far the layer may paint outside itself, in pixels.\n   *\n   * Held beside the bands rather than derived at render because it needs the\n   * LAYER's size, which only the measurement has.\n   */\n  const [escape, setEscape] = React.useState(0);\n  /*\n   * Over a canvas in a frame, the root's size and the frame's scale. The\n   * bands are areas of the page, so the layer holding them is laid out in the\n   * root's own coordinates and scaled with the page as a whole; the value\n   * chips and the handles inside it keep their own size.\n   */\n  const [framed, setFramed] = React.useState<FramedLayer | null>(null);\n\n  const { document, selectedId } = editor;\n\n  /*\n   * Handles are drawn only for a SINGLE selection.\n   *\n   * `selectedId` is the primary of the selection, and a handle commits to that\n   * node alone — so with six blocks outlined a drag would restyle one of them\n   * and say nothing about the other five. `StyleInspectorPanel` refuses its\n   * writable controls on the same reasoning, and a control on the canvas that\n   * did what the panel beside it declines would be the same partial edit\n   * reached by a route nobody thought to close.\n   *\n   * The BANDS stay. They report rather than write, and the primary's spacing is\n   * a true thing to report about a selection that includes it.\n   */\n  const singular = editor.selection.ids.length <= 1;\n  /*\n   * No handles either for a block whose design is held — its own Layers lock,\n   * or an area locked to its content: they write its spacing, which either\n   * lock fixes. Asked of the rule the inspector holds its Style tab read-only\n   * by, so the panel and the canvas agree. The bands stay, for the reason\n   * above.\n   */\n  const designHeld =\n    selectedId !== null &&\n    !designIsWritable(document, selectedId, lockViewOf(editor));\n\n  /*\n   * Measured before the browser paints, so the bands never appear over the\n   * position the block held on the previous render.\n   *\n   * Keyed on the document as well as the selection because an edit resizes the\n   * block — which is most of what the inspector does — and bands keyed on the\n   * selection alone would keep describing the layout it used to have.\n   */\n  const measure = React.useCallback(() => {\n    const apply = (\n      next: readonly SpacingBand[],\n      layerBox?: { width: number; height: number },\n      measured: SpacingSubject | null = null\n    ): void => {\n      setBands(current => (sameBands(current, next) ? current : next));\n      setSubject(current => {\n        // Never dropped out from under a live gesture. See `gestureLive`.\n        if (measured === null && gestureLive.current) return current;\n        return sameSubject(current, measured) ? current : measured;\n      });\n      setEscape(\n        next.length === 0 || layerBox === undefined\n          ? 0\n          : overlayEscape(next, layerBox, CHIP_OVERFLOW_PX)\n      );\n    };\n    const element = layer.current;\n    if (element === null || selectedId === null) {\n      apply(NO_BANDS);\n      return;\n    }\n    // The canvas the bands describe, in the ROOT's own realm, whether the\n    // layer sits inside the root or over the frame the root is in.\n    const space = overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) {\n      apply(NO_BANDS);\n      return;\n    }\n    const { root } = space;\n    const rootBox = canvasContentRect(root, root);\n    const nextFramed: FramedLayer | null =\n      space.frame === null\n        ? null\n        : { width: rootBox.width, height: rootBox.height, scale: space.scale };\n    setFramed(current =>\n      sameFramedLayer(current, nextFramed) ? current : nextFramed\n    );\n    const block = nodeElement(root, selectedId);\n    if (block === null) {\n      apply(NO_BANDS);\n      return;\n    }\n    /*\n     * The element's own view rather than the ambient `window`, so a canvas\n     * rendered into another document is measured against the styles that\n     * actually apply to it rather than against this one's.\n     */\n    const style = block.ownerDocument.defaultView?.getComputedStyle(block);\n    if (style === undefined) {\n      apply(NO_BANDS);\n      return;\n    }\n\n    const scale = renderedScale(block, root);\n    const boxes = drawableBoxes(style, block, scale);\n    const borders = {\n      x: boxes.borderWidths.left + boxes.borderWidths.right,\n      y: boxes.borderWidths.top + boxes.borderWidths.bottom,\n    };\n    /*\n     * Through `canvasContentRect` rather than a rectangle read here: this\n     * package reads a rectangle in one place, so chrome measured one way cannot\n     * disagree with chrome measured another at a scroll offset.\n     */\n    const border = canvasContentRect(block, root);\n    const scaledBy: Scale = { x: scale.x, y: scale.y };\n    const radii = usedRadiiOf(style, border, scaledBy);\n    /*\n     * A block whose own radii cannot be resolved is a shape this cannot\n     * describe, and drawing nothing is the answer it already gives for every\n     * other one. Deciding it here rather than inside `describable` keeps that\n     * predicate over the four values it is handed.\n     */\n    if (\n      radii === undefined ||\n      !describable(\n        layoutFragments(block),\n        viewportPositioned(block),\n        hasScrollbarGutter(block, borders),\n        /*\n         * The block's own curve goes in with it: a rounded block flush inside an\n         * equally rounded clipping container is not cut, while its bounding\n         * rectangle's corners are outside every one of that container's arcs.\n         *\n         * Scaled, because the clip walk compares rendered rectangles while the\n         * radii are resolved in layout pixels.\n         */\n        clippedByAncestor(block, root, scaleCornerRadii(radii, scaledBy)),\n        scale\n      )\n    ) {\n      apply(NO_BANDS);\n      return;\n    }\n\n    /*\n     * The layer's own box, measured the same way every other rectangle here is.\n     * It fills the root, so the root's content rectangle IS the layer's, and\n     * asking for it separately would be a second answer to one question.\n     */\n    /*\n     * How much smaller than its layout the canvas is PAINTED, which is the unit\n     * the probe's movement will be seen in. Read once per measurement.\n     */\n    const rootPainted = canvasPaintedScale(root);\n\n    /**\n     * This node's answer for one box and side, asked fresh on every measurement.\n     *\n     * NOT remembered between passes. The answer describes how the block responds\n     * under the CSS applying to it right now, and what changes that CSS is\n     * open-ended: an edit, a breakpoint re-resolving at a new canvas width, a\n     * container query answering to a sibling's size, a forced state, a pointer\n     * arriving and matching `:hover`. A remembered answer has to be dropped for\n     * each of those in turn, which is a list that stays complete until the next\n     * one — the same reasoning `spacing-response.ts` gives for asking the element\n     * rather than reading the CSS. Measured at 0.8ms for all eight sides on a\n     * fifteen-hundred-node page, which is the whole of what remembering saved.\n     *\n     * Asking every pass is only safe because the canvas ignores a batch of\n     * mutations that changed nothing. The probe writes to a node this overlay's\n     * own subscription watches and puts it back inside one task, so without that\n     * filter each measurement would schedule the next forever. See\n     * `changedNothing` in `canvas-geometry-watch.ts`.\n     */\n    const outwardFor = (box: SpacingBox, side: SpacingSide): boolean =>\n      styleCapable(block)\n        ? spacingRespondsOutward(\n            block,\n            box,\n            side,\n            probeScale(box, side, scale, rootPainted)\n          )\n        : false;\n\n    const layerBox = rootBox;\n    /*\n     * Whose space the block-start margin is. Asked once per measurement, after\n     * every reading above, because answering it takes the gap marker off the\n     * block's container for one synchronous read.\n     */\n    const gapFrom = gapOwnerOf(block, document, type => resolver.get(type));\n    const gapSide = blockStartSide(style.writingMode);\n    const attributed = (bands: readonly SpacingBand[]): SpacingBand[] =>\n      bands.map(band =>\n        gapFrom !== undefined && band.box === \"margin\" && band.side === gapSide\n          ? { ...band, gapFrom }\n          : band\n      );\n    apply(\n      attributed(\n        spacingBands({\n          border,\n          borderWidths: boxes.borderWidths,\n          margin: boxes.margin,\n          padding: boxes.padding,\n          // Composed from the real transform between the block and the root, so\n          // a scaled ancestor counts and no rounded layout value is involved.\n          scale: scaledBy,\n          // Margins take the ancestors' scale ALONE — a transform does not scale\n          // the space a margin reserves, only the box it is drawn beside.\n          marginScale: { x: scale.ancestor.x, y: scale.ancestor.y },\n          // Resolved against the LAYOUT box, which is why the scale goes in with\n          // it: a rounded block's bands have to be cut to the curve, and the curve\n          // is stated in the units the author declared it in.\n          radii,\n        })\n      ),\n      layerBox,\n      {\n        nodeId: selectedId,\n        // The USED lengths, unscaled, which is what a handle starts a drag from\n        // and what the band beside it already reports.\n        margin: boxes.margin,\n        padding: boxes.padding,\n        scales: {\n          scale: scaledBy,\n          marginScale: { x: scale.ancestor.x, y: scale.ancestor.y },\n        },\n        /*\n         * Read from the drawn element, and `undefined` when it cannot be. That\n         * absence removes the handles rather than defaulting to left-to-right:\n         * see `side-orientation.ts` on why an unread element and a\n         * left-to-right one must not collapse into one answer.\n         */\n        orientation: orientationOfElement(block),\n        /*\n         * ASKED of the element, once per node and side, for BOTH boxes. Which\n         * edge of a band moves depends on how the block's size and position are\n         * settled along that axis, and no stored style answers that — a margin\n         * no more than a padding. See `spacing-response.ts`.\n         */\n        outward: {\n          margin: {\n            top: outwardFor(\"margin\", \"top\"),\n            right: outwardFor(\"margin\", \"right\"),\n            bottom: outwardFor(\"margin\", \"bottom\"),\n            left: outwardFor(\"margin\", \"left\"),\n          },\n          padding: {\n            top: outwardFor(\"padding\", \"top\"),\n            right: outwardFor(\"padding\", \"right\"),\n            bottom: outwardFor(\"padding\", \"bottom\"),\n            left: outwardFor(\"padding\", \"left\"),\n          },\n        },\n      }\n    );\n    // The document and the resolver are read for one thing: which container a\n    // gap belongs to, so a block moved into another container is named against\n    // the right one. The rendered tree is still read as it stands.\n  }, [selectedId, document, resolver]);\n\n  // A zoom, or a page loading into the frame, moves the block on screen while\n  // nothing in the document changes.\n  const canvasFrame = useCanvasFrame();\n  React.useLayoutEffect(() => {\n    if (hidden) {\n      setBands(current => (current.length === 0 ? current : NO_BANDS));\n      // The subject goes with them. Left standing it would keep a handle's\n      // gesture alive against a measurement nothing is drawing.\n      setSubject(null);\n      return;\n    }\n    measure();\n    // `document` is listed here as well as on `measure` because this effect is\n    // what has to run again after an edit: an edit resizes the selected block, which is most of\n    // what the inspector does, and an effect keyed on the selection alone would\n    // leave the bands describing the layout it had.\n  }, [measure, hidden, document, canvasFrame]);\n\n  /*\n   * Re-measure when the layout moves for a reason no render reports — an image\n   * finishing, a webfont swapping, the panels being resized around the canvas,\n   * a scroller between a block and the root, a transition settling.\n   *\n   * That whole list is `watchCanvasFor`'s, shared with every other overlay\n   * measuring against this root: which changes can move a rectangle is one\n   * question, and a second copy of the answer drifts from the first silently —\n   * the copy simply never hears one of the mechanisms, and looks complete.\n   *\n   * The layer is handed over as a READ rather than as an element, because it\n   * does not exist yet on the first pass. It is what locates the canvas root,\n   * and it is also what tells a foreign mutation from the bands' own: drawing\n   * them mutates the very subtree being observed, so without it each\n   * measurement would schedule the next.\n   */\n  React.useEffect(() => {\n    if (hidden || selectedId === null) return;\n    return watchCanvasFor(() => layer.current, measure);\n    /*\n     * `document` re-subscribes, and dropping it strands the observer on a\n     * DETACHED element. An edit replaces the rendered tree while the selection\n     * survives, so every id resolves to a NEW element and this effect — keyed on\n     * the selection alone — would keep watching the old ones. Their later resizes\n     * fire nothing, and the bands stay at the size the block had before the edit.\n     */\n  }, [measure, hidden, selectedId, document, canvasFrame]);\n\n  return (\n    <div\n      ref={layer}\n      className=\"nx-spacing-overlay\"\n      /*\n       * Not marked as chrome, for the reason the drop indicator is not: it takes\n       * no pointer events at all, so a press travels through to the block\n       * underneath and resolves to that node rather than to the overlay drawn\n       * over it. The HANDLES inside it are marked, because they do take one.\n       *\n       * `aria-hidden` sits on each BAND rather than here, and that placement is\n       * load-bearing. The bands are hidden for the same reason as ever — the\n       * same values are in the inspector with real labels, and announcing up to\n       * eight numbers on every arrow-key move through the layer tree would bury\n       * that surface in exactly the readers it is for. The handles are\n       * focusable, and a focusable element inside an `aria-hidden` subtree is\n       * reachable by keyboard while screen readers are told it is not there.\n       * One attribute on this element would have made every handle that.\n       */\n      /*\n       * How far the clip may extend, measured rather than fixed. A band can\n       * legitimately sit outside the canvas — a collapsed top margin does — and\n       * any constant allowance is too small for some legal value.\n       */\n      style={framedLayerStyle(escape, framed)}\n    >\n      {bands.map(band => (\n        <div\n          key={`${band.box}-${band.side}`}\n          className=\"nx-spacing-overlay__band\"\n          data-box={band.box}\n          data-side={band.side}\n          data-negative={band.negative ? \"\" : undefined}\n          data-gap={band.gapFrom === undefined ? undefined : \"\"}\n          // See the layer above: the report is hidden, the control is not.\n          aria-hidden=\"true\"\n          style={bandStyle(band)}\n        >\n          <span className=\"nx-spacing-overlay__value\">\n            {band.gapFrom === undefined\n              ? band.label\n              : `${band.label} · Gap · from ${band.gapFrom}`}\n          </span>\n        </div>\n      ))}\n      {subject === null || !singular || designHeld ? null : (\n        <SpacingHandles\n          editor={editor}\n          bands={bands}\n          subject={subject}\n          context={scrub}\n          /*\n           * The measurement the preview needs, handed over as the callback the\n           * bands are already measured by. See `onPreviewChange`: the layer's\n           * own mutations are deliberately invisible to the style watcher, and\n           * the scrub preview lives in that layer.\n           */\n          onPreviewChange={measure}\n          /*\n           * So a measurement that finds nothing to draw cannot unmount the\n           * control the pointer is holding. See `gestureLive`.\n           */\n          onGestureChange={held => (gestureLive.current = held)}\n        />\n      )}\n    </div>\n  );\n}\n","/**\n * A repair, of locks and placements, as ops the editor's store applies, so\n * confirming it is one edit an author can undo.\n *\n * The engine's `planRepair` decides the repair: its `result` is the document\n * the author confirms, and its steps are what the preview shows. The store\n * takes only ops, so this turns the steps into them, applying each as it goes\n * so every position is read off the document as it then stands. The plan\n * stays the one answer: ops that do not give exactly its `result` are not the\n * repair the author confirmed, and are refused rather than applied.\n *\n * @module repair-ops\n */\nimport {\n  applyOp,\n  DEFAULT_LIMITS,\n  findNode,\n  layersLockBreak,\n  locateNode,\n  OpError,\n  positionOf,\n  sameStoredValue,\n  type BlockDocument,\n  type BlockNode,\n  type BuilderOp,\n  type DocumentLimits,\n  type RepairPlan,\n  type RepairStep,\n} from \"@nextlyhq/blocks-engine\";\n\n/** Why a repair cannot be applied as planned. */\nexport type RepairRefusal =\n  /**\n   * A block the repair changes is locked in Layers: the block it moves, one\n   * inside it, or one around a block it moves, changes or adds to.\n   */\n  | { readonly reason: \"locked-block\"; readonly nodeId: string }\n  /** The ops did not give the planned document. */\n  | { readonly reason: \"unplaceable\" };\n\n/** The ops that apply a repair, or why it cannot be applied. */\nexport type RepairOps =\n  | { readonly ops: readonly BuilderOp[] }\n  | { readonly refused: RepairRefusal };\n\ntype UpdateOp = Extract<BuilderOp, { kind: \"update\" }>;\ntype RemovableField = NonNullable<UpdateOp[\"unset\"]>[number];\n\n/** The document as the ops so far left it, and the ops. */\ninterface Translation {\n  current: BlockDocument;\n  readonly ops: BuilderOp[];\n  readonly limits: DocumentLimits;\n}\n\n/**\n * The ops that turn `document` into `plan.result`.\n *\n * @param document - the document the plan was made from\n * @param plan - its repair, from the engine's `planRepair`\n */\nexport function repairOps(\n  document: BlockDocument,\n  plan: RepairPlan,\n  limits: DocumentLimits = DEFAULT_LIMITS\n): RepairOps {\n  const at: Translation = { current: document, ops: [], limits };\n  // Every reset first: a reset puts a block's parts back as it starts and\n  // touches nothing another step does, so taking them first keeps each\n  // document on the way, and each undo back, within the caps the plan's\n  // result fits, where an add made before a large reset could pass them.\n  const resetsFirst = [\n    ...plan.steps.filter(step => step.kind === \"reset\"),\n    ...plan.steps.filter(step => step.kind !== \"reset\"),\n  ];\n  for (const group of slotGroups(resetsFirst)) {\n    // How many blocks this slot's repair has already placed after each block,\n    // so the next one goes after them, in the order the plan placed them.\n    const placedAfter = new Map<string, number>();\n    for (const step of inApplyOrder(group)) {\n      const refused = applyStep(at, step, plan.result, placedAfter);\n      if (refused !== undefined) return { refused };\n    }\n  }\n  if (!sameStoredValue(at.current.nodes, plan.result.nodes)) {\n    return { refused: { reason: \"unplaceable\" } };\n  }\n  return { ops: at.ops };\n}\n\n/**\n * The plan's steps, split by the slot each repairs: a slot's adds, reorder\n * and moves arrive together, and a reset is a group of its own.\n */\nfunction slotGroups(steps: readonly RepairStep[]): RepairStep[][] {\n  const groups: RepairStep[][] = [];\n  let key: string | undefined;\n  for (const step of steps) {\n    const next = placeOf(step);\n    if (next !== key || groups.length === 0) groups.push([]);\n    groups[groups.length - 1].push(step);\n    key = next;\n  }\n  return groups;\n}\n\nfunction placeOf(step: RepairStep): string {\n  switch (step.kind) {\n    case \"move\":\n      // A placement move names the exact block it lands after, so it is a\n      // group of its own: never counted against a lock move's anchor, and\n      // never sorted ahead of a lock add in the slot it leaves.\n      return step.cause === \"placement\"\n        ? `placement\\u0000${step.nodeId}`\n        : `${step.from.holderId}\\u0000${step.from.slot}`;\n    case \"add\":\n      return `${step.at.holderId}\\u0000${step.at.slot}`;\n    case \"reorder\":\n      return `${step.holderId}\\u0000${step.slot}`;\n    case \"reset\":\n      return `reset\\u0000${step.nodeId}`;\n  }\n}\n\n/**\n * A slot's steps in the order that places each block where the plan does:\n * the blocks it may not hold out first, so an added block's index counts\n * only the blocks that stay; then the adds, by index; then the order.\n */\nfunction inApplyOrder(group: readonly RepairStep[]): RepairStep[] {\n  const rank = { move: 0, add: 1, reorder: 2, reset: 3 } as const;\n  return [...group].sort((a, b) => rank[a.kind] - rank[b.kind]);\n}\n\n/** Apply one step's ops; the refusal when one cannot be applied. */\nfunction applyStep(\n  at: Translation,\n  step: RepairStep,\n  result: BlockDocument,\n  placedAfter: Map<string, number>\n): RepairRefusal | undefined {\n  for (const op of opsFor(at, step, result, placedAfter)) {\n    // Asked before applying, with the op layer's own rule: nothing a Layers\n    // lock covers changes until it is unlocked, whether the step moves a\n    // locked block, moves or changes one inside a locked block, or adds to\n    // one, and the author is told which block to unlock.\n    const broken = layersLockBreak(at.current.nodes, op);\n    if (broken !== undefined) {\n      return { reason: \"locked-block\", nodeId: broken.lockedId };\n    }\n    try {\n      at.current = applyOp(at.current, op, at.limits).document;\n    } catch (error) {\n      if (!(error instanceof OpError)) throw error;\n      return { reason: \"unplaceable\" };\n    }\n    at.ops.push(op);\n  }\n  return undefined;\n}\n\n/**\n * One step's ops, each built from the document as the ops before it left it.\n * A generator, so a reorder's second move is built after its first applied.\n */\nfunction* opsFor(\n  at: Translation,\n  step: RepairStep,\n  result: BlockDocument,\n  placedAfter: Map<string, number>\n): Generator<BuilderOp> {\n  switch (step.kind) {\n    case \"move\":\n      yield* moveOut(at, step, placedAfter);\n      return;\n    case \"add\":\n      yield* addStarting(at, step, result);\n      return;\n    case \"reorder\":\n      yield* putInOrder(at, step);\n      return;\n    case \"reset\":\n      yield* resetOp(at.current, result, step.nodeId);\n      return;\n  }\n}\n\ntype StepOf<K extends RepairStep[\"kind\"]> = Extract<RepairStep, { kind: K }>;\n\n/** A block moved to just after its anchor, after any the slot already put there. */\nfunction* moveOut(\n  at: Translation,\n  step: StepOf<\"move\">,\n  placedAfter: Map<string, number>\n): Generator<BuilderOp> {\n  const anchor = locateNode(at.current.nodes, step.after);\n  if (anchor === undefined) return;\n  const before = placedAfter.get(step.after) ?? 0;\n  placedAfter.set(step.after, before + 1);\n  yield {\n    kind: \"move\",\n    id: step.nodeId,\n    to: { ...positionOf(anchor), index: anchor.index + 1 + before },\n  };\n}\n\n/** A missing starting block, as the plan's result holds it. */\nfunction* addStarting(\n  at: Translation,\n  step: StepOf<\"add\">,\n  result: BlockDocument\n): Generator<BuilderOp> {\n  const node = findNode(result.nodes, step.nodeId);\n  if (node === undefined) return;\n  const held = slotOf(at.current, step.at.holderId, step.at.slot);\n  yield {\n    kind: \"insert\",\n    node,\n    at: {\n      parentId: step.at.holderId,\n      slot: step.at.slot,\n      index: Math.min(step.at.index, held.length),\n    },\n  };\n}\n\n/** Each block not already at its place in the order, moved there. */\nfunction* putInOrder(\n  at: Translation,\n  step: StepOf<\"reorder\">\n): Generator<BuilderOp> {\n  for (const [index, id] of step.order.entries()) {\n    const now = slotOf(at.current, step.holderId, step.slot);\n    if (now[index]?.id === id) continue;\n    yield {\n      kind: \"move\",\n      id,\n      to: { parentId: step.holderId, slot: step.slot, index },\n    };\n  }\n}\n\nfunction slotOf(\n  document: BlockDocument,\n  holderId: string,\n  slot: string\n): readonly BlockNode[] {\n  return findNode(document.nodes, holderId)?.slots?.[slot] ?? [];\n}\n\n/**\n * The update that gives a node the fields the plan's result gives it: each\n * one that differs set, each one the result drops removed. Its id, type and\n * slots are not an update's to change, and a reset leaves them alone.\n */\nfunction* resetOp(\n  current: BlockDocument,\n  result: BlockDocument,\n  id: string\n): Generator<UpdateOp> {\n  const held = findNode(current.nodes, id);\n  const target = findNode(result.nodes, id);\n  if (held === undefined || target === undefined) return;\n  const { patch, unset } = fieldChanges(\n    held as unknown as Record<string, unknown>,\n    target as unknown as Record<string, unknown>\n  );\n  if (Object.keys(patch).length === 0 && unset.length === 0) return;\n  yield {\n    kind: \"update\",\n    id,\n    patch: patch,\n    ...(unset.length === 0 ? {} : { unset }),\n  };\n}\n\n/** The fields to set and to remove so `held` becomes `target`. */\nfunction fieldChanges(\n  held: Record<string, unknown>,\n  target: Record<string, unknown>\n): { patch: Record<string, unknown>; unset: RemovableField[] } {\n  const patch: Record<string, unknown> = {};\n  const unset: RemovableField[] = [];\n  for (const key of new Set([...Object.keys(target), ...Object.keys(held)])) {\n    if (UNPATCHED.has(key)) continue;\n    if (!Object.hasOwn(target, key)) unset.push(key as RemovableField);\n    else if (!sameStoredValue(held[key], target[key])) patch[key] = target[key];\n  }\n  return { patch, unset };\n}\n\n/** The fields no update changes. */\nconst UNPATCHED: ReadonlySet<string> = new Set([\"id\", \"type\", \"slots\"]);\n","\"use client\";\n\n/**\n * The repair of a page whose locked areas hold what their locks don't allow,\n * or whose blocks sit where the placement rule refuses them.\n *\n * A page stored before its locks or the placement rule were enforced, or\n * written by an import, can hold blocks a locked area may not, a design inside\n * an area locked to its content, or a block where it isn't allowed: a Button\n * inside a linked Card, say. The editor goes on editing such a page, refusing\n * only a new break, and a save refuses or warns; this offers to put it right.\n * It shows each step first, in words, and changes nothing until the author\n * confirms; the repair is then one edit, which undo takes back. No block the\n * author placed is removed: the engine's planner moves what an area may not\n * hold to just after it, and a misplaced block to the nearest place it is\n * allowed.\n *\n * @module repair-notice\n */\nimport {\n  findNode,\n  type RepairPlan,\n  type RepairStep,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport { repairStepSentence } from \"../lock-refusal\";\nimport { blockLabel } from \"../panels/add/inserter\";\n\nimport { repairOps, type RepairRefusal } from \"./repair-ops\";\n\n/**\n * The notice, shown only while the document holds something to repair.\n *\n * Planned again whenever the document changes, so an edit that fixes an area\n * by hand, or an undo that brings a break back, is reflected straight away.\n */\nexport function RepairNotice({\n  editor,\n}: {\n  editor: EditorState;\n}): React.JSX.Element | null {\n  // Planned once per document and per set of rules it is judged by, which\n  // `planRepair` changes with. Not once per store object: that changes with\n  // the selection too, so each click would plan the whole page again.\n  const { document, planRepair } = editor;\n  const plan = React.useMemo(\n    () => planRepair(document),\n    [document, planRepair]\n  );\n  const [reviewing, setReviewing] = React.useState(false);\n  const [refused, setRefused] = React.useState<string | undefined>();\n  const headingId = React.useId();\n\n  // Nothing to say on a page every lock and the placement rule allow. A page\n  // whose only breaks are ones the plan can't repair still says so, with\n  // nothing to confirm: hiding the notice would read as a page the next save\n  // accepts.\n  if (!holdsAnything(plan)) return null;\n\n  const confirm = () => {\n    // The plan shown is this render's, made for the store as it stands: a\n    // save or an edit since the review gives the store, and so this plan, a\n    // new identity, and the list on screen with it. Planning again here would\n    // mint new ids for every block an add step brings, so no plan could ever\n    // match the one reviewed.\n    const translated = repairOps(editor.document, plan, editor.limits);\n    if (\"refused\" in translated) {\n      setRefused(refusalSentence(translated.refused, editor));\n      return;\n    }\n    if (editor.applyAll(translated.ops) === null) {\n      setRefused(\"This repair could not be applied here. Nothing was changed.\");\n      return;\n    }\n    setReviewing(false);\n    setRefused(undefined);\n  };\n\n  return (\n    <section className=\"nx-lock-repair\" aria-labelledby={headingId}>\n      <h2 id={headingId} className=\"nx-lock-repair__title\">\n        Repair this page\n      </h2>\n      <p className=\"nx-inspector__note\">{introSentence(plan)}</p>\n      {plan.steps.length === 0 ? (\n        <UnrepairableNote plan={plan} />\n      ) : reviewing ? (\n        <RepairReview\n          plan={plan}\n          editor={editor}\n          refused={refused}\n          onConfirm={confirm}\n          onCancel={() => {\n            setReviewing(false);\n            setRefused(undefined);\n          }}\n        />\n      ) : (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          onClick={() => setReviewing(true)}\n        >\n          Review the repair\n        </Button>\n      )}\n    </section>\n  );\n}\n\n/** The steps, in the order the repair takes them, and the choice. */\nfunction RepairReview({\n  plan,\n  editor,\n  refused,\n  onConfirm,\n  onCancel,\n}: {\n  plan: RepairPlan;\n  editor: EditorState;\n  refused: string | undefined;\n  onConfirm: () => void;\n  onCancel: () => void;\n}): React.JSX.Element {\n  return (\n    <>\n      <ol className=\"nx-lock-repair__steps\">\n        {plan.steps.map((step, index) => (\n          // Steps have no identity of their own; a plan is replaced whole.\n          <li key={index}>{repairStepSentence(step, editor.document)}</li>\n        ))}\n      </ol>\n      <p className=\"nx-inspector__note\">\n        No block is removed, and nothing changes until you repair.\n      </p>\n      {/* Said before the author confirms, so a repair that leaves a break is\n          never taken for one that fixes the page. */}\n      <UnrepairableNote plan={plan} />\n      {refused === undefined ? null : (\n        <p className=\"nx-inspector__note\" role=\"alert\">\n          {refused}\n        </p>\n      )}\n      <div className=\"nx-lock-repair__actions\">\n        <Button type=\"button\" size=\"sm\" onClick={onConfirm}>\n          Repair\n        </Button>\n        <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={onCancel}>\n          Cancel\n        </Button>\n      </div>\n    </>\n  );\n}\n\n/**\n * That some breaks have no repair here, whatever else is repaired: one\n * sentence for the locks and one for the placements the plan leaves, each\n * only when it leaves some. Nothing when it leaves none.\n */\nfunction UnrepairableNote({\n  plan,\n}: {\n  plan: RepairPlan;\n}): React.JSX.Element | null {\n  const locks = plan.remaining.length > 0;\n  const placements = plan.remainingPlacements.length > 0;\n  if (!locks && !placements) return null;\n  return (\n    <>\n      {locks ? (\n        <p className=\"nx-inspector__note\">\n          Some locked areas can’t be repaired here: a block they hold has\n          nowhere else it may go. Those stay as they are.\n        </p>\n      ) : null}\n      {placements ? (\n        <p className=\"nx-inspector__note\">\n          Some blocks can’t be repaired here: there is nowhere else on this page\n          they may go. Those stay where they are.\n        </p>\n      ) : null}\n    </>\n  );\n}\n\n/** Whether the plan has anything to repair or to say it can't. */\nfunction holdsAnything(plan: RepairPlan): boolean {\n  return (\n    plan.steps.length > 0 ||\n    plan.remaining.length > 0 ||\n    plan.remainingPlacements.length > 0\n  );\n}\n\n/** A move the placement rule makes, as opposed to one a lock makes. */\nfunction isPlacementMove(step: RepairStep): boolean {\n  return step.kind === \"move\" && step.cause === \"placement\";\n}\n\n/**\n * What the page holds, naming locks and placements each only when the plan\n * repairs or leaves one of that kind.\n */\nfunction introSentence(plan: RepairPlan): string {\n  const locks =\n    plan.remaining.length > 0 ||\n    plan.steps.some(step => !isPlacementMove(step));\n  const placements =\n    plan.remainingPlacements.length > 0 || plan.steps.some(isPlacementMove);\n  const lockWords =\n    \"Some locked areas on this page hold blocks or settings their lock doesn’t allow\";\n  if (locks && placements) {\n    return `${lockWords}, and some blocks sit where they aren’t allowed.`;\n  }\n  if (placements)\n    return \"Some blocks on this page sit where they aren’t allowed.\";\n  return `${lockWords}.`;\n}\n\n/** Why the repair can't be applied, and what the author can do about it. */\nfunction refusalSentence(refusal: RepairRefusal, editor: EditorState): string {\n  if (refusal.reason === \"unplaceable\") {\n    return \"This repair could not be applied here. Nothing was changed.\";\n  }\n  const node = findNode(editor.document.nodes, refusal.nodeId);\n  const name = node === undefined ? \"A block\" : blockLabel(node.type);\n  return `${name} is locked, and the repair moves it. Unlock it, then repair.`;\n}\n","\"use client\";\n\n/**\n * The affordance drawn over a container with nothing in it.\n *\n * An empty `core/box`, `core/card`, `core/section` or `core/columns` renders an\n * element with no children, so a container that exists only to HOLD something\n * else has no size, no visible boundary and nothing a pointer can land on.\n * `builder-chrome.css`'s `[data-nx-slots]:empty` rule already gives it a 44px\n * dashed box so it is not literally invisible, but a box is not a control:\n * nothing about it says \"click here\", nothing names what it would hold, and\n * pressing it only SELECTS the container rather than offering to fill it. That\n * rule's own docblock names the remedy: \"a follow-up that draws a real\n * positioned element over each empty container, rather than styling the\n * container itself\" — this is that follow-up.\n *\n * This draws a labelled \"+\" over each such container instead. Pressing one\n * only reports the container's id through\n * {@link EmptyContainerAppendersProps.onAppend}; it does not select anything\n * or open an inserter. The host hands that id to the Add panel as its\n * `inside`, and `insertionCandidates` reads {@link emptySlotOf} to put a new\n * block in the container's empty region — so wiring a press needs no new\n * targeting path, and this component needs no knowledge of the editor at all.\n *\n * ## One question, answered once\n *\n * \"Which of this node's declared slots is empty\" is `emptySlotOf`'s question,\n * already asked by the inserter to decide where a chosen block lands. A second\n * copy of that question here would agree with the inserter on the day both were\n * written and drift afterwards — an author offered a control that the inserter\n * then fills somewhere else, which is exactly the failure recomputing it would\n * risk.\n *\n * ## Positioning follows `spacing-overlay.tsx`\n *\n * Both draw a rectangle over a node found by its `NODE_ID_ATTRIBUTE` address,\n * and both need the same correction: the canvas is zoomable through CSS\n * `zoom`, so an element's `offsetWidth` is its LAYOUT size while\n * `getBoundingClientRect()` is its PAINTED one, and the two agree only at\n * 100%. `canvasContentRect` (`geometry-dom.ts`) already divides the painted\n * rectangle back down by the canvas root's own painted scale, so measuring\n * through it — exactly as `spacing-overlay.tsx` and `block-toolbar.tsx`\n * already do — inherits correct placement at any zoom without this file doing\n * any scale arithmetic of its own. Computing an offset directly from a client\n * rectangle here would be the second implementation `geometry.ts` warns\n * against: unscaled, it is wrong by `(1 - scale) * inset`, exactly zero at\n * 100% and invisible in precisely the configuration most testing happens in.\n *\n * ## A fixed, centred control rather than a rectangle sized to the container\n *\n * The button does not stretch to the measured rectangle's own width and\n * height. It is a fixed {@link APPENDER_WIDTH_PX} by {@link APPENDER_SIZE_PX}\n * control centred inside it, wide enough for its words, and that is a\n * correction rather than a style choice.\n *\n * `emptySlotOf` names which SLOT is empty, but there is no DOM address for\n * \"slot X of node Y\" to measure — `NODE_ID_ATTRIBUTE` marks a node's whole\n * root element, and a node with several declared slots renders all of them\n * inside that one root. So the only rectangle measurable here is the node's\n * entire root, whether or not every slot inside it is empty. A button sized\n * to that rectangle sits over a POPULATED later slot exactly as much as over\n * the empty first one, stealing the pointer clicks the populated slot's own\n * content should get. A fixed small square anchored to the root's centre\n * cannot do that: the worst it can overlap is a small area near the middle,\n * never the slot's whole content.\n *\n * The same fix answers a second problem for free. `canvasContentRect` reports\n * a node's rectangle whether or not an authored ancestor clips it, because\n * clipping happens in the DOM and this overlay draws in the root's flat\n * coordinate space above it — so a full-bleed button drawn there paints over\n * whatever unrelated content happens to sit at the un-clipped position. A\n * clipped container is excluded outright below (see `measure`, and\n * `clippedByAncestorRect` in `geometry-dom.ts`), and the fixed size is what\n * makes that exclusion cheap to reason about: declining a single small square\n * costs far less than declining a rectangle that might have spanned most of\n * the canvas, and a control that never reaches a container's corners has no\n * need of `clippedByAncestor`'s corner-aware refinement — see `measure` for\n * why asking that stricter question here would cost more than it protects.\n *\n * For the ordinary case this changes nothing an author can see: the container\n * the control is drawn on is one `builder-chrome.css` has already given a 44px\n * box, so centring a 44px square inside its measured rectangle places the\n * control exactly where that box already is. That sentence is only true\n * because of the condition below, which is what makes the box's presence a\n * guarantee rather than an assumption.\n *\n * ## Which containers get a control is the STYLESHEET's question\n *\n * `emptySlotOf` decides which containers this component knows about, and that\n * is a question about the stored document. Whether an affordance is drawn is a\n * question about the RENDER, and `builder-chrome.css` already asks it:\n * {@link EMPTY_CONTAINER_SELECTOR}. `measure` asks the same one of the same\n * element rather than trusting the two to describe the same containers.\n *\n * They do not. A node can have an empty slot inside a root that renders\n * content of its own — `core/accordion-item` puts a `<summary>` beside its\n * slot, so a closed one has an empty `children` slot and a root that is not\n * `:empty`. The stylesheet declined such a container, this component did not,\n * and the fixed-size control was then centred in a rectangle sized by the\n * summary rather than by a box that was never drawn. A node rendering several\n * slots is the same shape: its root is not `:empty` while a later slot holds\n * anything, which is precisely when a control over its centre would sit on a\n * populated region.\n *\n * The rule's ANCESTOR conditions are part of that question and not a detail of\n * how the stylesheet is written. Its box is scoped to a canvas inside a builder\n * shell, and `Canvas` and this component are both exported — so a host composing them with no shell renders containers\n * the element-level condition accepts and the rule never reaches. Asking the\n * whole selector is what keeps \"there is a box here\" a fact rather than an\n * assumption about how the caller mounted this.\n *\n * The consequence is that a container carrying no visual affordance gets no\n * control either, which is the point rather than a shortfall — it is still\n * fillable, by dropping a block onto it on the canvas or moving one into it in\n * Layers; only the Add panel's explicit \"inside\" goes through this control.\n *\n * ## Never outside its own container\n *\n * The control is additionally CLAMPED to the measured rectangle, because the\n * stylesheet guarantees a minimum height and not a minimum width. An empty\n * container narrower than the control is legitimate — a narrow column — and an\n * unclamped square centred in it hangs over both edges, onto whatever sits\n * beside it. Since the overlay paints in document order, a control that\n * escapes its own container lands on top of an earlier sibling and takes the\n * press meant for it. The full-bleed button this replaced could not do that;\n * containment is the property that had to be kept when the size stopped\n * matching the container.\n *\n * ## Identity is independent of geometry, and has to stay that way\n *\n * Which containers get a control comes from the DOCUMENT alone, and\n * {@link emptyContainersIn} has to stay that way — it reads no DOM, so a\n * component with no canvas root still knows its whole set. What a measurement\n * pass concludes about one of those containers is a LATER, separate question,\n * and it has three answers rather than two:\n *\n * - MEASURED — the pass found the element, accepted it, and holds a rectangle.\n * - DECLINED — the pass reached this container and refused it. The reasons are\n *   listed rather than counted, because a total kept by hand beside the list\n *   goes stale the moment one is inserted: the render produced no element for\n *   it at all; the stylesheet drew no box for the element it did produce (see\n *   the section above); the render laid out no box for that element, because\n *   something between it and the root generates none; the render SKIPPED that\n *   element, so the rectangle it still reports describes no place on the page;\n *   the author positioned it against the VIEWPORT rather than against the page;\n *   or an authored ancestor clips it. Each states its own case where it is\n *   asked — the first in `measure`, which is the only one with no element to\n *   ask anything of, and the rest in {@link declines}. Every one of them is\n *   re-decided on every pass, so each is a refusal for as long as the render\n *   keeps this shape rather than a permanent one.\n * - UNMEASURED — no pass has run at all, because there is no canvas root to\n *   run one against. Nothing has been asked about any container yet.\n *\n * An UNMEASURED control RENDERS, at `{ x: 0, y: 0, width: 0, height: 0 }`,\n * which is the property this section exists to protect: a control an author\n * cannot yet see on screen is still a control a screen reader can reach, and a\n * test asserting it exists must not depend on a browser having laid anything\n * out. Hiding it would remove it from the accessibility tree, which is exactly\n * the state the bare-mount cases in `empty-container-appender.test.tsx` render\n * in — a component with no canvas root at all — so a hidden-until-measured\n * design would make every one of those fail to find a control that, mounted\n * for real, is there all along.\n *\n * A DECLINED control renders NOTHING, which is the same argument read the\n * other way. It is not a control waiting to be placed; it is one this\n * component has decided not to offer, so keeping it in the accessibility tree\n * leaves a zero-sized button in the tab order — reachable, announced by name,\n * and invisible. `.nx-empty-container-appenders__button` is `display: flex`\n * and `pointer-events: auto`, and its `:focus-visible` rule would draw an\n * outline on a box with no area. A `core/accordion-item` whose `children` slot\n * is empty reaches that state from its own `defaultProps`, and so does any\n * node `PageRenderer` leaves out of the tree it draws — one carrying\n * `visibility.conditions`, or one whose props make it draw nothing — which the\n * document goes on listing for as long as the author keeps it.\n *\n * The two used to share one representation — no entry in the measurement map —\n * so \"not yet\" and \"never\" were the same value and the second inherited the\n * first's behaviour. A pass therefore records a {@link RecordedPlacement} for\n * every container it REACHED, a rectangle or a refusal, which leaves absence\n * meaning the one thing it can still mean. {@link controlRectFor} is the only\n * place those three become the two things a render can do, switched\n * exhaustively so a fourth state cannot fall through a `default` arm.\n *\n * @module empty-container-appender\n */\n\nimport {\n  walkNodes,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport { Plus } from \"lucide-react\";\nimport {\n  Fragment,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ReactElement,\n} from \"react\";\n\nimport type { Rect } from \"../geometry\";\nimport { isGallery } from \"../inspector/content/gallery-pictures\";\nimport type { SlotSource } from \"../panels/add/inserter\";\nimport { authoredName } from \"../panels/layers/layers\";\n\nimport { CANVAS_ROOT_CLASS, CHROME_ATTRIBUTE, nodeElement } from \"./canvas\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport {\n  EMPTY_CONTAINER_SELECTOR,\n  EMPTY_DISCLOSURE_SELECTOR,\n  emptySlotOf,\n} from \"./empty-slot\";\nimport {\n  canvasContentRect,\n  clippedByAncestorRect,\n  overlaySpaceOf,\n  layoutFragments,\n  renderSkips,\n  viewportPositioned,\n} from \"./geometry-dom\";\nimport { useHoveredBlock } from \"./hovered-block\";\n\n/**\n * The one property this component ever reads off a block's definition.\n *\n * A block's full definition (`AnyBlockDefinition` in `@nextlyhq/blocks-engine`)\n * requires `name`, `version`, `description`, `example`, `render` and more —\n * none of which `nameOf` below touches. Narrowed to just the field actually\n * read, so a fixture standing in for one is an honest, minimal object rather\n * than a full definition wearing a cast to get past the compiler.\n *\n * Still satisfied by the real thing with no adapter: `AnyBlockDefinition`'s\n * own `editor` field is `BlockEditorMeta`, which carries more than this needs\n * but remains structurally assignable to it, so the live registry's\n * `getBlock` — returning `AnyBlockDefinition | undefined` — is a valid\n * `BlockLookup[\"get\"]` as it stands.\n */\ninterface LabelledBlock {\n  readonly editor?: { readonly label?: string };\n}\n\n/**\n * Resolves a block type to (at most) the one property this component reads.\n *\n * Named apart from `AnyBlockDefinition` — the registry's own interface — for\n * the same reason `LabelledBlock` is narrowed: a caller may hand this the live\n * registry (`{ get: getBlock }`) or a plain fixture with nothing registered,\n * and both satisfy it with no adapter in between.\n */\ninterface BlockLookup {\n  get(type: string): LabelledBlock | undefined;\n}\n\n/** One container this component offers a control for, and its accessible name. */\ninterface EmptyContainer {\n  readonly id: string;\n  readonly label: string;\n}\n\n/**\n * The name this control announces for the block it would fill.\n *\n * The AUTHORED instance name wins when the node has one — via\n * `authoredName`, the same precedence `layerLabel` gives the Layers panel, so\n * two empty containers of the same type an author has told apart by name are\n * told apart here too rather than announcing as one indistinguishable\n * control. Without one, `editor.label` when the block declares it. Otherwise\n * the block's raw TYPE — not a humanised guess — because this is an\n * accessible NAME rather than a palette entry: a control an author cannot\n * name is one they cannot find, and the type string names the missing block\n * truthfully even when no definition is registered to describe it at all.\n *\n * `layerLabel` itself is not called directly: it resolves the type-level\n * fallback through the GLOBAL registry (`blockLabel`), where this component\n * takes an injected {@link BlockLookup} so its tests need not register\n * anything there. `authoredName` is the part of `layerLabel` that does not\n * depend on the registry, and it is exported from `layers.ts` for exactly\n * this reuse.\n *\n * An empty string is treated the same as an absent label: a block declaring\n * `editor: { label: \"\" }` has not actually named itself, and announcing an\n * empty string would leave the control with no accessible name at all.\n */\nfunction nameOf(node: BlockNode, blocks: BlockLookup): string {\n  const named = authoredName(node);\n  if (named !== undefined) return named;\n  const declared = blocks.get(node.type)?.editor?.label;\n  return declared !== undefined && declared !== \"\" ? declared : node.type;\n}\n\n/**\n * Every container in the document with nothing in its first declared slot.\n *\n * `walkNodes` rather than a walk written here: it is cycle-safe and\n * depth-bounded, and it descends into every slot of every node regardless of\n * whether that node itself gets a control — so a container nested inside\n * another empty one is still found. A hand-written recursive walk would lose\n * that depth guarantee the first time a document was deeper than the call\n * stack allows, which is exactly the shape a persisted document can arrive in\n * whether or not anything validated it first.\n */\nfunction emptyContainersIn(\n  document: BlockDocument,\n  slots: SlotSource,\n  blocks: BlockLookup\n): EmptyContainer[] {\n  const found: EmptyContainer[] = [];\n  walkNodes(document.nodes, node => {\n    // A Gallery draws its own empty state, \"Add images\" (`ImageStates`), so\n    // it is filled with pictures rather than with an empty Image to fill.\n    if (isGallery(node)) return;\n    if (emptySlotOf(node, slots) !== null) {\n      found.push({ id: node.id, label: nameOf(node, blocks) });\n    }\n  });\n  return found;\n}\n\n/**\n * A rectangle with no measurement yet.\n *\n * Zero-sized rather than absent, so an unmeasured control still occupies a\n * point in the canvas's coordinate space instead of carrying no position at\n * all — see the module docblock for why it must render regardless. It belongs\n * to the UNMEASURED state alone: a declined container draws nothing, so it\n * never reaches a rectangle at all.\n */\nconst UNMEASURED_RECT: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n/**\n * What one measurement pass concluded about a container it REACHED.\n *\n * A refusal is a value here rather than the absence of one, because absence\n * already means something else — see the module docblock's three states. Both\n * members are recorded by `measure`, which records one for EVERY container it\n * is handed once it has a root: the map is empty only where there was no root\n * to run a pass against.\n */\ntype RecordedPlacement =\n  | {\n      readonly kind: \"measured\";\n      /** Where the control is drawn, centred in the container. */\n      readonly rect: Rect;\n      /** The container's own box, which its hover overlay covers. */\n      readonly area: Rect;\n    }\n  | { readonly kind: \"declined\" };\n\n/** A container's state, including the one a pass records by omission. */\ntype Placement = RecordedPlacement | { readonly kind: \"unmeasured\" };\n\n/** The refusal, shared rather than allocated once per declined container. */\nconst DECLINED: RecordedPlacement = { kind: \"declined\" };\n\n/** What a container absent from a pass's map is in. */\nconst UNMEASURED: Placement = { kind: \"unmeasured\" };\n\n/** No container reached: the identity returned before any pass runs. */\nconst NO_PLACEMENTS: ReadonlyMap<string, RecordedPlacement> = new Map();\n\n/**\n * Where to draw a container's control, or `null` when it gets none.\n *\n * The single place a missing entry is given its meaning, so no caller has to\n * agree with another about what one stands for. `switch` with no `default`: a\n * fourth state would leave this able to return `undefined`, which the declared\n * type refuses — the same property `rectCut` in `geometry-dom.ts` relies on,\n * rather than a `default` arm that would silently absorb it.\n */\nfunction controlRectFor(\n  placements: ReadonlyMap<string, RecordedPlacement>,\n  id: string\n): Rect | null {\n  const placement: Placement = placements.get(id) ?? UNMEASURED;\n  switch (placement.kind) {\n    case \"measured\":\n      return placement.rect;\n    case \"declined\":\n      return null;\n    case \"unmeasured\":\n      return UNMEASURED_RECT;\n  }\n}\n\n/**\n * The container's own box, for the overlay drawn over it while it is pointed\n * at or its control has focus: only once a pass has measured it.\n */\nfunction areaRectFor(\n  placements: ReadonlyMap<string, RecordedPlacement>,\n  id: string\n): Rect | null {\n  const placement = placements.get(id);\n  return placement?.kind === \"measured\" ? placement.area : null;\n}\n\n/**\n * The control's fixed side length, in the canvas's content pixels.\n *\n * Matches `builder-chrome.css`'s `[data-nx-slots]:empty` rule, whose\n * `min-height: 2.75rem` (44px) is that stylesheet's own answer to \"how small\n * can a pointer target be and still be comfortable\". Reusing the number\n * rather than picking a second one keeps the control's footprint no larger\n * than the placeholder box it already draws attention to.\n */\nconst APPENDER_SIZE_PX = 44;\n\n/**\n * The control's width, in the canvas's content pixels: room for the \"+\" and\n * its words. A narrower container clamps it, and the words then shorten.\n */\nconst APPENDER_WIDTH_PX = 320;\n\n/**\n * What the control says, after its \"+\" icon: both ways a block gets in,\n * pressing here and dropping one here (\"＋ Add a block, or drop one here\").\n */\nconst APPENDER_WORDS = \"Add a block, or drop one here\";\n\n/**\n * A control of the given size centred inside a rectangle, never larger than\n * the rectangle itself.\n *\n * See the module docblock (\"A fixed, centred square\") for why the button is\n * not sized to the measured rectangle, and (\"Never outside its own container\")\n * for why it is clamped to it. Exported for its own tests: it is arithmetic on\n * two rectangles with no DOM in it, so it is the one part of this file's\n * geometry that can be asserted directly.\n *\n * The clamp is per axis because the guarantee is per axis. The stylesheet's\n * `min-height` makes the ordinary container at least as tall as the control,\n * so `Math.min` returns `size` and the result is byte-identical to an\n * unclamped one; there is no `min-width`, so a legitimately narrow empty\n * container — a column a few pixels wide — is the case that needs it.\n */\nexport function centeredControlRect(\n  rect: Rect,\n  controlWidth: number,\n  controlHeight: number\n): Rect {\n  const width = Math.min(controlWidth, rect.width);\n  const height = Math.min(controlHeight, rect.height);\n  return {\n    x: rect.x + (rect.width - width) / 2,\n    y: rect.y + (rect.height - height) / 2,\n    width,\n    height,\n  };\n}\n\n/**\n * Where a container's start is drawn, in the canvas root's coordinates: its\n * whole box, or for an open Question emptied of its answer the part under its\n * title, where the frame's sheet draws the box (`EMPTY_DISCLOSURE_SELECTOR`).\n */\nfunction answerAreaOf(target: Element, root: HTMLElement): Rect {\n  const box = canvasContentRect(target, root);\n  if (!target.matches(EMPTY_DISCLOSURE_SELECTOR)) return box;\n  const summary = target.querySelector(\":scope > summary\");\n  if (summary === null) return box;\n  const title = canvasContentRect(summary, root);\n  const top = title.y + title.height;\n  return {\n    x: box.x,\n    y: top,\n    width: box.width,\n    height: Math.max(0, box.y + box.height - top),\n  };\n}\n\n/**\n * Whether this pass refuses to place a control on this element.\n *\n * The refusals that have an ELEMENT to ask about, gathered into one named\n * question rather than left as conditions inside the measuring loop, so that\n * loop reads as find, decide, record and each refusal keeps its own reason\n * beside its own condition. The one refusal `measure` keeps is the one with no\n * element at all — a container the render does not produce — which this\n * function's signature cannot express and which is stated there instead. Every\n * refusal here is re-decided on each pass: none is a permanent property of a\n * container, only of the render as it currently stands.\n *\n * The ORDER is not arbitrary in one place. Whether the element generates a box\n * and whether the render skips it are the same question answered differently by\n * different engines, so the fragment count is asked first and the skip beside it\n * states what it adds. Everything else here is independent, and asking it in\n * another order would give the same answer.\n *\n * Takes the canvas root because one refusal is about the walk between this\n * element and it, and reading it from the element again would be a second\n * answer to a question `measure` has already settled for this pass.\n */\nfunction declines(target: Element, root: HTMLElement): boolean {\n  /*\n   * The stylesheet's own condition, WHOLE, asked of the element the\n   * stylesheet would ask it of — not a second condition computed here.\n   *\n   * `emptySlotOf` decided WHICH containers this component knows about,\n   * from the document. That is a different population from the one\n   * `builder-chrome.css` draws its 44px box for, and the module docblock\n   * above depends on them being the same: a container the stylesheet\n   * declined has no box, so a control centred in its measured rectangle is\n   * centred in whatever that block happens to render instead. Both halves\n   * of the rule produce that, and both are reachable:\n   *\n   * - the ELEMENT does not qualify. A closed `core/accordion-item` is the\n   *   first-party case — an empty `children` slot inside a root that also\n   *   renders a `<summary>`, so the root is not `:empty` and measures the\n   *   summary's own height.\n   * - the ANCESTORS do not qualify. `Canvas` and this component are both\n   *   exported, so a host can compose them with no builder shell around them,\n   *   and the rule's `.nx-builder-chrome` scope then never applies to any\n   *   container in that canvas — every one of them sizeless, and every control\n   *   drawn on one a focusable button with no area.\n   *\n   * `Element.matches` evaluates the ancestor combinators as well as the\n   * compound, so one call covers the rule rather than the part of it that\n   * happens to be about this element.\n   */\n  if (\n    !target.matches(EMPTY_CONTAINER_SELECTOR) &&\n    // An open Question emptied of its answer: its box is drawn under its\n    // title, and so is its control (`answerAreaOf`).\n    !target.matches(EMPTY_DISCLOSURE_SELECTOR)\n  ) {\n    return true;\n  }\n  /*\n   * The render lays out no box for this element, so there is nothing on\n   * the canvas for a control to be anchored to.\n   *\n   * `getBoundingClientRect` still answers for such an element — with the\n   * zero rectangle — so measuring on would centre a square of no area at\n   * the canvas origin. That is the same focusable, named, invisible button\n   * the refusals around this one exist to prevent, arriving through an\n   * element the render kept and never laid out.\n   *\n   * An ANCESTOR is what puts a container here. Its own `display` cannot:\n   * `builder-chrome.css` gives the very selector matched above\n   * `display: block` at five compound units of specificity, outranking the\n   * three of the per-node rule an author's `display: none` or\n   * `display: contents` compiles into — measured in Chromium, a container\n   * carrying either still computed to `block` and generated its box. A\n   * node BETWEEN this one and the root is under no such rule, because a\n   * node holding a child is not `:empty`, so an author who hides a wrapper\n   * leaves every empty container inside it rendered, matching, and\n   * generating nothing. Where that rule is not in force at all the\n   * element's own keyword reaches this too, and the answer is the same.\n   *\n   * `layoutFragments` rather than a rectangle's area judged here. Whether\n   * an element generates a box is `geometry-dom.ts`'s question and\n   * `SpacingOverlay` already refuses on the same answer; the area is a\n   * consequence of it rather than a second reading, since the rule matched\n   * above draws a dashed border and a 2.75rem minimum height, so an\n   * element that generates a box measures more than nothing.\n   *\n   * Re-decided on the next pass like every refusal beside it: an edit that\n   * un-hides the wrapper changes `document`, and a recompiled sheet that\n   * does the same reaches the `MutationObserver` in `watchCanvasFor`, so\n   * either way something re-measures and the control comes back.\n   */\n  if (layoutFragments(target) === 0) {\n    return true;\n  }\n  /*\n   * The render SKIPPED this element, and the rectangle it reports for it\n   * anyway is not a place on the page.\n   *\n   * The sibling of the refusal above, for the engines that answer that one\n   * differently. A container inside a CLOSED `core/accordion-item` is the\n   * first-party case, and its `children` slot accepts any block, so an\n   * author reaches it by selecting a section in the Layers panel and\n   * inserting a `core/box`. Where the engine removes a closed disclosure's\n   * contents from the rendering, that box generates no fragment and the\n   * check above has already declined it. Where the engine gives the\n   * contents `content-visibility: hidden` instead — the rendering the HTML\n   * specification now describes — it generates ONE, full width and sized as\n   * though the section were open, sitting over the NEXT section's title.\n   * Every question asked before this one passes it: the element exists, it\n   * carries the slots marker, it is `:empty` inside a shell and a canvas, it\n   * is `static`, no ancestor clips it, and it has a fragment. A 44px control\n   * centred in that rectangle lands on a title belonging to another\n   * container, and pressing it reports an id the author did not point at.\n   *\n   * `renderSkips` rather than a computed value read here, because the\n   * element cannot see this about itself: the skip belongs to a box above\n   * it, so the container's own `content-visibility` computes to `visible`\n   * under both renderings. See `geometry-dom.ts` for what the question\n   * covers, which options it deliberately does not pass, and why an engine\n   * that cannot answer it declines nothing.\n   *\n   * Re-decided on the next pass like every refusal beside it, and the\n   * disclosure is the case worth naming: opening it is a user press on the\n   * canvas rather than an edit, so `document` does not change and nothing\n   * re-renders. What hears it is the `MutationObserver` in `watchCanvasFor`\n   * — the browser writes the `open` attribute onto the `<details>`, which is\n   * an attribute record inside the canvas root and outside this overlay's\n   * own layer — and the control appears as soon as that pass runs.\n   */\n  if (renderSkips(target)) {\n    return true;\n  }\n  /*\n   * Positioned against the VIEWPORT rather than against the page this\n   * overlay draws in, which is a container no control can be anchored to.\n   *\n   * `position` is a catalog keyword, so `fixed` and `sticky` are values an\n   * author stores like any other. Both hold the container still while the\n   * canvas content under it travels, so the square measured here slides off\n   * the container on the first scroll and comes to rest over unrelated\n   * content — taking the presses meant for that content with it, since this\n   * button is one of the two pieces of chrome that accept pointer events.\n   *\n   * Nothing corrects the drift, which is why it is refused instead of\n   * re-measured: the shell scrolls a section ABOVE the canvas root and a\n   * scroll event does not bubble, so `watchCanvasFor`'s capture-phase\n   * listener on the root reaches a scroller nested INSIDE the canvas and\n   * never hears that one.\n   *\n   * The same predicate `SpacingOverlay` refuses on, asked here rather than\n   * `position` being read a second time — see `viewportPositioned` in\n   * `geometry-dom.ts` for why that question belongs to the coordinate space\n   * rather than to either overlay.\n   */\n  if (viewportPositioned(target)) {\n    return true;\n  }\n  /*\n   * Excluded outright rather than measured. `clippedByAncestorRect`\n   * answers \"is this element's own rectangle cut by an authored ancestor\n   * between it and the root\" — a clipped container's DOM is cut where\n   * this overlay is not, so a control measured from its un-clipped\n   * rectangle would be drawn over whatever the page actually shows at\n   * that position.\n   *\n   * The RECT question rather than `clippedByAncestor`'s corner-aware one.\n   * That refinement exists for a caller drawing chrome flush against a\n   * block's edges — a spacing band runs the full length of one and does\n   * reach the corners — and this control does not: it is a fixed square\n   * anchored to the container's CENTRE, nowhere near a corner unless the\n   * container itself is barely larger than the control. Measured against\n   * an ordinary full-width child sitting flush inside a rounded, clipping\n   * parent — `core/box` directly inside `core/card`, ordinary enough that\n   * `card.tsx` names it the commonest composition in the library — the\n   * two curves genuinely disagree by a few pixels at each corner, which\n   * `clippedByAncestor` correctly reports and which is irrelevant to\n   * anything drawn away from the corners. Asking the corner-aware\n   * question here would decline the control for exactly the composition\n   * an author reaches for most.\n   */\n  if (clippedByAncestorRect(target, root)) {\n    return true;\n  }\n  return false;\n}\n\nexport interface EmptyContainerAppendersProps {\n  /** The document to scan for containers with nothing in them. */\n  document: BlockDocument;\n  /** What each block type declares as its child regions. */\n  slots: SlotSource;\n  /**\n   * Resolves a block type to its definition, for the control's accessible\n   * name.\n   *\n   * An explicit resolver rather than the global registry: this keeps the\n   * component testable against a fixture that registers nothing, and lets a\n   * production caller hand it the very source the rest of the canvas already\n   * reads from.\n   */\n  blocks: BlockLookup;\n  /**\n   * Raised with the container's node id when its control is pressed, and the\n   * control itself, which the host opens its in-place picker beside.\n   *\n   * This component decides only WHICH containers may be filled and draws the\n   * control; it does not select anything or open an inserter itself. Turning\n   * an id into an opened picker is the caller's wiring, kept out of here so\n   * this component's tests do not need a whole editor to exist.\n   */\n  onAppend: (nodeId: string, control: HTMLElement) => void;\n  /**\n   * Suppress every control, for a host that is mid-gesture.\n   *\n   * Matches `BlockToolbar`: a drag is in the middle of changing the layout\n   * these controls are drawn against, and a press during one would run an\n   * insert against a container that is about to be somewhere else.\n   */\n  hidden?: boolean;\n}\n\n/**\n * One \"+\" per empty container, positioned over the element it would fill.\n */\nexport function EmptyContainerAppenders({\n  document,\n  slots,\n  blocks,\n  onAppend,\n  hidden = false,\n}: EmptyContainerAppendersProps): ReactElement | null {\n  const layer = useRef<HTMLDivElement | null>(null);\n  // The block pointed at on the canvas, whose overlay is drawn while it is.\n  const hovered = useHoveredBlock();\n\n  // WHICH containers get a control, decided from the document alone — see the\n  // module docblock on why this must not wait on geometry to succeed.\n  const containers = useMemo(\n    () => emptyContainersIn(document, slots, blocks),\n    [document, slots, blocks]\n  );\n\n  const [placements, setPlacements] =\n    useState<ReadonlyMap<string, RecordedPlacement>>(NO_PLACEMENTS);\n\n  /*\n   * WHERE to draw each control, read through the same helper\n   * `spacing-overlay.tsx` measures blocks with. `canvasContentRect` already\n   * divides by the canvas root's own painted scale, so a control positioned\n   * through it lands correctly whether the canvas is zoomed or not — this\n   * file performs no scale arithmetic of its own, which is the point.\n   */\n  const measure = useCallback(() => {\n    const element = layer.current;\n    // The canvas the controls are drawn over, and the space they are drawn\n    // in: see `overlaySpaceOf`.\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    const root = space?.root ?? null;\n    if (space === null || root === null) {\n      setPlacements(current => (current.size === 0 ? current : NO_PLACEMENTS));\n      return;\n    }\n    const next = new Map<string, RecordedPlacement>();\n    for (const container of containers) {\n      const target = nodeElement(root, container.id);\n      /*\n       * DECLINED rather than left out. This pass HAS a canvas root and has\n       * just searched it, so an id with no element is a container the render\n       * does not produce — not one it has not produced yet. `PageRenderer`\n       * drops whole subtrees before drawing anything: a node carrying\n       * `visibility.conditions` is omitted from output, and so is one whose\n       * props make it draw nothing. Neither ever reaches the DOM, however long\n       * this waits, so recording nothing would leave a zero-sized button in\n       * the tab order — announced by name, focusable, and pointing at content\n       * that is not on the canvas.\n       *\n       * That leaves absence from the map meaning only \"no pass has run\",\n       * which is the `root === null` return above and the one case where a\n       * control genuinely is waiting to be placed.\n       *\n       * Re-decided on the next pass exactly like every refusal in `declines`:\n       * a container that starts rendering — a condition that begins to hold,\n       * an edit that gives the node markup — gets its control back as soon as\n       * anything re-measures.\n       */\n      if (target === null) {\n        next.set(container.id, DECLINED);\n        continue;\n      }\n      if (declines(target, root)) {\n        next.set(container.id, DECLINED);\n        continue;\n      }\n      // Placed in the chrome's coordinates before the control is centred in\n      // it, so the control keeps its own size at any zoom.\n      const measured = space.place(answerAreaOf(target, root));\n      next.set(container.id, {\n        kind: \"measured\",\n        rect: centeredControlRect(\n          measured,\n          APPENDER_WIDTH_PX,\n          APPENDER_SIZE_PX\n        ),\n        area: measured,\n      });\n    }\n    setPlacements(next);\n  }, [containers]);\n\n  // Measured before paint, matching `BlockToolbar` and `SpacingOverlay`: a\n  // control drawn at a stale rectangle for one frame is worse than one that\n  // appears a frame late.\n  // A zoom, or a page loading into the frame, moves the containers on screen\n  // while nothing in the document changes.\n  const canvasFrame = useCanvasFrame();\n  useLayoutEffect(() => {\n    if (hidden) return;\n    measure();\n    // `document` is not read directly by `measure`, and is listed anyway: an\n    // edit can resize the container this control sits over without changing\n    // which containers are empty, and a re-measure keyed on the container set\n    // alone would keep describing the layout the container had before the\n    // edit.\n  }, [measure, hidden, document, canvasFrame]);\n\n  /*\n   * Re-measure for the changes no render reports, all of them: a resize with\n   * no render behind it (a breakpoint driven by the canvas's own width, a rail\n   * panel opening, a webfont swapping in) and a move with no resize at all (a\n   * scroller between the container and the root, a transition finishing on a\n   * neighbour). Both move a control off the container it names, and the second\n   * kind is invisible to every observer.\n   *\n   * A recompiled site sheet is the third kind and needs the same treatment: a\n   * changed class rule moves an empty container while resizing nothing and\n   * scrolling nothing, so only a mutation record reports it.\n   *\n   * `watchCanvasFor` owns the whole list rather than this file subscribing to\n   * the part it happened to think of — which is exactly how the site-sheet case\n   * came to be missing. The layer is handed over as a READ rather than as an\n   * element, because it does not exist yet on the first pass. It is what\n   * locates the canvas root, and it is also what tells a foreign mutation from\n   * this overlay's own: drawing a control mutates the very subtree being\n   * observed, so without it each measurement would schedule the next.\n   */\n  useEffect(() => {\n    if (hidden || containers.length === 0) return;\n    return watchCanvasFor(() => layer.current, measure);\n  }, [measure, hidden, containers, document, canvasFrame]);\n\n  // `hidden` renders NOTHING, matching how `BlockToolbar` is suppressed during\n  // a drag: a control that were merely invisible would still take a press, and\n  // a press mid-drag would run an insert against a layout that is about to\n  // move. Nothing to offer is the same answer: an empty overlay has no\n  // controls to measure and nothing for a keyboard user to tab into.\n  if (hidden || containers.length === 0) return null;\n\n  return (\n    <div\n      ref={layer}\n      className=\"nx-empty-container-appenders\"\n      // Marked as chrome so a press here resolves to this control rather than\n      // to the canvas background. `canvas.tsx` documents the failure this\n      // prevents: unmarked, a press on this overlay reads as a click on the\n      // page, which CLEARS the selection this very press is about to make.\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n    >\n      {containers.map(container => {\n        const rect = controlRectFor(placements, container.id);\n        // A DECLINED container gets no button at all. A zero-sized one would\n        // still be reachable by keyboard and announced by name, which is a\n        // control an author can focus and never see — see the module docblock.\n        if (rect === null) return null;\n        return (\n          <Fragment key={container.id}>\n            <ContainerOverlay\n              area={areaRectFor(placements, container.id)}\n              pointed={hovered === container.id}\n            />\n            <AppendControl\n              container={container}\n              rect={rect}\n              onAppend={onAppend}\n            />\n          </Fragment>\n        );\n      })}\n    </div>\n  );\n}\n\n/**\n * The overlay over an empty container while it is pointed at, on the canvas\n * or at its control, or its control has keyboard focus: a solid outline in\n * the selection colour and a light tint of it, drawn as chrome over the\n * block so the block's own background is never touched. Drawn before the\n * control, so the stylesheet can show it for the control's hover and focus.\n */\nfunction ContainerOverlay({\n  area,\n  pointed,\n}: {\n  readonly area: Rect | null;\n  readonly pointed: boolean;\n}): ReactElement | null {\n  if (area === null) return null;\n  return (\n    <span\n      className=\"nx-empty-container-appenders__area\"\n      aria-hidden=\"true\"\n      data-pointed={pointed ? \"\" : undefined}\n      style={{\n        left: area.x,\n        top: area.y,\n        width: area.width,\n        height: area.height,\n      }}\n    />\n  );\n}\n\n/** One container's \"+\" and its words, centred in the container. */\nfunction AppendControl({\n  container,\n  rect,\n  onAppend,\n}: {\n  readonly container: EmptyContainer;\n  readonly rect: Rect;\n  readonly onAppend: EmptyContainerAppendersProps[\"onAppend\"];\n}): ReactElement {\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-empty-container-appenders__button\"\n      style={{\n        left: rect.x,\n        top: rect.y,\n        width: rect.width,\n        height: rect.height,\n      }}\n      // The block's own name, so a control an author meets is one they can\n      // find by searching for the thing it fills rather than for a generic\n      // \"add block\" that says nothing about which container. Its name starts\n      // with the words it shows, so a voice command speaking them reaches it\n      // (WCAG 2.5.3), then says which container.\n      aria-label={`${APPENDER_WORDS}, in ${container.label}`}\n      title={`Add a block inside ${container.label}`}\n      onClick={event => onAppend(container.id, event.currentTarget)}\n    >\n      {/* On a plate of the editor's own surface: the box is drawn over the\n          SITE's ground, which can be any colour, and the editor's text colour\n          holds its contrast only against the editor's own surface. */}\n      <span className=\"nx-empty-container-appenders__plate\">\n        {/* The \"＋\" of the words as decided, drawn as the icon every \"+\" on\n            the canvas is, and kept whole when a narrow box shortens the\n            words. */}\n        <Plus size={16} aria-hidden=\"true\" />\n        <span className=\"nx-empty-container-appenders__words\">\n          {APPENDER_WORDS}\n        </span>\n      </span>\n    </button>\n  );\n}\n","/**\n * What a Gallery's empty state and its file drops decide without drawing\n * anything: which canvas boxes are galleries waiting for pictures, which\n * files a drop or the chooser handed over are pictures, and where a file\n * held over the canvas lands.\n *\n * The Image's own empty state (`image-states-model.ts`) answers the same\n * questions for one picture; these answer them for several, from its\n * answers: a file is a picture by the same check, and refused in the same\n * words.\n *\n * @module canvas/gallery-states-model\n */\n\nimport {\n  findNode,\n  walkNodes,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\nimport { INSTANCE_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport {\n  galleryPictureOf,\n  isGallery,\n} from \"../inspector/content/gallery-pictures\";\n\nimport { nodeElement } from \"./canvas-addressing\";\nimport { chosenFile } from \"./image-states-model\";\n\n/** The words a gallery's empty state uses, in one place. */\nexport const GALLERY_STATE_WORDS = {\n  title: \"Add images\",\n  drop: \"or drop files here\",\n  libraryTitle: \"Choose images\",\n  dropToAdd: \"Drop to add the images\",\n} as const;\n\n/** One empty gallery on the canvas, waiting for pictures. */\nexport interface EmptyGalleryBox {\n  readonly nodeId: string;\n  readonly element: Element;\n}\n\n/**\n * The galleries holding no pictures that this page owns and the canvas\n * draws, in document order. One inside a placed component belongs to the\n * component, which its own editor fills.\n */\nexport function emptyGalleryBoxes(\n  root: HTMLElement,\n  document: BlockDocument\n): EmptyGalleryBox[] {\n  const found: EmptyGalleryBox[] = [];\n  walkNodes(document.nodes, node => {\n    if (!isGallery(node) || (node.slots?.children?.length ?? 0) > 0) return;\n    const element = nodeElement(root, node.id);\n    if (element === null || element.hasAttribute(INSTANCE_ATTRIBUTE)) return;\n    found.push({ nodeId: node.id, element });\n  });\n  return found;\n}\n\n/**\n * The pictures among the files a drop or the chooser handed over, in the\n * order given, and whether any was refused for not being one: each judged\n * as an Image judges its one file.\n */\nexport function chosenPictures(files: FileList | readonly File[] | null): {\n  readonly pictures: readonly File[];\n  readonly refused: boolean;\n} {\n  const all = files === null ? [] : Array.from(files);\n  const pictures: File[] = [];\n  for (const file of all) {\n    if (chosenFile([file])?.image === true) pictures.push(file);\n  }\n  return { pictures, refused: pictures.length < all.length };\n}\n\n/** How many files a drag carries, as far as the browser says mid-drag. */\nexport function filesCarried(transfer: DataTransfer | null): number {\n  if (transfer === null) return 0;\n  // Mid-drag the files are not readable yet, only their entries.\n  const items = transfer.items as DataTransferItemList | undefined;\n  return items === undefined ? transfer.files.length : items.length;\n}\n\n/** Where a file held over a block lands: an Image, or a gallery. */\nexport type FileLanding =\n  | { readonly kind: \"image\"; readonly nodeId: string }\n  | { readonly kind: \"gallery\"; readonly nodeId: string };\n\n/**\n * Where files held over the block `nodeId` land: a gallery takes them as\n * pictures of its own, and so does a gallery's picture while more than one\n * file is held, since several files cannot replace one picture. One file\n * over any other Image replaces its picture. `null` where nothing takes\n * them.\n */\nexport function fileLanding(\n  document: BlockDocument,\n  nodeId: string,\n  count: number,\n  accepts: {\n    readonly image: (nodeId: string) => boolean;\n    readonly gallery: (nodeId: string) => boolean;\n  }\n): FileLanding | null {\n  const node = findNode(document.nodes, nodeId);\n  if (isGallery(node)) {\n    return accepts.gallery(nodeId) ? { kind: \"gallery\", nodeId } : null;\n  }\n  const inGallery = galleryPictureOf(document, nodeId)?.galleryId;\n  if (inGallery !== undefined && count > 1) {\n    return accepts.gallery(inGallery)\n      ? { kind: \"gallery\", nodeId: inGallery }\n      : null;\n  }\n  return accepts.image(nodeId) ? { kind: \"image\", nodeId } : null;\n}\n","\"use client\";\n\n/**\n * An Image's empty state on the canvas: what an author sees, and does, where\n * an Image has no picture yet.\n *\n * The Image block draws a box where it has no picture, only where an author\n * is looking, in the block's own classes, so the box takes the size and the\n * proportion the block has: 16:9 and the column's width until it is set.\n * This draws the editor's part over each box, in the editor's own colours:\n * \"Add an image\" with Upload, Media library and Link, and \"or drop a file\n * here\". A library file the library no longer has says so, with Replace.\n *\n * - **Upload** and a **dropped file** go through the host's media library\n *   upload (`uploadMedia`), with its checks, the progress drawn on the\n *   block. A file that is not a picture is refused here, before anything is\n *   sent: \"That file isn't an image\", and nothing changes. A file dropped\n *   on an Image that has a picture replaces it the same way.\n * - **Media library** opens the host's picker (`MediaPicker`).\n * - **Link** takes an address, checked by the rule the block draws by and\n *   then loaded where the page is drawn; only one that loads as a picture is\n *   stored. One that does not says \"This link didn't load an image\", with\n *   \"Try another link\", and the Image stays empty.\n *\n * Each choice writes through the editor's one write path, as the inspector's\n * Image fields do, so it is one step to undo, and it is refused where a lock\n * holds the picture. An Image inside a placed component, in the Layout around\n * the page, or bound to a field is not offered: its picture is set elsewhere.\n *\n * A Gallery holding no pictures is drawn over the same way: \"Add images\"\n * with Upload and Media library, and \"or drop files here\", in place of the\n * \"+\" an empty container draws, so no empty Image is ever made to be filled.\n * Upload takes several files, Media library picks several, and files\n * dropped on a gallery, empty or not, are uploaded and added after its\n * pictures. Each way adds one Image per picture, in the order chosen or\n * dropped, as ONE step to undo (`addPicturesTo`). Several files held over a\n * gallery's picture go to the gallery; one replaces that picture.\n *\n * Drawn like `EmptyContainerAppenders`, in the overlay over the canvas, at\n * each box's measured rectangle; see that module for why the rectangles are\n * read in the canvas's content coordinates and kept current by\n * `watchCanvasFor`. Each plate covers only the part of its box the page\n * shows (`visiblePartOf`), so a clipping ancestor's hidden part is never\n * covered.\n *\n * @module canvas/image-states\n */\n\nimport {\n  INSTANCE_ATTRIBUTE,\n  NODE_ID_ATTRIBUTE,\n  type RemotePatternInput,\n} from \"@nextlyhq/blocks-react\";\nimport { Button } from \"@nextlyhq/ui\";\nimport { ImageOff, ImagePlus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Rect } from \"../geometry\";\nimport type {\n  ContentServices,\n  PickedMedia,\n} from \"../inspector/content/content-services\";\nimport {\n  addPicturesTo,\n  picturesHeld,\n} from \"../inspector/content/gallery-pictures\";\nimport { lockViewOf, propIsWritable } from \"../inspector/inspector\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { nodeAddressOf, nodeElement } from \"./canvas-addressing\";\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport { isElement } from \"./dom-kind\";\nimport {\n  chosenPictures,\n  emptyGalleryBoxes,\n  fileLanding,\n  filesCarried,\n  GALLERY_STATE_WORDS,\n} from \"./gallery-states-model\";\nimport {\n  layoutFragments,\n  overlaySpaceOf,\n  renderSkips,\n  visiblePartOf,\n} from \"./geometry-dom\";\nimport {\n  carriesFiles,\n  chosenFile,\n  emptyImageBoxes,\n  failureWords,\n  IMAGE_STATE_WORDS as WORDS,\n  imageNodeOf,\n  linkAddress,\n  loadsAsImage,\n  pictureOp,\n  takesPicture,\n  type ImageEmptyReason,\n} from \"./image-states-model\";\nimport { selectionModeFor, type SelectionMode } from \"./selection\";\n\nexport interface ImageStatesProps {\n  /** The editor the choices write through. */\n  readonly editor: EditorState;\n  /**\n   * The host's media library: its upload and its picker. A choice whose\n   * service is absent is not offered.\n   */\n  readonly services?: Pick<ContentServices, \"MediaPicker\" | \"uploadMedia\">;\n  /** The hosts this site loads pictures from, as the canvas draws them. */\n  readonly remotePatterns?: readonly RemotePatternInput[];\n  /**\n   * A block is being dragged. The boxes stay drawn, so the page keeps its\n   * shape, and take no presses, so the drag reaches the canvas beneath.\n   */\n  readonly dragging?: boolean;\n}\n\n/** What an Image is in the middle of, here. */\ntype Activity =\n  | {\n      readonly kind: \"link\";\n      readonly typed: string;\n      readonly checking: boolean;\n    }\n  | { readonly kind: \"bad-link\"; readonly typed: string }\n  | {\n      readonly kind: \"uploading\";\n      readonly name: string;\n      readonly percent: number;\n    }\n  /** Stored, and waiting for the canvas to draw the picture. */\n  | { readonly kind: \"placing\" }\n  /** A short note: a file refused, or an upload that did not finish. */\n  | { readonly kind: \"note\"; readonly words: string };\n\n/** Where one plate is drawn, and for which Image. */\ninterface Plate {\n  readonly key: string;\n  readonly nodeId: string;\n  /**\n   * `filled`: a block with a picture, or a gallery with pictures, drawn\n   * over only while it is busy; `gallery`: a gallery waiting for pictures.\n   */\n  readonly reason: ImageEmptyReason | \"filled\" | \"gallery\";\n  readonly rect: Rect;\n}\n\n/** What on a plate does something of its own when pressed. */\nconst CONTROLS = \"button, input, label, select, textarea, a\";\n\n/** How long a note stays before the Image's choices come back. */\nconst NOTE_MS = 6000;\n\n/** How long a stored picture is waited for before the box is offered again. */\nconst PLACING_MS = 10_000;\n\nconst NO_ACTIVITY: ReadonlyMap<string, Activity> = new Map();\n\n/** The Image's choices, and its notes, drawn over its empty box. */\nexport function ImageStates({\n  editor,\n  services,\n  remotePatterns,\n  dragging = false,\n}: ImageStatesProps): React.JSX.Element {\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const [plates, setPlates] = React.useState<readonly Plate[]>([]);\n  const [activity, setActivity] =\n    React.useState<ReadonlyMap<string, Activity>>(NO_ACTIVITY);\n  const [dropTarget, setDropTarget] = React.useState<string | null>(null);\n  // The block the library is open for, and whether it takes several picks.\n  const [picking, setPicking] = React.useState<{\n    readonly nodeId: string;\n    readonly many: boolean;\n  } | null>(null);\n\n  // Read in callbacks that outlive the render that made them: an upload\n  // finishes against the document as it is then, not as it was.\n  const latest = React.useRef({ editor, activity, dropTarget });\n  latest.current = { editor, activity, dropTarget };\n\n  const upload = services?.uploadMedia;\n  const Picker = services?.MediaPicker;\n\n  const setFor = React.useCallback(\n    (nodeId: string, next: Activity | undefined) => {\n      setActivity(current => {\n        const map = new Map(current);\n        if (next === undefined) map.delete(nodeId);\n        else map.set(nodeId, next);\n        return map;\n      });\n    },\n    []\n  );\n\n  /*\n   * Each Image's latest choice, by a number every choice moves on. An upload\n   * or a link check answers later, and only the choice it was made for may\n   * act on its answer: one the author has since cancelled, or replaced with\n   * another (a library pick, a new link, another file), must not store\n   * anything or bring its state back.\n   */\n  const choices = React.useRef(new Map<string, number>());\n  const choose = React.useCallback((nodeId: string): (() => boolean) => {\n    const ticket = (choices.current.get(nodeId) ?? 0) + 1;\n    choices.current.set(nodeId, ticket);\n    return () => choices.current.get(nodeId) === ticket;\n  }, []);\n\n  // Notes and stored pictures clear themselves after a while.\n  React.useEffect(() => {\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    for (const [nodeId, now] of activity) {\n      if (now.kind !== \"note\" && now.kind !== \"placing\") continue;\n      timers.push(\n        setTimeout(\n          () =>\n            setActivity(current => {\n              if (current.get(nodeId) !== now) return current;\n              const map = new Map(current);\n              map.delete(nodeId);\n              return map;\n            }),\n          now.kind === \"note\" ? NOTE_MS : PLACING_MS\n        )\n      );\n    }\n    return () => timers.forEach(clearTimeout);\n  }, [activity]);\n\n  /** Whether the Image takes a picture from here, now. */\n  const writable = React.useCallback((nodeId: string): boolean => {\n    const { editor: now } = latest.current;\n    const node = imageNodeOf(now.document, nodeId);\n    if (node === undefined || !takesPicture(node)) return false;\n    const view = lockViewOf(now);\n    return (\n      propIsWritable(now.document, nodeId, \"mediaId\", view) &&\n      propIsWritable(now.document, nodeId, \"src\", view)\n    );\n  }, []);\n\n  /** Store a picture on the Image, through the editor's write path. */\n  const place = React.useCallback(\n    (\n      nodeId: string,\n      picture: { readonly mediaId: string } | { readonly address: string }\n    ): boolean => {\n      const { editor: now } = latest.current;\n      if (!writable(nodeId)) return false;\n      const op = pictureOp(now.document, nodeId, picture);\n      return op !== null && now.apply(op) !== null;\n    },\n    [writable]\n  );\n\n  /** Take the first file a drop or the chooser handed over. */\n  const take = React.useCallback(\n    (nodeId: string, files: FileList | readonly File[] | null) => {\n      const chosen = chosenFile(files);\n      if (chosen === undefined || upload === undefined) return;\n      const current = choose(nodeId);\n      if (!chosen.image) {\n        setFor(nodeId, { kind: \"note\", words: WORDS.notImage });\n        return;\n      }\n      if (!writable(nodeId)) return;\n      const { file } = chosen;\n      setFor(nodeId, { kind: \"uploading\", name: file.name, percent: 0 });\n      upload(file, percent =>\n        setActivity(shown => {\n          const now = shown.get(nodeId);\n          if (!current() || now?.kind !== \"uploading\") return shown;\n          const map = new Map(shown);\n          map.set(nodeId, {\n            ...now,\n            percent: Math.max(0, Math.min(100, percent)),\n          });\n          return map;\n        })\n      ).then(\n        (media: PickedMedia) => {\n          if (!current()) return;\n          setFor(\n            nodeId,\n            place(nodeId, { mediaId: media.id })\n              ? { kind: \"placing\" }\n              : undefined\n          );\n        },\n        (error: unknown) => {\n          if (!current()) return;\n          setFor(nodeId, {\n            kind: \"note\",\n            words: failureWords(error),\n          });\n        }\n      );\n    },\n    [choose, place, setFor, upload, writable]\n  );\n\n  /** Whether a gallery takes pictures from here, now: no lock holds them. */\n  const galleryWritable = React.useCallback(\n    (nodeId: string): boolean => !picturesHeld(latest.current.editor, nodeId),\n    []\n  );\n\n  /**\n   * Add every picture among the files to a gallery: each uploaded, with\n   * their progress together on the gallery, then all that uploaded added\n   * at once, in the order given, as one step. A file that is not a picture\n   * is left out and said, in the Image's words; an upload that did not\n   * finish is said, and the rest are still added. A later drop does not\n   * cancel an earlier one: each adds its own.\n   */\n  const takeMany = React.useCallback(\n    (nodeId: string, files: FileList | readonly File[] | null) => {\n      const { pictures, refused } = chosenPictures(files);\n      if (upload === undefined || (pictures.length === 0 && !refused)) return;\n      const current = choose(nodeId);\n      if (pictures.length === 0) {\n        setFor(nodeId, { kind: \"note\", words: WORDS.notImage });\n        return;\n      }\n      if (!galleryWritable(nodeId)) return;\n      const name =\n        pictures.length === 1\n          ? (pictures[0]?.name ?? \"\")\n          : `${String(pictures.length)} images`;\n      const percents = pictures.map(() => 0);\n      setFor(nodeId, { kind: \"uploading\", name, percent: 0 });\n      void Promise.allSettled(\n        pictures.map((file, index) =>\n          upload(file, percent => {\n            percents[index] = Math.max(0, Math.min(100, percent));\n            const together = Math.round(\n              percents.reduce((sum, each) => sum + each, 0) / percents.length\n            );\n            if (current())\n              setFor(nodeId, { kind: \"uploading\", name, percent: together });\n          })\n        )\n      ).then(results => {\n        const ids = results.flatMap(result =>\n          result.status === \"fulfilled\" ? [result.value.id] : []\n        );\n        const failed = results.find(\n          (result): result is PromiseRejectedResult =>\n            result.status === \"rejected\"\n        );\n        const added =\n          ids.length > 0 && addPicturesTo(latest.current.editor, nodeId, ids);\n        if (!current()) return;\n        if (failed !== undefined) {\n          setFor(nodeId, { kind: \"note\", words: failureWords(failed.reason) });\n        } else if (refused) {\n          setFor(nodeId, { kind: \"note\", words: WORDS.notImage });\n        } else {\n          setFor(nodeId, added ? { kind: \"placing\" } : undefined);\n        }\n      });\n    },\n    [choose, galleryWritable, setFor, upload]\n  );\n\n  /**\n   * Where files handed over for a block land, the one decision every drop\n   * and chooser asks (`fileLanding`): a gallery's, or several over one of\n   * its pictures, go to the gallery; one over an Image fills or replaces it.\n   */\n  const landingOf = React.useCallback(\n    (nodeId: string, count: number) =>\n      fileLanding(latest.current.editor.document, nodeId, count, {\n        image: writable,\n        gallery: galleryWritable,\n      }),\n    [galleryWritable, writable]\n  );\n\n  /** Take files handed over for a block, where `landingOf` sends them. */\n  const takeFor = React.useCallback(\n    (nodeId: string, files: FileList | readonly File[] | null) => {\n      const count = files === null ? 0 : files.length;\n      const landing = landingOf(nodeId, count);\n      if (landing === null) return;\n      if (landing.kind === \"gallery\") takeMany(landing.nodeId, files);\n      else take(landing.nodeId, files);\n    },\n    [landingOf, take, takeMany]\n  );\n\n  /** Check a typed link, and store it once it loads as a picture. */\n  const tryLink = React.useCallback(\n    (nodeId: string, typed: string) => {\n      const current = choose(nodeId);\n      const address = linkAddress(typed, remotePatterns);\n      const root = canvasRootOf(layer.current);\n      if (address === undefined || root === null) {\n        setFor(nodeId, { kind: \"bad-link\", typed });\n        return;\n      }\n      setFor(nodeId, { kind: \"link\", typed, checking: true });\n      void loadsAsImage(address, root.ownerDocument).then(loaded => {\n        if (!current()) return;\n        if (!loaded) {\n          setFor(nodeId, { kind: \"bad-link\", typed });\n          return;\n        }\n        setFor(\n          nodeId,\n          place(nodeId, { address }) ? { kind: \"placing\" } : undefined\n        );\n      });\n    },\n    [choose, place, remotePatterns, setFor]\n  );\n\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) {\n      setPlates(current => (current.length === 0 ? current : []));\n      return;\n    }\n    const { editor: now, activity: busy, dropTarget: over } = latest.current;\n    const empty = [\n      ...emptyPlates(space, now.document),\n      ...galleryPlates(space, now.document),\n    ];\n    const drawn = new Set(empty.map(plate => plate.nodeId));\n    setPlates([...empty, ...busyPlates(space, drawn, busy, over)]);\n    // A picture stored from here has been drawn once its box is gone.\n    for (const [nodeId, now2] of busy) {\n      if (now2.kind === \"placing\" && !drawn.has(nodeId))\n        setFor(nodeId, undefined);\n    }\n  }, [setFor]);\n\n  const canvasFrame = useCanvasFrame();\n  React.useLayoutEffect(() => {\n    measure();\n  }, [measure, editor.document, activity, dropTarget, canvasFrame]);\n  React.useEffect(\n    () => watchCanvasFor(() => layer.current, measure),\n    [measure, editor.document, canvasFrame]\n  );\n\n  // Files held over a block inside the page are taken by the page: listened\n  // for there. Over an Image with a picture, one file replaces it; over a\n  // gallery, or several over a gallery's picture, they are added to the\n  // gallery (`fileLanding`). Over an empty box, the plate drawn over it\n  // takes them instead.\n  React.useEffect(() => {\n    const root = canvasRootOf(layer.current);\n    if (root === null || upload === undefined) return;\n    const landingUnder = (\n      target: EventTarget | null,\n      count: number\n    ): ReturnType<typeof fileLanding> => {\n      if (!isElement(target)) return null;\n      const owner = target.closest(`[${NODE_ID_ATTRIBUTE}]`);\n      // A picture inside a placed component is the component's.\n      if (owner === null || owner.hasAttribute(INSTANCE_ATTRIBUTE)) return null;\n      const nodeId = nodeAddressOf(owner);\n      if (nodeId === null) return null;\n      return landingOf(nodeId, count);\n    };\n    const over = (event: DragEvent): void => {\n      if (!carriesFiles(event.dataTransfer)) return;\n      const landing = landingUnder(\n        event.target,\n        filesCarried(event.dataTransfer)\n      );\n      const nodeId = landing?.nodeId ?? null;\n      if (latest.current.dropTarget !== nodeId) setDropTarget(nodeId);\n      if (nodeId === null) return;\n      event.preventDefault();\n      if (event.dataTransfer !== null) event.dataTransfer.dropEffect = \"copy\";\n    };\n    const drop = (event: DragEvent): void => {\n      const files = event.dataTransfer?.files ?? null;\n      const landing = carriesFiles(event.dataTransfer)\n        ? landingUnder(event.target, files?.length ?? 0)\n        : null;\n      setDropTarget(null);\n      if (landing === null) return;\n      event.preventDefault();\n      takeFor(landing.nodeId, files);\n    };\n    const away = (event: DragEvent): void => {\n      const next = event.relatedTarget;\n      if (isElement(next) && root.contains(next)) return;\n      setDropTarget(null);\n    };\n    const ended = (): void => setDropTarget(null);\n    root.addEventListener(\"dragover\", over);\n    root.addEventListener(\"drop\", drop);\n    root.addEventListener(\"dragleave\", away);\n    root.ownerDocument.addEventListener(\"dragend\", ended);\n    return () => {\n      root.removeEventListener(\"dragover\", over);\n      root.removeEventListener(\"drop\", drop);\n      root.removeEventListener(\"dragleave\", away);\n      root.ownerDocument.removeEventListener(\"dragend\", ended);\n    };\n  }, [takeFor, landingOf, upload, canvasFrame, editor.document]);\n\n  const selectImage = (nodeId: string, mode?: SelectionMode): void => {\n    if (mode === undefined) editor.select(nodeId);\n    else editor.select(nodeId, mode);\n  };\n\n  return (\n    <div\n      ref={layer}\n      className=\"nx-image-states\"\n      data-dragging={dragging ? \"\" : undefined}\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n    >\n      {plates.map(plate => (\n        <ImagePlate\n          key={plate.key}\n          plate={plate}\n          activity={activity.get(plate.nodeId)}\n          held={dropTarget === plate.nodeId}\n          // A gallery takes pictures where no lock holds them; an Image,\n          // where its picture may be set.\n          writable={\n            isGalleryPlate(plate, editor.document)\n              ? galleryWritable(plate.nodeId)\n              : writable(plate.nodeId)\n          }\n          heldWords={\n            isGalleryPlate(plate, editor.document)\n              ? GALLERY_STATE_WORDS.dropToAdd\n              : WORDS.dropToReplace\n          }\n          dragging={dragging}\n          canUpload={upload !== undefined}\n          canPick={Picker !== undefined}\n          onSelect={mode => selectImage(plate.nodeId, mode)}\n          // Routed as a drop on the page is: several files on a gallery's\n          // picture, empty or not, go to the gallery.\n          onFiles={files => takeFor(plate.nodeId, files)}\n          onHeld={held =>\n            setDropTarget(current =>\n              held ? plate.nodeId : current === plate.nodeId ? null : current\n            )\n          }\n          onLibrary={() => {\n            selectImage(plate.nodeId);\n            setPicking({\n              nodeId: plate.nodeId,\n              many: plate.reason === \"gallery\",\n            });\n          }}\n          onLink={typed => {\n            selectImage(plate.nodeId);\n            setFor(plate.nodeId, { kind: \"link\", typed, checking: false });\n          }}\n          onTypeLink={typed =>\n            setFor(plate.nodeId, { kind: \"link\", typed, checking: false })\n          }\n          onSubmitLink={typed => tryLink(plate.nodeId, typed)}\n          onCancel={() => {\n            // A link still being checked is let go with it.\n            choose(plate.nodeId);\n            setFor(plate.nodeId, undefined);\n          }}\n        />\n      ))}\n      {/*\n        Beside the plates, not inside one: the picker's own presses would\n        otherwise reach a plate's, which selects the block under it.\n      */}\n      {Picker === undefined || picking === null ? null : (\n        <Picker\n          open\n          onOpenChange={open => {\n            if (!open) setPicking(null);\n          }}\n          // A gallery picks several, each one a picture to add.\n          {...(picking.many ? { mode: \"multi\" as const } : {})}\n          title={\n            picking.many ? GALLERY_STATE_WORDS.libraryTitle : WORDS.libraryTitle\n          }\n          accept=\"image/*\"\n          initialSelectedIds={new Set()}\n          onSelect={media => {\n            const { nodeId, many } = picking;\n            setPicking(null);\n            if (many) {\n              addPicturesTo(\n                latest.current.editor,\n                nodeId,\n                media.map(each => each.id)\n              );\n              return;\n            }\n            const first = media[0];\n            if (first === undefined) return;\n            // The pick wins over an upload or a link check still out.\n            choose(nodeId);\n            if (place(nodeId, { mediaId: first.id })) {\n              setFor(nodeId, { kind: \"placing\" });\n            }\n          }}\n        />\n      )}\n    </div>\n  );\n}\n\n/** The canvas root the layer is drawn over, or `null` when it is over none. */\nfunction canvasRootOf(layer: HTMLElement | null): HTMLElement | null {\n  if (layer === null) return null;\n  return overlaySpaceOf(layer, CANVAS_ROOT_CLASS)?.root ?? null;\n}\n\n/** The canvas the plates are drawn over, and how a rectangle is placed there. */\nexport type Space = NonNullable<ReturnType<typeof overlaySpaceOf>>;\n\n/**\n * Whether the canvas draws an element at all. A box the render keeps but lays\n * out nowhere (inside a closed accordion item, say) has no place on screen,\n * so a plate drawn for it would sit over whatever follows, or be a control of\n * no size that is still in the tab order. Asked as `EmptyContainerAppenders`\n * asks it.\n */\nfunction isDrawn(element: Element): boolean {\n  return layoutFragments(element) > 0 && !renderSkips(element);\n}\n\n/**\n * Where a plate goes for an element: the part of it the page shows, cut to\n * every ancestor that clips it (a fixed-height box with `overflow: hidden`, a\n * scroller it has scrolled out of), so a plate drawn over the page never\n * covers, or takes the clicks of, what that ancestor hides it under. `null`\n * when the page shows none of it, lays it out nowhere, or clips it in a way\n * that cannot be described.\n */\nexport function shownRectOf(element: Element, space: Space): Rect | null {\n  if (!isDrawn(element)) return null;\n  const visible = visiblePartOf(element, space.root);\n  if (visible === null || visible === \"hidden\") return null;\n  return space.place(visible);\n}\n\n/** A plate over each Image box this page owns that waits for a picture. */\nfunction emptyPlates(space: Space, document: EditorState[\"document\"]): Plate[] {\n  const plates: Plate[] = [];\n  emptyImageBoxes(space.root, document).forEach((box, index) => {\n    const rect = shownRectOf(box.element, space);\n    if (rect === null) return;\n    plates.push({\n      key: `${box.nodeId}:${String(index)}`,\n      nodeId: box.nodeId,\n      reason: box.reason,\n      rect,\n    });\n  });\n  return plates;\n}\n\n/** A plate over each gallery this page owns that waits for pictures. */\nfunction galleryPlates(\n  space: Space,\n  document: EditorState[\"document\"]\n): Plate[] {\n  const plates: Plate[] = [];\n  for (const box of emptyGalleryBoxes(space.root, document)) {\n    const rect = shownRectOf(box.element, space);\n    if (rect === null) continue;\n    plates.push({\n      key: `${box.nodeId}:gallery`,\n      nodeId: box.nodeId,\n      reason: \"gallery\",\n      rect,\n    });\n  }\n  return plates;\n}\n\n/**\n * Whether a plate is a gallery's: one waiting for pictures, or one with\n * pictures something is happening to.\n */\nfunction isGalleryPlate(\n  plate: Plate,\n  document: EditorState[\"document\"]\n): boolean {\n  return (\n    plate.reason === \"gallery\" ||\n    (plate.reason === \"filled\" &&\n      imageNodeOf(document, plate.nodeId) === undefined)\n  );\n}\n\n/**\n * A plate over each Image with a picture that something is happening to: a\n * file held over it, an upload, a note. One whose stored picture is drawn now\n * has nothing more to say.\n */\nfunction busyPlates(\n  space: Space,\n  drawn: ReadonlySet<string>,\n  busy: ReadonlyMap<string, Activity>,\n  over: string | null\n): Plate[] {\n  const ids = new Set<string>();\n  for (const [nodeId, now] of busy) {\n    if (now.kind !== \"placing\") ids.add(nodeId);\n  }\n  if (over !== null) ids.add(over);\n  const plates: Plate[] = [];\n  for (const nodeId of ids) {\n    if (drawn.has(nodeId)) continue;\n    const element = nodeElement(space.root, nodeId);\n    const rect = element === null ? null : shownRectOf(element, space);\n    if (rect === null) continue;\n    plates.push({ key: `${nodeId}:filled`, nodeId, reason: \"filled\", rect });\n  }\n  return plates;\n}\n\ninterface ImagePlateProps {\n  readonly plate: Plate;\n  readonly activity: Activity | undefined;\n  /** A file is held over it. */\n  readonly held: boolean;\n  /** What a file held over a filled plate does, said while it is held. */\n  readonly heldWords: string;\n  readonly writable: boolean;\n  readonly dragging: boolean;\n  readonly canUpload: boolean;\n  readonly canPick: boolean;\n  /** Select the Image, as a click on the canvas would: Shift extends, Ctrl or Cmd toggles. */\n  readonly onSelect: (mode: SelectionMode) => void;\n  readonly onFiles: (files: FileList | readonly File[] | null) => void;\n  readonly onHeld: (held: boolean) => void;\n  readonly onLibrary: () => void;\n  readonly onLink: (typed: string) => void;\n  readonly onTypeLink: (typed: string) => void;\n  readonly onSubmitLink: (typed: string) => void;\n  readonly onCancel: () => void;\n}\n\n/** One Image's plate: its box, in the editor's colours, and what it offers. */\nfunction ImagePlate(props: ImagePlateProps): React.JSX.Element {\n  const { plate, activity, held, writable, dragging, canUpload, onSelect } =\n    props;\n  const takesFiles = canUpload && writable && !dragging;\n  const { x, y, width, height } = plate.rect;\n  return (\n    <div\n      className=\"nx-image-state\"\n      data-image-state={plate.reason}\n      data-image-activity={activity?.kind}\n      data-held={held ? \"\" : undefined}\n      role=\"group\"\n      aria-label={\n        plate.reason === \"missing\"\n          ? WORDS.missing\n          : plate.reason === \"gallery\"\n            ? \"Gallery\"\n            : \"Image\"\n      }\n      style={{ left: x, top: y, width, height }}\n      onClick={event => {\n        // Anywhere on the box selects the Image, its words and its icon\n        // included; its controls do their own thing.\n        if (isElement(event.target) && event.target.closest(CONTROLS) !== null)\n          return;\n        onSelect(selectionModeFor(event));\n      }}\n      onContextMenu={event => event.stopPropagation()}\n      onDragOver={event => {\n        if (!takesFiles || !carriesFiles(event.dataTransfer)) return;\n        event.preventDefault();\n        event.dataTransfer.dropEffect = \"copy\";\n        if (!held) props.onHeld(true);\n      }}\n      onDragLeave={event => {\n        const next = event.relatedTarget;\n        if (isElement(next) && event.currentTarget.contains(next)) return;\n        props.onHeld(false);\n      }}\n      onDrop={event => {\n        props.onHeld(false);\n        if (!takesFiles || !carriesFiles(event.dataTransfer)) return;\n        event.preventDefault();\n        props.onFiles(event.dataTransfer.files);\n      }}\n    >\n      <PlateBody {...props} takesFiles={takesFiles} />\n    </div>\n  );\n}\n\n/** What the plate says and offers, for what its Image is doing. */\nfunction PlateBody(\n  props: ImagePlateProps & { readonly takesFiles: boolean }\n): React.JSX.Element | null {\n  const { plate, activity } = props;\n  switch (activity?.kind) {\n    case \"uploading\":\n      return <Progress percent={activity.percent} name={activity.name} />;\n    case \"placing\":\n      return <Progress percent={100} name=\"\" />;\n    case \"link\":\n      return <LinkForm {...props} activity={activity} />;\n    case \"bad-link\":\n      return <BadLink {...props} typed={activity.typed} />;\n    default:\n      break;\n  }\n  const note = activity?.kind === \"note\" ? activity.words : undefined;\n  if (plate.reason === \"filled\") {\n    return (\n      <OverPicture note={note} held={props.held} words={props.heldWords} />\n    );\n  }\n  if (plate.reason === \"gallery\") {\n    return <GalleryChoices {...props} note={note} />;\n  }\n  return (\n    <Choices {...props} note={note} missing={plate.reason === \"missing\"} />\n  );\n}\n\n/** An upload's progress, drawn on the block. */\nfunction Progress({\n  percent,\n  name,\n}: {\n  readonly percent: number;\n  readonly name: string;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-image-state__progress\" role=\"status\">\n      <span className=\"nx-image-state__words\">\n        {WORDS.uploading}\n        {name === \"\" ? \"\" : ` ${name}`}\n      </span>\n      <span\n        className=\"nx-image-state__bar\"\n        role=\"progressbar\"\n        aria-label={WORDS.uploading}\n        aria-valuemin={0}\n        aria-valuemax={100}\n        aria-valuenow={percent}\n      >\n        <span style={{ width: `${String(percent)}%` }} />\n      </span>\n    </div>\n  );\n}\n\n/** A link that did not load: say so, and offer another try. */\nfunction BadLink({\n  typed,\n  onLink,\n  onCancel,\n}: ImagePlateProps & { readonly typed: string }): React.JSX.Element {\n  return (\n    <div className=\"nx-image-state__stack\">\n      <p className=\"nx-image-state__problem\" role=\"alert\">\n        {WORDS.badLink}\n      </p>\n      <div className=\"nx-image-state__actions\">\n        <Button type=\"button\" size=\"sm\" onClick={() => onLink(typed)}>\n          {WORDS.tryAnotherLink}\n        </Button>\n        <Button type=\"button\" size=\"sm\" variant=\"outline\" onClick={onCancel}>\n          {WORDS.cancel}\n        </Button>\n      </div>\n    </div>\n  );\n}\n\n/** Over a picture: only what is happening to it. */\nfunction OverPicture({\n  note,\n  held,\n  words,\n}: {\n  readonly note: string | undefined;\n  readonly held: boolean;\n  readonly words: string;\n}): React.JSX.Element | null {\n  if (note !== undefined) {\n    return (\n      <p className=\"nx-image-state__problem\" role=\"alert\">\n        {note}\n      </p>\n    );\n  }\n  return held ? <p className=\"nx-image-state__words\">{words}</p> : null;\n}\n\n/** The Image's choices: an empty one's three, or a missing file's Replace. */\nfunction Choices(\n  props: ImagePlateProps & {\n    readonly missing: boolean;\n    readonly note: string | undefined;\n    readonly takesFiles: boolean;\n  }\n): React.JSX.Element {\n  const { missing, note, writable, canUpload, takesFiles, onFiles } = props;\n  const chooser = React.useRef<HTMLInputElement | null>(null);\n  const Icon = missing ? ImageOff : ImagePlus;\n  const hint = takesFiles && !missing;\n  return (\n    <div className=\"nx-image-state__stack\">\n      <Icon className=\"nx-image-state__icon\" size={28} aria-hidden=\"true\" />\n      <p className=\"nx-image-state__title\">\n        {missing ? WORDS.missing : WORDS.title}\n      </p>\n      {writable ? (\n        <ChoiceButtons {...props} upload={() => chooser.current?.click()} />\n      ) : null}\n      {note === undefined ? null : (\n        <p className=\"nx-image-state__problem\" role=\"alert\">\n          {note}\n        </p>\n      )}\n      {note === undefined && hint ? (\n        <p className=\"nx-image-state__hint\">{WORDS.drop}</p>\n      ) : null}\n      {canUpload ? (\n        <input\n          ref={chooser}\n          type=\"file\"\n          accept=\"image/*\"\n          className=\"nx-image-state__chooser\"\n          tabIndex={-1}\n          aria-hidden=\"true\"\n          onChange={event => {\n            onFiles(event.currentTarget.files);\n            event.currentTarget.value = \"\";\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * A gallery's choices: \"Add images\" with Upload, which takes several files,\n * and Media library, which picks several, and \"or drop files here\".\n */\nfunction GalleryChoices(\n  props: ImagePlateProps & {\n    readonly note: string | undefined;\n    readonly takesFiles: boolean;\n  }\n): React.JSX.Element {\n  const { note, writable, canUpload, canPick, takesFiles, onFiles } = props;\n  const chooser = React.useRef<HTMLInputElement | null>(null);\n  return (\n    <div className=\"nx-image-state__stack\">\n      <ImagePlus\n        className=\"nx-image-state__icon\"\n        size={28}\n        aria-hidden=\"true\"\n      />\n      <p className=\"nx-image-state__title\">{GALLERY_STATE_WORDS.title}</p>\n      {writable ? (\n        <div className=\"nx-image-state__actions\">\n          {canUpload ? (\n            <Button\n              type=\"button\"\n              size=\"sm\"\n              onClick={() => chooser.current?.click()}\n            >\n              {WORDS.upload}\n            </Button>\n          ) : null}\n          {canPick ? (\n            <Button\n              type=\"button\"\n              size=\"sm\"\n              variant=\"outline\"\n              onClick={props.onLibrary}\n            >\n              {WORDS.library}\n            </Button>\n          ) : null}\n        </div>\n      ) : null}\n      {note === undefined ? null : (\n        <p className=\"nx-image-state__problem\" role=\"alert\">\n          {note}\n        </p>\n      )}\n      {note === undefined && takesFiles ? (\n        <p className=\"nx-image-state__hint\">{GALLERY_STATE_WORDS.drop}</p>\n      ) : null}\n      {canUpload ? (\n        <input\n          ref={chooser}\n          type=\"file\"\n          accept=\"image/*\"\n          multiple\n          className=\"nx-image-state__chooser\"\n          tabIndex={-1}\n          aria-hidden=\"true\"\n          onChange={event => {\n            // Copied before the field is emptied, which empties its list.\n            onFiles(Array.from(event.currentTarget.files ?? []));\n            event.currentTarget.value = \"\";\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/** The buttons: Upload, Media library and Link, or a missing file's Replace. */\nfunction ChoiceButtons({\n  missing,\n  canUpload,\n  canPick,\n  upload,\n  onLibrary,\n  onLink,\n}: ImagePlateProps & {\n  readonly missing: boolean;\n  readonly upload: () => void;\n}): React.JSX.Element {\n  if (missing) {\n    return (\n      <div className=\"nx-image-state__actions\">\n        {canPick ? (\n          <Button type=\"button\" size=\"sm\" onClick={onLibrary}>\n            {WORDS.replace}\n          </Button>\n        ) : null}\n      </div>\n    );\n  }\n  return (\n    <div className=\"nx-image-state__actions\">\n      {canUpload ? (\n        <Button type=\"button\" size=\"sm\" onClick={upload}>\n          {WORDS.upload}\n        </Button>\n      ) : null}\n      {canPick ? (\n        <Button type=\"button\" size=\"sm\" variant=\"outline\" onClick={onLibrary}>\n          {WORDS.library}\n        </Button>\n      ) : null}\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        onClick={() => onLink(\"\")}\n      >\n        {WORDS.link}\n      </Button>\n    </div>\n  );\n}\n\n/** The Link choice: an address, checked before it is stored. */\nfunction LinkForm({\n  plate,\n  activity,\n  onTypeLink,\n  onSubmitLink,\n  onCancel,\n}: ImagePlateProps & {\n  readonly activity: Extract<Activity, { kind: \"link\" }>;\n}): React.JSX.Element {\n  const id = React.useId();\n  const field = React.useRef<HTMLInputElement | null>(null);\n  // Focused when the choice opens, as a dialog's first field is, and again\n  // when \"Try another link\" brings it back.\n  React.useEffect(() => {\n    field.current?.focus();\n    field.current?.select();\n  }, []);\n  return (\n    <form\n      className=\"nx-image-state__link\"\n      onSubmit={event => {\n        event.preventDefault();\n        if (!activity.checking) onSubmitLink(activity.typed);\n      }}\n      onKeyDown={event => {\n        if (event.key !== \"Escape\") return;\n        event.stopPropagation();\n        onCancel();\n      }}\n    >\n      <label\n        className=\"nx-image-state__words\"\n        htmlFor={`${id}-${plate.nodeId}`}\n      >\n        {WORDS.linkLabel}\n      </label>\n      <input\n        id={`${id}-${plate.nodeId}`}\n        className=\"nx-image-state__address\"\n        type=\"text\"\n        inputMode=\"url\"\n        autoComplete=\"off\"\n        spellCheck={false}\n        placeholder=\"https://\"\n        ref={field}\n        value={activity.typed}\n        disabled={activity.checking}\n        onChange={event => onTypeLink(event.currentTarget.value)}\n      />\n      <div className=\"nx-image-state__actions\">\n        <Button\n          type=\"submit\"\n          size=\"sm\"\n          disabled={activity.checking || activity.typed.trim() === \"\"}\n        >\n          {activity.checking ? `${WORDS.checking}…` : WORDS.addLink}\n        </Button>\n        <Button type=\"button\" size=\"sm\" variant=\"outline\" onClick={onCancel}>\n          {WORDS.cancel}\n        </Button>\n      </div>\n    </form>\n  );\n}\n","\"use client\";\n\n/**\n * An Embed's empty state on the canvas: the field an author pastes a link\n * into, where an Embed has none yet.\n *\n * The Embed block draws a box where it has no link, only where an author is\n * looking, in the block's own classes, so the box takes the size the frame\n * would. This draws the editor's part over each box, in the editor's own\n * colours: \"Paste a YouTube, Vimeo or other link\", a field, and Embed.\n *\n * A pasted link is stored at once, as pasting one is the whole act; a typed\n * one is stored on Enter or Embed. Either way it goes through the editor's one\n * write path as one step to undo (`embedLinkOp`): the link as typed and, for\n * a provider the block knows, the provider's shape as the block's own style\n * values. The box then goes, the Embed draws what it loads, and the\n * inspector's Link setting says what was found.\n *\n * An Embed whose link a lock holds, or one inside a placed component, is not\n * offered the field: its link is set elsewhere.\n *\n * An Embed with a link draws a frame, a document of its own that takes every\n * press made over it, so the canvas would never see a click there, and a\n * poster's play link would start the player inside the editor. Each frame is\n * covered by a see-through plate that takes the press instead and selects\n * the Embed, as a click on any other block does.\n *\n * Drawn like `ImageStates`, in the overlay over the canvas, at each box's\n * measured rectangle (`shownRectOf`), and kept current by `watchCanvasFor`.\n *\n * @module canvas/embed-states\n */\n\nimport { Button } from \"@nextlyhq/ui\";\nimport { MonitorPlay } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Rect } from \"../geometry\";\nimport {\n  designIsWritable,\n  lockViewOf,\n  propIsWritable,\n} from \"../inspector/inspector\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport { isElement } from \"./dom-kind\";\nimport {\n  EMBED_STATE_WORDS as WORDS,\n  embedFrames,\n  embedLinkOp,\n  emptyEmbedBoxes,\n} from \"./embed-states-model\";\nimport { overlaySpaceOf } from \"./geometry-dom\";\nimport { shownRectOf } from \"./image-states\";\nimport { selectionModeFor, type SelectionMode } from \"./selection\";\n\nexport interface EmbedStatesProps {\n  /** The editor the links are written through. */\n  readonly editor: EditorState;\n  /**\n   * A block is being dragged. The boxes stay drawn, so the page keeps its\n   * shape, and take no presses, so the drag reaches the canvas beneath.\n   */\n  readonly dragging?: boolean;\n}\n\n/** Where one plate is drawn, and for which Embed. */\ninterface Plate {\n  readonly key: string;\n  readonly nodeId: string;\n  readonly rect: Rect;\n  /** `empty`: the link field; `frame`: the cover over a frame. */\n  readonly kind: \"empty\" | \"frame\";\n}\n\n/** What on a plate does something of its own when pressed. */\nconst CONTROLS = \"button, input, label\";\n\n/** The field over each Embed that waits for a link. */\nexport function EmbedStates({\n  editor,\n  dragging = false,\n}: EmbedStatesProps): React.JSX.Element {\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const [plates, setPlates] = React.useState<readonly Plate[]>([]);\n\n  // Read in callbacks that outlive the render that made them.\n  const latest = React.useRef(editor);\n  latest.current = editor;\n\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) {\n      setPlates(current => (current.length === 0 ? current : []));\n      return;\n    }\n    const found: Plate[] = [];\n    const { document } = latest.current;\n    for (const [kind, boxes] of [\n      [\"empty\", emptyEmbedBoxes(space.root, document)],\n      [\"frame\", embedFrames(space.root, document)],\n    ] as const) {\n      boxes.forEach((box, index) => {\n        const rect = shownRectOf(box.element, space);\n        if (rect === null) return;\n        found.push({\n          key: `${box.nodeId}:${kind}:${String(index)}`,\n          nodeId: box.nodeId,\n          rect,\n          kind,\n        });\n      });\n    }\n    setPlates(found);\n  }, []);\n\n  const canvasFrame = useCanvasFrame();\n  React.useLayoutEffect(() => {\n    measure();\n  }, [measure, editor.document, canvasFrame]);\n  React.useEffect(\n    () => watchCanvasFor(() => layer.current, measure),\n    [measure, editor.document, canvasFrame]\n  );\n\n  /** Whether the Embed takes a link from here, now: no lock holds it. */\n  const writable = (nodeId: string): boolean =>\n    propIsWritable(editor.document, nodeId, \"src\", lockViewOf(editor));\n\n  const select = (nodeId: string, mode?: SelectionMode): void => {\n    if (mode === undefined) editor.select(nodeId);\n    else editor.select(nodeId, mode);\n  };\n\n  /** Store a link on the Embed, through the editor's write path. */\n  const store = (nodeId: string, link: string): boolean => {\n    const now = latest.current;\n    if (!propIsWritable(now.document, nodeId, \"src\", lockViewOf(now))) {\n      return false;\n    }\n    // The provider's size only where the block's design may change: a\n    // content-only area takes the link alone.\n    const op = embedLinkOp(now.document, nodeId, link, {\n      shape: designIsWritable(now.document, nodeId, lockViewOf(now)),\n    });\n    if (op === null) return false;\n    select(nodeId);\n    return now.apply(op) !== null;\n  };\n\n  return (\n    <div\n      ref={layer}\n      className=\"nx-embed-states\"\n      data-dragging={dragging ? \"\" : undefined}\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n    >\n      {plates.map(plate =>\n        plate.kind === \"frame\" ? (\n          <FrameCover\n            key={plate.key}\n            plate={plate}\n            onSelect={mode => select(plate.nodeId, mode)}\n          />\n        ) : (\n          <EmbedPlate\n            key={plate.key}\n            plate={plate}\n            writable={writable(plate.nodeId)}\n            onSelect={mode => select(plate.nodeId, mode)}\n            onLink={link => store(plate.nodeId, link)}\n          />\n        )\n      )}\n    </div>\n  );\n}\n\n/**\n * The see-through cover over an Embed's frame: a press on it selects the\n * Embed. Hidden from assistive technology and the tab order, which reach the\n * block through Layers as they reach any other.\n */\nfunction FrameCover({\n  plate,\n  onSelect,\n}: {\n  readonly plate: Plate;\n  readonly onSelect: (mode: SelectionMode) => void;\n}): React.JSX.Element {\n  const { x, y, width, height } = plate.rect;\n  return (\n    <div\n      className=\"nx-embed-state\"\n      data-embed-state=\"frame\"\n      aria-hidden=\"true\"\n      style={{ left: x, top: y, width, height }}\n      onClick={event => onSelect(selectionModeFor(event))}\n      // A secondary press or a touch selects the Embed before its menu\n      // opens, which the menu around the canvas then opens for: the menu\n      // never acts on the block selected before.\n      onPointerDown={event => {\n        if (event.button === 2 || event.pointerType === \"touch\") {\n          onSelect(selectionModeFor(event));\n        }\n      }}\n    />\n  );\n}\n\ninterface EmbedPlateProps {\n  readonly plate: Plate;\n  /** Whether the Embed's link may be set here. */\n  readonly writable: boolean;\n  readonly onSelect: (mode: SelectionMode) => void;\n  /** Store a link; whether the editor took it. */\n  readonly onLink: (link: string) => boolean;\n}\n\n/** One Embed's field, drawn over its empty box. */\nfunction EmbedPlate({\n  plate,\n  writable,\n  onSelect,\n  onLink,\n}: EmbedPlateProps): React.JSX.Element {\n  const id = React.useId();\n  const [typed, setTyped] = React.useState(\"\");\n  const fieldId = `${id}-${plate.nodeId}`;\n  const { x, y, width, height } = plate.rect;\n  return (\n    <div\n      className=\"nx-embed-state\"\n      role=\"group\"\n      aria-label=\"Embed\"\n      style={{ left: x, top: y, width, height }}\n      onClick={event => {\n        // Anywhere on the box selects the Embed; its controls do their own\n        // thing.\n        if (isElement(event.target) && event.target.closest(CONTROLS) !== null)\n          return;\n        onSelect(selectionModeFor(event));\n      }}\n      onContextMenu={event => event.stopPropagation()}\n    >\n      <form\n        className=\"nx-embed-state__form\"\n        onSubmit={event => {\n          event.preventDefault();\n          if (onLink(typed)) setTyped(\"\");\n        }}\n      >\n        <MonitorPlay\n          className=\"nx-embed-state__icon\"\n          size={24}\n          aria-hidden=\"true\"\n        />\n        <label className=\"nx-embed-state__title\" htmlFor={fieldId}>\n          {WORDS.field}\n        </label>\n        <div className=\"nx-embed-state__row\">\n          <input\n            id={fieldId}\n            className=\"nx-embed-state__address\"\n            type=\"text\"\n            inputMode=\"url\"\n            autoComplete=\"off\"\n            spellCheck={false}\n            placeholder=\"https://\"\n            value={typed}\n            disabled={!writable}\n            onChange={event => setTyped(event.currentTarget.value)}\n            onPaste={event => {\n              // Pasting a link is the whole act: stored at once, without a\n              // second press. Anything that is not one line of text is\n              // left to the field as usual.\n              const pasted = event.clipboardData.getData(\"text/plain\").trim();\n              if (pasted === \"\" || /\\s/.test(pasted)) return;\n              event.preventDefault();\n              if (!onLink(pasted)) setTyped(pasted);\n            }}\n          />\n          <Button\n            type=\"submit\"\n            size=\"sm\"\n            disabled={!writable || typed.trim() === \"\"}\n          >\n            {WORDS.add}\n          </Button>\n        </div>\n      </form>\n    </div>\n  );\n}\n","/**\n * What the canvas says over each Form block (`form-states.tsx`), worked out\n * from the document, the drawn page and each picked form's state, with no\n * React.\n *\n * - A picked form that is a **draft**: \"Draft form: visitors can't send it\n *   until it's published\".\n * - One that is **closed**: \"This form is closed. Visitors see its closed\n *   message.\" with \"Pick another form\".\n * - One that was **deleted** (or that the author can no longer read):\n *   \"This form was deleted.\" with \"Pick another form\", over the empty box\n *   the block draws in its place where an author is looking.\n * - A **simple form with nowhere to send answers** (\"Send to\" empty):\n *   \"Answers have nowhere to go yet: add an address, or install the Forms\n *   plugin to save them\".\n *\n * A form whose state could not be read is said nothing about: a failed read\n * is never told as a deleted form.\n *\n * @module canvas/form-states-model\n */\nimport {\n  findNode,\n  walkNodes,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport { INSTANCE_ATTRIBUTE, NODE_ID_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\n\nimport type { PickedFormState } from \"../inspector/content/content-services\";\nimport {\n  answersGoNowhere,\n  FORM_BLOCK,\n  pickedFormOf,\n  type PickedForm,\n} from \"../inspector/content/form-picked\";\n\n/** What the canvas says over one Form. */\nexport type FormNoticeKind = \"draft\" | \"closed\" | \"deleted\" | \"nowhere\";\n\n/** One Form block the page draws and the document owns. */\nexport interface DrawnForm {\n  readonly nodeId: string;\n  readonly element: Element;\n  /** Its picked form, or `undefined` for a simple form. */\n  readonly picked: PickedForm | undefined;\n  /** A simple form with no address to send its answers to. */\n  readonly nowhere: boolean;\n}\n\n/** The Form node by its id, or `undefined` when it is not one. */\nexport function formNodeOf(\n  document: BlockDocument,\n  nodeId: string\n): BlockNode | undefined {\n  const node = findNode(document.nodes, nodeId);\n  return node?.type === FORM_BLOCK ? node : undefined;\n}\n\n/**\n * The Forms the page draws that the document holds, each once. A Form drawn\n * inside a placed component, or in the Layout around the page, is set where\n * it is defined, so nothing is said over it here.\n */\nexport function drawnForms(\n  elements: readonly Element[],\n  document: BlockDocument\n): DrawnForm[] {\n  const forms = formsById(document);\n  if (forms.size === 0) return [];\n  const found: DrawnForm[] = [];\n  const seen = new Set<string>();\n  for (const element of elements) {\n    if (element.hasAttribute(INSTANCE_ATTRIBUTE)) continue;\n    const nodeId = element.getAttribute(NODE_ID_ATTRIBUTE);\n    if (nodeId === null || seen.has(nodeId)) continue;\n    const node = forms.get(nodeId);\n    if (node === undefined) continue;\n    seen.add(nodeId);\n    const picked = pickedFormOf(node.props.form);\n    found.push({\n      nodeId,\n      element,\n      picked,\n      nowhere: answersGoNowhere(node.props),\n    });\n  }\n  return found;\n}\n\n/**\n * Each id {@link formNodeOf} answers a Form for, with that Form, from one walk\n * of the document. The canvas measures on every edit and every change of\n * layout, and asking `formNodeOf` per drawn block walked the whole page once\n * for each of them. The first node an id names wins, as `findNode` finds it,\n * so an id whose first node is not a Form names none here either.\n */\nfunction formsById(document: BlockDocument): Map<string, BlockNode> {\n  const named = new Set<string>();\n  const forms = new Map<string, BlockNode>();\n  walkNodes(document.nodes, node => {\n    if (named.has(node.id)) return;\n    named.add(node.id);\n    if (node.type === FORM_BLOCK) forms.set(node.id, node);\n  });\n  return forms;\n}\n\n/** The key a picked form's state is kept under. */\nexport function pickedFormKey(form: PickedForm): string {\n  return JSON.stringify([form.provider, form.ref]);\n}\n\n/**\n * What the canvas says over `form`, given its picked form's state as read\n * (`undefined` while unread, or where the read failed): nothing for a\n * published form, nor for one whose state is not known.\n */\nexport function noticeOf(\n  form: Pick<DrawnForm, \"picked\" | \"nowhere\">,\n  state: PickedFormState | undefined\n): FormNoticeKind | undefined {\n  if (form.picked === undefined) return form.nowhere ? \"nowhere\" : undefined;\n  switch (state) {\n    case \"draft\":\n      return \"draft\";\n    case \"closed\":\n      return \"closed\";\n    case \"missing\":\n      return \"deleted\";\n    default:\n      return undefined;\n  }\n}\n","\"use client\";\n\n/**\n * What the canvas says over a Form block, in the editor's own colours: a\n * picked form that is a draft, closed or deleted, and a simple form whose\n * answers have nowhere to go (`form-states-model.ts` says which and why).\n *\n * The form itself is drawn by the block, as a visitor will see it: a picked\n * form from its provider's description, read as the author through the\n * editor's own route. This draws only the editor's words about it:\n *\n * - **A tag on the block's top edge** for a draft, a closed form, and a\n *   simple form with nowhere to send answers, so the form beneath stays in\n *   view.\n * - **A plate over the block** for a deleted form, which draws an empty box\n *   in its place where an author is looking; the box is given room for the\n *   plate on the canvas only, and its room is taken back once the plate goes.\n *\n * A closed or deleted form's notice offers \"Pick another form\": the forms\n * the author may pick, written as the inspector's picker writes them, so it\n * is one step to undo and refused where a lock holds the block's form.\n *\n * Drawn like `ImageStates`, in the overlay over the canvas, at each block's\n * measured rectangle, kept current by `watchCanvasFor`.\n *\n * @module canvas/form-states\n */\nimport { walkNodes } from \"@nextlyhq/blocks-engine\";\nimport { Select, SelectContent, SelectTrigger } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Rect } from \"../geometry\";\nimport type {\n  ContentServices,\n  PickedFormState,\n} from \"../inspector/content/content-services\";\nimport {\n  FORM_BLOCK,\n  FORM_WORDS,\n  pickedFormOf,\n  type PickedForm,\n} from \"../inspector/content/form-picked\";\nimport {\n  FormChoiceItems,\n  formOfChoice,\n  useFormSources,\n  useShownAgain,\n} from \"../inspector/content/form-source-control\";\nimport { lockViewOf, propIsWritable, propPatch } from \"../inspector/inspector\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport { isHTMLElement } from \"./dom-kind\";\nimport {\n  drawnForms,\n  formNodeOf,\n  noticeOf,\n  pickedFormKey,\n  type FormNoticeKind,\n} from \"./form-states-model\";\nimport {\n  layoutFragments,\n  overlaySpaceOf,\n  renderSkips,\n  visiblePartOf,\n} from \"./geometry-dom\";\nimport { nodeElements } from \"./rendered-nodes\";\nimport { selectionModeFor } from \"./selection\";\n\n/** @experimental Settles with the form provider contract. */\nexport interface FormStatesProps {\n  readonly editor: EditorState;\n  /** The host's reads of the author's forms; absent, a picked form is said nothing about. */\n  readonly services?: Pick<ContentServices, \"pickedFormState\" | \"listForms\">;\n  /** A block is being dragged: nothing is drawn, so the drag reaches the canvas. */\n  readonly hidden?: boolean;\n}\n\n/** The room a deleted form's box is given for its plate, on the canvas only. */\nconst DELETED_ROOM = \"6rem\";\n\n/** One notice, where the canvas draws it. */\ninterface Plate {\n  readonly nodeId: string;\n  readonly kind: FormNoticeKind;\n  readonly rect: Rect;\n}\n\n/** The words of each notice. */\nconst NOTICE_WORDS: Readonly<Record<FormNoticeKind, string>> = {\n  draft: FORM_WORDS.draft,\n  closed: FORM_WORDS.closed,\n  deleted: FORM_WORDS.deleted,\n  nowhere: FORM_WORDS.nowhere,\n};\n\n/** Every form the document's Forms pick, each once. */\nfunction pickedForms(document: EditorState[\"document\"]): PickedForm[] {\n  const picks = new Map<string, PickedForm>();\n  walkNodes(document.nodes, node => {\n    if (node.type !== FORM_BLOCK) return;\n    const picked = pickedFormOf(node.props.form);\n    if (picked !== undefined) picks.set(pickedFormKey(picked), picked);\n  });\n  return [...picks.values()];\n}\n\n/** What `usePickedFormStates` has asked, and in which round of asking. */\ninterface Asked {\n  readonly read: ContentServices[\"pickedFormState\"];\n  readonly again: number;\n  /** The round, bumped whenever everything is to be read afresh. */\n  round: number;\n  /** Each form asked in this round, by key. */\n  readonly keys: Set<string>;\n}\n\n/**\n * Each picked form's state, read once per form, and read again for every\n * form when the author comes back to the editor (`useShownAgain`), since the\n * form may have changed in its own tab, or when the host's reader changes. A\n * form no longer picked is read afresh if it is picked again. A read that\n * fails leaves its form unread, so nothing is said over it, until the next\n * time everything is read. An answer from an earlier round is dropped, so a\n * slow old read never puts back a state that was read since.\n */\nfunction usePickedFormStates(\n  document: EditorState[\"document\"],\n  read: ContentServices[\"pickedFormState\"]\n): ReadonlyMap<string, PickedFormState> {\n  const [states, setStates] = React.useState<\n    ReadonlyMap<string, PickedFormState>\n  >(() => new Map());\n  const again = useShownAgain();\n  const asked = React.useRef<Asked>({\n    read,\n    again,\n    round: 0,\n    keys: new Set(),\n  });\n  React.useEffect(() => {\n    const kept = asked.current;\n    if (kept.read !== read || kept.again !== again) {\n      asked.current = { read, again, round: kept.round + 1, keys: new Set() };\n    }\n    const now = asked.current;\n    if (read === undefined) return;\n    const forms = pickedForms(document);\n    const picked = new Set(forms.map(pickedFormKey));\n    for (const key of now.keys) if (!picked.has(key)) now.keys.delete(key);\n    for (const form of forms) {\n      const key = pickedFormKey(form);\n      if (now.keys.has(key)) continue;\n      now.keys.add(key);\n      const round = now.round;\n      read(form).then(\n        state => {\n          if (asked.current.round !== round) return;\n          setStates(current =>\n            current.get(key) === state\n              ? current\n              : new Map(current).set(key, state)\n          );\n        },\n        () => undefined\n      );\n    }\n  }, [document, read, again]);\n  return states;\n}\n\n/** Where a notice goes for an element: the part of it the page shows. */\nfunction shownRectOf(\n  element: Element,\n  space: NonNullable<ReturnType<typeof overlaySpaceOf>>\n): Rect | null {\n  if (layoutFragments(element) === 0 || renderSkips(element)) return null;\n  const visible = visiblePartOf(element, space.root);\n  if (visible === null || visible === \"hidden\") return null;\n  return space.place(visible);\n}\n\n/** Two lists of plates that draw the same. */\nfunction samePlates(a: readonly Plate[], b: readonly Plate[]): boolean {\n  return (\n    a.length === b.length &&\n    a.every((plate, index) => {\n      const other = b[index];\n      return (\n        other !== undefined &&\n        other.nodeId === plate.nodeId &&\n        other.kind === plate.kind &&\n        other.rect.x === plate.rect.x &&\n        other.rect.y === plate.rect.y &&\n        other.rect.width === plate.rect.width &&\n        other.rect.height === plate.rect.height\n      );\n    })\n  );\n}\n\n/** Give a deleted form's box its plate's room; `kept` notes what was given. */\nfunction reserveRoom(element: Element, kept: Map<Element, string>): void {\n  if (!isHTMLElement(element)) return;\n  if (!kept.has(element)) {\n    kept.set(element, element.style.getPropertyValue(\"min-block-size\"));\n  }\n  if (element.style.getPropertyValue(\"min-block-size\") !== DELETED_ROOM) {\n    element.style.setProperty(\"min-block-size\", DELETED_ROOM);\n  }\n}\n\n/** Take back the room given to every box no longer in `still`. */\nfunction releaseRoom(\n  kept: Map<Element, string>,\n  still: ReadonlySet<Element>\n): void {\n  for (const [element, before] of kept) {\n    if (still.has(element)) continue;\n    kept.delete(element);\n    if (!isHTMLElement(element)) continue;\n    if (before === \"\") element.style.removeProperty(\"min-block-size\");\n    else element.style.setProperty(\"min-block-size\", before);\n  }\n}\n\n/** The canvas's notices over its Form blocks. */\nexport function FormStates({\n  editor,\n  services,\n  hidden = false,\n}: FormStatesProps): React.JSX.Element {\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const [plates, setPlates] = React.useState<readonly Plate[]>([]);\n  const states = usePickedFormStates(\n    editor.document,\n    services?.pickedFormState\n  );\n  // Read by the measure, which outlives the render that made it.\n  const latest = React.useRef({ document: editor.document, states });\n  latest.current = { document: editor.document, states };\n  const reserved = React.useRef(new Map<Element, string>());\n\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (space === null) {\n      releaseRoom(reserved.current, new Set());\n      setPlates(current => (current.length === 0 ? current : []));\n      return;\n    }\n    const { document, states: known } = latest.current;\n    const next: Plate[] = [];\n    const roomed = new Set<Element>();\n    for (const form of drawnForms(nodeElements(space.root), document)) {\n      const kind = noticeOf(\n        form,\n        form.picked === undefined\n          ? undefined\n          : known.get(pickedFormKey(form.picked))\n      );\n      if (kind === undefined) continue;\n      if (kind === \"deleted\") {\n        reserveRoom(form.element, reserved.current);\n        roomed.add(form.element);\n      }\n      const rect = shownRectOf(form.element, space);\n      if (rect !== null) next.push({ nodeId: form.nodeId, kind, rect });\n    }\n    releaseRoom(reserved.current, roomed);\n    setPlates(current => (samePlates(current, next) ? current : next));\n  }, []);\n\n  const canvasFrame = useCanvasFrame();\n  React.useLayoutEffect(() => {\n    measure();\n  }, [measure, editor.document, states, canvasFrame]);\n  React.useEffect(\n    () => watchCanvasFor(() => layer.current, measure),\n    [measure, canvasFrame]\n  );\n  // Every box's own height comes back once the notices go.\n  React.useEffect(() => {\n    const kept = reserved.current;\n    return () => releaseRoom(kept, new Set());\n  }, []);\n\n  const picking = plates.some(\n    plate => plate.kind === \"closed\" || plate.kind === \"deleted\"\n  );\n  const sources = useFormSources(picking ? services?.listForms : undefined);\n\n  return (\n    <div ref={layer} className=\"nx-form-states\" {...{ [CHROME_ATTRIBUTE]: \"\" }}>\n      {hidden\n        ? null\n        : plates.map(plate => (\n            <FormNotice\n              key={plate.nodeId}\n              plate={plate}\n              editor={editor}\n              sources={sources.status === \"ready\" ? sources.sources : []}\n            />\n          ))}\n    </div>\n  );\n}\n\n/** One notice: a tag on the block's top edge, or a plate over a deleted form. */\nfunction FormNotice({\n  plate,\n  editor,\n  sources,\n}: {\n  readonly plate: Plate;\n  readonly editor: EditorState;\n  readonly sources: Parameters<typeof FormChoiceItems>[0][\"sources\"];\n}): React.JSX.Element {\n  const { rect, kind, nodeId } = plate;\n  const writable = propIsWritable(\n    editor.document,\n    nodeId,\n    \"form\",\n    lockViewOf(editor)\n  );\n  const pick = (value: string) => {\n    const form = formOfChoice(value);\n    const node = formNodeOf(editor.document, nodeId);\n    if (form === undefined || node === undefined) return;\n    editor.apply({\n      kind: \"update\",\n      id: nodeId,\n      patch: propPatch(node, \"form\", form),\n    });\n  };\n  const offersPick =\n    (kind === \"closed\" || kind === \"deleted\") &&\n    writable &&\n    sources.some(source => source.forms.length > 0);\n  return (\n    <div\n      className=\"nx-form-states__place\"\n      data-form-notice={kind}\n      style={{\n        left: rect.x,\n        top: rect.y,\n        width: rect.width,\n        height: rect.height,\n      }}\n    >\n      <div\n        className={\n          kind === \"deleted\" ? \"nx-form-states__plate\" : \"nx-form-states__tag\"\n        }\n        role=\"note\"\n        // The notice's own presses stay on it: the canvas beneath would\n        // otherwise select whatever block is under the pointer. A click on\n        // the notice selects its Form instead, so a deleted form's box,\n        // which the plate covers, still opens its settings; the picker's\n        // own presses stop at the picker.\n        onClick={event => {\n          event.stopPropagation();\n          const mode = selectionModeFor(event);\n          if (mode === \"replace\") editor.select(nodeId);\n          else editor.select(nodeId, mode);\n        }}\n        onPointerDown={event => event.stopPropagation()}\n        onContextMenu={event => event.stopPropagation()}\n      >\n        <span className=\"nx-form-states__words\">{NOTICE_WORDS[kind]}</span>\n        {offersPick ? (\n          <span\n            className=\"nx-form-states__picker\"\n            onClick={event => event.stopPropagation()}\n          >\n            <Select value=\"\" onValueChange={pick}>\n              <SelectTrigger\n                className=\"nx-form-states__pick\"\n                aria-label={FORM_WORDS.pickAnother}\n              >\n                {FORM_WORDS.pickAnother}\n              </SelectTrigger>\n              <SelectContent>\n                <FormChoiceItems sources={sources} />\n              </SelectContent>\n            </Select>\n          </span>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n","/**\n * The item a new Collection list starts with: ordinary blocks, already bound\n * to the entry each repeat draws, built from the collection's fields by one\n * fixed rule.\n *\n * - **Title:** the collection's title field, else its first text field named\n *   `title` or `name`. A Heading 3, linked to the entry's page when the\n *   collection's entries have pages.\n * - **Picture:** its first single upload field that takes images, never a\n *   link or text field. An Image.\n * - **Summary:** its first text or long-text field named like `excerpt`,\n *   `summary`, `description`, `intro` or `subtitle`, else its first\n *   long-text field. A Text.\n *\n * Each starting layout arranges those: \"Cards, 3 across\" (a Card each, the\n * picture 16:9 above a linked title and the summary), \"List rows\" (a row of a\n * 96px square picture beside the title and summary, wrapping under it on a\n * phone) and\n * \"Titles only\" (linked titles alone). Every binding is an ordinary one, on\n * the item, so the author can change any of it after.\n *\n * Pure: the same fields give the same blocks, apart from their new ids.\n *\n * @module collection-list-item\n */\nimport {\n  BASE_BREAKPOINT,\n  fieldFitsProp,\n  findNode,\n  type FieldStoragePrimitive,\n  getBlock,\n  makeNode,\n  type BlockDocument,\n  type BlockNode,\n  type NodeStyles,\n  type StyleValues,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\n\n/** The starting layouts an author picks from. */\nexport type StartingLayout = \"cards\" | \"rows\" | \"titles\";\n\n/** One field an entry has, as the collection's readable fields list it. */\nexport interface ItemField {\n  readonly name: string;\n  readonly type: string;\n  readonly hasMany?: boolean;\n  readonly relationTo?: string | readonly string[];\n  /** The primitive a plugin's field type is stored as, which gives its kind. */\n  readonly storage?: FieldStoragePrimitive;\n  /**\n   * For an upload field: whether it takes images. Absent, an upload field is\n   * taken to: the media library is mostly pictures, and an Image bound to a\n   * file that is not one draws its fallback.\n   */\n  readonly takesImages?: boolean;\n}\n\n/** What the rule reads of a collection. */\nexport interface ItemSource {\n  readonly slug: string;\n  /** The field the admin titles its entries by, where it says. */\n  readonly titleField?: string;\n  /** Whether its entries are served as pages of their own. */\n  readonly entriesHavePages?: boolean;\n  /** Every field a visitor may read. */\n  readonly readable?: readonly ItemField[];\n  /**\n   * Whether a list may sort it by the date its entries were created on: a\n   * collection with timestamps turned off has no such field, and a list\n   * sorting by it is refused when saved.\n   */\n  readonly sortsByCreated?: boolean;\n}\n\n/** The fields the item binds, by role; `undefined` for a role with none. */\nexport interface ItemFields {\n  readonly title?: string;\n  readonly picture?: string;\n  readonly summary?: string;\n  /** Whether the title links to the entry's page. */\n  readonly link: boolean;\n}\n\n/** The field types that hold longer words, as plain text. */\nconst LONG_TEXT_TYPES = new Set([\"textarea\"]);\n\n/** Names a title field goes by, where the collection names none. */\nconst TITLE_NAMES = [\"title\", \"name\"];\n\n/** Names a summary goes by, best first. */\nconst SUMMARY_NAMES = [\n  \"excerpt\",\n  \"summary\",\n  \"description\",\n  \"intro\",\n  \"subtitle\",\n];\n\n/**\n * Whether `field` may fill `prop` of `blockType` as it is: the engine's one\n * binding rule (`fieldFitsProp`), the rule a save judges the page by, so the\n * item never carries a binding the save refuses.\n */\nfunction fits(field: ItemField, blockType: string, prop: string): boolean {\n  const schema = getBlock(blockType)?.props?.[prop];\n  if (schema === undefined) return false;\n  return fieldFitsProp(\n    {\n      name: field.name,\n      type: field.type,\n      ...(field.hasMany === true ? { hasMany: true } : {}),\n      ...(field.relationTo === undefined\n        ? {}\n        : { relationTo: field.relationTo }),\n      ...(field.storage === undefined ? {} : { storage: field.storage }),\n    },\n    schema\n  );\n}\n\n/**\n * Whether `field` fills an Image's picture: an upload that takes images, and\n * the rule's answer. Only an upload: the rule also lets an Image take a URL\n * or text field, which may hold any address, such as a website's, and drawn\n * as a picture that is a broken image. An author may still bind one by hand.\n */\nfunction holdsPicture(field: ItemField): boolean {\n  return (\n    field.type === \"upload\" &&\n    field.takesImages !== false &&\n    fits(field, \"core/image\", \"mediaId\")\n  );\n}\n\n/** Whether `field` fills a Heading's words. */\nfunction fillsTitle(field: ItemField): boolean {\n  return fits(field, \"core/heading\", \"text\");\n}\n\n/** Whether `field` fills a Text's words. */\nfunction fillsSummary(field: ItemField): boolean {\n  return fits(field, \"core/text\", \"text\");\n}\n\n/** The fields the rule binds, read from the collection's readable fields. */\nexport function itemFieldsOf(source: ItemSource): ItemFields {\n  const readable = source.readable ?? [];\n  const single = readable.filter(field => field.hasMany !== true);\n  const named = (\n    names: readonly string[],\n    takes: (field: ItemField) => boolean\n  ): string | undefined => {\n    for (const name of names) {\n      const found = single.find(\n        field => field.name.toLowerCase() === name && takes(field)\n      );\n      if (found !== undefined) return found.name;\n    }\n    return undefined;\n  };\n  // The admin's title field, where a heading may show it as it is: a number\n  // or a date bound with no format is refused when the page is saved.\n  const declaredTitle = single.find(\n    field => field.name === source.titleField && fillsTitle(field)\n  )?.name;\n  const title = declaredTitle ?? named(TITLE_NAMES, fillsTitle);\n  const summary =\n    named(SUMMARY_NAMES, fillsSummary) ??\n    single.find(\n      field =>\n        LONG_TEXT_TYPES.has(field.type) &&\n        field.name !== title &&\n        fillsSummary(field)\n    )?.name;\n  const picture = single.find(holdsPicture)?.name;\n  return {\n    ...(title === undefined ? {} : { title }),\n    ...(picture === undefined ? {} : { picture }),\n    ...(summary === undefined || summary === title ? {} : { summary }),\n    link: source.entriesHavePages === true,\n  };\n}\n\n/** A binding of a prop to the entry each repeat draws. */\nfunction itemBinding(path: string) {\n  return { $bind: path, source: \"item\" as const };\n}\n\n/** A block of `type` with its own defaults, or `undefined` while unknown. */\nfunction blockOf(\n  type: string,\n  props: Record<string, unknown> = {},\n  slots?: Record<string, BlockNode[]>\n): BlockNode | undefined {\n  const definition = getBlock(type);\n  if (definition === undefined) return undefined;\n  return makeNode(\n    definition.name,\n    definition.version,\n    {\n      ...structuredClone(\n        (definition.defaultProps ?? {}) as Record<string, unknown>\n      ),\n      ...props,\n    },\n    slots\n  );\n}\n\n/** `node` with these bindings and base style values added. */\nfunction dressed(\n  node: BlockNode | undefined,\n  bindings: BlockNode[\"bindings\"],\n  base?: Record<string, string>\n): BlockNode | undefined {\n  if (node === undefined) return undefined;\n  const styles: NodeStyles | undefined =\n    base === undefined ? undefined : { base: { base } };\n  return {\n    ...node,\n    ...(bindings === undefined ? {} : { bindings }),\n    ...(styles === undefined ? {} : { styles }),\n  };\n}\n\n/** The entry's title, linked to its page where entries have one. */\nfunction titleBlock(fields: ItemFields, slug: string): BlockNode | undefined {\n  if (fields.title === undefined) return undefined;\n  const linked = fields.link;\n  return dressed(\n    blockOf(\"core/heading\", {\n      level: \"h3\",\n      ...(linked ? { entryCollection: slug } : {}),\n    }),\n    {\n      text: itemBinding(fields.title),\n      ...(linked ? { entryId: itemBinding(\"id\") } : {}),\n    }\n  );\n}\n\n/** The entry's picture, shaped by `base`. */\nfunction pictureBlock(\n  fields: ItemFields,\n  base: Record<string, string>\n): BlockNode | undefined {\n  if (fields.picture === undefined) return undefined;\n  return dressed(\n    blockOf(\"core/image\"),\n    { mediaId: itemBinding(fields.picture) },\n    base\n  );\n}\n\n/** The entry's summary. */\nfunction summaryBlock(fields: ItemFields): BlockNode | undefined {\n  if (fields.summary === undefined) return undefined;\n  return dressed(blockOf(\"core/text\"), { text: itemBinding(fields.summary) });\n}\n\n/** The blocks that are present, in order. */\nfunction present(...nodes: (BlockNode | undefined)[]): BlockNode[] {\n  return nodes.filter((node): node is BlockNode => node !== undefined);\n}\n\n/**\n * The blocks of the list's item for `layout`: what its repeated slot holds.\n * Empty where the collection has none of the fields the layout shows, which\n * leaves an empty item, as Skip does.\n */\nexport function startingItem(\n  source: ItemSource,\n  layout: StartingLayout\n): BlockNode[] {\n  const fields = itemFieldsOf(source);\n  const title = titleBlock(fields, source.slug);\n  if (layout === \"titles\") return present(title);\n  if (layout === \"cards\") {\n    const inside = present(\n      pictureBlock(fields, {\n        width: \"100%\",\n        aspectRatio: \"16 / 9\",\n        objectFit: \"cover\",\n      }),\n      title,\n      summaryBlock(fields)\n    );\n    if (inside.length === 0) return [];\n    const card = blockOf(\"core/card\", {}, { children: inside });\n    return present(card);\n  }\n  const words = present(title, summaryBlock(fields));\n  const stack =\n    words.length === 0\n      ? undefined\n      : dressed(blockOf(\"core/box\", {}, { children: words }), undefined, {\n          display: \"flex\",\n          flexDirection: \"column\",\n          gap: \"0.25rem\",\n          minWidth: \"0\",\n          // Beside the picture while the row has room for 12rem of words,\n          // under it on a phone: the row wraps, with no device to name.\n          flex: \"1 1 12rem\",\n        });\n  const picture = pictureBlock(fields, {\n    width: \"96px\",\n    height: \"96px\",\n    aspectRatio: \"1 / 1\",\n    objectFit: \"cover\",\n    flex: \"none\",\n  });\n  const inside = present(picture, stack);\n  if (inside.length === 0) return [];\n  // A row only where there are two things to set side by side.\n  if (inside.length === 1) return inside;\n  return present(\n    dressed(blockOf(\"core/box\", {}, { children: inside }), undefined, {\n      display: \"flex\",\n      flexDirection: \"row\",\n      flexWrap: \"wrap\",\n      alignItems: \"flex-start\",\n      gap: \"1rem\",\n    })\n  );\n}\n\n/**\n * The style values the list itself takes for `layout`, at its base: Cards\n * lay the items in a grid, three across where there is room and one under\n * a phone's width, with no device to name (the Gallery's own default grid);\n * Titles only sets them closer together. List rows keep the list's own\n * spacing.\n */\nfunction startingListStyles(\n  layout: StartingLayout\n): Record<string, string> | undefined {\n  switch (layout) {\n    case \"cards\":\n      return {\n        display: \"grid\",\n        gridTemplateColumns:\n          \"repeat(auto-fit, minmax(max(calc(33.333% - 2rem), min(100%, 20rem)), 1fr))\",\n        gap: \"1.5rem\",\n      };\n    case \"titles\":\n      return { gap: \"0.5rem\" };\n    case \"rows\":\n      return undefined;\n  }\n}\n\n/** The slot of a list that its item is built in, repeated per entry. */\nconst ITEM_SLOT = \"children\";\n\n/**\n * What choosing a source and a starting layout writes to a list, as ops to\n * apply together (ONE step): the source and the layout's own style values on\n * the list, whatever its item held taken out, and the item built for the\n * layout put in. `skip` sets the source and leaves an empty item to build.\n * `null` where there is no such list.\n */\nexport function planStartingList(\n  document: BlockDocument,\n  listId: string,\n  source: ItemSource,\n  layout: StartingLayout | \"skip\"\n): BuilderOp[] | null {\n  const list = findNode(document.nodes, listId);\n  if (list === undefined) return null;\n  const own = layout === \"skip\" ? undefined : startingListStyles(layout);\n  const base: StyleValues = {\n    ...(list.styles?.base?.[BASE_BREAKPOINT] ?? {}),\n    ...own,\n  };\n  // A new list's Newest first sorts by `createdAt`, which a collection with\n  // timestamps off does not have: there the list keeps no sort and draws in\n  // the order its entries were created.\n  const props: Record<string, unknown> = {\n    ...list.props,\n    collection: source.slug,\n  };\n  if (source.sortsByCreated === false && props.sort === \"-createdAt\") {\n    delete props.sort;\n  }\n  const update: BuilderOp = {\n    kind: \"update\",\n    id: listId,\n    patch: {\n      props,\n      ...(own === undefined\n        ? {}\n        : {\n            styles: {\n              ...list.styles,\n              base: { ...list.styles?.base, [BASE_BREAKPOINT]: base },\n            },\n          }),\n    },\n  };\n  // Skip sets the source and nothing else: an item the author already built\n  // stays. A layout replaces the item, which the picker says first and one\n  // Undo puts back.\n  if (layout === \"skip\") return [update];\n  const removed: BuilderOp[] = (list.slots?.[ITEM_SLOT] ?? []).map(child => ({\n    kind: \"remove\",\n    id: child.id,\n  }));\n  const item = startingItem(source, layout);\n  const inserted: BuilderOp[] = item.map((node, index) => ({\n    kind: \"insert\",\n    node,\n    at: { parentId: listId, slot: ITEM_SLOT, index },\n  }));\n  return [update, ...removed, ...inserted];\n}\n","\"use client\";\n\n/**\n * A new Collection list's two steps, drawn on the canvas over the list: which\n * entries it shows, then how they start out.\n *\n * - **Show entries from** offers one button per collection visitors can read\n *   (the host's list), and \"More sources…\" where the site registers custom\n *   sources, which are chosen in the panel.\n * - **\"<Collection> · choose a starting layout\"** offers three tiles, \"Cards,\n *   3 across\", \"List rows\" and \"Titles only\", and Skip, which sets the source\n *   and leaves an empty item to build.\n *\n * A layout fills the list at once (`planStartingList`): the source, the\n * item, already bound to each entry, and the layout's spacing, joined to the\n * list's insert as ONE step, so one undo takes the whole list away.\n * Escape on the first step leaves a blank list; on the second it goes back.\n * Both steps are a group named by their heading, and their buttons are\n * reached with Tab and the arrow keys.\n *\n * @module collection-list-picker\n */\nimport { findNode } from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type {\n  ContentServices,\n  LoopCollection,\n} from \"../inspector/content/content-services\";\nimport { radioGroupStep } from \"../roving-radios\";\n\nimport {\n  planStartingList,\n  type ItemSource,\n  type StartingLayout,\n} from \"./collection-list-item\";\nimport type { FirstAdd } from \"./first-add\";\n\n/** The words the two steps use, in one place. */\nconst COLLECTION_PICKER_WORDS = {\n  source: \"Show entries from\",\n  moreSources: \"More sources…\",\n  moreSourcesHint: \"Choose a custom source in the panel.\",\n  loading: \"Finding collections…\",\n  failed: \"The collections couldn't be listed.\",\n  none: \"No collection visitors can read.\",\n  layout: (label: string) => `${label} · choose a starting layout`,\n  skip: \"Skip\",\n  back: \"Back\",\n  replaces:\n    \"Choosing one replaces the blocks already in this list's item. Skip keeps them.\",\n} as const;\n\n/** The starting layouts, in the order offered, with their words. */\nconst STARTING_LAYOUTS: readonly {\n  readonly key: StartingLayout;\n  readonly label: string;\n}[] = [\n  { key: \"cards\", label: \"Cards, 3 across\" },\n  { key: \"rows\", label: \"List rows\" },\n  { key: \"titles\", label: \"Titles only\" },\n];\n\n/** What the picker reads from the host. */\nexport type CollectionPickerServices = Pick<\n  ContentServices,\n  \"listLoopCollections\" | \"listCustomSources\"\n>;\n\n/** A collection as the item rule reads it. */\nfunction itemSourceOf(collection: LoopCollection): ItemSource {\n  return {\n    slug: collection.slug,\n    ...(collection.titleField === undefined\n      ? {}\n      : { titleField: collection.titleField }),\n    ...(collection.entriesHavePages === undefined\n      ? {}\n      : { entriesHavePages: collection.entriesHavePages }),\n    // The sortable fields list a collection's timestamps where it keeps them.\n    sortsByCreated: collection.fields.some(field => field.name === \"createdAt\"),\n    readable: (collection.readable ?? []).map(field => ({\n      name: field.name,\n      type: field.type,\n      ...(field.hasMany === undefined ? {} : { hasMany: field.hasMany }),\n      ...(field.relationTo === undefined\n        ? {}\n        : { relationTo: field.relationTo }),\n      ...(field.storage === undefined ? {} : { storage: field.storage }),\n      ...(field.takesImages === undefined\n        ? {}\n        : { takesImages: field.takesImages }),\n    })),\n  };\n}\n\n/** The host's collections, as the first step lists them. */\ntype Listing =\n  | { readonly kind: \"loading\" }\n  | { readonly kind: \"failed\" }\n  | {\n      readonly kind: \"ready\";\n      readonly collections: readonly LoopCollection[];\n      readonly custom: boolean;\n    };\n\n/** The host's readable collections and whether it has custom sources. */\nfunction useListing(services: CollectionPickerServices | undefined): Listing {\n  const [listing, setListing] = React.useState<Listing>({ kind: \"loading\" });\n  const list = services?.listLoopCollections;\n  const custom = services?.listCustomSources;\n  React.useEffect(() => {\n    let live = true;\n    if (list === undefined) {\n      setListing({ kind: \"failed\" });\n      return;\n    }\n    Promise.all([\n      list(),\n      custom === undefined ? Promise.resolve([]) : custom().catch(() => []),\n    ]).then(\n      ([collections, sources]) => {\n        if (live) {\n          setListing({\n            kind: \"ready\",\n            collections: [...collections].sort((a, b) =>\n              a.label.localeCompare(b.label)\n            ),\n            custom: sources.length > 0,\n          });\n        }\n      },\n      () => {\n        if (live) setListing({ kind: \"failed\" });\n      }\n    );\n    return () => {\n      live = false;\n    };\n  }, [list, custom]);\n  return listing;\n}\n\n/** Arrow keys move between `buttons`, as a row of tiles is moved through. */\nfunction arrowsBetween(\n  event: React.KeyboardEvent,\n  buttons: readonly (HTMLButtonElement | null)[],\n  from: number\n): void {\n  const step = radioGroupStep(event.key);\n  if (step === null || buttons.length === 0) return;\n  event.preventDefault();\n  const next = (from + step + buttons.length) % buttons.length;\n  buttons[next]?.focus();\n}\n\nexport interface CollectionListPickerProps {\n  /** The list just added, or the selected list with no source. */\n  readonly firstAdd: FirstAdd;\n  /** The document the list is in, for the pick's write. */\n  readonly document: Parameters<typeof planStartingList>[0];\n  readonly services?: CollectionPickerServices | undefined;\n  readonly onDone?: () => void;\n}\n\n/** The two steps over a list that has no source yet. */\nexport function CollectionListPicker({\n  firstAdd,\n  document,\n  services,\n  onDone,\n}: CollectionListPickerProps): React.JSX.Element {\n  const listing = useListing(services);\n  const [source, setSource] = React.useState<LoopCollection | null>(null);\n  const titleId = React.useId();\n  const buttons = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const heading = React.useRef<HTMLParagraphElement | null>(null);\n\n  // Each step starts with its first button focused, so the keyboard carries\n  // on from a pick to the next step.\n  React.useEffect(() => {\n    buttons.current[0]?.focus({ preventScroll: true });\n  }, [source, listing.kind]);\n\n  const skip = (): void => {\n    firstAdd.skip();\n    onDone?.();\n  };\n  const pick = (layout: StartingLayout | \"skip\"): void => {\n    if (source === null) return;\n    const ops = planStartingList(\n      document,\n      firstAdd.nodeId,\n      itemSourceOf(source),\n      layout\n    );\n    if (ops === null) firstAdd.skip();\n    else firstAdd.choose(ops);\n    onDone?.();\n  };\n\n  buttons.current = [];\n  const keep = (index: number) => (element: HTMLButtonElement | null) => {\n    buttons.current[index] = element;\n  };\n\n  if (source !== null) {\n    // A list whose item already holds blocks: a layout replaces them, so the\n    // step says so before the pick rather than after it.\n    const built =\n      (findNode(document.nodes, firstAdd.nodeId)?.slots?.children?.length ??\n        0) > 0;\n    return (\n      <div\n        className=\"nx-first-add__body nx-list-picker\"\n        role=\"group\"\n        aria-labelledby={titleId}\n        onKeyDown={event => {\n          if (event.key !== \"Escape\") return;\n          event.preventDefault();\n          event.stopPropagation();\n          setSource(null);\n        }}\n      >\n        <p className=\"nx-first-add__title\" id={titleId} ref={heading}>\n          {COLLECTION_PICKER_WORDS.layout(source.label)}\n        </p>\n        <div className=\"nx-first-add__tiles nx-list-picker__layouts\">\n          {STARTING_LAYOUTS.map((layout, index) => (\n            <button\n              key={layout.key}\n              ref={keep(index)}\n              type=\"button\"\n              className=\"nx-list-picker__tile\"\n              data-layout={layout.key}\n              tabIndex={index === 0 ? 0 : -1}\n              onKeyDown={event =>\n                arrowsBetween(event, buttons.current.slice(0, 3), index)\n              }\n              onClick={() => pick(layout.key)}\n            >\n              <LayoutGlyph layout={layout.key} />\n              <span>{layout.label}</span>\n            </button>\n          ))}\n        </div>\n        {built ? (\n          <p className=\"nx-list-picker__note\">\n            {COLLECTION_PICKER_WORDS.replaces}\n          </p>\n        ) : null}\n        <div className=\"nx-list-picker__actions\">\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"ghost\"\n            onClick={() => setSource(null)}\n          >\n            {COLLECTION_PICKER_WORDS.back}\n          </Button>\n          <Button\n            type=\"button\"\n            size=\"sm\"\n            variant=\"ghost\"\n            className=\"nx-first-add__skip\"\n            onClick={() => pick(\"skip\")}\n          >\n            {COLLECTION_PICKER_WORDS.skip}\n          </Button>\n        </div>\n      </div>\n    );\n  }\n\n  return (\n    <div\n      className=\"nx-first-add__body nx-list-picker\"\n      role=\"group\"\n      aria-labelledby={titleId}\n      aria-busy={listing.kind === \"loading\"}\n      onKeyDown={event => {\n        if (event.key !== \"Escape\") return;\n        event.preventDefault();\n        event.stopPropagation();\n        skip();\n      }}\n    >\n      <p className=\"nx-first-add__title\" id={titleId}>\n        {COLLECTION_PICKER_WORDS.source}\n      </p>\n      {listing.kind === \"loading\" ? (\n        <p className=\"nx-list-picker__note\" role=\"status\">\n          {COLLECTION_PICKER_WORDS.loading}\n        </p>\n      ) : listing.kind === \"failed\" ? (\n        <p className=\"nx-list-picker__note\" role=\"status\">\n          {COLLECTION_PICKER_WORDS.failed}\n        </p>\n      ) : (\n        <>\n          {listing.collections.length === 0 ? (\n            <p className=\"nx-list-picker__note\">\n              {COLLECTION_PICKER_WORDS.none}\n            </p>\n          ) : (\n            <div className=\"nx-list-picker__sources\">\n              {listing.collections.map((collection, index) => (\n                <Button\n                  key={collection.slug}\n                  ref={keep(index)}\n                  type=\"button\"\n                  size=\"sm\"\n                  variant=\"outline\"\n                  tabIndex={index === 0 ? 0 : -1}\n                  onKeyDown={event =>\n                    arrowsBetween(event, buttons.current, index)\n                  }\n                  onClick={() => setSource(collection)}\n                >\n                  {collection.label}\n                </Button>\n              ))}\n            </div>\n          )}\n          {listing.custom ? (\n            <p className=\"nx-list-picker__note\">\n              <span className=\"nx-list-picker__more\">\n                {COLLECTION_PICKER_WORDS.moreSources}\n              </span>{\" \"}\n              {COLLECTION_PICKER_WORDS.moreSourcesHint}\n            </p>\n          ) : null}\n        </>\n      )}\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"nx-first-add__skip\"\n        onClick={skip}\n      >\n        {COLLECTION_PICKER_WORDS.skip}\n      </Button>\n    </div>\n  );\n}\n\n/** A small drawing of each starting layout, in the tile. */\nfunction LayoutGlyph({\n  layout,\n}: {\n  readonly layout: StartingLayout;\n}): React.JSX.Element {\n  const box = { width: 72, height: 44 };\n  return (\n    <svg\n      className=\"nx-list-picker__glyph\"\n      viewBox={`0 0 ${String(box.width)} ${String(box.height)}`}\n      aria-hidden=\"true\"\n      focusable=\"false\"\n    >\n      {layout === \"cards\"\n        ? [0, 1, 2].map(column => (\n            <g\n              key={column}\n              transform={`translate(${String(column * 24 + 2)} 4)`}\n            >\n              <rect\n                width=\"20\"\n                height=\"12\"\n                rx=\"2\"\n                className=\"nx-list-picker__fill\"\n              />\n              <rect y=\"15\" width=\"16\" height=\"3\" rx=\"1\" />\n              <rect\n                y=\"21\"\n                width=\"20\"\n                height=\"2\"\n                rx=\"1\"\n                className=\"nx-list-picker__faint\"\n              />\n              <rect\n                y=\"25\"\n                width=\"14\"\n                height=\"2\"\n                rx=\"1\"\n                className=\"nx-list-picker__faint\"\n              />\n            </g>\n          ))\n        : layout === \"rows\"\n          ? [0, 1, 2].map(row => (\n              <g key={row} transform={`translate(4 ${String(row * 14 + 2)})`}>\n                <rect\n                  width=\"11\"\n                  height=\"11\"\n                  rx=\"2\"\n                  className=\"nx-list-picker__fill\"\n                />\n                <rect x=\"15\" y=\"1\" width=\"30\" height=\"3\" rx=\"1\" />\n                <rect\n                  x=\"15\"\n                  y=\"6\"\n                  width=\"46\"\n                  height=\"2\"\n                  rx=\"1\"\n                  className=\"nx-list-picker__faint\"\n                />\n              </g>\n            ))\n          : [0, 1, 2, 3].map(row => (\n              <rect\n                key={row}\n                x=\"4\"\n                y={String(row * 10 + 4)}\n                width={String(40 + (row % 2) * 16)}\n                height=\"4\"\n                rx=\"1\"\n              />\n            ))}\n    </svg>\n  );\n}\n","\"use client\";\n\n/**\n * The Columns chooser drawn on the canvas when a Columns row is first added:\n * the row's layout tiles, the same six the Content tab offers, and Skip,\n * which keeps the two equal columns it was added with.\n *\n * A pick writes what the Content tab's tile writes (`planLayout`), joined to\n * the insert as one step, so one undo still takes the whole row away. The\n * tiles are one tab stop: the arrows, Home and End move between them, Enter\n * or Space picks, and Escape skips.\n *\n * @module columns-layout-picker\n */\nimport { findNode } from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport {\n  ColumnsLayoutGlyph,\n  ROW_OWN,\n} from \"../inspector/content/columns-layout-field\";\n\nimport { COLUMNS_LAYOUTS, planLayout } from \"./columns-layout\";\nimport type { FirstAdd } from \"./first-add\";\n\n/** The chooser's words. */\nexport const COLUMNS_PICKER_WORDS = {\n  title: \"Choose a layout\",\n  skip: \"Skip\",\n} as const;\n\n/** The tile a key moves to from `from`, or `undefined` for any other key. */\nfunction movedTo(key: string, from: number, count: number): number | undefined {\n  switch (key) {\n    case \"ArrowRight\":\n    case \"ArrowDown\":\n      return (from + 1) % count;\n    case \"ArrowLeft\":\n    case \"ArrowUp\":\n      return (from - 1 + count) % count;\n    case \"Home\":\n      return 0;\n    case \"End\":\n      return count - 1;\n    default:\n      return undefined;\n  }\n}\n\nexport interface ColumnsLayoutPickerProps {\n  readonly editor: EditorState;\n  /** The step holding the row just added. */\n  readonly firstAdd: FirstAdd;\n  /**\n   * Called once the author has picked or skipped, so the canvas can hand\n   * focus back to where it was.\n   */\n  readonly onDone?: () => void;\n}\n\n/** \"Choose a layout\": the six tiles and Skip, for the row just added. */\nexport function ColumnsLayoutPicker({\n  editor,\n  firstAdd,\n  onDone,\n}: ColumnsLayoutPickerProps): React.JSX.Element | null {\n  const titleId = React.useId();\n  const [stop, setStop] = React.useState(0);\n  const tiles = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const row = findNode(editor.document.nodes, firstAdd.nodeId);\n  if (row === undefined) return null;\n\n  const pick = (key: string) => {\n    const plan = planLayout(row, key, ROW_OWN);\n    // A tile a new row cannot lay out (none today: it holds only empty\n    // columns) leaves the row as it was added.\n    if (plan.ok) firstAdd.choose(plan.ops);\n    else firstAdd.skip();\n    onDone?.();\n  };\n  const skip = () => {\n    firstAdd.skip();\n    onDone?.();\n  };\n\n  return (\n    <div\n      className=\"nx-first-add__body\"\n      role=\"group\"\n      aria-labelledby={titleId}\n      onKeyDown={event => {\n        if (event.key !== \"Escape\") return;\n        // Skip, and kept here: the canvas's own Escape would also move the\n        // selection to the row's parent.\n        event.preventDefault();\n        event.stopPropagation();\n        skip();\n      }}\n    >\n      <p className=\"nx-first-add__title\" id={titleId}>\n        {COLUMNS_PICKER_WORDS.title}\n      </p>\n      <div className=\"nx-columns-layout__tiles nx-first-add__tiles\">\n        {COLUMNS_LAYOUTS.map((layout, index) => (\n          <button\n            key={layout.key}\n            ref={element => {\n              tiles.current[index] = element;\n            }}\n            type=\"button\"\n            className=\"nx-columns-layout__tile\"\n            data-layout={layout.key}\n            tabIndex={index === stop ? 0 : -1}\n            onFocus={() => setStop(index)}\n            onKeyDown={event => {\n              const next = movedTo(event.key, index, COLUMNS_LAYOUTS.length);\n              if (next === undefined) return;\n              event.preventDefault();\n              setStop(next);\n              tiles.current[next]?.focus();\n            }}\n            onClick={() => pick(layout.key)}\n          >\n            <ColumnsLayoutGlyph layout={layout} />\n            <span>{layout.label}</span>\n          </button>\n        ))}\n      </div>\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"ghost\"\n        className=\"nx-first-add__skip\"\n        onClick={skip}\n      >\n        {COLUMNS_PICKER_WORDS.skip}\n      </Button>\n    </div>\n  );\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","\"use client\";\n\n/**\n * The chooser a block just added asks for, drawn on the canvas in place of\n * the block's body while the editor's first-add step holds (`first-add.ts`).\n *\n * Drawn like `ImageStates`, in the overlay over the canvas, at the block's\n * measured rectangle and kept current by `watchCanvasFor`. A new block is\n * often shorter than its chooser (a Columns row of two empty columns is one\n * empty-container's height), so while the chooser shows the block is given\n * the chooser's height as its minimum, on the canvas only: the page makes\n * room for it rather than the chooser covering what follows. That minimum is\n * taken back the moment the chooser goes.\n *\n * Focus moves to the chooser when it opens (the block brought into view\n * first), so it is reached from the keyboard whichever way the block was added, and goes back where it was\n * once the author picks or skips.\n *\n * @module canvas/first-add-choosers\n */\nimport { COLLECTION_LIST_TYPE, findNode } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Rect } from \"../geometry\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { nodeElement } from \"./canvas-addressing\";\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { returnFocusToCanvas } from \"./canvas-escape\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport {\n  CollectionListPicker,\n  type CollectionPickerServices,\n} from \"./collection-list-picker\";\nimport { ColumnsLayoutPicker } from \"./columns-layout-picker\";\nimport { isHTMLElement } from \"./dom-kind\";\nimport type { FirstAdd } from \"./first-add\";\nimport {\n  layoutFragments,\n  overlaySpaceOf,\n  renderSkips,\n  visiblePartOf,\n} from \"./geometry-dom\";\nimport { revealNode } from \"./reveal-node\";\n\nexport interface FirstAddChoosersProps {\n  /** The editor whose first-add step this draws. */\n  readonly editor: EditorState;\n  /**\n   * A block is being dragged: the chooser is not drawn, so the drag reaches\n   * the canvas beneath. The step itself holds.\n   */\n  readonly hidden?: boolean;\n  /**\n   * The host's collections, for a Collection list's first step. Absent, the\n   * step says the collections couldn't be listed, and Skip still leaves a\n   * blank list.\n   */\n  readonly services?: CollectionPickerServices | undefined;\n}\n\n/**\n * Whether a list has no source: no collection, no custom source and no\n * related entries. Such a list asks which entries it shows whenever it is\n * selected, not only just after it is added, so a reload or an Escape lands\n * on the same question.\n */\nfunction hasNoSource(props: Readonly<Record<string, unknown>>): boolean {\n  const collection = props.collection;\n  return (\n    (typeof collection !== \"string\" || collection.trim() === \"\") &&\n    props.namedQuery === undefined &&\n    props.relation === undefined\n  );\n}\n\n/**\n * The selected list's question, where the editor holds no first-add step:\n * a pick is its own step of the history, and Skip puts the question away\n * until the list is selected again.\n */\nfunction useSourcelessListAsk(\n  editor: EditorState,\n  dismissed: string | undefined,\n  dismiss: (nodeId: string) => void\n): FirstAdd | undefined {\n  const selected = editor.selectedId;\n  const node =\n    selected === null ? undefined : findNode(editor.document.nodes, selected);\n  const asks =\n    node !== undefined &&\n    node.type === COLLECTION_LIST_TYPE &&\n    node.id !== dismissed &&\n    hasNoSource(node.props);\n  const nodeId = asks ? node.id : undefined;\n  const { applyAll } = editor;\n  return React.useMemo(\n    () =>\n      nodeId === undefined\n        ? undefined\n        : {\n            nodeId,\n            chooser: \"collection-source\",\n            choose: ops => applyAll(ops) !== null,\n            skip: () => dismiss(nodeId),\n          },\n    [nodeId, applyAll, dismiss]\n  );\n}\n\n/** The block's minimum height while its chooser shows, and what it had. */\ninterface Reserved {\n  readonly element: HTMLElement;\n  /** The inline value the block carried before, put back afterwards. */\n  readonly before: string;\n}\n\n/** Where the chooser is drawn: its block's shown part, in overlay space. */\nfunction shownRectOf(\n  layer: HTMLElement,\n  nodeId: string\n): { rect: Rect; element: Element; scale: number } | null {\n  const space = overlaySpaceOf(layer, CANVAS_ROOT_CLASS);\n  if (space === null) return null;\n  const element = nodeElement(space.root, nodeId);\n  // A block the canvas lays out nowhere has no place for a chooser.\n  if (element === null || layoutFragments(element) === 0) return null;\n  if (renderSkips(element)) return null;\n  const visible = visiblePartOf(element, space.root);\n  if (visible === null || visible === \"hidden\") return null;\n  return { rect: space.place(visible), element, scale: space.scale };\n}\n\n/** Where the chooser goes, when there is a layer and a block to draw it for. */\nfunction shownFor(\n  layer: HTMLElement | null,\n  nodeId: string | undefined\n): ReturnType<typeof shownRectOf> {\n  return layer === null || nodeId === undefined\n    ? null\n    : shownRectOf(layer, nodeId);\n}\n\n/**\n * A block a scrolling box around it hides entirely (added below the box's\n * view) has no part to draw a chooser over: it is scrolled into view once,\n * then measured again.\n */\nfunction unhide(\n  layer: HTMLElement | null,\n  nodeId: string | undefined,\n  unhiddenFor: { current: string | undefined }\n): ReturnType<typeof shownRectOf> {\n  if (layer === null || nodeId === undefined) return null;\n  if (unhiddenFor.current === nodeId) return null;\n  const root = overlaySpaceOf(layer, CANVAS_ROOT_CLASS)?.root;\n  const element = root === undefined ? null : nodeElement(root, nodeId);\n  if (element === null || layoutFragments(element) === 0) return null;\n  if (renderSkips(element)) return null;\n  unhiddenFor.current = nodeId;\n  revealNode(element.ownerDocument, nodeId, { instant: true });\n  return shownRectOf(layer, nodeId);\n}\n\n/** Two rectangles at the same place and size. */\nfunction sameRect(a: Rect | null, b: Rect | null): boolean {\n  if (a === null || b === null) return a === b;\n  return (\n    a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height\n  );\n}\n\n/** Put back the minimum height a block carried before its chooser showed. */\nfunction release(reserved: Reserved | null): void {\n  if (reserved === null) return;\n  if (reserved.before === \"\")\n    reserved.element.style.removeProperty(\"min-block-size\");\n  else reserved.element.style.setProperty(\"min-block-size\", reserved.before);\n}\n\n/**\n * The chooser's own height, its padding and the plate's edge included. Read\n * from the body, not the plate, whose height follows the block's and would\n * hold a room once made.\n */\nfunction chooserHeight(body: HTMLDivElement | null): number {\n  if (body === null) return 0;\n  const plate = body.parentElement;\n  const edge = plate === null ? 0 : plate.offsetHeight - plate.clientHeight;\n  return body.offsetHeight + edge;\n}\n\n/**\n * Give the block the chooser's height as its minimum, as the page measures\n * it: the overlay is drawn at the canvas's zoom, the page at its own size.\n * What the block carried before is kept, to be put back.\n */\nfunction reserveRoom(\n  reserved: { current: Reserved | null },\n  found: { readonly element: Element; readonly scale: number },\n  height: number\n): void {\n  const { element: block } = found;\n  if (height <= 0 || !isHTMLElement(block)) return;\n  const wanted = `${String(Math.ceil(height / found.scale))}px`;\n  if (reserved.current?.element !== block) {\n    release(reserved.current);\n    reserved.current = {\n      element: block,\n      before: block.style.getPropertyValue(\"min-block-size\"),\n    };\n  }\n  // Only when it changes: the canvas watches the page's styles, and an\n  // unchanged write would measure again for nothing.\n  if (block.style.getPropertyValue(\"min-block-size\") !== wanted) {\n    block.style.setProperty(\"min-block-size\", wanted);\n  }\n}\n\n/**\n * Bring a block added off screen (at the end of a long page) into view once,\n * as soon as its room is laid out at the plate's real width, so the whole\n * chooser is shown rather than the empty row the block was.\n */\nfunction revealOnce(\n  revealedFor: { current: string | undefined },\n  id: string,\n  found: { readonly element: Element; readonly rect: Rect },\n  laid: { readonly reserved: Reserved | null; readonly plateWidth: number }\n): void {\n  if (revealedFor.current === id) return;\n  if (laid.reserved?.element !== found.element) return;\n  if (Math.abs(laid.plateWidth - found.rect.width) >= 1) return;\n  revealedFor.current = id;\n  // At once: the plate is measured and focused at the block's new place.\n  revealNode(found.element.ownerDocument, id, { instant: true });\n}\n\n/** The chooser for the block just added, over the canvas. */\nexport function FirstAddChoosers({\n  editor,\n  hidden = false,\n  services,\n}: FirstAddChoosersProps): React.JSX.Element {\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const body = React.useRef<HTMLDivElement | null>(null);\n  const reserved = React.useRef<Reserved | null>(null);\n  // The block last brought into view, so it is brought there once.\n  const revealedFor = React.useRef<string | undefined>(undefined);\n  // The block last scrolled out from under a box that hid it, likewise.\n  const unhiddenFor = React.useRef<string | undefined>(undefined);\n  const [rect, setRect] = React.useState<Rect | null>(null);\n  // A list put away with Skip, until another block is selected.\n  const [dismissed, setDismissed] = React.useState<string | undefined>();\n  const dismiss = React.useCallback((id: string) => setDismissed(id), []);\n  React.useEffect(() => {\n    if (editor.selectedId !== dismissed) setDismissed(undefined);\n  }, [editor.selectedId, dismissed]);\n  const sourceless = useSourcelessListAsk(editor, dismissed, dismiss);\n  // Skipping a just-added list's question also puts it away while the list\n  // stays selected, or the question it asks with no source would come\n  // straight back.\n  const added = editor.firstAdd;\n  const justAdded = React.useMemo<FirstAdd | undefined>(\n    () =>\n      added === undefined\n        ? undefined\n        : {\n            ...added,\n            skip: () => {\n              dismiss(added.nodeId);\n              added.skip();\n            },\n          },\n    [added, dismiss]\n  );\n  const firstAdd = hidden ? undefined : (justAdded ?? sourceless);\n  const nodeId = firstAdd?.nodeId;\n\n  // Read by the measure, which outlives the render that made it.\n  const latest = React.useRef(nodeId);\n  latest.current = nodeId;\n\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    const id = latest.current;\n    const found = shownFor(element, id) ?? unhide(element, id, unhiddenFor);\n    if (element === null || id === undefined || found === null) {\n      setRect(current => (current === null ? current : null));\n      return;\n    }\n    reserveRoom(reserved, found, chooserHeight(body.current));\n    revealOnce(revealedFor, id, found, {\n      reserved: reserved.current,\n      plateWidth: body.current?.parentElement?.offsetWidth ?? 0,\n    });\n    // Read again: the room just made moves what follows, and may grow it.\n    const next = shownRectOf(element, id)?.rect ?? found.rect;\n    setRect(current => (sameRect(current, next) ? current : next));\n  }, []);\n\n  const canvasFrame = useCanvasFrame();\n  React.useLayoutEffect(() => {\n    measure();\n  }, [measure, editor.document, nodeId, rect, canvasFrame]);\n  React.useEffect(\n    () => watchCanvasFor(() => layer.current, measure),\n    [measure, nodeId, canvasFrame]\n  );\n\n  // The block's own height comes back once its chooser goes.\n  React.useEffect(\n    () => () => {\n      release(reserved.current);\n      reserved.current = null;\n    },\n    [nodeId]\n  );\n\n  // Focus moves into the chooser once it is placed, and goes back afterwards.\n  // Once per block: a chooser placed again (scrolled back into view, or\n  // after a drag) does not take focus from where the author has since gone.\n  const { frame } = canvasFrame;\n  const returnTo = React.useRef<Element | null>(null);\n  const focusedFor = React.useRef<string | undefined>(undefined);\n  const placed = rect !== null;\n  React.useEffect(() => {\n    if (nodeId === undefined || !placed) return;\n    if (focusedFor.current === nodeId) return;\n    focusedFor.current = nodeId;\n    const own = layer.current?.ownerDocument;\n    returnTo.current = own?.activeElement ?? null;\n    const tile = (): HTMLElement | null | undefined =>\n      body.current?.querySelector<HTMLElement>(\"[tabindex='0']\");\n    tile()?.focus({ preventScroll: true });\n    const later = setTimeout(() => {\n      // The surface the block was added from may hand focus on once it has\n      // closed (the block picker hands it to the canvas, a turn later). Taken\n      // back only from where nothing is being done: the canvas itself, or no\n      // element at all.\n      const active = own?.activeElement ?? null;\n      const idle = active === null || active === own?.body || active === frame;\n      if (idle && !body.current?.contains(active)) {\n        tile()?.focus({ preventScroll: true });\n      }\n    }, 0);\n    return () => clearTimeout(later);\n  }, [nodeId, placed, frame]);\n  const done = React.useCallback(() => {\n    const back = returnTo.current;\n    returnTo.current = null;\n    if (isHTMLElement(back) && back.isConnected && back !== frame) {\n      back.focus({ preventScroll: true });\n      return;\n    }\n    // From a surface that has gone (the block picker), back to the canvas.\n    if (frame !== null) returnFocusToCanvas(frame);\n  }, [frame]);\n\n  return (\n    <div ref={layer} className=\"nx-first-add\" {...{ [CHROME_ATTRIBUTE]: \"\" }}>\n      {firstAdd === undefined ? null : (\n        <div\n          className=\"nx-first-add__plate\"\n          data-first-add={firstAdd.chooser}\n          // Off screen until measured, so focus never lands on a chooser the\n          // author cannot see.\n          style={\n            rect === null\n              ? { visibility: \"hidden\", left: 0, top: 0 }\n              : {\n                  left: rect.x,\n                  top: rect.y,\n                  width: rect.width,\n                  minHeight: rect.height,\n                }\n          }\n          // The plate's own presses stay on it: the canvas beneath would\n          // otherwise select whatever block is under the pointer.\n          onClick={event => event.stopPropagation()}\n          onPointerDown={event => event.stopPropagation()}\n          onContextMenu={event => event.stopPropagation()}\n        >\n          <div ref={body} className=\"nx-first-add__room\">\n            <Chooser\n              editor={editor}\n              firstAdd={firstAdd}\n              services={services}\n              onDone={done}\n            />\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n\n/** The chooser the step names. */\nfunction Chooser({\n  editor,\n  firstAdd,\n  services,\n  onDone,\n}: {\n  editor: EditorState;\n  firstAdd: FirstAdd;\n  services: CollectionPickerServices | undefined;\n  onDone: () => void;\n}): React.JSX.Element | null {\n  switch (firstAdd.chooser) {\n    case \"collection-source\":\n      return (\n        <CollectionListPicker\n          // One picker per list: a step taken for one list never carries to\n          // another selected after it.\n          key={firstAdd.nodeId}\n          firstAdd={firstAdd}\n          document={editor.document}\n          services={services}\n          onDone={onDone}\n        />\n      );\n    case \"columns-layout\":\n      return (\n        <ColumnsLayoutPicker\n          editor={editor}\n          firstAdd={firstAdd}\n          onDone={onDone}\n        />\n      );\n    default:\n      return null;\n  }\n}\n","\"use client\";\n\n/**\n * \"+ Add a question\", drawn on the canvas under an Accordion's last question\n * while the accordion or one of its questions is selected.\n *\n * Pressed, it adds a question at the end, numbered after the others\n * (`accordion-questions.ts`), as one step to undo; selects it; opens it on\n * the canvas, so its answer shows; and puts the cursor in its title, through\n * the host's way into typing a block's text. With one question open at a\n * time, opening it closes the others, as a visitor's click would.\n *\n * Drawn like the other controls over the canvas, in the overlay at the\n * accordion's measured rectangle (`watchCanvasFor` keeps it current). The\n * accordion is given a row of room after its last question, on the canvas\n * only and inside its own box, where the button sits, so the button never\n * covers a question or the block that follows; the room is taken back as\n * soon as the accordion is no longer selected. Not drawn where a lock\n * refuses the insert.\n *\n * @module canvas/accordion-add-question\n */\nimport {\n  expandSlotDefaults,\n  findNode,\n  getBlock,\n  locateNode,\n  makeNode,\n  registryBlockSource,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\nimport { Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\nimport type { Rect } from \"../geometry\";\nimport type { BuilderOp } from \"../op-vocabulary\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport {\n  numberedForPlace,\n  QUESTION_BLOCK,\n  QUESTION_ROOM_ATTRIBUTE,\n  QUESTION_ROOM_PROPERTY,\n} from \"./accordion-questions\";\nimport { nodeElement } from \"./canvas-addressing\";\nimport { CHROME_ATTRIBUTE } from \"./canvas-chrome\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport { isHTMLElement } from \"./dom-kind\";\nimport {\n  canvasContentRect,\n  layoutFragments,\n  overlaySpaceOf,\n  renderSkips,\n  visiblePartOf,\n} from \"./geometry-dom\";\n\n/** The button's words. */\nconst ADD_QUESTION_WORDS = \"Add a question\";\n\n/** The Accordion's registered name. */\nconst ACCORDION_BLOCK = \"core/accordion\";\n\n/** The room's height, in the page's pixels, as the frame's sheet draws it. */\nconst ROOM_PX = 44;\n\nexport interface AccordionAddQuestionProps {\n  /** The editor the question is added through. */\n  readonly editor: EditorState;\n  /** A block is being dragged: nothing is drawn, so the drag reaches the page. */\n  readonly hidden?: boolean;\n  /**\n   * The host's way into typing a block's text on the canvas, begun on the\n   * new question, whose first value typed in place is its title. Without\n   * one, the question is added and opened, and selected for the panel.\n   */\n  readonly onEditText?: ((nodeId: string) => boolean) | undefined;\n}\n\n/**\n * The accordion the button is drawn for: the one selected, or the one\n * holding the selected question. One selected block only, as the toolbar\n * acts on one.\n */\nexport function accordionForSelection(\n  document: EditorState[\"document\"],\n  ids: readonly string[]\n): BlockNode | undefined {\n  if (ids.length !== 1) return undefined;\n  const [id] = ids;\n  if (id === undefined) return undefined;\n  const node = findNode(document.nodes, id);\n  if (node?.type === ACCORDION_BLOCK) return node;\n  if (node?.type !== QUESTION_BLOCK) return undefined;\n  const parent = locateNode(document.nodes, id)?.parent;\n  return parent?.type === ACCORDION_BLOCK ? parent : undefined;\n}\n\n/**\n * The insert that adds a question at the end of an accordion: a new\n * question made as the Add panel makes one, its answer included, numbered\n * after the others. `undefined` where the question block is not registered.\n */\nexport function addQuestionOp(\n  document: EditorState[\"document\"],\n  accordion: BlockNode\n): Extract<BuilderOp, { kind: \"insert\" }> | undefined {\n  const definition = getBlock(QUESTION_BLOCK);\n  if (definition === undefined) return undefined;\n  const at = {\n    parentId: accordion.id,\n    slot: \"children\",\n    index: accordion.slots?.children?.length ?? 0,\n  };\n  const made = makeNode(\n    QUESTION_BLOCK,\n    definition.version,\n    structuredClone({\n      ...(definition.defaultProps as Record<string, unknown> | undefined),\n    }),\n    expandSlotDefaults(QUESTION_BLOCK, registryBlockSource())\n  );\n  return { kind: \"insert\", node: numberedForPlace(made, at, document), at };\n}\n\n/** How far an edge may sit past another and still count as inside it. */\nconst EDGE_SLACK_PX = 0.5;\n\n/** The room's height in the page's pixels: the button's 44px at the zoom. */\nfunction roomHeight(scale: number): number {\n  return ROOM_PX / (scale > 0 ? scale : 1);\n}\n\n/**\n * The room after an accordion's last question, where the button sits, in the\n * canvas's content coordinates: the last row of the accordion's whole box,\n * as the frame's sheet draws it. `null` while a clipping container leaves\n * any of it, or the left edge the button starts from, out of view, so the\n * button is never drawn over a question when the room is scrolled away;\n * as wide as the part of the room in view.\n */\nexport function questionRoomRow(\n  full: Rect,\n  visible: Rect,\n  scale: number\n): Rect | null {\n  const height = roomHeight(scale);\n  const row = {\n    x: full.x,\n    y: full.y + full.height - height,\n    width: full.width,\n    height,\n  };\n  const shows =\n    row.y >= visible.y - EDGE_SLACK_PX &&\n    row.y + row.height <= visible.y + visible.height + EDGE_SLACK_PX &&\n    row.x >= visible.x - EDGE_SLACK_PX &&\n    row.x < visible.x + visible.width;\n  if (!shows) return null;\n  // As wide as the room shows: a container cutting the accordion's right\n  // side cuts the room too, and the button, drawn over the canvas, is\n  // never clipped by it, so it is kept to what shows.\n  const right = Math.min(row.x + row.width, visible.x + visible.width);\n  return { ...row, width: right - row.x };\n}\n\n/**\n * Where the button sits and how wide it may grow, in the overlay's pixels:\n * at the room's start, and never wider than the room, so over a narrow\n * accordion its words shorten rather than reach the block beside it.\n */\nexport function questionButtonBox(room: Rect): {\n  readonly left: number;\n  readonly top: number;\n  readonly maxWidth: number;\n} {\n  return { left: room.x, top: room.y, maxWidth: room.width };\n}\n\n/** Where the button is drawn: the accordion's room, and the zoom. */\ninterface Place {\n  readonly rect: Rect;\n  readonly scale: number;\n}\n\n/** A place as one comparable value, so an unchanged measure sets nothing. */\nfunction placeKey(place: Place | null): string {\n  if (place === null) return \"\";\n  const { x, y, width, height } = place.rect;\n  return [x, y, width, height, place.scale].join(\" \");\n}\n\n/**\n * Mark the accordion the button is drawn for, on the canvas's element only,\n * never stored: the frame's sheet gives a marked accordion a 44px row after\n * its last question (`canvas-frame-sheet.ts`), where the button sits. Inside\n * the accordion's own box, so its margins, and the blocks around it, are as\n * the author set them. Written only when it changes, since the canvas\n * watches the page's attributes and measures again.\n */\nfunction markRoom(\n  holder: { current: Element | null },\n  element: Element,\n  scale: number\n) {\n  if (holder.current !== element) {\n    unmarkRoom(holder);\n    holder.current = element;\n  }\n  if (!element.hasAttribute(QUESTION_ROOM_ATTRIBUTE)) {\n    element.setAttribute(QUESTION_ROOM_ATTRIBUTE, \"\");\n  }\n  // The room as tall as the button at the canvas's zoom: the button keeps\n  // its own size over a zoomed page, so the page's pixels are scaled back.\n  // A custom property only, which no author value is overridden by.\n  const height = `${String(roomHeight(scale))}px`;\n  if (\n    isHTMLElement(element) &&\n    element.style.getPropertyValue(QUESTION_ROOM_PROPERTY) !== height\n  ) {\n    element.style.setProperty(QUESTION_ROOM_PROPERTY, height);\n  }\n}\n\n/** Take the room back from the accordion last given it. */\nfunction unmarkRoom(holder: { current: Element | null }): void {\n  const element = holder.current;\n  element?.removeAttribute(QUESTION_ROOM_ATTRIBUTE);\n  if (isHTMLElement(element)) {\n    element.style.removeProperty(QUESTION_ROOM_PROPERTY);\n  }\n  holder.current = null;\n}\n\n/** \"+ Add a question\" under the selected accordion's last question. */\nexport function AccordionAddQuestion({\n  editor,\n  hidden = false,\n  onEditText,\n}: AccordionAddQuestionProps): React.JSX.Element {\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const room = React.useRef<Element | null>(null);\n  const [place, setPlace] = React.useState<Place | null>(null);\n  // The question just added, opened and typed into once the canvas draws it.\n  const [added, setAdded] = React.useState<string | undefined>(undefined);\n  const selected = accordionForSelection(editor.document, editor.selection.ids);\n  // Not offered where a lock refuses the insert, as the Add panel's are not.\n  const op =\n    selected === undefined\n      ? undefined\n      : addQuestionOp(editor.document, selected);\n  const accordion =\n    op === undefined || editor.lockRefusalFor([op]) !== undefined\n      ? undefined\n      : selected;\n  // The room is kept mid-drag, with only the button hidden: taking it away\n  // would move every block below the accordion under the drag's measured\n  // targets.\n  const accordionId = accordion?.id;\n\n  const latest = React.useRef(accordionId);\n  latest.current = accordionId;\n\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    const id = latest.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    const block =\n      space === null || id === undefined ? null : nodeElement(space.root, id);\n    if (\n      space === null ||\n      block === null ||\n      layoutFragments(block) === 0 ||\n      renderSkips(block)\n    ) {\n      unmarkRoom(room);\n      setPlace(current => (current === null ? current : null));\n      return;\n    }\n    markRoom(room, block, space.scale);\n    // Placed from the accordion's whole box, where the room is, and drawn\n    // only while a clipping container leaves the room in view.\n    const visible = visiblePartOf(block, space.root);\n    const row =\n      visible === null || visible === \"hidden\"\n        ? null\n        : questionRoomRow(\n            canvasContentRect(block, space.root),\n            visible,\n            space.scale\n          );\n    const rect = row === null ? null : space.place(row);\n    const next = rect === null ? null : { rect, scale: space.scale };\n    setPlace(current =>\n      placeKey(current) === placeKey(next) ? current : next\n    );\n  }, []);\n\n  const canvasFrame = useCanvasFrame();\n  React.useLayoutEffect(() => {\n    measure();\n  }, [measure, editor.document, accordionId, canvasFrame]);\n  React.useEffect(\n    () => watchCanvasFor(() => layer.current, measure),\n    [measure, accordionId, canvasFrame]\n  );\n  // The room goes once the accordion is no longer the one drawn for.\n  React.useEffect(() => () => unmarkRoom(room), [accordionId]);\n\n  // Once the canvas draws the new question: open it, and type its title.\n  React.useLayoutEffect(() => {\n    if (added === undefined) return;\n    const space =\n      layer.current === null\n        ? null\n        : overlaySpaceOf(layer.current, CANVAS_ROOT_CLASS);\n    const element = space === null ? null : nodeElement(space.root, added);\n    if (element === null) return;\n    setAdded(undefined);\n    if (element.tagName === \"DETAILS\") element.setAttribute(\"open\", \"\");\n    onEditText?.(added);\n  }, [added, editor.document, onEditText]);\n\n  const add = (): void => {\n    if (accordion === undefined || op === undefined) return;\n    if (editor.apply(op) === null) return;\n    editor.select(op.node.id);\n    setAdded(op.node.id);\n  };\n\n  return (\n    <div\n      ref={layer}\n      className=\"nx-add-question\"\n      {...{ [CHROME_ATTRIBUTE]: \"\" }}\n    >\n      {accordion === undefined || place === null || hidden ? null : (\n        <button\n          type=\"button\"\n          className=\"nx-add-question__button\"\n          data-add-question={accordion.id}\n          // In the room at the foot of the accordion, at the canvas's zoom.\n          style={questionButtonBox(place.rect)}\n          // Named in full, and told in full on hover, when a narrow\n          // accordion shortens the words it shows.\n          aria-label={ADD_QUESTION_WORDS}\n          title={ADD_QUESTION_WORDS}\n          onClick={event => {\n            // Kept off the canvas, which would select what lies under it.\n            event.stopPropagation();\n            add();\n          }}\n          onPointerDown={event => event.stopPropagation()}\n        >\n          <Plus size={14} aria-hidden=\"true\" />\n          <span className=\"nx-add-question__words\">{ADD_QUESTION_WORDS}</span>\n        </button>\n      )}\n    </div>\n  );\n}\n","/**\n * Visibility conditions applied for the entry a template is previewed with,\n * as the editor's host hands them to the canvas and to the Previewing strip.\n *\n * @module use-applied-conditions\n */\nimport type {\n  BlockDocument,\n  DefinitionsById,\n  DocumentLimits,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  conditionDayStart,\n  type BlocksFieldShapes,\n  type ItemHiddenAs,\n} from \"@nextlyhq/blocks-react\";\nimport { useMemo } from \"react\";\n\nimport type { PreviewedEntry } from \"../canvas/previewed-entry\";\nimport { useLoopCollections } from \"../inspector/content/collection-loop-controls\";\nimport type { ContentServices } from \"../inspector/content/content-controls\";\nimport { layerLabel, type ComponentTitleOf } from \"../panels/layers/layers\";\n\nimport {\n  appliedConditionsOf,\n  itemHiddenAsOf,\n  type AppliedConditions,\n  type ConditionsPreview,\n  type DrawnWith,\n} from \"./applied-conditions\";\nimport {\n  conditionFieldsOf,\n  conditionFieldsOfShapes,\n  type ConditionField,\n} from \"./condition-model\";\n\n/**\n * What a template's conditions are checked against, from the entry it is\n * previewed with: its published values as a visitor reads them, and the\n * fields a visitor may read. `undefined` while there is no entry to check.\n *\n * The values are the published entry's, never the working draft the canvas\n * otherwise draws, so the canvas hides what a visitor would not see. An entry\n * a visitor reads none of (never published, or the public may not read it)\n * hides every conditioned block, as the published page does.\n *\n * `labelled` are the collection's fields as the \"Show when\" rows name them,\n * where the host lists them; the entry's own field shapes, named by their\n * stored names, otherwise.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function conditionsPreviewOf(\n  previewed: PreviewedEntry | undefined,\n  noun: string,\n  labelled?: readonly ConditionField[],\n  /** The site's zone, where a day compared by a condition starts. */\n  timeZone?: string\n): ConditionsPreview | undefined {\n  if (previewed?.kind !== \"entry\") return undefined;\n  const readable = previewed.fields;\n  return {\n    subject:\n      previewed.publicValues === null\n        ? undefined\n        : {\n            fields: {\n              declared: new Set(readable.map(field => field.name)),\n              readable,\n            },\n            values: previewed.publicValues,\n          },\n    noun,\n    fields: labelled ?? conditionFieldsOfShapes(readable),\n    // The published page's own rule for when a day starts, in the site's\n    // zone, so a date compared by day is judged as a visitor gets it.\n    dayStart: conditionDayStart(timeZone),\n  };\n}\n\n/** What the conditions are applied with, besides the entry. */\nexport interface AppliedConditionsOptions {\n  /** What the entry is called in words, lower case: \"post\". */\n  readonly noun: string;\n  /** The collections the inspector lists, for the fields' names. */\n  readonly services?: Pick<ContentServices, \"listLoopCollections\">;\n  /** A placed component's title, for a hidden placement's name. */\n  readonly componentTitle?: ComponentTitleOf;\n  /** The limits the canvas draws under. */\n  readonly limits?: DocumentLimits;\n  /** The definitions of the components the page places. */\n  readonly definitions?: DefinitionsById;\n  /** The regions of the page's Layout the canvas draws around it. */\n  readonly regions?: DrawnWith[\"regions\"];\n  /** The site's time zone, as the canvas's bindings read it. */\n  readonly timeZone?: string;\n  /**\n   * Whether the canvas's lists draw the entries a visitor reads, so a block\n   * a list's item decides is judged for each item drawn.\n   */\n  readonly itemsJudged?: boolean;\n}\n\n/**\n * The page with its conditions applied for `previewed`, the entry a template\n * is previewed with, which the host hands only while the author's switch is\n * on; `undefined` otherwise, when the canvas draws every conditioned block.\n * Each hidden block is named as its Layers row names it, and each condition\n * that hides it as its \"Show when\" row does.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function useAppliedConditions(\n  document: BlockDocument,\n  previewed: PreviewedEntry | undefined,\n  {\n    noun,\n    services,\n    componentTitle,\n    limits,\n    definitions,\n    regions,\n    timeZone,\n    itemsJudged,\n  }: AppliedConditionsOptions\n): AppliedConditions | undefined {\n  // The collections the inspector lists, read once and shared, for the\n  // fields' names as the rows give them.\n  const listed = useLoopCollections(services?.listLoopCollections);\n  const collection = previewed?.kind === \"entry\" ? previewed.collection : \"\";\n  const labelled = useMemo(() => {\n    if (listed?.kind !== \"ready\") return undefined;\n    const found = listed.collections.find(each => each.slug === collection);\n    return found === undefined ? undefined : conditionFieldsOf(found);\n  }, [listed, collection]);\n  const preview = useMemo(\n    () => conditionsPreviewOf(previewed, noun, labelled, timeZone),\n    [previewed, noun, labelled, timeZone]\n  );\n  return useMemo(\n    () =>\n      preview === undefined\n        ? undefined\n        : appliedConditionsOf(\n            document,\n            preview,\n            node => layerLabel(node, undefined, componentTitle),\n            {\n              ...(limits === undefined ? {} : { limits }),\n              ...(definitions === undefined ? {} : { definitions }),\n              ...(regions === undefined ? {} : { regions }),\n              ...(itemsJudged === true ? { itemsJudged } : {}),\n            }\n          ),\n    [\n      document,\n      preview,\n      componentTitle,\n      limits,\n      definitions,\n      regions,\n      itemsJudged,\n    ]\n  );\n}\n\n/** What a list item's hidden block is drawn with, besides the item. */\nexport interface ItemHiddenOptions {\n  /** The fields a visitor may read of each collection, as the canvas's bindings read them. */\n  readonly fieldShapes: BlocksFieldShapes | undefined;\n  /** The collections the inspector lists, for the fields' names. */\n  readonly services?: Pick<ContentServices, \"listLoopCollections\">;\n  /** A placed component's title, for a hidden placement's name. */\n  readonly componentTitle?: ComponentTitleOf;\n  /** The site's time zone, as the canvas's bindings read it. */\n  readonly timeZone?: string;\n}\n\n/**\n * What the canvas draws where a list's item hides a block while conditions\n * apply: the block's marker, named as its Layers row names it, saying why\n * that entry hides it as the \"Show when\" rows word it.\n *\n * @experimental Settles with the editor's condition controls.\n */\nexport function useItemHiddenAs({\n  fieldShapes,\n  services,\n  componentTitle,\n  timeZone,\n}: ItemHiddenOptions): ItemHiddenAs {\n  const listed = useLoopCollections(services?.listLoopCollections);\n  return useMemo(() => {\n    const collections =\n      listed?.kind === \"ready\" ? listed.collections : undefined;\n    return itemHiddenAsOf({\n      fieldsOf: collection => fieldShapes?.fieldsOf({ collection }),\n      labelledOf: collection => {\n        const found = collections?.find(each => each.slug === collection);\n        return found === undefined ? undefined : conditionFieldsOf(found);\n      },\n      nameOf: node => layerLabel(node, undefined, componentTitle),\n      dayStart: conditionDayStart(timeZone),\n    });\n  }, [listed, fieldShapes, componentTitle, timeZone]);\n}\n","/**\n * Where the canvas's gap \"+\" controls go: in each gap between two top-level\n * blocks, after the last top-level block, and between the children of the\n * selected block, in the direction they are laid out.\n *\n * Pure measurement and arithmetic, kept apart from the component that draws\n * the controls: which gaps exist, where each one's middle is in the chrome's\n * coordinates, which one the pointer is near, and the order a keyboard meets\n * them in.\n *\n * ## The direction is the layout's\n *\n * A Section can lay its children out in a column, a row, or a wrapping grid.\n * The gap between two children is read from where the browser drew them: one\n * beside the other is a gap down the row (a vertical line), one below the\n * other is a gap across the column (a horizontal line). Reading the drawn\n * boxes rather than the container's `flex-direction` alone covers a row that\n * wraps, a reversed row and a grid, each of which the computed layout has\n * already resolved into boxes.\n *\n * @module page-gaps\n */\n\nimport { findNode, type BlockDocument } from \"@nextlyhq/blocks-engine\";\n\nimport type { Rect } from \"../geometry\";\n\nimport { outermostElementsOf } from \"./canvas-addressing\";\nimport {\n  canvasContentRect,\n  clippedByAncestorRect,\n  drawnBoxes,\n  type OverlaySpace,\n} from \"./geometry-dom\";\nimport { unionRect } from \"./toolbar-actions\";\n\n/**\n * Which way a gap's line runs: `across` a column of blocks (one above the\n * other), or `down` a row of them (one beside the other).\n */\nexport type GapLine = \"across\" | \"down\";\n\n/** One gap a \"+\" is drawn in. */\nexport interface Gap {\n  /** The block before the gap, which a new block goes after. */\n  readonly after: string;\n  /** The block after it, or `undefined` for the gap after the last block. */\n  readonly before: string | undefined;\n  /** Which way the gap's line runs. */\n  readonly line: GapLine;\n  /** The gap's middle, in the chrome's coordinates. */\n  readonly x: number;\n  readonly y: number;\n  /** How long the line along the gap is drawn. */\n  readonly length: number;\n  /**\n   * How near the pointer must be to the line for the \"+\" to show: never more\n   * than a quarter of the shorter block beside it, so the middle of a block\n   * is never near a gap however short the block is drawn.\n   */\n  readonly reach: number;\n  /**\n   * Whether a \"+\" centred on the line leaves the middle of both blocks beside\n   * it uncovered: each is at least as deep as the \"+\" is.\n   */\n  readonly roomy: boolean;\n}\n\n/**\n * How near the pointer must be to a gap for its \"+\" to show, in the chrome's\n * pixels: less than half a short block's height, so the middle of a block\n * one line tall stays the block's to press.\n */\nconst NEAR_GAP_PX = 8;\n\n/** The \"+\"'s side on screen, in the chrome's pixels: the 24px target floor. */\nconst GAP_CONTROL_PX = 24;\n\n/**\n * How deep the blocks beside a gap are, across its line: their heights\n * beside a line across, their widths beside a line down.\n */\nfunction depthBeside(line: GapLine, rects: readonly Rect[]): number {\n  return Math.min(\n    ...rects.map(rect => (line === \"across\" ? rect.height : rect.width))\n  );\n}\n\n/** The reach and room of a gap between blocks this deep. */\nfunction clearance(depth: number): Pick<Gap, \"reach\" | \"roomy\"> {\n  return {\n    reach: Math.min(NEAR_GAP_PX, depth / 4),\n    roomy: depth >= GAP_CONTROL_PX,\n  };\n}\n\n/** A drawn block: its id and the union of the boxes it is drawn as. */\ninterface Drawn {\n  readonly id: string;\n  readonly rect: Rect;\n}\n\n/**\n * Each of `ids` that is drawn, in the order given, measured as the union of\n * every element drawn for it that generates a box.\n *\n * A component placement draws one element per top-level node of its\n * definition, so its first element alone would end it early and put the next\n * gap's \"+\" inside it; a block hidden on this device (`display: none`)\n * generates no box, and a gap measured from its empty rectangle would add a\n * \"+\" beside a block nobody can see. Outermost only, as the drag measures a\n * block, so an element nested inside the same placement is not counted twice.\n */\nfunction drawnOf(space: OverlaySpace, ids: readonly string[]): Drawn[] {\n  const { root } = space;\n  const parts = new Map<string, Rect[]>();\n  for (const [id, elements] of outermostElementsOf(root, new Set(ids))) {\n    parts.set(\n      id,\n      elements\n        .flatMap(drawnBoxes)\n        .map(drawn => space.place(canvasContentRect(drawn, root)))\n    );\n  }\n  return ids.flatMap(id => {\n    const rect = unionRect(parts.get(id) ?? []);\n    return rect === undefined ? [] : [{ id, rect }];\n  });\n}\n\n/**\n * Where the line between two boxes drawn beside each other runs, or\n * `undefined` where one is not beside the other. Either order, so a reversed\n * row reads as a row.\n */\nfunction edgeBetween(a: Rect, b: Rect): number | undefined {\n  const shareHeight = a.y < b.y + b.height && b.y < a.y + a.height;\n  if (!shareHeight) return undefined;\n  if (b.x >= a.x + a.width) return (a.x + a.width + b.x) / 2;\n  if (b.x + b.width <= a.x) return (b.x + b.width + a.x) / 2;\n  return undefined;\n}\n\n/**\n * Where the line between two boxes stacked one above the other runs: midway\n * between the edges that face each other, in either order, so a reversed\n * column reads as a column. Boxes that overlap meet at the first's bottom.\n */\nfunction facingMiddle(a: Rect, b: Rect): number {\n  if (a.y + a.height <= b.y) return (a.y + a.height + b.y) / 2;\n  if (b.y + b.height <= a.y) return (b.y + b.height + a.y) / 2;\n  return a.y + a.height;\n}\n\n/**\n * The gap between two blocks drawn one after the other, from their boxes:\n * down the line between them where one is beside the other, across it where\n * one is below the other. `span`, when given, is what a line across runs the\n * width of: the page, for its top-level blocks.\n */\nfunction gapBetween(above: Drawn, below: Drawn, span?: Rect): Gap {\n  const a = above.rect;\n  const b = below.rect;\n  const edge = edgeBetween(a, b);\n  if (edge !== undefined) {\n    const top = Math.min(a.y, b.y);\n    const bottom = Math.max(a.y + a.height, b.y + b.height);\n    return {\n      after: above.id,\n      before: below.id,\n      line: \"down\",\n      x: edge,\n      y: (top + bottom) / 2,\n      length: bottom - top,\n      ...clearance(depthBeside(\"down\", [a, b])),\n    };\n  }\n  const run = span ?? unionRect([a, b]) ?? a;\n  return {\n    after: above.id,\n    before: below.id,\n    line: \"across\",\n    x: run.x + run.width / 2,\n    y: facingMiddle(a, b),\n    length: run.width,\n    ...clearance(depthBeside(\"across\", [a, b])),\n  };\n}\n\n/** The gaps between consecutive drawn blocks. */\nfunction gapsAlong(drawn: readonly Drawn[], span?: Rect): Gap[] {\n  return drawn.slice(1).map((below, index) => {\n    // `index` is the block before `below`, as the slice starts one in.\n    const above = drawn[index];\n    return gapBetween(above, below, span);\n  });\n}\n\n/**\n * The gaps between the selected block's children, in each region it holds\n * blocks in: none when nothing is selected, or the selection holds fewer than\n * two drawn blocks in every region.\n */\nfunction childGaps(\n  space: OverlaySpace,\n  document: BlockDocument,\n  selectedId: string | null\n): Gap[] {\n  if (selectedId === null) return [];\n  const node = findNode(document.nodes, selectedId);\n  return Object.values(node?.slots ?? {}).flatMap(children =>\n    gapsAlong(\n      drawnOf(\n        space,\n        children\n          .map(child => child.id)\n          .filter(id => !clippedFromSight(space.root, id))\n      )\n    )\n  );\n}\n\n/**\n * Whether something the block is drawn inside cuts it: a fixed-height\n * container with its overflow hidden or scrolled. The \"+\" is drawn in the\n * chrome above the page, outside that clip, so a gap beside a child cut out\n * of sight would float over whatever the page shows there instead.\n */\nfunction clippedFromSight(root: HTMLElement, id: string): boolean {\n  const elements = outermostElementsOf(root, new Set([id])).get(id) ?? [];\n  return elements.some(element => clippedByAncestorRect(element, root));\n}\n\n/**\n * Every gap a \"+\" is drawn in, in the order a reader meets them: from the top\n * of the page down, then from the left.\n *\n * @param space - the chrome the controls are drawn in, over the canvas root\n * @param document - the page, whose top-level blocks the first gaps are between\n * @param selectedId - the selected block, whose children get gaps of their own\n */\nexport function measureGaps(\n  space: OverlaySpace,\n  document: BlockDocument,\n  selectedId: string | null\n): readonly Gap[] {\n  const { root } = space;\n  const page = space.place(canvasContentRect(root, root));\n  const top = drawnOf(\n    space,\n    document.nodes.map(node => node.id)\n  );\n  const last = top.at(-1);\n  // After the last top-level block, on its bottom edge: where the page's own\n  // blocks end, above a Layout's footer.\n  const end: Gap[] =\n    last === undefined\n      ? []\n      : [\n          {\n            after: last.id,\n            before: undefined,\n            line: \"across\",\n            x: page.x + page.width / 2,\n            y: last.rect.y + last.rect.height,\n            length: page.width,\n            ...clearance(last.rect.height),\n          },\n        ];\n  return [\n    ...gapsAlong(top, page),\n    ...end,\n    ...childGaps(space, document, selectedId),\n  ].sort(readingOrder);\n}\n\n/** From the top of the page down, then from the left. */\nfunction readingOrder(a: Gap, b: Gap): number {\n  return a.y - b.y || a.x - b.x;\n}\n\n/**\n * How far a point is from a gap's line, or `undefined` where it is past the\n * line's ends: beside a row's gap, not above or below the row.\n */\nfunction distanceTo(gap: Gap, x: number, y: number): number | undefined {\n  const [across, along] =\n    gap.line === \"across\" ? [y - gap.y, x - gap.x] : [x - gap.x, y - gap.y];\n  if (Math.abs(along) > gap.length / 2) return undefined;\n  return Math.abs(across);\n}\n\n/**\n * The gap the pointer is within reach of, by its key: the nearest, where it\n * is near two (a child's gap close to the page's).\n */\nexport function gapNear(\n  gaps: readonly Gap[],\n  x: number,\n  y: number\n): string | undefined {\n  let nearest: { key: string; distance: number } | undefined;\n  for (const gap of gaps) {\n    const distance = distanceTo(gap, x, y);\n    if (distance === undefined || distance > gap.reach) continue;\n    if (nearest === undefined || distance < nearest.distance) {\n      nearest = { key: gapKey(gap), distance };\n    }\n  }\n  return nearest?.key;\n}\n\n/** A gap's identity: the two blocks it is between. */\nexport function gapKey(gap: Gap): string {\n  // Encoded rather than joined: an id can hold any character, so a separator\n  // could make two different pairs read the same.\n  return JSON.stringify([gap.after, gap.before ?? null]);\n}\n\n/**\n * The first gap a reader meets below the top of `block`: the \"+\" Tab moves\n * to from that block. The one below it, or, for a selected block holding a\n * row, the first between its own children.\n */\nexport function gapAfter(gaps: readonly Gap[], block: Rect): Gap | undefined {\n  return gaps.find(gap => gap.y > block.y);\n}\n\n/**\n * The box a block is drawn as, in the chrome's coordinates, or `undefined`\n * where it is not drawn: measured as a gap's blocks are.\n */\nexport function blockRectOf(space: OverlaySpace, id: string): Rect | undefined {\n  return drawnOf(space, [id])[0]?.rect;\n}\n","/**\n * What the editor says about starting an empty document, and about adding in\n * a gap between blocks. The start area greets a page by its title and every\n * other kind of document with \"Add the first block\"; a gap's \"+\" names where\n * it adds. One source for the canvas's start area and gaps and for the\n * Getting started checklist, so the checklist names the control that is\n * there.\n *\n * @module page-start-words\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\n\n/** The start area's words, the same in every kind of document. */\nconst START_AREA = {\n  /** The primary button, after its \"＋\" icon. */\n  start: \"Add a block\",\n  /** The secondary button. */\n  savedSection: \"Insert a saved section\",\n  /** The line under the buttons. */\n  drag: \"or drag a block here\",\n  /** The heading over the row of starter pages, where there are any. */\n  starters: \"or start from a page\",\n  /** Under a starter page the site can't use, above the host's reason. */\n  notAvailable: \"Not available on this site\",\n} as const;\n\n/** What the start area of an empty document says. */\nexport interface StartWords {\n  readonly title: string;\n  readonly start: string;\n  readonly savedSection: string;\n  readonly drag: string;\n  readonly starters: string;\n  readonly notAvailable: string;\n}\n\n/**\n * The start area's heading: a page is greeted by its own title, every other\n * kind of document (a saved section, a component, a collection template) by\n * what an author does first. Asked as an own property, so a kind newer than\n * this editor, or one spelled like an object's inherited names\n * (`toString`), reads as a document of blocks too.\n */\nfunction titleOf(kind: BlockDocument[\"kind\"], pageTitle: string | undefined) {\n  const page = Object.hasOwn({ page: true }, kind);\n  if (!page) return \"Add the first block\";\n  const named = pageTitle?.trim();\n  return named === undefined || named === \"\"\n    ? \"Start building your page\"\n    : `Start building ${named}`;\n}\n\n/**\n * The words for an empty document of this kind.\n *\n * @param kind - the document's kind\n * @param pageTitle - a page's title, which its heading names\n */\nexport function startWords(\n  kind: BlockDocument[\"kind\"],\n  pageTitle?: string\n): StartWords {\n  return { ...START_AREA, title: titleOf(kind, pageTitle) };\n}\n\n/**\n * What a gap's \"+\" says, as its name and its tooltip: where the block it adds\n * goes. \"Add a block between Hero and Pricing\" between two blocks, and \"Add a\n * block after Contact\" after the last one, in every kind of document: the \"+\"\n * adds any block, so it names none.\n *\n * @param after - the name of the block before the gap\n * @param before - the name of the block after it, absent after the last\n */\nexport function gapWords(after: string, before?: string): string {\n  return before === undefined\n    ? `Add a block after ${after}`\n    : `Add a block between ${after} and ${before}`;\n}\n","\"use client\";\n\n/**\n * The start area of an empty document: drawn in the page's body, between the\n * Layout's header and footer, in the builder's own look and at the screen's\n * size whatever the zoom.\n *\n * It holds a heading (\"Start building About us\" on a page, \"Add the first\n * block\" elsewhere), a primary \"＋ Add a block\", a secondary \"Insert a saved\n * section\" where the host offers one, the line \"or drag a block here\", and a\n * row of starter pages under \"or start from a page\" when the host passes any.\n *\n * ## In the body, holding it open\n *\n * An empty page's body is as tall as nothing in it, so the footer sits right\n * under the header and a card centred on the screen lands over the footer.\n * The start area is placed near the top of the body instead, centred across\n * the page, and the body is held open for it in the editor alone: the canvas\n * root is given the area's height in the page's own pixels\n * (`--nx-canvas-start-room`), which the frame's sheet adds above the footer. The\n * published page has no such rule, so it draws nothing there.\n *\n * Like the rest of the canvas's add controls, this only REPORTS what was\n * pressed: the host opens the in-place picker, or the Add panel's saved\n * sections.\n *\n * @module page-start-area\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport { Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { Point } from \"../geometry\";\nimport { CANVAS_ROOT_CLASS } from \"../shell-state\";\n\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { REGION_ATTRIBUTE } from \"./canvas-regions\";\nimport {\n  canvasContentRect,\n  overlaySpaceOf,\n  type OverlaySpace,\n} from \"./geometry-dom\";\nimport { startWords } from \"./page-start-words\";\n\n/** A starter page an empty page can begin from, as the host lists it. */\nexport interface StarterPage {\n  readonly id: string;\n  readonly title: string;\n  /** A small picture of the page, drawn by the host. */\n  readonly picture?: React.ReactNode;\n  /**\n   * Why the site can't use this starter, in the host's words; absent for one\n   * it can. Such a starter is still listed, dimmed, so an author sees it and\n   * why rather than wondering where it went, but pressing it starts nothing.\n   */\n  readonly unavailable?: string | undefined;\n}\n\n/**\n * The room left above and below the start area inside the body, in the\n * chrome's pixels, so it sits near the top of the body and clear of the\n * footer.\n */\nconst START_ROOM_PX = 32;\n\n/** The custom property the frame's sheet holds the empty body open by. */\nconst START_ROOM_PROPERTY = \"--nx-canvas-start-room\";\n\n/** The Layout's header drawn on this canvas, or `null`. */\nfunction headerOf(root: HTMLElement): Element | null {\n  let found: Element | null = null;\n  root.querySelectorAll(`[${REGION_ATTRIBUTE}]`).forEach(region => {\n    if (found === null && region.getAttribute(REGION_ATTRIBUTE) === \"header\") {\n      found = region;\n    }\n  });\n  return found;\n}\n\n/**\n * Where the start area's top centre goes, in the chrome: centred across the\n * page, near the top of its body (under the header, or the page's top).\n */\nexport function startPlaceIn(space: OverlaySpace): Point {\n  const { root } = space;\n  const page = space.place(canvasContentRect(root, root));\n  const header = headerOf(root);\n  const top =\n    header === null\n      ? page.y\n      : (() => {\n          const box = space.place(canvasContentRect(header, root));\n          return box.y + box.height;\n        })();\n  return { x: page.x + page.width / 2, y: top + START_ROOM_PX };\n}\n\n/**\n * Holds the empty body open, in the editor only, by the start area's height\n * and its room in the page's own pixels; and lets go when the page has blocks\n * or the area is gone. Written only when it changes, since the write is a\n * change inside the canvas that every geometry watch hears.\n */\nfunction useBodyRoom(\n  area: React.RefObject<HTMLDivElement | null>,\n  shown: boolean\n): void {\n  const canvasFrame = useCanvasFrame();\n  const held = React.useRef<HTMLElement | null>(null);\n  React.useLayoutEffect(() => {\n    const element = area.current;\n    const root =\n      element === null\n        ? null\n        : (overlaySpaceOf(element, CANVAS_ROOT_CLASS)?.root ?? null);\n    // A root the area moved off of, a page loaded into the frame anew, is let\n    // go of as well.\n    if (held.current !== root) letGo(held.current);\n    held.current = root;\n    if (root === null || element === null) return;\n    if (!shown) {\n      letGo(root);\n      return;\n    }\n    const room = element.offsetHeight + START_ROOM_PX * 2;\n    const value = `${String(Math.ceil(room / canvasFrame.scale))}px`;\n    if (root.style.getPropertyValue(START_ROOM_PROPERTY) !== value) {\n      root.style.setProperty(START_ROOM_PROPERTY, value);\n    }\n  });\n  React.useEffect(() => () => letGo(held.current), []);\n}\n\n/** The body let go of, when it was held at all. */\nfunction letGo(root: HTMLElement | null): void {\n  if (\n    root !== null &&\n    root.style.getPropertyValue(START_ROOM_PROPERTY) !== \"\"\n  ) {\n    root.style.removeProperty(START_ROOM_PROPERTY);\n  }\n}\n\n/** What the start area is handed. */\ninterface StartAreaProps {\n  readonly document: BlockDocument;\n  /** The page's title, which a page's heading names. */\n  readonly title?: string | undefined;\n  /** Where its top centre goes, or `null` until measured. */\n  readonly place: Point | null;\n  /** A block is dragged over the canvas: the area is where it drops. */\n  readonly dragging: boolean;\n  /** \"＋ Add a block\" was pressed; `control` is the button. */\n  readonly onStart: (control: HTMLElement) => void;\n  /** \"Insert a saved section\" was pressed; absent, the button is too. */\n  readonly onSavedSection?: (() => void) | undefined;\n  /** Starter pages to begin from; absent or empty, no row is drawn. */\n  readonly starters?: readonly StarterPage[] | undefined;\n  /** A starter page was chosen. */\n  readonly onStarter?: ((id: string) => void) | undefined;\n}\n\n/** The row of starter pages, under its heading. */\nfunction StarterRow({\n  heading,\n  notAvailable,\n  starters,\n  onStarter,\n}: {\n  readonly heading: string;\n  /** What a starter the site can't use says above its reason. */\n  readonly notAvailable: string;\n  readonly starters: readonly StarterPage[];\n  readonly onStarter: ((id: string) => void) | undefined;\n}): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <div className=\"nx-page-start__starters\">\n      <p className=\"nx-page-start__line\">{heading}</p>\n      <ul className=\"nx-page-start__tiles\">\n        {starters.map((starter, index) => (\n          <li key={starter.id}>\n            <StarterTile\n              id={`${id}-${String(index)}`}\n              starter={starter}\n              notAvailable={notAvailable}\n              onStarter={onStarter}\n            />\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\n/**\n * One starter's tile: its picture and title, pressed to start the page from\n * it. A starter the site can't use is dimmed and says so, with the host's\n * reason, on a panel over its picture, so its tile is as tall as the others\n * and the reason is still there to read; pressing it does nothing. It stays\n * a focusable button (`aria-disabled`, not `disabled`) so a keyboard user can\n * reach it and hear why; its name is its title alone, and the note and\n * reason describe it.\n */\nfunction StarterTile({\n  id,\n  starter,\n  notAvailable,\n  onStarter,\n}: {\n  /** A prefix unique on the page, for the ids its words are read by. */\n  readonly id: string;\n  readonly starter: StarterPage;\n  readonly notAvailable: string;\n  readonly onStarter: ((id: string) => void) | undefined;\n}): React.JSX.Element {\n  const reason = starter.unavailable;\n  if (reason === undefined) {\n    return (\n      <button\n        type=\"button\"\n        className=\"nx-page-start__tile\"\n        // Named by its title alone: a picture of a page draws words of its\n        // own (a form's labels, a heading), which would otherwise run into\n        // the name before the title.\n        aria-labelledby={`${id}-title`}\n        onClick={() => onStarter?.(starter.id)}\n      >\n        {starter.picture}\n        <span id={`${id}-title`}>{starter.title}</span>\n      </button>\n    );\n  }\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-page-start__tile\"\n      aria-disabled=\"true\"\n      aria-labelledby={`${id}-title`}\n      aria-describedby={`${id}-note ${id}-reason`}\n      // Reported to nobody: the site can't hold this starter, so there is\n      // nothing for the host to start.\n      onClick={event => event.preventDefault()}\n    >\n      {/* The picture's box holds the dimmed picture and, over it, the words\n        that say why: the tile stays a picture and a title, as tall as the\n        others, and the words keep their contrast on their own panel. */}\n      <span className=\"nx-page-start__tile-picture\">\n        <span className=\"nx-page-start__tile-thumb\">{starter.picture}</span>\n        <span className=\"nx-page-start__tile-why\">\n          <span id={`${id}-note`} className=\"nx-page-start__tile-note\">\n            {notAvailable}\n          </span>\n          <span id={`${id}-reason`} className=\"nx-page-start__tile-reason\">\n            {reason}\n          </span>\n        </span>\n      </span>\n      <span id={`${id}-title`}>{starter.title}</span>\n    </button>\n  );\n}\n\n/**\n * The start area.\n *\n * @experimental\n */\nexport function StartArea({\n  document,\n  title,\n  place,\n  dragging,\n  onStart,\n  onSavedSection,\n  starters = [],\n  onStarter,\n}: StartAreaProps): React.JSX.Element {\n  const area = React.useRef<HTMLDivElement | null>(null);\n  useBodyRoom(area, place !== null);\n  const words = startWords(document.kind, title);\n  return (\n    <div\n      ref={area}\n      className=\"nx-page-start\"\n      // While a block is dragged, the area is where it drops: drawn as the\n      // target, and taking no pointer so the drag reaches the page.\n      data-drop-target={dragging ? \"\" : undefined}\n      // Kept out of sight until it has been placed, rather than drawn at the\n      // layer's corner for a frame.\n      style={\n        place === null\n          ? { visibility: \"hidden\" }\n          : { left: place.x, top: place.y }\n      }\n    >\n      <p className=\"nx-page-start__title\" role=\"heading\" aria-level={2}>\n        {words.title}\n      </p>\n      <div className=\"nx-page-start__actions\">\n        <button\n          type=\"button\"\n          className=\"nx-page-start__add\"\n          onClick={event => onStart(event.currentTarget)}\n        >\n          <Plus size={16} aria-hidden=\"true\" />\n          {words.start}\n        </button>\n        {onSavedSection === undefined ? null : (\n          <button\n            type=\"button\"\n            className=\"nx-page-start__saved\"\n            onClick={onSavedSection}\n          >\n            {words.savedSection}\n          </button>\n        )}\n      </div>\n      <p className=\"nx-page-start__line\">{words.drag}</p>\n      {starters.length === 0 ? null : (\n        <StarterRow\n          heading={words.starters}\n          notAvailable={words.notAvailable}\n          starters={starters}\n          onStarter={onStarter}\n        />\n      )}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The controls that add a block to the page itself: the start area on an\n * empty page (`page-start-area.tsx`), and a \"+\" in each gap between blocks.\n *\n * An empty page used to be a blank frame with nothing on it to press, and a\n * block could only be added after the selected one, by opening Add first.\n * These put the control where the block will go.\n *\n * ## Where the \"+\" controls are\n *\n * In each gap between two top-level blocks, after the last top-level block\n * (above a Layout's footer), and between the children of the selected block,\n * in the direction they are laid out: a vertical gap between two Boxes in a\n * row. `page-gaps.ts` measures them. Each is drawn floating over its gap as\n * chrome, so showing one never moves, resizes or reflows the page.\n *\n * Like the empty-container appenders beside it, this only REPORTS: pressing\n * the start area's \"＋ Add a block\" calls {@link PageInsertersProps.onStart},\n * and pressing a \"+\"\n * calls {@link PageInsertersProps.onAddAfter} with the block before its gap\n * and the control itself, which the host opens the in-place picker beside,\n * aimed at exactly that gap. Nothing is selected on the way.\n *\n * ## When the \"+\" shows\n *\n * At rest a gap's \"+\" is not drawn, and takes no pointer events: a row of\n * buttons down the page would sit on every block's edge, and an unseen one\n * would take the press an author meant for a short block beside the gap. It\n * shows, and takes the pointer, only while the pointer is within the gap's\n * reach of its line, on the canvas or on the \"+\" itself, and while it has\n * keyboard focus. Nearness is measured rather than read from the hovered\n * block: a short block's middle is as close to its edge as a \"+\" is tall, so\n * \"the pointer is in the block beside it\" would put the \"+\" under a press\n * meant for that block.\n *\n * ## Never over a short block's middle\n *\n * The \"+\" is 24px on screen, so centred on the line between two blocks drawn\n * shorter than that (a line of text at a zoomed-out canvas) it covers their\n * middles. The reach is therefore at most a quarter of the shorter block,\n * and it holds on the \"+\" too: moving from the line towards a block's middle\n * lets the \"+\" go before the pointer gets there, so the press lands on the\n * block. A touch screen, which has no pointer to come near, keeps a \"+\"\n * shown only where both blocks beside it are at least as deep as the \"+\".\n * Nothing shows while a block is dragged: the drag's own line says where it\n * will land.\n *\n * ## The keyboard\n *\n * Every \"+\" is a Tab stop, in reading order. Tab on the canvas with a block\n * selected moves to the \"+\" below that block, so the next stop after a block\n * is the gap after it; from there Tab and Shift+Tab move through the others.\n *\n * @module page-inserters\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport { TooltipProvider } from \"@nextlyhq/ui\";\nimport { Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../chrome-tooltip\";\nimport type { Point } from \"../geometry\";\nimport { blockNameOf, type ComponentTitleOf } from \"../panels/layers/layers\";\n\nimport { CANVAS_ROOT_CLASS, CHROME_ATTRIBUTE } from \"./canvas\";\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport { watchCanvasFor } from \"./canvas-geometry-watch\";\nimport { isElement } from \"./dom-kind\";\nimport {\n  boxInFrameViewport,\n  canvasContentPoint,\n  overlaySpaceOf,\n} from \"./geometry-dom\";\nimport {\n  blockRectOf,\n  gapAfter,\n  gapKey,\n  gapNear,\n  measureGaps,\n  type Gap,\n} from \"./page-gaps\";\nimport { StartArea, startPlaceIn, type StarterPage } from \"./page-start-area\";\nimport { gapWords } from \"./page-start-words\";\n\n/**\n * What an empty page's start area says and reports.\n *\n * @experimental\n */\nexport interface StartOptions {\n  /** The page's title, which a page's start area is headed with. */\n  readonly title?: string;\n  /** \"＋ Add a block\" was pressed; `control` is the button. */\n  readonly onStart: (control: HTMLElement) => void;\n  /**\n   * \"Insert a saved section\" was pressed. Absent where a saved section cannot\n   * be inserted, and so is the button.\n   */\n  readonly onSavedSection?: () => void;\n  /** Starter pages an empty page can begin from; none, no row. */\n  readonly starters?: readonly StarterPage[];\n  /** A starter page was chosen. */\n  readonly onStarter?: (id: string) => void;\n}\n\n/** @experimental */\nexport interface PageInsertersProps {\n  /** The page whose blocks the controls sit between. */\n  readonly document: BlockDocument;\n  /**\n   * The selected block, whose children get a \"+\" between them too, and from\n   * which Tab moves to the \"+\" below it. `null` or absent for none.\n   */\n  readonly selectedId?: string | null;\n  /**\n   * Draws nothing: while a block is dragged, and wherever the host offers no\n   * adding at all.\n   */\n  readonly hidden?: boolean;\n  /**\n   * A block is dragged over the canvas: no \"+\" shows, and an empty page's\n   * start area is drawn as where it drops.\n   */\n  readonly dragging?: boolean;\n  /** What an empty page's start area says and reports. */\n  readonly start: StartOptions;\n  /**\n   * A gap's \"+\" was pressed: add a block in that gap, after `nodeId`, beside\n   * it. `control` is the \"+\" pressed, for the host to open its picker beside.\n   */\n  readonly onAddAfter: (nodeId: string, control: HTMLElement) => void;\n  /**\n   * Names a component by its library title, as Layers does, so the \"+\" after a\n   * placement names the component rather than \"Component\".\n   */\n  readonly componentTitle?: ComponentTitleOf;\n}\n\n/** Where the start area goes on an empty page, or `null` outside a canvas. */\nfunction measureStart(layer: HTMLElement): Point | null {\n  const space = overlaySpaceOf(layer, CANVAS_ROOT_CLASS);\n  return space === null ? null : startPlaceIn(space);\n}\n\n/** The gaps measured in `layer`'s chrome, or none outside a canvas. */\nfunction gapsIn(\n  layer: HTMLElement | null,\n  document: BlockDocument,\n  selectedId: string | null\n): readonly Gap[] {\n  const space =\n    layer === null ? null : overlaySpaceOf(layer, CANVAS_ROOT_CLASS);\n  return space === null ? [] : measureGaps(space, document, selectedId);\n}\n\n/** What the gaps and the start area are measured from, and what moves them. */\ninterface Measured {\n  readonly gaps: readonly Gap[];\n  readonly start: Point | null;\n}\n\nconst NOTHING_MEASURED: Measured = { gaps: [], start: null };\n\n/**\n * The gaps, or the start area's place on an empty page, measured now and\n * again on everything that moves the canvas: a change inside it, a resize and\n * a zoom.\n */\nfunction useMeasured(\n  layer: React.RefObject<HTMLDivElement | null>,\n  document: BlockDocument,\n  selectedId: string | null,\n  hidden: boolean\n): Measured {\n  const [measured, setMeasured] = React.useState<Measured>(NOTHING_MEASURED);\n  const canvasFrame = useCanvasFrame();\n  const empty = document.nodes.length === 0;\n  const measure = React.useCallback(() => {\n    const element = layer.current;\n    setMeasured({\n      gaps: empty ? [] : gapsIn(element, document, selectedId),\n      start: element === null || !empty ? null : measureStart(element),\n    });\n  }, [layer, document, selectedId, empty]);\n\n  React.useLayoutEffect(() => {\n    if (!hidden) measure();\n  }, [measure, hidden, canvasFrame]);\n\n  React.useEffect(() => {\n    if (hidden) return;\n    return watchCanvasFor(() => layer.current, measure);\n  }, [layer, measure, hidden, canvasFrame]);\n\n  return measured;\n}\n\n/** The gap the pointer is near, by its key, from its moves over the canvas. */\nfunction useNearGap(\n  layer: React.RefObject<HTMLDivElement | null>,\n  gaps: readonly Gap[],\n  hidden: boolean\n): readonly [string | undefined, (key: string | undefined) => void] {\n  const [near, setNear] = React.useState<string | undefined>(undefined);\n  const canvasFrame = useCanvasFrame();\n  React.useEffect(() => {\n    const element = layer.current;\n    const space =\n      element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n    if (hidden || gaps.length === 0 || space === null) return;\n    const { root } = space;\n    const move = (event: PointerEvent): void => {\n      const point = canvasContentPoint(event.clientX, event.clientY, root);\n      const placed = space.place({ ...point, width: 0, height: 0 });\n      setNear(gapNear(gaps, placed.x, placed.y));\n    };\n    const leave = (): void => setNear(undefined);\n    root.addEventListener(\"pointermove\", move);\n    root.addEventListener(\"pointerleave\", leave);\n    return () => {\n      root.removeEventListener(\"pointermove\", move);\n      root.removeEventListener(\"pointerleave\", leave);\n    };\n  }, [layer, gaps, hidden, canvasFrame]);\n  return [near, setNear];\n}\n\n/**\n * Whether a Tab pressed here is a Tab on the canvas itself: the page's own\n * document focused, rather than a control on the page or text being typed.\n */\nfunction tabOnCanvas(event: KeyboardEvent, page: Document): boolean {\n  if (event.key !== \"Tab\" || event.defaultPrevented) return false;\n  if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {\n    return false;\n  }\n  const target = event.target;\n  return (\n    isElement(target) &&\n    (target === page.body || target === page.documentElement)\n  );\n}\n\n/**\n * Tab on the canvas with a block selected moves to the \"+\" below it, rather\n * than to whichever chrome comes first after the frame. Only in a frame: the\n * keys of an editor sharing the page's document are the editor's own.\n */\nfunction useTabToGap(\n  layer: React.RefObject<HTMLDivElement | null>,\n  gaps: readonly Gap[],\n  selectedId: string | null\n): void {\n  const canvasFrame = useCanvasFrame();\n  const page = canvasFrame.frame === null ? null : canvasFrame.document;\n  React.useEffect(() => {\n    if (page === null || selectedId === null || gaps.length === 0) return;\n    const keydown = (event: KeyboardEvent): void => {\n      const element = layer.current;\n      const space =\n        element === null ? null : overlaySpaceOf(element, CANVAS_ROOT_CLASS);\n      if (space === null || !tabOnCanvas(event, page)) return;\n      const block = blockRectOf(space, selectedId);\n      const gap = block === undefined ? undefined : gapAfter(gaps, block);\n      const control = gap === undefined ? null : controlOf(element, gap);\n      if (control === null) return;\n      event.preventDefault();\n      control.focus({ preventScroll: true });\n    };\n    page.addEventListener(\"keydown\", keydown);\n    return () => page.removeEventListener(\"keydown\", keydown);\n  }, [layer, page, gaps, selectedId]);\n}\n\n/** The attribute a \"+\" carries its gap's key in, so Tab can find it. */\nconst GAP_ATTRIBUTE = \"data-nx-gap\";\n\n/** The \"+\" drawn for a gap, in this layer. */\nfunction controlOf(layer: HTMLElement | null, gap: Gap): HTMLElement | null {\n  const key = gapKey(gap);\n  let found: HTMLElement | null = null;\n  layer?.querySelectorAll<HTMLElement>(`[${GAP_ATTRIBUTE}]`).forEach(button => {\n    if (found === null && button.getAttribute(GAP_ATTRIBUTE) === key) {\n      found = button;\n    }\n  });\n  return found;\n}\n\n/** One gap's \"+\", floating over the gap, with the line it adds on. */\nfunction GapControl({\n  gap,\n  words,\n  shown,\n  onHold,\n  onAddAfter,\n}: {\n  readonly gap: Gap;\n  readonly words: string;\n  readonly shown: boolean;\n  readonly onHold: (key: string | undefined) => void;\n  readonly onAddAfter: PageInsertersProps[\"onAddAfter\"];\n}): React.JSX.Element {\n  const key = gapKey(gap);\n  const across = gap.line === \"across\";\n  // Held only while the pointer on the \"+\" is within the gap's reach of its\n  // line, which runs through the \"+\"'s middle: further, towards a block's\n  // middle, the \"+\" lets go so a press there is the block's.\n  //\n  // Let go at once, too, not on the next render: a press can follow the move\n  // that left the reach before React draws again, and it must reach the\n  // block under the \"+\" rather than the \"+\". Taken back once the \"+\" shows\n  // again.\n  const button = React.useRef<HTMLButtonElement | null>(null);\n  // On every render that shows it, since a let-go and a fresh show can land\n  // in one render, which leaves `shown` as it was.\n  React.useLayoutEffect(() => {\n    if (shown && button.current !== null) {\n      button.current.style.pointerEvents = \"\";\n    }\n  });\n  const hold = (event: React.PointerEvent<HTMLButtonElement>): void => {\n    // A finger has no hover to come near with: a touch screen keeps a roomy\n    // \"+\" shown and pressable all over, and the stylesheet decides which.\n    if (event.nativeEvent.pointerType === \"touch\") return;\n    const target = event.currentTarget;\n    // Both in the editor window's coordinates, which the chrome is drawn at.\n    const box = boxInFrameViewport(target);\n    const off = across\n      ? event.clientY - (box.y + box.height / 2)\n      : event.clientX - (box.x + box.width / 2);\n    const inReach = Math.abs(off) <= gap.reach;\n    if (!inReach) target.style.pointerEvents = \"none\";\n    onHold(inReach ? key : undefined);\n  };\n  return (\n    <div\n      className=\"nx-page-inserters__gap\"\n      data-line={gap.line}\n      data-near={shown ? \"\" : undefined}\n      data-roomy={gap.roomy ? \"\" : undefined}\n      style={\n        across\n          ? { left: gap.x - gap.length / 2, top: gap.y, width: gap.length }\n          : { left: gap.x, top: gap.y - gap.length / 2, height: gap.length }\n      }\n    >\n      <span className=\"nx-page-inserters__line\" aria-hidden=\"true\" />\n      <ChromeTooltip content={words} side={across ? \"top\" : \"right\"}>\n        <button\n          ref={button}\n          type=\"button\"\n          className=\"nx-page-inserters__add\"\n          aria-label={words}\n          {...{ [GAP_ATTRIBUTE]: key }}\n          onClick={event => onAddAfter(gap.after, event.currentTarget)}\n          onPointerEnter={hold}\n          onPointerMove={hold}\n          onPointerLeave={() => onHold(undefined)}\n        >\n          <Plus size={14} aria-hidden=\"true\" />\n        </button>\n      </ChromeTooltip>\n    </div>\n  );\n}\n\n/**\n * The start area on an empty page and the \"+\" in the gaps between blocks.\n *\n * @experimental\n */\nexport function PageInserters({\n  document,\n  selectedId = null,\n  hidden = false,\n  dragging = false,\n  start,\n  onAddAfter,\n  componentTitle,\n}: PageInsertersProps): React.JSX.Element | null {\n  const layer = React.useRef<HTMLDivElement | null>(null);\n  const empty = document.nodes.length === 0;\n  // While a block is dragged no \"+\" shows: the drag's own line says where it\n  // lands. An empty page's start area stays, as where it drops.\n  const noGaps = hidden || dragging;\n  const measured = useMeasured(layer, document, selectedId, hidden);\n  const gaps = noGaps ? NO_GAPS : measured.gaps;\n  const [near, setNear] = useNearGap(layer, gaps, noGaps);\n  useTabToGap(layer, gaps, selectedId);\n  // The gap whose \"+\" the pointer is on: a pointer moving onto the \"+\"\n  // leaves the canvas's frame, which then reports no further move, so the\n  // \"+\" holds itself shown while it is pointed at.\n  const [held, setHeld] = React.useState<string | undefined>(undefined);\n  // Let go on the \"+\" is let go everywhere: the frame under it may not have\n  // heard the pointer leave, and a \"+\" still shown would take the press.\n  const hold = React.useCallback(\n    (key: string | undefined) => {\n      setHeld(key);\n      if (key === undefined) setNear(undefined);\n    },\n    [setNear]\n  );\n  const nameOf = (id: string): string =>\n    blockNameOf(document, id, componentTitle) ?? \"this block\";\n\n  if (hidden) return null;\n\n  return (\n    <TooltipProvider delayDuration={300}>\n      <div\n        ref={layer}\n        className=\"nx-page-inserters\"\n        data-empty={empty ? \"\" : undefined}\n        // Chrome, so a press here is not read as a click on the page, which\n        // would clear the selection.\n        {...{ [CHROME_ATTRIBUTE]: \"\" }}\n      >\n        {empty ? (\n          <StartArea\n            document={document}\n            place={measured.start}\n            dragging={dragging}\n            {...start}\n          />\n        ) : (\n          gaps.map(gap => (\n            <GapControl\n              key={gapKey(gap)}\n              gap={gap}\n              words={gapWords(\n                nameOf(gap.after),\n                gap.before === undefined ? undefined : nameOf(gap.before)\n              )}\n              shown={near === gapKey(gap) || held === gapKey(gap)}\n              onHold={hold}\n              onAddAfter={onAddAfter}\n            />\n          ))\n        )}\n      </div>\n    </TooltipProvider>\n  );\n}\n\n/** No gaps, the one value, so a drag's render changes no gap watcher. */\nconst NO_GAPS: readonly Gap[] = [];\n","/**\n * Starting an empty page from a starter page's blocks, inside the builder:\n * the start area's \"or start from a page\" row.\n *\n * Through the existing ops, as every edit is: the engine's paste planner\n * makes a fresh-id copy of the starter's blocks (the copy a paste makes, with\n * no record of a saved section it did not come from), and the editor's\n * `applyAll` commits the whole copy as ONE step, so a single Undo empties the\n * page again. Nothing links the page back to the starter: a later change to\n * the starter never reaches it.\n *\n * Only an empty page is started this way. The row is drawn on an empty page\n * alone, and a page that gained a block meanwhile is left as it is rather\n * than having the starter's blocks put beside its own.\n *\n * @module starter-page\n */\nimport {\n  planPasteBlocks,\n  registryNestingSource,\n  type BlockDocument,\n  type BlockNode,\n  type BuilderOp,\n  type ComponentLookup,\n  type NestingSource,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { EditorState } from \"../editor-state\";\n\n/** What the copy is judged by: the site's nesting rules, and its components. */\nexport interface StarterPageSources {\n  readonly nesting?: NestingSource;\n  readonly components?: ComponentLookup;\n}\n\n/**\n * The ops that start `document` from `blocks`, or `undefined` where the page\n * is not empty or the planner refuses the copy.\n *\n * @experimental\n */\nexport function planStarterPage(\n  document: BlockDocument,\n  blocks: readonly BlockNode[],\n  sources: StarterPageSources = {}\n): readonly BuilderOp[] | undefined {\n  if (document.nodes.length > 0) return undefined;\n  const plan = planPasteBlocks(\n    document,\n    blocks,\n    { index: 0 },\n    sources.nesting ?? registryNestingSource(),\n    sources.components\n  );\n  return plan.pageOps;\n}\n\n/**\n * Start the editor's empty page from `blocks`, as one undo step. Returns\n * whether it was started; nothing changes when it was not.\n *\n * @experimental\n */\nexport function applyStarterPage(\n  editor: Pick<EditorState, \"document\" | \"applyAll\">,\n  blocks: readonly BlockNode[],\n  sources: StarterPageSources = {}\n): boolean {\n  const ops = planStarterPage(editor.document, blocks, sources);\n  if (ops === undefined || ops.length === 0) return false;\n  return editor.applyAll(ops) !== null;\n}\n","/**\n * A passage the canvas edits in place, wherever it is stored: a node's own\n * rich text, or a component placement's exposed one, which the canvas shows\n * on a composed node the page document does not hold and which is stored on\n * the placement under its exposure.\n *\n * The rich surface asks three questions of a passage — what it holds now,\n * whether it changed while the editor was open, and what writing an edit\n * means — and the answers differ only by where it lives. Each is answered\n * here once, from the address, so the surface keeps one path.\n *\n * @module rich-passage\n */\nimport type { BlockDocument, SlotDefaultSource } from \"@nextlyhq/blocks-engine\";\n\nimport type { BuilderOp } from \"../op-vocabulary\";\n\nimport {\n  exposedPassage,\n  exposedRichOp,\n  type ExposedRichTarget,\n} from \"./exposed-inline\";\nimport {\n  richInlineTarget,\n  richInlineTextOp,\n  richTextChanged,\n  richTextMovedOn,\n  type InlineRichTextTarget,\n} from \"./inline-rich-text\";\n\n/** Where a passage being edited lives. */\nexport interface RichPassageAddress {\n  /** The node the element belongs to: the page's, or a composed one. */\n  readonly nodeId: string;\n  readonly prop: string;\n  /**\n   * The placement and exposure the passage is stored under, when it is a\n   * component's exposed passage; absent for a node's own.\n   */\n  readonly exposure?: Pick<ExposedRichTarget, \"placementId\" | \"exposureId\">;\n}\n\n/** What the questions read: the page, its composition, and the lock rules. */\nexport interface RichPassageEditor {\n  readonly document: BlockDocument;\n  readonly composed?: () => BlockDocument | undefined;\n  readonly lockDefinitions?: SlotDefaultSource;\n}\n\n/** The exposed target an address names, when it names one. */\nfunction exposedTarget(\n  address: RichPassageAddress\n): ExposedRichTarget | undefined {\n  return address.exposure === undefined\n    ? undefined\n    : {\n        nodeId: address.nodeId,\n        prop: address.prop,\n        placementId: address.exposure.placementId,\n        exposureId: address.exposure.exposureId,\n      };\n}\n\n/** The passage as it stands now, or `null` once it is not editable in place. */\nexport function passageNow(\n  editor: RichPassageEditor,\n  address: RichPassageAddress\n): InlineRichTextTarget | null {\n  const exposed = exposedTarget(address);\n  if (exposed === undefined) {\n    return richInlineTarget(editor.document, address.nodeId, address.prop);\n  }\n  const now = exposedPassage(\n    editor.document,\n    editor.composed?.(),\n    exposed,\n    editor.lockDefinitions\n  );\n  return now === null\n    ? null\n    : { nodeId: address.nodeId, prop: address.prop, ...now };\n}\n\n/** Whether the stored passage changed since the editor opened it. */\nexport function passageMovedOn(\n  editor: RichPassageEditor,\n  address: RichPassageAddress,\n  opened: unknown\n): boolean {\n  if (address.exposure === undefined) {\n    return richTextMovedOn(\n      editor.document,\n      address.nodeId,\n      address.prop,\n      opened\n    );\n  }\n  // As the node's own: one no longer editable is the write's to refuse.\n  const now = passageNow(editor, address);\n  return now !== null && richTextChanged(opened, now.stored);\n}\n\n/** The op a finished edit writes, or `null` when there is nothing to write. */\nexport function passageOp(\n  editor: RichPassageEditor,\n  address: RichPassageAddress,\n  next: unknown,\n  before: unknown,\n  opened: unknown\n): BuilderOp | null {\n  const exposed = exposedTarget(address);\n  return exposed === undefined\n    ? richInlineTextOp(\n        editor.document,\n        address.nodeId,\n        address.prop,\n        next,\n        before,\n        opened\n      )\n    : exposedRichOp(\n        editor.document,\n        editor.composed?.(),\n        exposed,\n        next,\n        before,\n        opened,\n        editor.lockDefinitions\n      );\n}\n\n/**\n * The block whose selection keeps the passage open: the node itself, or, for\n * an exposed passage, its placement, which is what a click on a component\n * selects.\n */\nexport function passageKeptBy(address: RichPassageAddress): string {\n  return address.exposure?.placementId ?? address.nodeId;\n}\n","/**\n * The format bar's \"Turn into\", for the block whose words are being edited:\n * what the editor's verbs (`BlockActions.turnIntoIn`) need from the passage.\n *\n * The choices are judged on the page as it would stand with the words typed\n * so far, so what a choice says it removes is about those words. Choosing one\n * finishes the edit first, then turns the block in the page the edit wrote:\n * the words typed are what is turned, and the turn is its own undo step after\n * the edit's.\n *\n * Not offered for a component's exposed words, which are a placement's value\n * rather than a block of their own, nor for a block that turns into nothing.\n *\n * @module format-turn-into\n */\n\nimport {\n  applyOp,\n  findNode,\n  turnIntoTargets,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { EditorState } from \"../editor-state\";\n\nimport type { FormatTurnInto } from \"./format-bar-state\";\nimport type { InlineEditOutcome } from \"./inline-edit-outcome\";\nimport { passageOp, type RichPassageAddress } from \"./rich-passage\";\n\n/** The passage being edited, as the turn reads it. */\nexport interface TypedPassage {\n  readonly editing: RichPassageAddress;\n  /** The words as typed so far. */\n  readonly words: unknown;\n  readonly baseline: unknown;\n  readonly opened: unknown;\n}\n\n/** What the format bar's \"Turn into\" is built from. */\nexport interface FormatTurnIntoSource {\n  readonly editing: RichPassageAddress;\n  /** The editor as it stands now. */\n  readonly editor: () => EditorState;\n  /** The passage as typed so far, or `null` once it is no longer open. */\n  readonly typed: () => TypedPassage | null;\n  /** Finish the edit, writing the words, as leaving the passage does. */\n  readonly commit: () => InlineEditOutcome;\n}\n\n/** The page as it would stand with the words typed so far written. */\nfunction pageAsTyped(editor: EditorState, typed: TypedPassage | null) {\n  if (typed === null) return editor.document;\n  const op = passageOp(\n    editor,\n    typed.editing,\n    typed.words,\n    typed.baseline,\n    typed.opened\n  );\n  if (op === null) return editor.document;\n  try {\n    // Judged by the editor's own limits, as writing the words will be.\n    return applyOp(editor.document, op, editor.limits).document;\n  } catch {\n    return editor.document;\n  }\n}\n\n/** The page a finished edit left, or `null` when it was not finished. */\nfunction pageAfter(\n  outcome: InlineEditOutcome,\n  editor: EditorState\n): BlockDocument | null {\n  if (outcome.status === \"written\") return outcome.document;\n  if (outcome.status === \"unchanged\") return editor.document;\n  return null;\n}\n\n/** The format bar's \"Turn into\" for a passage, or nothing where none. */\nexport function formatTurnInto(\n  source: FormatTurnIntoSource\n): FormatTurnInto | undefined {\n  const { editing } = source;\n  if (editing.exposure !== undefined) return undefined;\n  const node = findNode(source.editor().document.nodes, editing.nodeId);\n  if (node === undefined || turnIntoTargets(node.type).length === 0) {\n    return undefined;\n  }\n  return {\n    nodeId: editing.nodeId,\n    typedPage: () => pageAsTyped(source.editor(), source.typed()),\n    finish: () => pageAfter(source.commit(), source.editor()),\n  };\n}\n","\"use client\";\n\n/**\n * Editing a block's passage directly on the canvas.\n *\n * The DOM half of {@link module:inline-rich-text}, which decides WHAT may be\n * edited; this decides how. The split is the same one the plain-text pair\n * makes, and earns its keep the same way: the rules are asserted without a\n * browser, and the part that genuinely needs one stays small enough to read.\n *\n * ## ONE editor, moved between passages\n *\n * The editor is not built here. It is loaded from the admin facade, which hands\n * over four operations rather than Lexical itself — because building an editor\n * means importing Lexical, and a second copy of Lexical anywhere produces nodes\n * that fail their own `instanceof` checks, with content saving and reading back\n * as plain text on documents that already saved.\n *\n * It is loaded on FIRST EDIT rather than on mount. The node classes carry a\n * 630KB chunk, and an author who never edits a passage should never fetch it.\n *\n * ## The subtree is given back exactly as it was found\n *\n * React renders the passage from the document; the editor then owns that DOM\n * for the duration and rewrites it as the author types. When the edit ends,\n * React's picture of the subtree is whatever it last rendered, and the real DOM\n * is whatever the editor left — so a later render would diff against a tree\n * that is no longer there and patch around the editor's nodes.\n *\n * So the markup is snapshotted before the handover and restored after it, on\n * EVERY exit rather than only on cancel. That puts the DOM back in agreement\n * with React, and a committed edit then re-renders from the document the\n * ordinary way, because the op changed it.\n *\n * @module use-inline-rich-text\n */\n\nimport { toOneParagraph } from \"@nextlyhq/blocks-engine\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\n\nimport { useCanvasFrame } from \"./canvas-frame-context\";\nimport {\n  formatBar,\n  RICH_TEXT_FORMAT_ACTIONS,\n  TEXT_FORMAT_ACTIONS,\n  type FormatAction,\n  type FormatBlockAction,\n  type FormatSelection,\n  type FormatSession,\n  type FormatTurnInto,\n} from \"./format-bar-state\";\nimport { formatTurnInto } from \"./format-turn-into\";\nimport {\n  INLINE_EDIT_DISCARDED,\n  INLINE_EDIT_UNAVAILABLE,\n  INLINE_EDIT_UNCHANGED,\n  type InlineEditOutcome,\n} from \"./inline-edit-outcome\";\nimport { richInlineTargets, richTextChanged } from \"./inline-rich-text\";\nimport { namedTarget } from \"./inline-target\";\nimport {\n  passageKeptBy,\n  passageMovedOn,\n  passageNow,\n  passageOp,\n  type RichPassageAddress,\n} from \"./rich-passage\";\nimport { editableElement, EDITING_ATTRIBUTE } from \"./use-inline-text\";\n\n/** What a pointer handed over with a `begin`: the element, and where it fell. */\ninterface Handover {\n  readonly element: HTMLElement | null;\n  readonly point: CaretPoint | null;\n}\n\nconst NO_HANDOVER: Handover = { element: null, point: null };\n\n/**\n * The passage's element in the document the canvas is drawn in, or `null`\n * when there is no document to search, as in a server render.\n */\nfunction passageIn(\n  doc: Document | null,\n  editing: InlineRichTextEditing\n): HTMLElement | null {\n  return doc === null\n    ? null\n    : editableElement(doc, { nodeId: editing.nodeId, prop: editing.prop });\n}\n\n/** Where a point falls in a document's text, however this engine spells it. */\ninterface CaretLocator {\n  /** WebKit and Chromium. */\n  caretRangeFromPoint?: (x: number, y: number) => Range | null;\n  /** The standard spelling, which Firefox implements. */\n  caretPositionFromPoint?: (\n    x: number,\n    y: number\n  ) => { offsetNode: Node; offset: number } | null;\n}\n\n/** A point where the author pressed, in client coordinates. */\nexport interface CaretPoint {\n  readonly x: number;\n  readonly y: number;\n}\n\n/**\n * The text position under a point, as a range.\n *\n * Two spellings because no single one is implemented everywhere, and both are\n * optional because a runtime may have neither — jsdom does not, which is one of\n * the reasons this behaviour cannot be observed there at all.\n */\nfunction caretRangeAt(\n  document: Document,\n  point: CaretPoint\n): { container: Node; offset: number } | undefined {\n  const locator: CaretLocator = document;\n  const range = locator.caretRangeFromPoint?.(point.x, point.y);\n  if (range)\n    return { container: range.startContainer, offset: range.startOffset };\n  const position = locator.caretPositionFromPoint?.(point.x, point.y);\n  if (position)\n    return { container: position.offsetNode, offset: position.offset };\n  return undefined;\n}\n\n/**\n * Where the author's pointer fell inside an element, as a character offset into\n * its text.\n *\n * Taken from the POINT rather than from the document's selection, and that is\n * the whole difficulty. A press on a block is a grab, not a text selection —\n * the canvas suppresses the browser's own selection so that dragging a block\n * does not highlight its words — so at the moment a double-click arrives there\n * is no selection to read. Measured in a browser: `rangeCount` is 0. An earlier\n * version of this read the selection and therefore always answered `undefined`,\n * which sent every edit's caret to the end of the passage.\n *\n * Counted rather than kept as a range, because attaching REBUILDS the subtree:\n * a range captured now points at nodes that will not be in the document by the\n * time there is an editor to hand it to. An offset survives that.\n *\n * `undefined` when the point is outside this element or the engine cannot\n * locate it — both meaning \"no better answer than the editor's own\".\n */\nfunction caretOffsetAt(\n  element: HTMLElement,\n  point: CaretPoint\n): number | undefined {\n  const found = caretRangeAt(element.ownerDocument, point);\n  if (found === undefined) return undefined;\n  return characterOffsetIn(element, found.container, found.offset);\n}\n\n/**\n * How many characters of `element`'s text come before a position in it, or\n * `undefined` when the position is outside it or no range can end there. The\n * one measure both a pointer's caret and the selection's are taken by.\n */\nfunction characterOffsetIn(\n  element: HTMLElement,\n  container: Node,\n  offset: number\n): number | undefined {\n  if (!element.contains(container)) return undefined;\n  const upToCaret = element.ownerDocument.createRange();\n  upToCaret.selectNodeContents(element);\n  try {\n    upToCaret.setEnd(container, offset);\n  } catch {\n    // The located node is not one this range can end in — an offset past its\n    // length, or a node type the range refuses. The editor's own answer stands.\n    return undefined;\n  }\n  return upToCaret.toString().length;\n}\n\n/** Where the selection's caret is in `element`, as a character offset. */\nfunction selectionOffsetIn(element: HTMLElement): number | undefined {\n  const selection = element.ownerDocument.getSelection();\n  const at = selection?.focusNode;\n  if (selection === null || at === null || at === undefined) return undefined;\n  return characterOffsetIn(element, at, selection.focusOffset);\n}\n\n/** Which passage is being edited. */\nexport interface InlineRichTextEditing {\n  readonly nodeId: string;\n  readonly prop: string;\n  /**\n   * The placement and exposure a component's exposed passage is stored\n   * under; absent for a node's own passage.\n   */\n  readonly exposure?: RichPassageAddress[\"exposure\"];\n}\n\nexport interface UseInlineRichTextResult {\n  /** The passage being edited, or `null` when none is. */\n  editing: InlineRichTextEditing | null;\n  /**\n   * Start editing a passage, reporting whether it could be.\n   *\n   * `prop` defaults to the block's FIRST declared rich value, which is what a\n   * keyboard caller wants: it has a selected block and no element.\n   *\n   * `element` is the one a pointer landed on. A caller that has it should pass\n   * it: finding the element again from the document alone searches the whole\n   * page, and two canvases showing one document carry the same node ids — so\n   * the search can answer with the other canvas's passage, attaching there\n   * while committing here.\n   */\n  begin: (\n    nodeId: string,\n    prop?: string,\n    element?: HTMLElement,\n    point?: CaretPoint,\n    exposure?: RichPassageAddress[\"exposure\"]\n  ) => boolean;\n  /**\n   * Finish, writing whatever the author left behind.\n   *\n   * A caller about to hand the document somewhere else needs the outcome, not\n   * just the document: its own copy is the one from before this commit, and a\n   * REFUSED commit leaves the passage open with the author's words in it, so\n   * closing or opening anything else on top of that destroys them.\n   */\n  commit: () => InlineEditOutcome;\n  /** Finish, discarding it. */\n  cancel: () => void;\n}\n\n/** One consumer's hold on the shared editor, as this module uses it. */\ninterface EditorSession {\n  focus(at?: number): void;\n  read(): unknown;\n  detach(): void;\n  /** Keep this attachment when something else asks for the shared editor. */\n  hold(): void;\n  /** The format bar's verbs, where the editor offers them. */\n  format?(mark: \"bold\" | \"italic\"): void;\n  link?(url: string | null, options?: { readonly newTab?: boolean }): void;\n  selection?(): FormatSelection | undefined;\n  /** A whole passage's headings, lists and quote, where the editor has them. */\n  block?(kind: FormatBlockAction): void;\n}\n\n/**\n * How a passage is attached: held to ONE paragraph, for a value restricted\n * to one (`oneParagraph`), by the engine's own restriction.\n */\ninterface AttachOptions {\n  readonly paragraph?: {\n    readonly restrict: (value: unknown) => {\n      readonly value: unknown;\n      readonly dropped: boolean;\n    };\n    readonly onDropped?: () => void;\n    /** Told after every change of the words, with the restricted value. */\n    readonly onChange?: (value: unknown) => void;\n    readonly onSelection?: (state: FormatSelection) => void;\n  };\n  /** A whole passage's selection, told as it moves and changes. */\n  readonly onSelection?: (state: FormatSelection) => void;\n}\n\n/** The bar's verbs on a session, when the editor offers all of them. */\nfunction formatVerbs(session: EditorSession): FormatSession | null {\n  if (\n    session.format === undefined ||\n    session.link === undefined ||\n    session.selection === undefined\n  )\n    return null;\n  return {\n    format: mark => session.format?.(mark),\n    link: (url, options) => session.link?.(url, options),\n    selection: () => session.selection?.(),\n    focus: () => session.focus(),\n    // Offered only where the editor has it, so the bar draws its block\n    // buttons only where pressing one does something.\n    ...(session.block === undefined\n      ? {}\n      : { block: (kind: FormatBlockAction) => session.block?.(kind) }),\n  };\n}\n\n/**\n * How a one-paragraph value is attached: held to one paragraph by the engine's\n * own restriction, so the editor holds what is saved and drawn, with a paste\n * that lost formatting and every move of the selection told to the format bar.\n */\nconst ONE_PARAGRAPH: AttachOptions = {\n  paragraph: {\n    restrict: toOneParagraph,\n    onDropped: () => formatBar.setDropped(true),\n    onSelection: state => formatBar.selected(state),\n  },\n};\n\n/**\n * How a whole passage is attached: its selection told to the format bar, so\n * the bar says which marks, link and block are on under it.\n */\nconst WHOLE_PASSAGE: AttachOptions = {\n  onSelection: state => formatBar.selected(state),\n};\n\n/** Hand the editor a passage, held to one paragraph when its value is one. */\nfunction attachPassage(\n  live: LoadedEditor,\n  element: HTMLElement,\n  target: { readonly oneParagraph?: true },\n  value: unknown\n): Attachment {\n  return live.attach(\n    element,\n    value,\n    target.oneParagraph === true ? ONE_PARAGRAPH : WHOLE_PASSAGE\n  );\n}\n\n/**\n * What the bar offers a passage: a one-paragraph value (a Text's) its marks\n * and link; a whole passage (a Rich text's) those and its headings, lists and\n * quote, where the editor can change a block. `null` where the editor offers\n * the bar no verbs.\n */\nfunction barActionsFor(\n  target: { readonly oneParagraph?: true },\n  verbs: FormatSession\n): readonly FormatAction[] | null {\n  if (target.oneParagraph === true) return TEXT_FORMAT_ACTIONS;\n  return verbs.block === undefined ? null : RICH_TEXT_FORMAT_ACTIONS;\n}\n\n/**\n * Serve the format bar for the passage, where the editor can, with\n * \"Turn into\" where the block can be turned.\n */\nfunction serveFormatBar(\n  target: { readonly oneParagraph?: true },\n  session: EditorSession,\n  element: HTMLElement,\n  finish: () => unknown,\n  turnInto: () => FormatTurnInto | undefined\n): void {\n  const verbs = formatVerbs(session);\n  if (verbs === null) return;\n  const actions = barActionsFor(target, verbs);\n  if (actions === null) return;\n  const turn = turnInto();\n  formatBar.open({\n    element,\n    session: verbs,\n    actions,\n    finish: () => {\n      finish();\n    },\n    ...(turn === undefined ? {} : { turnInto: turn }),\n  });\n}\n\n/** Which of the format bar's keys a press is, if any. */\nfunction formatKeyOf(event: KeyboardEvent): \"mark\" | \"link\" | \"bar\" | null {\n  if (commandWith(event, \"b\") || commandWith(event, \"i\")) return \"mark\";\n  if (commandWith(event, \"k\")) return \"link\";\n  return event.altKey && event.key === \"F10\" ? \"bar\" : null;\n}\n\n/**\n * The format bar's keys, for a passage it serves, answering whether the press\n * was one of them. ⌘B and ⌘I are the editor's own and are only kept from the\n * page's shortcuts; ⌘K opens the address field for the selected words (or the\n * link the caret is in); Alt+F10 takes the focus to the bar, as it takes it\n * to a toolbar everywhere else in the builder.\n */\nfunction handleFormatKey(event: KeyboardEvent, element: HTMLElement): boolean {\n  const served = formatBar.get().target;\n  if (served?.element !== element) return false;\n  const key = formatKeyOf(event);\n  if (key === null) return false;\n  event.stopPropagation();\n  if (key === \"mark\") return true;\n  event.preventDefault();\n  if (key === \"bar\") {\n    formatBar.requestFocus();\n    return true;\n  }\n  const selection = served.session.selection();\n  if (selection !== undefined && (!selection.collapsed || selection.link))\n    formatBar.setLinking(true);\n  return true;\n}\n\n/** Whether a key press is the platform's command modifier with `key`. */\nfunction commandWith(event: KeyboardEvent, key: string): boolean {\n  return (\n    (event.metaKey || event.ctrlKey) &&\n    !event.altKey &&\n    event.key.toLowerCase() === key\n  );\n}\n\n/** What asking the facade for the editor produced, as this module reads it. */\ntype Attachment =\n  | { readonly status: \"attached\"; readonly session: EditorSession }\n  | { readonly status: \"refused\"; readonly reason: \"unsupported\" | \"held\" };\n\n/** The facade's editor, as this module uses it. */\ninterface LoadedEditor {\n  /** Refused for a passage this editor cannot take, or while it is held. */\n  attach(\n    element: HTMLElement,\n    value: unknown,\n    options?: AttachOptions\n  ): Attachment;\n}\n\n/**\n * Told how every finished edit turned out.\n *\n * A host cannot learn this from `commit`'s return value alone, because most\n * edits do not end by the host calling `commit`. Leaving the passage ends one,\n * so does opening another, so does the canvas unmounting — and the outcome that\n * most needs saying, an edit whose value stopped being editable while it was\n * open, is reached almost entirely through the first of those. A host reporting\n * only what its own calls returned would say nothing on the common path.\n *\n * Called for EVERY commit including the host's own, so that reporting has one\n * home. A host should read `commit`'s return value for control flow — whether\n * it may close, which document to save — and this for anything it says to the\n * author; doing both from the return value reports the same edit twice.\n */\nexport type InlineRichTextFinished = (outcome: InlineEditOutcome) => void;\n\n/**\n * A passage carried across a frame's page replacement: its words as typed and\n * the baselines it opened with, for the next attach to take up.\n */\ninterface CarriedPassage {\n  readonly editing: InlineRichTextEditing;\n  readonly words: unknown;\n  readonly opened: unknown;\n  readonly baseline: unknown;\n  /** Where the caret was, so the passage resumes there. */\n  readonly caret?: number;\n}\n\n/**\n * Finish a carried passage that cannot go on in a page: written, as finishing\n * the edit would write it, unless the document moved on meanwhile or the\n * value can no longer be stored, which loses the words and is said.\n */\nfunction settleCarried(\n  editor: EditorState,\n  carry: CarriedPassage\n): InlineEditOutcome {\n  if (!richTextChanged(carry.baseline, carry.words)) {\n    return INLINE_EDIT_UNCHANGED;\n  }\n  if (passageMovedOn(editor, carry.editing, carry.opened)) {\n    return INLINE_EDIT_DISCARDED;\n  }\n  const op = passageOp(\n    editor,\n    carry.editing,\n    carry.words,\n    carry.baseline,\n    carry.opened\n  );\n  const written = op === null ? null : editor.apply(op);\n  return written === null\n    ? INLINE_EDIT_DISCARDED\n    : { status: \"written\", document: written };\n}\n\n/**\n * How the editor is fetched.\n *\n * A parameter rather than a hard import so the rules of this hook can be\n * exercised without loading Lexical — and because the editor is genuinely\n * optional: a builder embedded somewhere that never supplies one still edits\n * plain text, and a passage simply does not open.\n */\nexport type InlineRichTextEditorLoader = () => Promise<LoadedEditor>;\n\n/**\n * @param editor - the editor state whose document is being edited\n * @param load - how to obtain the shared rich-text editor\n * @returns the current edit and the ways in and out\n */\nexport function useInlineRichText(\n  editor: EditorState,\n  load: InlineRichTextEditorLoader | undefined,\n  onFinished?: InlineRichTextFinished\n): UseInlineRichTextResult {\n  const [editing, setEditing] = useState<InlineRichTextEditing | null>(null);\n  // The document the canvas is drawn in: the frame's when it is in one, where\n  // a keyboard caller's passage is found.\n  const canvasDocument = useCanvasFrame().document;\n\n  /*\n   * Read through refs inside the callbacks below rather than captured as\n   * dependencies, so a commit is decided against the document as it stands now\n   * rather than the one that was current when the caret went in.\n   */\n  const editorRef = useRef(editor);\n  editorRef.current = editor;\n  const editingRef = useRef(editing);\n  editingRef.current = editing;\n  // Held in a ref for the same reason, and for one more: a host passing an\n  // inline arrow would otherwise give `commit` a new identity every render, and\n  // `commit` is what the handover effect depends on.\n\n  /*\n   * The loader, read through a ref for a reason that costs an author their\n   * words otherwise.\n   *\n   * A consumer passing an inline closure — the ordinary way to write\n   * `useInlineRichText(editor, () => import(\"...\"))` — gives it a new identity\n   * every render. As a DEPENDENCY that reruns the handover effect while the\n   * element is still mounted, and the cleanup below deliberately releases a\n   * held session because it assumes it is unmounting. So a re-render for any\n   * unrelated reason would tear down a passage being kept open precisely\n   * because its words exist nowhere else.\n   *\n   * The effect therefore depends on WHICH passage is being edited, not on how\n   * the editor is fetched. A loader that changes mid-edit is not a reason to\n   * re-open anything; the chunk in flight is already the right one.\n   */\n  /*\n   * The host's ear and the loader, held together, and the document the canvas\n   * draws in as of this render: the effect's cleanup compares it with the one\n   * it attached in, which is how a frame REPLACING its page is told from the\n   * passage closing.\n   */\n  const latest = useRef({ finished: onFinished, load, canvasDocument });\n  latest.current = { finished: onFinished, load, canvasDocument };\n  /*\n   * A passage carried across a frame's page replacement: its words as typed\n   * and the baselines it opened with, for the next attach to take up, so the\n   * replacement neither writes an unfinished edit nor loses a refused one.\n   */\n  const carried = useRef<CarriedPassage | null>(null);\n\n  /**\n   * The element a pointer handed over, used in place of searching for one,\n   * and where the pointer fell on it. Both or neither: they come with one\n   * `begin` and are read together by the effect that follows it.\n   *\n   * A ref rather than state: it is read once by that effect, and re-rendering\n   * for it would be a render nobody needs.\n   */\n  const handed = useRef<Handover>(NO_HANDOVER);\n\n  /** The live editor, the element it holds, and what to put back. */\n  const mounted = useRef<{\n    session: EditorSession;\n    element: HTMLElement;\n    /**\n     * WHICH passage this session was mounted for.\n     *\n     * Recorded with the session rather than read from the hook's current state\n     * when the write happens. A caller that begins a second passage before the\n     * first has released changes that state first, and the cleanup that follows\n     * would then read the live session — the first passage — while addressing\n     * the op with the second's node and prop, copying one block's words over\n     * another. Bound here, a session can only ever write to the passage it was\n     * opened for.\n     */\n    editing: InlineRichTextEditing;\n    /**\n     * The STORED passage the session was handed.\n     *\n     * Kept so the write can refuse when the document's copy has moved on:\n     * another surface, an undo or an op from anywhere else can rewrite the same\n     * prop while the caret is open, and this editor is holding a copy from\n     * before that.\n     */\n    opened: unknown;\n    /** The editor's own reading of the passage when it opened. */\n    baseline: unknown;\n    /**\n     * Where the caret last was, as a character offset, kept as the author\n     * moves it: by the time a frame replaces its page, the old page's\n     * selection may be gone with it.\n     */\n    caret?: number;\n    /**\n     * The passage as it was when its write was last refused, while it stays\n     * open. A second deliberate Escape over the SAME passage lets it go; one\n     * revised since is a new write, tried again. Gone with the session.\n     */\n    refusedWith?: unknown;\n  } | null>(null);\n\n  /**\n   * Take the subtree back, whatever else happens.\n   *\n   * Reads nothing. Whether the passage is worth reading is the caller's\n   * question, and a `release` that answered it too made every caller look like\n   * it had considered the answer.\n   */\n  const letGo = useCallback(() => {\n    const live = mounted.current;\n    mounted.current = null;\n    setEditing(null);\n    if (live === null) return;\n    formatBar.close(live.element);\n    // The element's markup and attributes are the editor's to put back: it is\n    // what changed them, and it is what a plugin using the facade directly\n    // relies on. Only this module's own mark is this module's to remove.\n    live.session.detach();\n    live.element.removeAttribute(EDITING_ATTRIBUTE);\n  }, []);\n\n  /**\n   * Say how an edit turned out, and answer with it.\n   *\n   * Every path out of `commit` goes through this, so a new one cannot be added\n   * that a host never hears about — which is the defect this exists to close:\n   * the outcome was reported at the two places the host itself called, and the\n   * ways an edit actually ends most often are not those.\n   */\n  const report = useCallback(\n    (outcome: InlineEditOutcome): InlineEditOutcome => {\n      latest.current.finished?.(outcome);\n      return outcome;\n    },\n    []\n  );\n\n  const commit = useCallback((): InlineEditOutcome => {\n    const live = mounted.current;\n    if (live === null) {\n      // No session, but possibly a pending one: `editing` is set from the\n      // moment the passage is requested and the editor arrives later. A\n      // passage carried across a page replacement is the edit's outcome\n      // while its editor loads, and is settled NOW: a host asking before it\n      // saves or closes must not be told nothing changed.\n      const pending = carried.current;\n      carried.current = null;\n      letGo();\n      return report(\n        pending === null\n          ? INLINE_EDIT_UNCHANGED\n          : settleCarried(editorRef.current, pending)\n      );\n    }\n    /*\n     * Let go only once the write is SETTLED, never before.\n     *\n     * Releasing is what destroys an author's words: they exist in the editor\n     * and nowhere else, so tearing it down loses them and puts the page's older\n     * copy back in their place with nothing said. So each way of failing to\n     * write is asked first, and the ones an author can still act on keep the\n     * passage open — their text stays on screen, and a second Escape discards\n     * it deliberately.\n     */\n    // Read BEFORE detaching: a detached session answers nothing, deliberately,\n    // so that a superseded one cannot read the live passage. Read before\n    // JUDGING as well — every refusal below is a refusal to destroy something,\n    // so whether there is anything to destroy is the first question.\n    const next = live.session.read();\n    const typed = richTextChanged(live.baseline, next);\n    if (passageMovedOn(editorRef.current, live.editing, live.opened)) {\n      /*\n       * The document moved on. Holding the passage open protects an author's\n       * words from being replaced by the older copy — but only if they wrote\n       * any. A caret that merely sat in a passage has nothing to protect, and\n       * refusing there is worse than doing nothing: the host cannot close, and\n       * the untouched editor goes on showing the stale passage over the newer\n       * one that arrived, until somebody presses Escape.\n       */\n      if (!typed) {\n        letGo();\n        return report(INLINE_EDIT_UNCHANGED);\n      }\n      /*\n       * Held at the SHARED editor as well as here. This hook's own `begin`\n       * guard covers one canvas; ownership of the editor is global, so a second\n       * canvas with its own hook sees nothing mounted and would attach straight\n       * over the top of these words.\n       */\n      live.session.hold();\n      live.refusedWith = next;\n      return report({ status: \"refused\", reason: \"moved-on\" });\n    }\n    // The passage this session was opened for, not whichever is current now.\n    const op = passageOp(\n      editorRef.current,\n      live.editing,\n      next,\n      live.baseline,\n      live.opened\n    );\n    if (op === null) {\n      /*\n       * Nothing to write here.\n       *\n       * `richInlineTextOp` refuses an unchanged passage, one the editor did not\n       * return as rich text, and one whose node was deleted or locked while the\n       * caret was in it. Where the author typed and the passage is still on the\n       * page, it stays open with their words: they can copy them, and a second\n       * Escape lets them go, so holding traps nobody. Where the element has left\n       * the page there is nothing to hold them in, and whether the typing was\n       * lost is worth saying; the comparison that says it is the one the op\n       * made.\n       */\n      if (typed && live.element.isConnected) {\n        live.session.hold();\n        live.refusedWith = next;\n        return report({ status: \"refused\", reason: \"no-longer-editable\" });\n      }\n      letGo();\n      return report(typed ? INLINE_EDIT_DISCARDED : INLINE_EDIT_UNCHANGED);\n    }\n    const written = editorRef.current.apply(op);\n    if (written === null) {\n      /*\n       * The op layer refused the group — a cap this passage would exceed, or a\n       * node that went between the checks above and the write. Nothing was\n       * applied, so the words are still only in the editor and the passage\n       * stays open: an author who has hit a cap can shorten what they wrote.\n       */\n      live.session.hold();\n      live.refusedWith = next;\n      return report({ status: \"refused\", reason: \"rejected\" });\n    }\n    letGo();\n    return report({ status: \"written\", document: written });\n  }, [letGo, report]);\n\n  const cancel = useCallback(() => {\n    // Cancelling lets the words go, carried ones included.\n    carried.current = null;\n    letGo();\n  }, [letGo]);\n\n  const begin = useCallback(\n    (\n      nodeId: string,\n      prop?: string,\n      element?: HTMLElement,\n      point?: CaretPoint,\n      exposure?: RichPassageAddress[\"exposure\"]\n    ) => {\n      if (load === undefined) return false;\n      // A component's exposed passage is named outright, through its\n      // placement; a node's own is found among the passages it declares.\n      const target =\n        exposure === undefined\n          ? namedTarget(\n              richInlineTargets(editorRef.current.document, nodeId),\n              prop\n            )\n          : prop === undefined\n            ? undefined\n            : (passageNow(editorRef.current, { nodeId, prop, exposure }) ??\n              undefined);\n      if (target === undefined) return false;\n      /*\n       * Finish the open passage FIRST, synchronously.\n       *\n       * Otherwise the old edit's effect cleanup runs after this one's state is\n       * installed, and its `commit` clears `editing` — cancelling the passage\n       * just requested instead of the one it belongs to. `useInlineEditing`\n       * sequences this correctly, but this hook is exported on its own and its\n       * `begin` does not oblige a caller to.\n       *\n       * A commit that REFUSED is still holding the previous passage, and the\n       * words in it are the author's only copy. There is one editor, so opening\n       * anything else supersedes that session and takes them with it — the\n       * request is declined instead, which is what the return value is for.\n       */\n      if (mounted.current !== null && commit().status === \"refused\")\n        return false;\n      handed.current = { element: element ?? null, point: point ?? null };\n      setEditing({\n        nodeId: target.nodeId,\n        prop: target.prop,\n        ...(exposure === undefined ? {} : { exposure }),\n      });\n      return true;\n    },\n    [commit, load]\n  );\n\n  /*\n   * Drop an edit the author has already walked away from.\n   *\n   * The editor arrives asynchronously, and until it does the element is neither\n   * focused nor editable — this module marks it inside `attach`. So none of the\n   * ordinary ways of leaving a block emit `blur`: clicking the canvas\n   * background, selecting another block, or deselecting from the keyboard each\n   * change only the selection. Nothing would cancel the pending load, and when\n   * it landed it would attach to the passage they left and take the caret back.\n   *\n   * Only a load that has NOT attached yet is dropped this way. Once the editor\n   * is live the element is focused, leaving it blurs, and blur commits — so\n   * cancelling here as well would throw away what the author had just typed.\n   */\n  useEffect(() => {\n    if (editing === null || mounted.current !== null) return;\n    if (editor.selectedId === passageKeptBy(editing)) return;\n    cancel();\n  }, [editor.selectedId, editing, cancel]);\n\n  /*\n   * Hand the subtree over, and take it back on the way out.\n   *\n   * In an effect rather than in `begin` so the handover happens after React has\n   * finished rendering: attaching an editor mid-render fights whatever the\n   * renderer is about to commit.\n   */\n  useEffect(() => {\n    if (editing === null) return;\n    // Read once, here, rather than depended on — see `latest`. A host that\n    // supplies no loader edits plain text and simply never opens a passage.\n    const fetch = latest.current.load;\n    if (fetch === undefined) {\n      // No editor to resume a carried passage in: it is finished here.\n      const pending = carried.current;\n      if (pending !== null) {\n        carried.current = null;\n        setEditing(null);\n        report(settleCarried(editorRef.current, pending));\n      }\n      return;\n    }\n    // The element the gesture landed on, when there was one. Searching the\n    // canvas's document is the fallback for a keyboard caller, which has no\n    // element: the frame's when the canvas is in one.\n    const { element: given, point } = handed.current;\n    handed.current = NO_HANDOVER;\n    /*\n     * The carry stays where it is until a session takes it up: a second page\n     * replacement before the editor arrives runs this again, and the words\n     * must still be there. One carried for a different passage cannot go on.\n     */\n    const pending = carried.current;\n    const carry = pending?.editing === editing ? pending : null;\n    if (pending !== null && carry === null) {\n      carried.current = null;\n      report(settleCarried(editorRef.current, pending));\n    }\n    const element = given ?? passageIn(canvasDocument, editing);\n    if (element === null) {\n      // Nothing on screen carries this passage. The node may have been removed\n      // between the request and this effect; dropping the edit is the honest\n      // answer, and leaving `editing` set would show a caret nobody can see.\n      // Words carried from a replaced page have nowhere to go here.\n      setEditing(null);\n      if (carry !== null) {\n        carried.current = null;\n        report(settleCarried(editorRef.current, carry));\n      }\n      return;\n    }\n\n    let cancelled = false;\n    /*\n     * The POINT is taken now and the offset from it later.\n     *\n     * The ref has to be cleared synchronously, or a second edit begun before\n     * this one attaches inherits its gesture. The offset must not be computed\n     * yet though: it is a character count into the passage, and the passage can\n     * be rewritten while the editor loads — an offset measured against the old\n     * text lands somewhere unrelated in the new, or past its end. The element\n     * still holds what the page rendered when the loader resolves, because this\n     * is what replaces it.\n     */\n    void fetch().then(\n      live => {\n        /*\n         * The author may have left before the chunk arrived. Attaching then\n         * would put a caret into a passage they are no longer editing.\n         *\n         * All three conditions are asked, because `cancelled` alone is not\n         * enough: it is set by an effect CLEANUP, and this callback can run\n         * before React has flushed that — so a selection that has already moved\n         * is visible here while the cleanup that would record it has not run.\n         */\n        if (cancelled) return;\n        if (editingRef.current !== editing) return;\n        if (editorRef.current.selectedId !== passageKeptBy(editing)) return;\n        /*\n         * The ELEMENT can go while the chunk is in flight, without the edit\n         * being cancelled: React re-renders the canvas and replaces this\n         * subtree, and the node captured before the request is then detached\n         * while the passage is still selected and still being edited. None of\n         * the three checks above sees that — they ask about the edit, not about\n         * the element it was measured against.\n         *\n         * Attaching anyway puts the editor on a node nobody is looking at: no\n         * caret appears, typing goes nowhere visible, and the commit writes\n         * back whatever that orphan holds.\n         */\n        if (!element.isConnected) {\n          setEditing(null);\n          return;\n        }\n        /*\n         * Read the passage NOW, not before the chunk was requested.\n         *\n         * An undo, a remote update or another surface can rewrite it while the\n         * editor is in flight, and the page has already re-rendered with the\n         * new words by the time this runs. Attaching the copy taken earlier\n         * puts the caret into content nobody can see any more, and the first\n         * thing the author types is refused as `moved-on` — a write lost to a\n         * conflict that had already resolved before the editor existed.\n         */\n        const target = passageNow(editorRef.current, editing);\n        if (target === null) {\n          // The passage stopped being editable while the chunk was loading.\n          // A carry is settled by the cleanup this sets off.\n          setEditing(null);\n          return;\n        }\n        /*\n         * Measured BEFORE the handover, and that ordering is the whole point.\n         *\n         * Attaching replaces this subtree and applies the editor's own theme —\n         * a heading's size, a list's indentation, a table's box all change — so\n         * hit-testing afterwards asks where a point falls in a layout the\n         * author never saw. It is measured here rather than before the chunk\n         * was requested, because the passage may have been rewritten while it\n         * was in flight: this is the first moment where what is on screen is\n         * also what is about to be edited.\n         */\n        const caret =\n          point === null ? undefined : caretOffsetAt(element, point);\n        // A one-paragraph value is held to it while it is typed, by the\n        // restriction it is saved and drawn by; either kind of passage has\n        // its selection told to the format bar.\n        const attachment = attachPassage(\n          live,\n          element,\n          target,\n          carry === null ? target.value : carry.words\n        );\n        if (attachment.status === \"refused\") {\n          /*\n           * Dropping this edit is right either way: it leaves the passage as the\n           * page rendered it, which is the only outcome that cannot lose words,\n           * here or in whatever is holding on.\n           *\n           * The two reasons differ in what a host can say about it. A passage\n           * this editor cannot represent is nothing the author did and nothing\n           * they can act on, so it passes in silence. An editor busy protecting\n           * an edit elsewhere is worth saying: otherwise their gesture appears\n           * to do nothing, which is the same silent refusal this module already\n           * refuses to ship on the way OUT of an edit.\n           */\n          setEditing(null);\n          if (attachment.reason === \"held\") report(INLINE_EDIT_UNAVAILABLE);\n          return;\n        }\n        const session = attachment.session;\n        // Taken up: the session holds the words now.\n        carried.current = null;\n        element.setAttribute(EDITING_ATTRIBUTE, editing.prop);\n        session.focus(carry?.caret ?? caret);\n        mounted.current = {\n          session,\n          element,\n          editing,\n          // The RAW stored value, kept so the write can tell one unusable value\n          // from another — the narrowed form collapses them all to `undefined`.\n          opened: carry === null ? target.stored : carry.opened,\n          // Taken AFTER the editor loaded the value, so it is the editor's own\n          // reading of an untouched passage — which is what makes an unchanged\n          // edit compare equal rather than differing by normalisation alone.\n          // A carried passage keeps the baselines it opened with.\n          baseline: carry === null ? session.read() : carry.baseline,\n        };\n        serveFormatBar(target, session, element, commit, () =>\n          formatTurnInto({\n            editing,\n            editor: () => editorRef.current,\n            typed: () => {\n              const live = mounted.current;\n              return live === null || live.session !== session\n                ? null\n                : {\n                    editing: live.editing,\n                    words: session.read(),\n                    baseline: live.baseline,\n                    opened: live.opened,\n                  };\n            },\n            commit,\n          })\n        );\n      },\n      () => {\n        /*\n         * The chunk did not arrive. Leaving `editing` set would show a passage\n         * marked as being edited with no editor behind it — and because the\n         * element then swallows the double-click that would retry, the author\n         * would be locked out of it for the rest of the session.\n         *\n         * Dropping the edit puts the gesture back in their hands. The loader\n         * discards its rejected promise, so the next double-click genuinely\n         * tries again rather than replaying the failure.\n         */\n        if (!cancelled) setEditing(null);\n      }\n    );\n\n    /*\n     * Stopped at the element rather than by teaching the canvas about editing.\n     * Selection and dragging both listen on the canvas root, so a press inside\n     * the passage would start a drag instead of placing the caret — and the\n     * rule belongs to the element that is currently something else.\n     */\n    const swallow = (event: Event) => event.stopPropagation();\n    /*\n     * Escape keeps what was typed and ends the edit, as leaving the passage\n     * does; the NEXT Escape selects the block's parent. Where the write is\n     * refused the passage stays open with the words in it, and a second\n     * Escape then lets them go: the author's deliberate way out of a write\n     * the page will not take. A passage revised since the refusal is a new\n     * write, tried again. A held key's auto-repeat is not a second press: it\n     * would destroy the words before the author let go of the key.\n     */\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (handleFormatKey(event, element)) return;\n      if (event.key !== \"Escape\") return;\n      event.preventDefault();\n      event.stopPropagation();\n      if (event.repeat) return;\n      const live = mounted.current;\n      if (\n        live?.refusedWith !== undefined &&\n        !richTextChanged(live.refusedWith, live.session.read())\n      ) {\n        cancel();\n        return;\n      }\n      commit();\n    };\n\n    /*\n     * Leaving the passage finishes the edit, as it does for plain text. Enter\n     * is deliberately NOT an exit here: a passage holds paragraphs, so Enter\n     * belongs to the value. Nor is moving to the format bar: an author pressing\n     * its buttons, or typing a link's address, is still editing.\n     */\n    const onBlur = () => {\n      if (formatBar.holdsFocus()) return;\n      commit();\n    };\n\n    const trackCaret = () => {\n      const live = mounted.current;\n      if (live?.element === element) live.caret = selectionOffsetIn(element);\n    };\n    element.ownerDocument.addEventListener(\"selectionchange\", trackCaret);\n    element.addEventListener(\"keydown\", onKeyDown);\n    element.addEventListener(\"blur\", onBlur);\n    element.addEventListener(\"pointerdown\", swallow);\n    element.addEventListener(\"click\", swallow);\n    element.addEventListener(\"dblclick\", swallow);\n    return () => {\n      cancelled = true;\n      /*\n       * Give the element back on the way out, not only when the author leaves\n       * the passage. Unmounting the canvas — a navigation, a field removed,\n       * access revoked — removes the focused element without reliably firing\n       * `blur`, so nothing else would run: the editor would stay attached to a\n       * detached tree, holding its listeners and its state, until some later\n       * passage displaced it.\n       */\n      /*\n       * COMMITTED, not discarded. Rich keystrokes go into the editor's own\n       * history and never touch the document until an edit finishes, so the\n       * canvas op history — which is what the unsaved-work guard reads — is\n       * still at zero while a passage is being typed. Detaching without writing\n       * would drop the words AND leave the guard silent about it, so a\n       * navigation nobody warned about takes the work with it.\n       */\n      const live = mounted.current;\n      const replaced =\n        latest.current.canvasDocument !== canvasDocument &&\n        editingRef.current === editing;\n      if (live !== null && replaced) {\n        /*\n         * The frame REPLACED its page under the open passage, and this effect\n         * runs again for the new one. Carried rather than committed: the\n         * author has not finished, and a refused write here would lose the\n         * words with the old page.\n         */\n        carried.current = {\n          editing,\n          words: live.session.read(),\n          opened: live.opened,\n          baseline: live.baseline,\n          caret: live.caret,\n        };\n        mounted.current = null;\n        formatBar.close(live.element);\n        live.session.detach();\n        live.element.removeAttribute(EDITING_ATTRIBUTE);\n      } else if (live !== null) {\n        commit();\n        /*\n         * A refusal keeps the session by design, because staying open is what\n         * saves the words. Here there is nowhere to stay: the element is being\n         * removed, so the choice is between losing the text and ALSO leaving an\n         * editor attached to a detached tree, holding its listeners and its\n         * state until some later passage displaces it. Released explicitly.\n         */\n        if (mounted.current !== null) letGo();\n      } else if (!replaced && carried.current !== null) {\n        // A carry no session took up — the passage closed, the canvas went,\n        // or the editor never arrived — is finished here, never dropped.\n        const pending = carried.current;\n        carried.current = null;\n        report(settleCarried(editorRef.current, pending));\n      }\n      element.ownerDocument.removeEventListener(\"selectionchange\", trackCaret);\n      element.removeEventListener(\"keydown\", onKeyDown);\n      element.removeEventListener(\"blur\", onBlur);\n      element.removeEventListener(\"pointerdown\", swallow);\n      element.removeEventListener(\"click\", swallow);\n      element.removeEventListener(\"dblclick\", swallow);\n    };\n  }, [editing, cancel, commit, letGo, report, canvasDocument]);\n\n  return { editing, begin, commit, cancel };\n}\n","\"use client\";\n\n/**\n * One double-click, routed to whichever surface owns the value under it.\n *\n * A block declares a value editable on the canvas; what that MEANS depends on\n * the value. A line of text is handed to a `contenteditable` element and read\n * back as a string; a passage is handed to a rich-text editor and read back as\n * a tree. An author performs the same gesture for both and should not have to\n * know which they are about to get.\n *\n * So the gesture is decided ONCE, here, rather than by two handlers on one\n * tree. Two would each see every double-click and each decide whether it was\n * theirs, and the failure mode is the pair disagreeing: both open, and the two\n * editors fight over one element — or neither does, and the value reads as\n * simply not editable.\n *\n * The kind is asked of the block's schema through the shared classifier, which\n * is the same answer the two rule modules use to decide what they offer. The\n * routing cannot drift from what the surfaces accept, because it is not a\n * second opinion about which values are whose.\n *\n * @module use-inline-editing\n */\n\nimport { getBlock, findNode } from \"@nextlyhq/blocks-engine\";\nimport { INSTANCE_ATTRIBUTE } from \"@nextlyhq/blocks-react\";\nimport { useCallback, useSyncExternalStore } from \"react\";\n\nimport type { EditorState } from \"../editor-state\";\n\nimport { composedTextAt } from \"./exposed-inline\";\nimport {\n  INLINE_EDIT_UNCHANGED,\n  type InlineEditOutcome,\n} from \"./inline-edit-outcome\";\nimport {\n  editedAsRichText,\n  inlinePropKindAt,\n  type InlinePropKind,\n} from \"./inline-prop-kind\";\nimport { firstInlineProp } from \"./inline-target\";\nimport type { OpenPassages } from \"./open-passages\";\nimport {\n  useInlineRichText,\n  type CaretPoint,\n  type InlineRichTextEditing,\n  type InlineRichTextEditorLoader,\n  type InlineRichTextFinished,\n} from \"./use-inline-rich-text\";\nimport {\n  editableFrom,\n  useInlineText,\n  type InlineTextEditing,\n} from \"./use-inline-text\";\n\nexport interface UseInlineEditingResult {\n  /** The plain value being edited, or `null`. */\n  editing: InlineTextEditing | null;\n  /** The passage being edited, or `null`. Never set at the same time as {@link editing}. */\n  editingRich: InlineRichTextEditing | null;\n  /**\n   * Whether an inspector field holds a passage open in the shared editor:\n   * unsaved work, as an open passage on the canvas is.\n   */\n  inspecting: boolean;\n  /**\n   * Start editing a value, reporting whether it could be.\n   *\n   * Routed by the prop's declared kind, so a keyboard caller with a selected\n   * block gets whichever surface that block's first inline value asks for.\n   */\n  begin: (nodeId: string, prop?: string) => boolean;\n  /**\n   * Finish whichever edit is open, writing what the author left behind.\n   *\n   * A host about to hand the document to a form needs the outcome: the copy it\n   * rendered with is the one from before this commit, an edit that has not been\n   * written yet is invisible in it, and a REFUSED commit is still holding the\n   * author's words — so closing over it is what loses them.\n   */\n  commit: () => InlineEditOutcome;\n  /** Finish whichever edit is open, discarding it. */\n  cancel: () => void;\n  /**\n   * Enter an edit from a double-click on the canvas.\n   *\n   * The pointer's position is read when it is there. A passage needs it to put\n   * the caret where the author aimed: the canvas suppresses the browser's own\n   * text selection so a press on a block is a grab rather than a highlight, so\n   * there is no selection to ask and the point is the only record of where they\n   * meant to type.\n   */\n  onDoubleClick: (event: {\n    target: EventTarget | null;\n    clientX?: number;\n    clientY?: number;\n  }) => void;\n}\n\n/** What a double-click landed on, or `null` when it was not on a value. */\nfunction markedAt(target: EventTarget | null): {\n  nodeId: string;\n  prop: string;\n  element: HTMLElement;\n  /** Whether the node is one a component contributed, by its marker. */\n  inComponent: boolean;\n} | null {\n  const found = editableFrom(target);\n  if (found === null) return null;\n  const placement =\n    found.element.closest(\"[data-nx-node]\")?.getAttribute(INSTANCE_ATTRIBUTE) ??\n    \"\";\n  return { ...found, inComponent: placement !== \"\" };\n}\n\n/**\n * @param editor - the editor state whose document is being edited\n * @param loadRichText - how to obtain the shared rich-text editor, when there is one\n * @param onFinished - told how every finished PASSAGE turned out; see {@link InlineRichTextFinished}\n * @param onPartOf - told the placement whose text was double-clicked when that\n *   text belongs to the component's design rather than to a field it exposes,\n *   or to a field a lock the component sets holds, by that field's exposure\n *   id; the placement is selected first, and the host says so\n * @param passages - where inspector fields hold open passages; `commit`\n *   finishes them first, see {@link OpenPassages}\n * @returns one edit at a time, and the canvas handler that starts it\n */\nexport function useInlineEditing(\n  editor: EditorState,\n  loadRichText?: InlineRichTextEditorLoader,\n  onFinished?: InlineRichTextFinished,\n  onPartOf?: (placementId: string, heldExposureId?: string) => void,\n  passages?: OpenPassages\n): UseInlineEditingResult {\n  const subscribe = useCallback(\n    (listener: () => void) => passages?.subscribe(listener) ?? noSubscription(),\n    [passages]\n  );\n  const inspecting = useSyncExternalStore(\n    subscribe,\n    () => passages?.isOpen() ?? false,\n    () => false\n  );\n  /*\n   * The plain surface reports only a key's refused way out, the case where its\n   * line stays open: its blur commits and answers the pre-union way, so a line\n   * lost to a capped write on blur still goes unreported. Stated so a host\n   * does not read silence there as \"nothing happened\".\n   */\n  const plain = useInlineText(editor, onFinished);\n  const rich = useInlineRichText(editor, loadRichText, onFinished);\n\n  /** The kind the block declared for this value, or `null` if it declared none. */\n  const kindOf = useCallback(\n    (nodeId: string, prop: string) => {\n      const node = findNode(editor.document.nodes, nodeId);\n      if (node === undefined) return null;\n      // By the value's name, so an item of a list of words routes as the\n      // line of text it is.\n      return inlinePropKindAt(getBlock(node.type)?.props, prop);\n    },\n    [editor]\n  );\n\n  /**\n   * Open one surface, having finished whatever the other was doing.\n   *\n   * Both are asked to commit first, and each is a no-op when it holds nothing.\n   * Without it an author who starts a passage and then double-clicks a line of\n   * text before the editor's chunk arrives leaves BOTH surfaces live: the\n   * loader resolves, focuses the passage, and the focus it steals blurs the\n   * line of text into a commit the author never asked for — with the caret\n   * ending up somewhere they were not looking.\n   */\n  const openOn = useCallback(\n    (\n      kind: InlinePropKind,\n      nodeId: string,\n      prop: string,\n      element?: HTMLElement,\n      point?: CaretPoint,\n      exposure?: InlineRichTextEditing[\"exposure\"]\n    ) => {\n      plain.commit();\n      const finished = rich.commit();\n      /*\n       * A refused passage is still open and still holds the only copy of what\n       * the author typed. There is one editor behind both surfaces, so opening\n       * anything at all supersedes that session — declined instead, the same\n       * answer `begin` gives for a value that cannot be edited.\n       */\n      if (finished.status === \"refused\") return false;\n      return editedAsRichText(kind)\n        ? rich.begin(nodeId, prop, element, point, exposure)\n        : plain.begin(nodeId, prop);\n    },\n    [plain, rich]\n  );\n\n  const begin = useCallback(\n    (nodeId: string, prop?: string) => {\n      if (prop === undefined) {\n        // The block's first inline value in DECLARATION order, across both\n        // kinds. Asking one surface and then the other answers with that\n        // surface's first instead, which is a different value whenever a block\n        // declares a passage after a line of text.\n        const first = firstInlineProp(editor.document, nodeId);\n        if (first === null) return false;\n        return openOn(first.kind, nodeId, first.prop);\n      }\n      const kind = kindOf(nodeId, prop);\n      if (kind === null) return false;\n      return openOn(kind, nodeId, prop);\n    },\n    [editor, kindOf, openOn]\n  );\n\n  const commit = useCallback((): InlineEditOutcome => {\n    // Both are asked, and at most one is open. Asking only the one believed to\n    // be open would leave the other's edit hanging whenever that belief was\n    // wrong, and each reports nothing when it holds nothing.\n    // The inspector's passages first, through their own commit: their words\n    // are in the shared editor alone, and the document the caller holds is\n    // from before them. What they wrote is the base the rest answers with.\n    const inspected = passages?.finishAll() ?? null;\n    const written = plain.commit();\n    const passage = rich.commit();\n    // The passage's answer wins whenever it has one, because it is the surface\n    // that can refuse. The plain surface reports the pre-union way — a document\n    // or `null` — and cannot refuse: it has no equivalent of a passage kept\n    // open, which is why a plain edit lost to a capped write is a defect of its\n    // own rather than something this can translate.\n    if (passage.status !== \"unchanged\") return passage;\n    const latest = written ?? inspected;\n    return latest === null\n      ? INLINE_EDIT_UNCHANGED\n      : { status: \"written\", document: latest };\n  }, [plain, rich, passages]);\n\n  const cancel = useCallback(() => {\n    plain.cancel();\n    rich.cancel();\n  }, [plain, rich]);\n\n  const onDoubleClick = useCallback(\n    (event: {\n      target: EventTarget | null;\n      clientX?: number;\n      clientY?: number;\n    }) => {\n      const found = markedAt(event.target);\n      if (found === null) return;\n      // Text inside a component: its exposed text and passages are edited in\n      // place through the placement (the plain surface below finds the text),\n      // and anything else is the component's own, which selects the\n      // placement and says so.\n      // Asked only of an element a component contributed, which the renderer\n      // marks with its placement: the page's own text never needs the\n      // composition.\n      const composed = found.inComponent\n        ? composedTextAt(\n            editor.document,\n            editor.composed(),\n            found.nodeId,\n            found.prop,\n            editor.lockDefinitions\n          )\n        : null;\n      if (composed?.kind === \"part-of\") {\n        if (rich.commit().status === \"refused\") return;\n        plain.commit();\n        editor.select(composed.placementId);\n        if (composed.heldExposureId === undefined) {\n          onPartOf?.(composed.placementId);\n        } else {\n          onPartOf?.(composed.placementId, composed.heldExposureId);\n        }\n        return;\n      }\n      const point =\n        event.clientX === undefined || event.clientY === undefined\n          ? undefined\n          : { x: event.clientX, y: event.clientY };\n      // A component's exposed passage, edited in place on its placement.\n      if (composed?.kind === \"exposed-rich\") {\n        const { placementId, exposureId } = composed.target;\n        openOn(\"rich\", found.nodeId, found.prop, found.element, point, {\n          placementId,\n          exposureId,\n        });\n        return;\n      }\n      // A component's exposed line of text is edited as text through its\n      // placement (`composed` above); the node's own restricted value takes\n      // the rich-text editor, held to one paragraph.\n      if (\n        composed === null &&\n        editedAsRichText(kindOf(found.nodeId, found.prop))\n      ) {\n        // The element the gesture landed on is passed rather than looked up\n        // again: two canvases showing one document carry the same node ids, so\n        // a search of the page can answer with the other one's passage.\n        openOn(\"rich\", found.nodeId, found.prop, found.element, point);\n        return;\n      }\n      // Finished for the same reason `openOn` does it, then delegated: the\n      // plain surface has to keep the element the gesture landed on, because a\n      // value whose element cannot be found again from the document alone is\n      // still editable from a click.\n      if (rich.commit().status === \"refused\") return;\n      plain.onDoubleClick(event);\n    },\n    [editor, kindOf, onPartOf, openOn, plain, rich]\n  );\n\n  return {\n    editing: plain.editing,\n    editingRich: rich.editing,\n    inspecting,\n    begin,\n    commit,\n    cancel,\n    onDoubleClick,\n  };\n}\n\n/** A subscription to nothing, for an editor with no inspector passages. */\nfunction noSubscription(): () => void {\n  return () => {};\n}\n","/**\n * The passages an inspector field holds open in the shared rich-text editor.\n *\n * While a passage is open its words exist only in that editor, and they reach\n * the document when the field is left. A Save or an exit that came first would\n * store the document without them. So a field holding a passage says so here,\n * and whoever finishes the canvas's open edit before storing the document\n * (`useInlineEditing`'s `commit`) finishes these too, through the field's own\n * commit, and is handed the document that commit wrote.\n *\n * One registry per editor, made by the host and lent both to the inspector and\n * to the inline editing it finishes: the two never import each other.\n *\n * @module open-passages\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\n\n/** How a field finishes its passage: the document its write produced, if any. */\nexport type FinishPassage = () => BlockDocument | null | void;\n\nexport interface OpenPassages {\n  /** Hold a passage open; the answer releases it. */\n  hold(finish: FinishPassage): () => void;\n  /**\n   * Finish every passage held, in the order they opened, and answer the\n   * document the last write produced, or `null` when none wrote.\n   */\n  finishAll(): BlockDocument | null;\n  /** Whether any passage is open, which is unsaved work. */\n  isOpen(): boolean;\n  /** Told whenever a passage opens or closes. */\n  subscribe(listener: () => void): () => void;\n}\n\n/** A fresh registry, for one editor. */\nexport function createOpenPassages(): OpenPassages {\n  const held = new Set<{ finish: FinishPassage }>();\n  const listeners = new Set<() => void>();\n  const changed = () => {\n    for (const listener of [...listeners]) listener();\n  };\n  return {\n    hold(finish) {\n      const entry = { finish };\n      held.add(entry);\n      changed();\n      return () => {\n        if (held.delete(entry)) changed();\n      };\n    },\n    finishAll() {\n      let written: BlockDocument | null = null;\n      // Copied first: a field releases its hold as it finishes.\n      for (const entry of [...held]) {\n        const document = entry.finish();\n        if (document !== null && document !== undefined) written = document;\n      }\n      return written;\n    },\n    isOpen: () => held.size > 0,\n    subscribe(listener) {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n  };\n}\n","/**\n * What a first-time author has not done yet, derived from the page itself.\n *\n * Every step is DERIVED from the document rather than tracked as the author\n * works. Tracking would need a second store of \"has this person inserted a\n * block\", which drifts from the page the moment anything else changes it —\n * an import, a duplicate of an existing page, a colleague's edit — and then\n * congratulates someone for work they did not do, or asks them to do what is\n * already there.\n *\n * Derivation has one honest cost: a step completed and then undone goes back to\n * incomplete. That is the right reading. The checklist describes the PAGE, not\n * a person's history with it, and a page with no blocks is a page whose author\n * still needs to add one.\n *\n * ## Why these three\n *\n * They are the gestures nothing else in the editor teaches, in the order an\n * author meets them, and each is separately observable in the document. A step\n * that completed as a side effect of another would tell an author they had\n * learned something they never did.\n *\n * @module onboarding\n */\n\nimport {\n  getBlock,\n  oneParagraphWords,\n  walkNodes,\n  type BlockDocument,\n  type BlockNode,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { richInlineTargets } from \"../canvas/inline-rich-text\";\nimport { inlineTargets } from \"../canvas/inline-text\";\nimport { startWords } from \"../canvas/page-start-words\";\nimport { insertionPropSets } from \"../panels/add/inserter\";\n\n/** One thing to do, and whether the page shows it has been done. */\nexport interface ChecklistStep {\n  readonly id: string;\n  /** What to do, in the imperative. */\n  readonly label: string;\n  /** How to do it, naming the gesture. */\n  readonly hint: string;\n  readonly done: boolean;\n}\n\n/**\n * The texts a block can start with when it is placed, for one of its values:\n * what the inserter places it with, as itself or as any of its variations,\n * none of which an author has written.\n */\nfunction startingTexts(node: BlockNode, prop: string): ReadonlySet<string> {\n  const definition = getBlock(node.type);\n  if (definition === undefined) return new Set();\n  return new Set(\n    insertionPropSets(definition).flatMap(props => {\n      const value = props[prop];\n      // A Text starts with a one-paragraph value: its words are what it\n      // started with.\n      if (typeof value === \"string\") return [value.trim()];\n      const words = oneParagraphWords(value).trim();\n      return words === \"\" ? [] : [words];\n    })\n  );\n}\n\n/**\n * Whether any block on the page carries text an author typed: text that is\n * neither empty nor what the block started with, so placing a heading whose\n * default reads \"Heading\" does not count as writing something.\n */\nfunction hasAuthoredText(document: BlockDocument): boolean {\n  let found = false;\n  walkNodes(document.nodes, node => {\n    if (found) return;\n    // Asked of the same rule the canvas uses to decide what may be typed into,\n    // so \"text an author could have written here\" means one thing in both\n    // places. A block with no inline values cannot satisfy this step, which is\n    // correct: there was nothing to type.\n    // A Text's words count as typed text as a line's do: its one-paragraph\n    // value, read as the words it draws.\n    const typed = [\n      ...inlineTargets(document, node.id),\n      ...richInlineTargets(document, node.id)\n        .filter(target => target.oneParagraph === true)\n        .map(target => ({\n          prop: target.prop,\n          value: oneParagraphWords(target.stored),\n        })),\n    ];\n    found = typed.some(target => {\n      const text = target.value.trim();\n      return text !== \"\" && !startingTexts(node, target.prop).has(text);\n    });\n  });\n  return found;\n}\n\n/** How many top-level blocks the page holds. */\nfunction topLevelCount(document: BlockDocument): number {\n  return document.nodes.length;\n}\n\n/**\n * The checklist for this page.\n *\n * @param document - the page being edited\n * @returns the steps, in the order an author meets them\n */\nexport function builderChecklist(\n  document: BlockDocument\n): readonly ChecklistStep[] {\n  const blocks = topLevelCount(document);\n  return [\n    {\n      id: \"add-block\",\n      label: \"Add your first block\",\n      // The empty page's own Add section button first, which is on the canvas\n      // beside this step, then the rail, which is there on every page.\n      hint: `Click ${startWords(document.kind).start}, or open Add in the left rail.`,\n      done: blocks > 0,\n    },\n    {\n      id: \"write-text\",\n      label: \"Write something\",\n      hint: \"Double-click text on the canvas, or select a block and press Enter.\",\n      done: hasAuthoredText(document),\n    },\n    {\n      id: \"build-page\",\n      label: \"Add a second block\",\n      hint: \"A page is a stack of blocks. Drag one above another to reorder.\",\n      done: blocks > 1,\n    },\n  ];\n}\n\n/**\n * Whether every step is done.\n *\n * Derived here rather than counted by each caller, so the card and anything\n * that decides whether to render it cannot disagree about what finished means.\n */\nexport function checklistComplete(steps: readonly ChecklistStep[]): boolean {\n  return steps.length > 0 && steps.every(step => step.done);\n}\n\n/** How many are done, for a progress reading. */\nexport function checklistDoneCount(steps: readonly ChecklistStep[]): number {\n  return steps.filter(step => step.done).length;\n}\n","\"use client\";\n\n/**\n * The first-run card: what an author has not done on this page yet.\n *\n * Presentational. What the steps ARE and whether each is done is\n * {@link module:onboarding}'s derivation from the document; whether the card\n * should be on screen at all is {@link useBuilderChecklist}'s. Splitting the\n * three keeps the part with a rule in it testable without a DOM, which is the\n * same split the rest of this package makes.\n *\n * ## It stays after the last box is ticked\n *\n * Vanishing at the moment of completion takes away the only confirmation the\n * author gets, and reads as the card having crashed rather than as work being\n * finished. It stays, saying so, until it is dismissed — one click, on a card\n * that is plainly done.\n *\n * @module onboarding-checklist\n */\n\nimport type { BlockDocument } from \"@nextlyhq/blocks-engine\";\nimport { cn } from \"@nextlyhq/ui/utils\";\nimport { Check, X } from \"lucide-react\";\nimport { type JSX, useCallback, useMemo, useState } from \"react\";\n\nimport { browserStore, type PreferenceStore } from \"../shell-state\";\n\nimport {\n  builderChecklist,\n  checklistComplete,\n  checklistDoneCount,\n  type ChecklistStep,\n} from \"./onboarding\";\n\n/** Where the dismissal is remembered. */\nexport const CHECKLIST_STORAGE_KEY = \"nextly.builder.checklist.dismissed\";\n\nexport interface UseBuilderChecklistOptions {\n  /** The page being edited. Every step is derived from it. */\n  document: BlockDocument;\n  /**\n   * Which page this is, for an editor that can open another page without\n   * remounting: whether the page opened empty is read again when it changes.\n   * Absent, the first page read stands for the editor's life.\n   */\n  documentKey?: string;\n  /**\n   * Whether the checklist may be shown at all. Defaults to true.\n   *\n   * The host's kill switch. A site that has taught its authors the editor\n   * another way turns it off rather than asking every one of them to dismiss\n   * it.\n   */\n  enabled?: boolean;\n  /**\n   * Where the dismissal is remembered. Defaults to `localStorage`.\n   *\n   * A port rather than a direct call, so a test can drive it and a server\n   * render can have one that remembers nothing. Note what this is NOT: storage\n   * is per BROWSER, so two people sharing a profile share the dismissal. Per\n   * user in the sense that matters — nobody dismisses it for anyone else's\n   * machine — and not a claim about accounts.\n   *\n   * Keep the same store from render to render (memoise it): a new one is read\n   * afresh, which is how a store that arrives late is honoured.\n   */\n  store?: PreferenceStore;\n}\n\nexport interface UseBuilderChecklistResult {\n  readonly steps: readonly ChecklistStep[];\n  readonly visible: boolean;\n  readonly dismiss: () => void;\n}\n\n/**\n * Whether to show the card, and what it should say.\n *\n * @param options - the document, the kill switch, and where dismissal lives\n * @returns the steps, whether to render, and the way to stop\n */\nexport function useBuilderChecklist({\n  document,\n  documentKey,\n  enabled = true,\n  store,\n}: UseBuilderChecklistOptions): UseBuilderChecklistResult {\n  const source = useMemo(\n    () => store ?? browserStore(CHECKLIST_STORAGE_KEY),\n    [store]\n  );\n  // Read as a store arrives rather than once on mount: a host can hand its\n  // store over a render late (the author's id resolving after the editor\n  // opens), and the dismissal it holds is the one that counts.\n  const [dismissal, setDismissal] = useState(() => ({\n    source,\n    dismissed: readDismissed(source),\n  }));\n  let dismissed = dismissal.dismissed;\n  if (dismissal.source !== source) {\n    dismissed = readDismissed(source);\n    setDismissal({ source, dismissed });\n  }\n\n  const dismiss = useCallback(() => {\n    // Written before the state changes, and a failure is swallowed: private\n    // browsing refuses storage, and an author who cannot persist the dismissal\n    // should still get the card off their screen for this session.\n    try {\n      source.write(\"true\");\n    } catch {\n      // Storage refused. The in-memory dismissal below still stands.\n    }\n    setDismissal({ source, dismissed: true });\n  }, [source]);\n\n  // A first-run card, for a page the author starts from nothing. A page that\n  // opens with blocks was built already, by this author or another, and the\n  // card would only list steps nobody here just took. Read as each page\n  // opens, keyed by its identity: emptying the page later doesn't make it a\n  // first run, and opening another page in the same editor asks again.\n  const [opening, setOpening] = useState(() => ({\n    key: documentKey,\n    empty: document.nodes.length === 0,\n  }));\n  let openedEmpty = opening.empty;\n  if (opening.key !== documentKey) {\n    openedEmpty = document.nodes.length === 0;\n    setOpening({ key: documentKey, empty: openedEmpty });\n  }\n\n  // Once per page: the steps read every block, and the editor renders this on\n  // every click, which changes no block. An edit makes a new document.\n  const steps = useMemo(() => builderChecklist(document), [document]);\n  return { steps, visible: enabled && openedEmpty && !dismissed, dismiss };\n}\n\n/** Whether a store holds a dismissal; a store that can't be read holds none. */\nfunction readDismissed(source: PreferenceStore): boolean {\n  try {\n    return source.read() === \"true\";\n  } catch {\n    return false;\n  }\n}\n\nexport interface OnboardingChecklistProps {\n  steps: readonly ChecklistStep[];\n  /** Stop showing it. */\n  onDismiss: () => void;\n  className?: string;\n}\n\n/**\n * @param props - the steps and the way to dismiss them\n * @returns the card, or nothing when there are no steps to show\n */\nexport function OnboardingChecklist({\n  steps,\n  onDismiss,\n  className,\n}: OnboardingChecklistProps): JSX.Element | null {\n  if (steps.length === 0) return null;\n  const done = checklistDoneCount(steps);\n  const complete = checklistComplete(steps);\n\n  return (\n    // `complementary` with a name: the card is beside the editor's work rather\n    // than part of it, and an unnamed region is announced as \"region\".\n    <aside\n      aria-label=\"Getting started\"\n      className={cn(\n        // Above the canvas's own overlays (the spacing bands sit at 1), which\n        // would otherwise paint over the card; below the toolbar's menus.\n        \"border-[color:var(--nx-builder-border)] bg-[color:var(--nx-builder-surface-raised)] text-[color:var(--nx-builder-text)] relative z-10 w-72 rounded-lg border p-4 shadow-lg\",\n        className\n      )}\n    >\n      <div className=\"flex items-start justify-between gap-2\">\n        <div>\n          <p className=\"text-sm font-semibold\">\n            {complete ? \"You're all set\" : \"Getting started\"}\n          </p>\n          {/* The count is text rather than only a bar, so it is readable\n              without colour and announced without a label of its own. */}\n          <p className=\"text-[color:var(--nx-builder-text-muted)] text-xs\">\n            {done} of {steps.length} done\n          </p>\n        </div>\n        <button\n          type=\"button\"\n          onClick={onDismiss}\n          aria-label=\"Dismiss getting started\"\n          className=\"focus-visible:ring-ring text-[color:var(--nx-builder-text-muted)] -m-1 rounded p-1 focus-visible:ring-2 focus-visible:outline-none\"\n        >\n          <X className=\"size-4\" />\n        </button>\n      </div>\n\n      <ul className=\"mt-3 flex flex-col gap-3\">\n        {steps.map(step => (\n          <li key={step.id} className=\"flex gap-2\">\n            {/* Weight and a mark carry the state, not colour alone: a done\n                step reads as done in monochrome and to anyone who cannot\n                separate the two hues. */}\n            <span\n              aria-hidden\n              className=\"border-[color:var(--nx-builder-border)] mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border\"\n            >\n              {step.done ? <Check className=\"size-3\" /> : null}\n            </span>\n            <span className=\"min-w-0\">\n              <span\n                className={cn(\n                  \"block text-sm\",\n                  step.done\n                    ? \"text-[color:var(--nx-builder-text-muted)] font-normal line-through\"\n                    : \"font-medium\"\n                )}\n              >\n                {step.label}\n              </span>\n              {/* The hint stays on a done step rather than disappearing: the\n                  card is also how an author looks the gesture up again. */}\n              <span className=\"text-[color:var(--nx-builder-text-muted)] block text-xs\">\n                {step.hint}\n              </span>\n            </span>\n          </li>\n        ))}\n      </ul>\n    </aside>\n  );\n}\n","\"use client\";\n\n/**\n * What an Entry content block's Layers row says beside its name: the field\n * it draws, as a list's row says what it shows, and, where the collection no\n * longer has that field, the warning a row marks a problem with.\n *\n * Named by the one derivation the canvas's tab and the inspector use\n * (`fieldName`), so the three never name a field differently.\n *\n * @experimental Settles when collection templates ship.\n * @module entry-content-layers\n */\nimport {\n  entryContentFieldOf,\n  entryContentPlacements,\n  type BlockDocument,\n} from \"@nextlyhq/blocks-engine\";\nimport { AlertCircle } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport {\n  entryFieldRemoved,\n  fieldName,\n  usePreviewedCollection,\n} from \"../../canvas/previewed-entry\";\n\n/** One Entry content row's facts: its field's name, and whether it is gone. */\nexport interface EntryContentRowFacts {\n  readonly field: string;\n  readonly removed: boolean;\n}\n\n/** Each Entry content block's row facts, by its id, from one walk. */\nexport function useEntryContentRows(\n  document: BlockDocument\n): ReadonlyMap<string, EntryContentRowFacts> {\n  const collection = usePreviewedCollection();\n  return React.useMemo(() => {\n    const rows = new Map<string, EntryContentRowFacts>();\n    for (const { node } of entryContentPlacements(document.nodes)) {\n      const field = entryContentFieldOf(node);\n      if (field === undefined) continue;\n      rows.set(node.id, {\n        field: fieldName(field, collection),\n        removed: entryFieldRemoved(field, collection),\n      });\n    }\n    return rows;\n  }, [document, collection]);\n}\n\n/** The field an Entry content row names, and its warning where it is gone. */\nexport function EntryContentRowFact({\n  facts,\n}: {\n  facts: EntryContentRowFacts | undefined;\n}): React.JSX.Element | null {\n  if (facts === undefined) return null;\n  if (facts.removed) {\n    return (\n      <span className=\"nx-layer-row__badge\" data-problem=\"\">\n        {/* The icon is for the eye; the words are the fact. */}\n        <span aria-hidden=\"true\">\n          <AlertCircle size={12} />\n        </span>\n        <span className=\"nx-sr-only\">\n          {`${facts.field} no longer exists in this collection`}\n        </span>\n      </span>\n    );\n  }\n  return <span className=\"nx-layer-row__tag\">{facts.field}</span>;\n}\n","\"use client\";\n\n/**\n * The right-click menu over Layers rows.\n *\n * The row's own verbs first (Rename, hiding on the device being edited, the\n * lock), then the block verbs every other surface offers, from the SAME\n * shared set the inspector's card menu reads, so a verb is offered here\n * exactly when the toolbar and the canvas menu offer it, with the same\n * reason when it may not run.\n *\n * A right-click on a row the selection does not hold selects that row first,\n * as the canvas menu does, so the verbs act on the block the author pointed\n * at rather than on whatever was selected before.\n *\n * Each item names its keystroke, so the menu teaches the keyboard path to\n * the eye and the lock, whose icons are pointer-only.\n *\n * @module layer-row-menu\n */\n\nimport {\n  ContextMenu,\n  ContextMenuContent,\n  ContextMenuItem,\n  ContextMenuSeparator,\n  ContextMenuShortcut,\n  ContextMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { isElement } from \"../../canvas/dom-kind\";\nimport { useAskedSharedVerbs } from \"../../canvas/selection-offer\";\nimport { keyHint } from \"../../shell/key-hint\";\nimport type { SharedBlockVerbs } from \"../../shell/keyboard-actions\";\n\n/** One of the row's own verbs, as the menu offers it. */\nexport interface RowMenuItem {\n  readonly id: string;\n  readonly label: string;\n  /** Why it may not run, or `undefined` while it may. */\n  readonly reason?: string | undefined;\n  /** Its keystroke, in the binding grammar (\"mod+shift+h\"). */\n  readonly keys?: string;\n  readonly run: () => void;\n}\n\nexport interface LayerRowMenuProps {\n  /** The block a press on `target` points at, or `null` off the rows. */\n  readonly rowOf: (target: EventTarget | null) => string | null;\n  /** The selected ids, so a press on a selected row keeps the selection. */\n  readonly selectedIds: readonly string[];\n  /** Select one block, replacing the selection. */\n  readonly select: (id: string) => void;\n  /**\n   * The row's own verbs, for the row the menu was opened on: with several\n   * blocks selected, Rename acts on the row pointed at, not on the primary\n   * selection. Asked only while the menu is open: each item's reason is a\n   * lock question, and asking on every render of the panel would pay for a\n   * menu nobody opened.\n   */\n  readonly items: (id: string | null) => readonly RowMenuItem[];\n  /**\n   * Told when the menu opens, so a gesture that started on the same press\n   * gives way: a touch's long press first arms the row drag.\n   */\n  readonly onOpen?: () => void;\n  /** The shared block verbs, when the host shares them. */\n  readonly verbs: SharedBlockVerbs | undefined;\n  /** Whether the reader's keyboard is Apple's, `null` until known. */\n  readonly apple: boolean | null;\n  readonly children: React.ReactNode;\n}\n\n/** The wrapper generates no box, so the panel lays out as it did. */\nconst TRANSPARENT_WRAPPER: React.CSSProperties = { display: \"contents\" };\n\n/** One item, held with its reason as visible text when it may not run. */\nfunction Item({\n  label,\n  reason,\n  shortcut,\n  onSelect,\n}: {\n  label: string;\n  reason: string | undefined;\n  shortcut: string | null;\n  onSelect: () => void;\n}): React.JSX.Element {\n  return (\n    <ContextMenuItem\n      disabled={reason !== undefined}\n      className={reason === undefined ? undefined : \"flex-wrap\"}\n      onSelect={onSelect}\n    >\n      <span>{label}</span>\n      {shortcut === null ? null : (\n        <ContextMenuShortcut>{shortcut}</ContextMenuShortcut>\n      )}\n      {reason === undefined || reason === \"\" ? null : (\n        // Part of the item's content: a disabled item takes neither focus nor\n        // pointer, so an explanation outside it would reach nobody.\n        <span className=\"nx-layer-menu__reason\">{reason}</span>\n      )}\n    </ContextMenuItem>\n  );\n}\n\n/**\n * A group of the shared block verbs, after a separator, each held with the\n * reason the toolbar gives. Nothing at all for an empty group.\n */\nfunction SharedItems({\n  actions,\n  verbs,\n}: {\n  actions: SharedBlockVerbs[\"actions\"];\n  verbs: SharedBlockVerbs | undefined;\n}): React.JSX.Element | null {\n  if (actions.length === 0) return null;\n  return (\n    <>\n      <ContextMenuSeparator />\n      {actions.map(action => (\n        <Item\n          key={action.id}\n          label={action.label}\n          reason={action.enabled ? undefined : (action.reason ?? \"\")}\n          shortcut={null}\n          onSelect={() => verbs?.run(action.id)}\n        />\n      ))}\n    </>\n  );\n}\n\n/**\n * The shared block verbs, Delete last on its own, as the locks answer them:\n * drawn only while the menu is open, so the locks are asked when it opens.\n */\nfunction SharedGroups({\n  verbs,\n}: {\n  verbs: SharedBlockVerbs | undefined;\n}): React.JSX.Element {\n  const shared = useAskedSharedVerbs(verbs);\n  const deletion = shared.filter(action => action.id === \"delete\");\n  const others = shared.filter(action => action.id !== \"delete\");\n  return (\n    <>\n      <SharedItems actions={others} verbs={verbs} />\n      <SharedItems actions={deletion} verbs={verbs} />\n    </>\n  );\n}\n\n/** The row's own verbs, read when the menu's content is drawn. */\nfunction OwnItems({\n  items,\n  target,\n  hint,\n}: {\n  items: (id: string | null) => readonly RowMenuItem[];\n  target: string | null;\n  hint: (keys: string | undefined) => string | null;\n}): React.JSX.Element {\n  return (\n    <>\n      {items(target).map(item => (\n        <Item\n          key={item.id}\n          label={item.label}\n          reason={item.reason}\n          shortcut={hint(item.keys)}\n          onSelect={item.run}\n        />\n      ))}\n    </>\n  );\n}\n\nexport function LayerRowMenu({\n  rowOf,\n  selectedIds,\n  select,\n  items,\n  verbs,\n  apple,\n  onOpen,\n  children,\n}: LayerRowMenuProps): React.JSX.Element {\n  // The row the last press aimed at, kept until the menu opens: a touch's\n  // long press opens the menu without a context event of its own.\n  const pressed = React.useRef<string | null>(null);\n  // The row the open menu was opened on, which its own verbs act on.\n  const [target, setTarget] = React.useState<string | null>(null);\n  const note = React.useCallback(\n    (event: React.SyntheticEvent) => {\n      pressed.current = isElement(event.target) ? rowOf(event.target) : null;\n    },\n    [rowOf]\n  );\n  const onOpenChange = React.useCallback(\n    (next: boolean) => {\n      const id = pressed.current;\n      pressed.current = null;\n      if (next) {\n        setTarget(id);\n        onOpen?.();\n      }\n      if (!next || id === null || selectedIds.includes(id)) return;\n      select(id);\n    },\n    [select, selectedIds, onOpen]\n  );\n  const hint = (keys: string | undefined): string | null =>\n    keys === undefined || apple === null ? null : keyHint(keys, apple);\n  return (\n    // Not modal, as the canvas menu is not: a modal menu marks the editor\n    // around it aria-hidden while its controls stay focusable.\n    <ContextMenu modal={false} onOpenChange={onOpenChange}>\n      <ContextMenuTrigger asChild>\n        <div\n          style={TRANSPARENT_WRAPPER}\n          onPointerDown={note}\n          onContextMenu={event => {\n            note(event);\n            // Off the rows (the gaps between them) there is nothing to act\n            // on, so no menu opens: the trigger's own handler stands down for\n            // an event already handled.\n            if (pressed.current === null) event.preventDefault();\n          }}\n        >\n          {children}\n        </div>\n      </ContextMenuTrigger>\n      <ContextMenuContent aria-label=\"Layer actions\">\n        <OwnItems items={items} target={target} hint={hint} />\n        <SharedGroups verbs={verbs} />\n      </ContextMenuContent>\n    </ContextMenu>\n  );\n}\n","/**\n * The Layers rows' own keystrokes (rename, hide or show, lock or unlock), as\n * the editor's shortcut manager runs them and Help lists them, and how an\n * event finds the row it happened in.\n *\n * Its own module so the Layers panel stays the entry that draws the tree.\n *\n * @module panels/layers/layer-row-shortcuts\n */\nimport { useShortcuts } from \"@nextlyhq/ui\";\nimport type * as React from \"react\";\n\nimport { isElement } from \"../../canvas/dom-kind\";\n\nimport { ROW_KEYS, type RowKeyAction } from \"./layer-row-actions\";\n\n/** The block of the row an event happened in, or `null` off the rows. */\nexport function rowIdOf(target: EventTarget | null): string | null {\n  // Asked by node kind, so a row in another document still answers.\n  if (!isElement(target)) return null;\n  const row = target.closest('[role=\"treeitem\"]');\n  return (\n    row?.querySelector(\"[data-nx-layer]\")?.getAttribute(\"data-nx-layer\") ?? null\n  );\n}\n\n/** What each row keystroke does, as Help lists it. */\nconst ROW_KEY_DESCRIPTIONS: Readonly<Record<RowKeyAction, string>> = {\n  rename: \"Rename the block of the focused Layers row\",\n  \"toggle-hidden\":\n    \"Hide or show the block of the focused Layers row on the device being edited\",\n  \"toggle-lock\": \"Lock or unlock the block of the focused Layers row\",\n};\n\nconst ROW_KEY_ACTIONS: readonly RowKeyAction[] = [\n  \"rename\",\n  \"toggle-hidden\",\n  \"toggle-lock\",\n];\n\n/**\n * The row keystrokes, registered with the editor's shortcut manager so Help\n * lists them with every other binding. Each acts on the row that has focus,\n * and only while one of this panel's rows has it: the same keys elsewhere,\n * or in a rename's field, are left alone.\n */\nexport function RowShortcuts({\n  scope,\n  act,\n}: {\n  scope: React.RefObject<HTMLElement | null>;\n  act: (id: string, action: RowKeyAction) => void;\n}): null {\n  const focusedRow = (): string | null => {\n    const root = scope.current;\n    const active = root?.ownerDocument.activeElement;\n    if (\n      root === null ||\n      root === undefined ||\n      active === null ||\n      active === undefined ||\n      !root.contains(active) ||\n      active.getAttribute(\"role\") !== \"treeitem\"\n    ) {\n      return null;\n    }\n    return rowIdOf(active);\n  };\n  useShortcuts(\n    ROW_KEY_ACTIONS.map(action => ({\n      keys: ROW_KEYS[action],\n      description: ROW_KEY_DESCRIPTIONS[action],\n      when: () => focusedRow() !== null,\n      run: () => {\n        const id = focusedRow();\n        if (id !== null) act(id, action);\n      },\n    })),\n    { name: \"builder-layers-rows\" }\n  );\n  return null;\n}\n","/**\n * Where a Layers row dragged by the pointer would land, and whether it may.\n *\n * The Layers panel is a list of rows, so a drag there asks two things the\n * canvas never does: WHICH GAP between two rows the pointer is at, and HOW\n * DEEP the block should sit there. The gap comes from the pointer's height\n * against the rows; the depth from how far right the pointer has travelled.\n * Both are answered here, from measured rows and the document, so every rule\n * below is assertable without a browser — jsdom draws every row zero pixels\n * tall and could not exercise one of them.\n *\n * ## Depth is the pointer's x, one level per {@link LAYERS_DEPTH_PX}\n *\n * Measured from `left`, the x at which depth zero begins. The panel puts that\n * where the pressed row's own depth started, so a drag straight down keeps the\n * block at the depth it had, and a drag to the right nests it.\n *\n * The depth is then clamped to what the gap allows. It may be no shallower\n * than the row below the gap — anything less would leave that row with no\n * parent above it — and no deeper than one more than the row above, and that\n * only when the row above can hold blocks at all. A block dropped one level\n * deeper than the row above goes INSIDE that row; at the row's own depth or\n * less it goes after the row's ancestor at that depth.\n *\n * ## Judged by the one placement rule, and the locks\n *\n * A position the gap allows is not therefore allowed. Each is asked of\n * `canPlaceIn`, the rule a save and every other surface ask, and of the\n * editor's own lock question, the one its apply asks — so a drop is refused\n * with the rule's reason rather than offered and then undone. Their answers are\n * kept for the gesture in a {@link LayersVerdictCache}: the document, the block\n * and the sources cannot change while a drag lasts.\n *\n * @module layers-drop\n */\n\nimport {\n  canPlaceIn,\n  DEFAULT_SLOT,\n  findNode,\n  locateNode,\n  type BlockDocument,\n  type BlockNode,\n  type PlacementRefused,\n  type PlacementSources,\n  type PlacementVerdict,\n} from \"@nextlyhq/blocks-engine\";\nimport { TREE_INDENT_PX } from \"@nextlyhq/ui\";\n\nimport {\n  placementWording,\n  type RefusalWording,\n} from \"../../canvas/drag-refusal\";\nimport { movingSubtree } from \"../../canvas/drop-targets\";\nimport { indentSlot } from \"../../canvas/keyboard-move\";\nimport type { Point } from \"../../geometry\";\nimport {\n  lockedBlockWording,\n  lockRefusalWording,\n  type LockRefusalFacts,\n} from \"../../lock-refusal\";\nimport { lockBlockingMove } from \"../../locking\";\nimport type { BuilderOp, OpPosition, SlotAddress } from \"../../op-vocabulary\";\n\nimport { pathTo } from \"./layers\";\n\n/**\n * How far right the pointer travels to nest a block one level deeper: the\n * tree's own indent, so a depth the pointer reaches is drawn exactly where a\n * row at that depth starts.\n */\nexport const LAYERS_DEPTH_PX: typeof TREE_INDENT_PX = TREE_INDENT_PX;\n\n/** One row on screen, measured, with where its block sits in the document. */\nexport interface LayersRow {\n  readonly id: string;\n  /** 0 for a block at the top of the page. */\n  readonly depth: number;\n  /** The block's container, absent at the top of the page. */\n  readonly parentId: string | undefined;\n  /** The slot it sits in inside that container, absent at the top. */\n  readonly slot: string | undefined;\n  /** Its index in that slot. */\n  readonly index: number;\n  /** Whether the row is open, showing the rows of what it holds. */\n  readonly expanded: boolean;\n  /** Whether the block has anywhere to put a block (`holdsBlocks`). */\n  readonly canHoldChildren: boolean;\n  /** Where the row starts and how tall it is, in the pointer's coordinates. */\n  readonly top: number;\n  readonly height: number;\n}\n\n/**\n * The answers already reached in one gesture.\n *\n * Keyed by the parent id and the slot as SEPARATE map keys rather than one\n * joined string. Ids are stored data and slot names are a definition's, and\n * either may hold any character, so any separator could collide: parent `a:b`\n * slot `c` and parent `a` slot `b:c` would join to the same key and share a\n * verdict. `null` is the top of the page, which has no parent.\n *\n * The placement verdict depends on the container alone; a lock's also on the\n * index, since a slot locked to its order refuses one place and not another.\n */\nexport interface LayersVerdictCache {\n  readonly placement: Map<string | null, Map<string, PlacementVerdict>>;\n  readonly locks: Map<\n    string | null,\n    Map<string, Map<number, LockRefusalFacts | null>>\n  >;\n}\n\n/** An empty cache, for the start of a gesture. */\nexport function layersVerdictCache(): LayersVerdictCache {\n  return { placement: new Map(), locks: new Map() };\n}\n\n/** What the drop is judged against. */\nexport interface LayersPlacement {\n  /** The document the drag began on. */\n  readonly document: BlockDocument;\n  /** Where the placement rule reads its answers (`placementSources`). */\n  readonly sources: PlacementSources;\n  /** The editor's own lock question, the one its apply asks. */\n  readonly lockRefusalFor: (\n    ops: readonly BuilderOp[]\n  ) => LockRefusalFacts | undefined;\n  /** The answers this gesture has already reached. */\n  readonly verdicts: LayersVerdictCache;\n}\n\n/** What {@link layersDrop} reads. */\nexport interface LayersDropInput {\n  /** The rows on screen, in order. */\n  readonly rows: readonly LayersRow[];\n  /** The block being dragged. */\n  readonly draggedId: string;\n  /** The pointer, in the rows' coordinates. */\n  readonly pointer: Point;\n  /** The x at which depth zero begins; see the module docblock. */\n  readonly left: number;\n  readonly placement: LayersPlacement;\n}\n\n/** Where the line is drawn: the gap's height, and the depth it is at. */\nexport interface LayersLine {\n  readonly y: number;\n  readonly depth: number;\n}\n\n/**\n * Why a drop is refused: the placement rule's whole answer with the two types\n * its words name, or the lock a move there would break.\n */\nexport type LayersRefusal =\n  | {\n      readonly kind: \"placement\";\n      readonly verdict: PlacementRefused;\n      readonly movingType: string;\n      readonly regionType: string | undefined;\n    }\n  | { readonly kind: \"lock\"; readonly lock: LockRefusalFacts }\n  /**\n   * The dragged block holds a block the author locked, itself or deeper. The\n   * op layer relocates no subtree holding a locked block, so this refuses\n   * every place, before release rather than by an apply that does nothing.\n   */\n  | {\n      readonly kind: \"held\";\n      readonly locked: BlockNode;\n      /** The dragged block, which the locked one is, holds or sits inside. */\n      readonly movingId: string;\n    };\n\n/** What the pointer means right now. */\nexport type LayersDropResult =\n  | { readonly kind: \"none\" }\n  | {\n      readonly kind: \"drop\";\n      /** The move's position, in the shape the op store consumes. */\n      readonly to: OpPosition;\n      /** The slot the block leaves, for the store to drop if left empty. */\n      readonly dropSlotIfEmpty?: SlotAddress;\n      readonly line: LayersLine;\n    }\n  | {\n      readonly kind: \"refused\";\n      readonly refusal: LayersRefusal;\n      readonly line: LayersLine;\n    };\n\nconst NONE: LayersDropResult = { kind: \"none\" };\n\n/**\n * The row the pointer's height is over, or `undefined` outside every row.\n *\n * Top edge in, bottom edge out, so two touching rows never both claim the\n * boundary between them.\n */\nexport function rowAt(\n  rows: readonly LayersRow[],\n  y: number\n): LayersRow | undefined {\n  return rows.find(row => y >= row.top && y < row.top + row.height);\n}\n\n/** The words a refusal is shown and announced with, from the shared wording. */\nexport function layersRefusalWording(refusal: LayersRefusal): RefusalWording {\n  switch (refusal.kind) {\n    case \"lock\":\n      return lockRefusalWording(refusal.lock);\n    case \"held\":\n      return lockedBlockWording(refusal.locked, refusal.movingId);\n    case \"placement\":\n      return placementWording(\n        refusal.verdict,\n        refusal.movingType,\n        refusal.regionType\n      );\n  }\n}\n\n/** The nearest row outside the dragged block, stepping from `from` by `step`. */\nfunction nearestOutside(\n  rows: readonly LayersRow[],\n  from: number,\n  step: 1 | -1,\n  moving: ReadonlySet<string>\n): LayersRow | undefined {\n  for (let at = from; at >= 0 && at < rows.length; at += step) {\n    const row = rows[at];\n    if (row !== undefined && !moving.has(row.id)) return row;\n  }\n  return undefined;\n}\n\n/** A value from a two-level map, made and stored on the first ask. */\nfunction heldIn<K, S, V>(\n  outer: Map<K, Map<S, V>>,\n  first: K,\n  second: S,\n  make: () => V\n): V {\n  let inner = outer.get(first);\n  if (inner === undefined) {\n    inner = new Map();\n    outer.set(first, inner);\n  }\n  const held = inner.get(second);\n  if (held !== undefined) return held;\n  const made = make();\n  inner.set(second, made);\n  return made;\n}\n\n/** The position a row's block occupies now, read from the measured row. */\nfunction positionOf(row: LayersRow): OpPosition {\n  return row.parentId === undefined || row.slot === undefined\n    ? { index: row.index }\n    : { parentId: row.parentId, slot: row.slot, index: row.index };\n}\n\n/** The position after the block `id`, in the container it sits in. */\nfunction positionAfter(nodes: BlockNode[], id: string): OpPosition | undefined {\n  const at = locateNode(nodes, id);\n  if (at === undefined) return undefined;\n  return at.parent === undefined || at.slot === undefined\n    ? { index: at.index + 1 }\n    : { parentId: at.parent.id, slot: at.slot, index: at.index + 1 };\n}\n\n/** The gap the pointer is at: the rows either side of it, outside the block. */\ninterface Gap {\n  readonly above: LayersRow | undefined;\n  readonly below: LayersRow | undefined;\n  /** Where the line is drawn for it. */\n  readonly y: number;\n}\n\n/**\n * The position a gap and a depth name, before the dragged block is lifted out.\n *\n * Inside the row above when the depth is one more than its own. At the row\n * below's depth, before that row, in its own slot and at its own index: the\n * rows of a container's slots are drawn as one run, so the row above can sit\n * in a different slot from the row below, and \"after the row above\" would put\n * the block in the wrong one. Otherwise after the row above's ancestor at that\n * depth.\n */\nfunction positionFor(\n  document: BlockDocument,\n  components: PlacementSources[\"components\"],\n  gap: Gap,\n  depth: number\n): OpPosition | undefined {\n  const { above, below } = gap;\n  if (above === undefined) return { index: 0 };\n  if (depth > above.depth) {\n    return positionInside(document.nodes, components, above, below);\n  }\n  if (below !== undefined && below.depth === depth) return positionOf(below);\n  // The trail from the top of the page down to the row above, so its entry at\n  // `depth` is the block the drop goes after. Read from the document rather\n  // than from the rows: an ancestor may be scrolled out of the drawn window.\n  const anchor = pathTo(document, above.id)[depth];\n  return anchor === undefined\n    ? undefined\n    : positionAfter(document.nodes, anchor.id);\n}\n\n/**\n * The position inside the row above: before the row below when that row is\n * the first thing it shows, at the end of the slot an indent enters otherwise.\n * A container that cannot name one slot for an indent is aimed at the default\n * slot, which the placement rule then refuses in its own words.\n */\nfunction positionInside(\n  nodes: BlockNode[],\n  components: PlacementSources[\"components\"],\n  above: LayersRow,\n  below: LayersRow | undefined\n): OpPosition | undefined {\n  if (below?.parentId === above.id && below.slot !== undefined) {\n    return { parentId: above.id, slot: below.slot, index: below.index };\n  }\n  const container = findNode(nodes, above.id);\n  if (container === undefined) return undefined;\n  const slot = indentSlot(container, components) ?? DEFAULT_SLOT;\n  return {\n    parentId: above.id,\n    slot,\n    index: container.slots?.[slot]?.length ?? 0,\n  };\n}\n\n/**\n * The position with the dragged block lifted out first, which is what the\n * store's `move` addresses; `undefined` when that is where it already is.\n */\nfunction liftedPosition(\n  nodes: BlockNode[],\n  draggedId: string,\n  to: OpPosition\n): OpPosition | undefined {\n  const here = locateNode(nodes, draggedId);\n  if (here === undefined) return undefined;\n  const sameList =\n    here.parent?.id === to.parentId &&\n    (to.parentId === undefined || here.slot === to.slot);\n  if (!sameList) return to;\n  const index = here.index < to.index ? to.index - 1 : to.index;\n  if (index === here.index) return undefined;\n  return { ...to, index };\n}\n\n/** The slot a move would leave, when the block leaves the list it is in. */\nfunction vacated(\n  nodes: BlockNode[],\n  draggedId: string,\n  to: OpPosition\n): SlotAddress | undefined {\n  const here = locateNode(nodes, draggedId);\n  if (here?.parent === undefined || here.slot === undefined) return undefined;\n  if (here.parent.id === to.parentId && here.slot === to.slot) return undefined;\n  return { parentId: here.parent.id, slot: here.slot };\n}\n\n/** The placement rule's refusal of the block at `to`, or `undefined`. */\nfunction placementRefusal(\n  placement: LayersPlacement,\n  moving: BlockNode,\n  to: OpPosition\n): LayersRefusal | undefined {\n  const { document, sources, verdicts } = placement;\n  const verdict = heldIn(\n    verdicts.placement,\n    to.parentId ?? null,\n    to.slot ?? \"\",\n    () =>\n      canPlaceIn(\n        document.nodes,\n        [moving],\n        to.parentId === undefined\n          ? { kind: \"root\" }\n          : { kind: \"slot\", parentId: to.parentId, slot: to.slot },\n        sources\n      )\n  );\n  if (verdict.allowed) return undefined;\n  const parent =\n    to.parentId === undefined\n      ? undefined\n      : findNode(document.nodes, to.parentId);\n  return {\n    kind: \"placement\",\n    verdict,\n    movingType: moving.type,\n    regionType: parent?.type,\n  };\n}\n\n/** The lock a move to `to` would break, as a refusal, or `undefined`. */\nfunction lockRefusalAt(\n  placement: LayersPlacement,\n  op: Extract<BuilderOp, { kind: \"move\" }>\n): LayersRefusal | undefined {\n  const { to } = op;\n  const slots = heldIn(\n    placement.verdicts.locks,\n    to.parentId ?? null,\n    to.slot ?? \"\",\n    () => new Map<number, LockRefusalFacts | null>()\n  );\n  let lock = slots.get(to.index);\n  if (lock === undefined) {\n    lock = placement.lockRefusalFor([op]) ?? null;\n    slots.set(to.index, lock);\n  }\n  return lock === null ? undefined : { kind: \"lock\", lock };\n}\n\n/**\n * The gap at the pointer's height, or `undefined` outside every row.\n *\n * The upper half of a row is the gap before it, the lower half the gap after.\n * The dragged block and everything inside it are not places it can go, so the\n * gap is between the nearest rows outside it.\n */\nfunction gapAt(\n  rows: readonly LayersRow[],\n  y: number,\n  moving: ReadonlySet<string>\n): Gap | undefined {\n  const over = rowAt(rows, y);\n  if (over === undefined) return undefined;\n  const at = rows.indexOf(over);\n  const before = y < over.top + over.height / 2;\n  const above = nearestOutside(rows, before ? at - 1 : at, -1, moving);\n  const below = nearestOutside(rows, before ? at : at + 1, 1, moving);\n  if (above === undefined && below === undefined) return undefined;\n  return { above, below, y: before ? over.top : over.top + over.height };\n}\n\n/**\n * The depth the pointer's x asks for, clamped to what the gap allows: no\n * shallower than the row below, no deeper than one past a row above that holds\n * blocks. The floor wins when the two cross, so the row below always keeps a\n * parent.\n */\nfunction depthAt(gap: Gap, x: number, left: number): number {\n  const { above, below } = gap;\n  const deepest =\n    above === undefined ? 0 : above.depth + (above.canHoldChildren ? 1 : 0);\n  const wanted = Math.round((x - left) / LAYERS_DEPTH_PX);\n  return Math.max(below?.depth ?? 0, Math.min(wanted, deepest));\n}\n\n/**\n * Whether a gap and a depth name the place the dragged block already holds:\n * its own row lies between the rows either side of the gap, and the depth is\n * its own.\n */\nfunction isOwnPlace(\n  rows: readonly LayersRow[],\n  gap: Gap,\n  draggedId: string,\n  depth: number\n): boolean {\n  const own = rows.findIndex(row => row.id === draggedId);\n  if (own === -1 || rows[own]?.depth !== depth) return false;\n  const above = gap.above === undefined ? -1 : rows.indexOf(gap.above);\n  const below = gap.below === undefined ? rows.length : rows.indexOf(gap.below);\n  return above < own && own < below;\n}\n\n/** The move to `to`, judged by the placement rule and then the locks. */\nfunction judged(\n  placement: LayersPlacement,\n  moving: BlockNode,\n  to: OpPosition,\n  line: LayersLine\n): LayersDropResult {\n  // The editor's own question first (`lockBlockingMove`): a locked block,\n  // one inside the dragged block or one it sits inside holds it wherever it\n  // would go, so every place answers the same way.\n  const held = lockBlockingMove(placement.document, moving.id);\n  if (held !== undefined) {\n    return {\n      kind: \"refused\",\n      refusal: { kind: \"held\", locked: held, movingId: moving.id },\n      line,\n    };\n  }\n  const refused = placementRefusal(placement, moving, to);\n  if (refused !== undefined) return { kind: \"refused\", refusal: refused, line };\n  const dropSlotIfEmpty = vacated(placement.document.nodes, moving.id, to);\n  const leaves = dropSlotIfEmpty === undefined ? {} : { dropSlotIfEmpty };\n  const locked = lockRefusalAt(placement, {\n    kind: \"move\",\n    id: moving.id,\n    to,\n    ...leaves,\n  });\n  if (locked !== undefined) return { kind: \"refused\", refusal: locked, line };\n  return { kind: \"drop\", to, ...leaves, line };\n}\n\n/**\n * Where a dragged row would land, and whether it may.\n *\n * `none` outside every row, and at the place the block already occupies —\n * a drop there would be an edit that changes nothing, and an undo step the\n * author never made.\n */\nexport function layersDrop(input: LayersDropInput): LayersDropResult {\n  const { rows, draggedId, pointer, placement } = input;\n  const { document } = placement;\n  const moving = findNode(document.nodes, draggedId);\n  if (moving === undefined) return NONE;\n  const gap = gapAt(rows, pointer.y, movingSubtree(document, draggedId));\n  if (gap === undefined) return NONE;\n\n  const depth = depthAt(gap, pointer.x, input.left);\n  // The gap the block was lifted from, at the depth it had, is where it\n  // already is. Asked of its own row rather than of the rows either side:\n  // those can sit in two different slots of one container, and either one\n  // would move the block into the wrong slot.\n  if (isOwnPlace(rows, gap, draggedId, depth)) return NONE;\n  const aimed = positionFor(document, placement.sources.components, gap, depth);\n  const to =\n    aimed === undefined\n      ? undefined\n      : liftedPosition(document.nodes, draggedId, aimed);\n  if (to === undefined) return NONE;\n  return judged(placement, moving, to, { y: gap.y, depth });\n}\n","\"use client\";\n\n/**\n * Dragging a Layers row: the pointer, the line, and the reason a drop is\n * refused.\n *\n * Decides nothing about WHERE a row lands — {@link layersDrop} does that, from\n * measured rows, and judges it by the one placement rule and the editor's\n * locks. This is the seam between that and a browser: it reads the rows the\n * tree drew, follows one gesture, and commits the drop through the editor's\n * own `move`, the op a keyboard move applies, as one undo step.\n *\n * ## Driven from the panel, not the tree\n *\n * The rows are the shared `TreeView`'s, and nothing here changes it. The\n * gesture is read by delegation on an element around the tree: a press finds\n * its row through `role=\"treeitem\"` and the block through `data-nx-layer`, and\n * the depth through `aria-level` — the attributes the tree already draws for\n * assistive technology, so the drag reads the same structure a screen reader\n * does.\n *\n * ## Drag is an enhancement, never the only way\n *\n * WCAG 2.2 SC 2.5.7 asks for a way to do what a drag does without dragging.\n * The editor's move keys and the block menu's Move up, down, in and out do\n * every move this does, judged by the same rule.\n *\n * ## The rows are measured on every move\n *\n * Unlike the canvas, which measures once, a Layers drag changes the list under\n * the pointer: a collapsed row opens after a hover, and the tree draws only\n * the rows near the visible window, so a scroll swaps rows in and out. The rows\n * are therefore read again for each aim — a few dozen rectangles at most.\n *\n * @module layers-drag\n */\n\nimport type {\n  BlockDocument,\n  BlockNode,\n  ComponentLookup,\n  NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport { useIsomorphicLayoutEffect } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { autoscrollStep } from \"../../canvas/autoscroll\";\nimport { DEFAULT_ACTIVATION_PX } from \"../../canvas/canvas-drag\";\nimport { isElement } from \"../../canvas/dom-kind\";\nimport { placementSources } from \"../../canvas/drop-targets\";\nimport {\n  canvasContentPoint,\n  canvasContentRect,\n  containerEdges,\n} from \"../../canvas/geometry-dom\";\nimport { holdsBlocks } from \"../../canvas/keyboard-move\";\nimport { RefusalNotice } from \"../../canvas/refusal-notice\";\nimport type { EditorState } from \"../../editor-state\";\nimport type { Point, Rect } from \"../../geometry\";\nimport { isLayersLockFacts } from \"../../lock-refusal\";\nimport { refusalAnnouncement, unmovedAnnouncement } from \"../../move-refusal\";\n\nimport {\n  LAYERS_DEPTH_PX,\n  layersDrop,\n  layersRefusalWording,\n  layersVerdictCache,\n  rowAt,\n  type LayersDropResult,\n  type LayersRow,\n  type LayersVerdictCache,\n} from \"./layers-drop\";\n\n/** How long the pointer rests on a collapsed row before it opens. */\nexport const LAYERS_OPEN_DELAY_MS = 500;\n\n/**\n * How long a finger holds a row before it is picked up.\n *\n * A touch cannot use the mouse's distance threshold: a finger moving on a list\n * is a scroll, and the tree keeps the browser's own touch panning so that it\n * stays one. So a touch drag begins with a HOLD, the sortable-list pattern a\n * touch user already knows, and only a still finger becomes a drag.\n */\nexport const LAYERS_TOUCH_HOLD_MS = 300;\n\n/**\n * How far a finger may tremble during the hold and still be holding. Past it\n * the finger is moving, which is a scroll, and the press is let go.\n */\nexport const LAYERS_TOUCH_TOLERANCE_PX = 5;\n\n/** How far past the panel's edge a refusal's reason sits. */\nconst NOTICE_GAP_PX = 8;\n/** How far above the line the reason starts, so its first line meets it. */\nconst NOTICE_LIFT_PX = 10;\n/** The least margin a reason keeps from the window's edges. */\nconst NOTICE_MARGIN_PX = 8;\n\n/** The class the tree's scrolling element carries, set by the panel. */\nexport const LAYERS_TREE_CLASS = \"nx-layers-panel__tree\";\n\nexport interface UseLayersDragOptions {\n  /** The editor whose document a drop moves a block in. */\n  editor: EditorState;\n  /** The nesting rules the placement is judged by. */\n  nesting: NestingSource;\n  /** The component definitions an instance is judged by, when there are any. */\n  definitions?: ComponentLookup;\n  /**\n   * Whether a press may start a drag. Off while a search filters the rows:\n   * a filtered list hides the neighbours a gap is between, so a line drawn\n   * there would name a place the author cannot see.\n   */\n  enabled: boolean;\n  /** Opens a collapsed row the pointer has rested on. */\n  onOpen: (id: string) => void;\n}\n\n/** What the panel draws while a drag is aimed somewhere. */\nexport interface LayersDrawn {\n  readonly result: Exclude<LayersDropResult, { kind: \"none\" }>;\n  /** The line's height, measured from the top of the element the drag is on. */\n  readonly top: number;\n  /** The line's start, measured from the left of that element. */\n  readonly left: number;\n  /**\n   * Where a refusal's reason is placed, in WINDOW coordinates: level with the\n   * line, just past the panel's right edge, so it covers none of the rows the\n   * author is aiming between.\n   */\n  readonly notice: { readonly top: number; readonly left: number };\n}\n\nexport interface LayersDrag {\n  /** The handlers the element around the tree must carry. */\n  readonly handlers: {\n    readonly onPointerDown: React.PointerEventHandler<HTMLElement>;\n    readonly onPointerMove: React.PointerEventHandler<HTMLElement>;\n    readonly onPointerUp: React.PointerEventHandler<HTMLElement>;\n    readonly onPointerCancel: React.PointerEventHandler<HTMLElement>;\n    readonly onLostPointerCapture: React.PointerEventHandler<HTMLElement>;\n  };\n  /** The block being dragged, or null when no drag is in flight. */\n  readonly draggingId: string | null;\n  /** What to draw, or null when the pointer aims nowhere. */\n  readonly drawn: LayersDrawn | null;\n  /** The live region's text: why the drop under the pointer is refused. */\n  readonly announcement: string;\n  /**\n   * Abandon the gesture, held or in flight, drawing nothing: for another\n   * gesture that claims the same press, such as a touch's long press opening\n   * the row menu.\n   */\n  readonly cancel: () => void;\n}\n\n/** What one gesture remembers, none of which renders. */\ninterface Gesture {\n  readonly owner: number;\n  readonly id: string;\n  /** The element the handlers are on, which the rows are read inside. */\n  readonly host: HTMLElement;\n  readonly originX: number;\n  readonly originY: number;\n  /** Where depth zero begins: the press, less the pressed row's own depth. */\n  readonly left: number;\n  readonly document: BlockDocument;\n  /** Every block of that document by id, read once (`placesIn`). */\n  readonly places: ReadonlyMap<string, Placed>;\n  /** Replaced, not kept, when the sources it was judged by are replaced. */\n  verdicts: LayersVerdictCache;\n  active: boolean;\n  clientX: number;\n  clientY: number;\n  result: LayersDropResult;\n  frame: number | null;\n  /** The collapsed row being rested on, and the timer that opens it. */\n  resting: { readonly id: string; readonly timer: number } | null;\n  /**\n   * Set when a row has opened under a pointer that may not move again: the\n   * rows below it have shifted, so the aim is read again on the next frame\n   * rather than leaving the line, and the release, on a list that has gone.\n   */\n  stale: boolean;\n  /** The reason this gesture last put in the live region, or \"\". */\n  spoken: string;\n  /** The tree's scroll offset when the gesture last aimed. */\n  seenScroll: number;\n  /** Whether a finger drives it, which picks up by a hold, not a distance. */\n  readonly touch: boolean;\n  /** The hold that picks a touched row up, while it is still being held. */\n  hold: number | null;\n  /** Lets the page pan again; set while a touched row is picked up. */\n  release: (() => void) | null;\n}\n\n/** The block a row stands for, read from the label the panel draws in it. */\nfunction rowBlockId(row: Element): string | null {\n  return (\n    row.querySelector(\"[data-nx-layer]\")?.getAttribute(\"data-nx-layer\") ?? null\n  );\n}\n\n/** Where one block sits in the document the drag began on. */\ninterface Placed {\n  readonly node: BlockNode;\n  readonly parentId: string | undefined;\n  readonly slot: string | undefined;\n  readonly index: number;\n}\n\n/**\n * Every block in the document by id, with where it sits, from ONE walk.\n *\n * Built when the gesture begins, because the document cannot change while a\n * drag lasts: the drag is the only gesture in flight and nothing is applied\n * until it ends. Each pointer move then places the rows on screen by lookup,\n * where finding each one in the document would walk it once per row per move.\n */\nfunction placesIn(document: BlockDocument): ReadonlyMap<string, Placed> {\n  const places = new Map<string, Placed>();\n  const walk = (\n    nodes: readonly BlockNode[],\n    parentId: string | undefined,\n    slot: string | undefined\n  ): void => {\n    nodes.forEach((node, index) => {\n      // Read defensively, as the engine's own walk is: a stored document may\n      // hold a hole or a slot that is not a list.\n      if (typeof node?.id !== \"string\") return;\n      places.set(node.id, { node, parentId, slot, index });\n      for (const [name, children] of Object.entries(node.slots ?? {})) {\n        if (Array.isArray(children)) walk(children, node.id, name);\n      }\n    });\n  };\n  walk(document.nodes, undefined, undefined);\n  return places;\n}\n\n/**\n * The rows on screen, in order, with where each block sits, measured in the\n * coordinates of the element the drag is on — the space the line is drawn in,\n * so a measured gap can be handed to `top` and lands on what was measured.\n */\nfunction measureRows(\n  host: HTMLElement,\n  places: ReadonlyMap<string, Placed>,\n  definitions: ComponentLookup | undefined\n): LayersRow[] {\n  const items = Array.from(\n    host.querySelectorAll<HTMLElement>('[role=\"treeitem\"]')\n  ).sort(\n    (a, b) =>\n      Number(a.getAttribute(\"data-tree-index\")) -\n      Number(b.getAttribute(\"data-tree-index\"))\n  );\n  return items.flatMap(item => {\n    const id = rowBlockId(item);\n    const at = id === null ? undefined : places.get(id);\n    if (id === null || at === undefined) return [];\n    const box = canvasContentRect(item, host);\n    return [\n      {\n        id,\n        depth: Number(item.getAttribute(\"aria-level\") ?? \"1\") - 1,\n        parentId: at.parentId,\n        slot: at.slot,\n        index: at.index,\n        expanded: item.getAttribute(\"aria-expanded\") === \"true\",\n        canHoldChildren: holdsBlocks(at.node, definitions),\n        top: box.y,\n        height: box.height,\n      },\n    ];\n  });\n}\n\n/**\n * Keep the browser from panning the page while a touched row is held.\n *\n * The tree leaves `touch-action` alone so a finger still scrolls it, which\n * means the browser would take a moving finger for a pan and cancel the\n * pointer. A `touchmove` cancelled before the pan starts stops that, and is\n * listened for only while a row is picked up. The long-press menu a held\n * finger would open is stopped for the same span. Answers the undo.\n */\nfunction holdPage(host: HTMLElement): () => void {\n  const stop = (event: Event): void => {\n    event.preventDefault();\n  };\n  // Not passive, or the cancel is ignored.\n  host.addEventListener(\"touchmove\", stop, { passive: false });\n  host.addEventListener(\"contextmenu\", stop);\n  return () => {\n    host.removeEventListener(\"touchmove\", stop);\n    host.removeEventListener(\"contextmenu\", stop);\n  };\n}\n\n/**\n * Where a row at depth zero starts its content, measured from a row on screen\n * and stepped back by the tree's indent: the line for a depth then starts\n * where a row at that depth draws its icon, with no offset assumed about how\n * the tree pads a row.\n */\nfunction depthStart(host: HTMLElement): number {\n  const content = host.querySelector(\".nx-layer-row\");\n  const row = content?.closest('[role=\"treeitem\"]');\n  if (\n    content === null ||\n    content === undefined ||\n    row === null ||\n    row === undefined\n  ) {\n    return 0;\n  }\n  const depth = Number(row.getAttribute(\"aria-level\") ?? \"1\") - 1;\n  return canvasContentRect(content, host).x - depth * LAYERS_DEPTH_PX;\n}\n\n/** Whether a point is inside a rectangle, edges included. */\nfunction inside(box: Rect, point: Point): boolean {\n  return (\n    point.x >= box.x &&\n    point.x <= box.x + box.width &&\n    point.y >= box.y &&\n    point.y <= box.y + box.height\n  );\n}\n\n/**\n * Whether the editor's locks hold a block where it is, so no drag can move it.\n *\n * A block in an area locked \"all\" or to its content may not move at all, not\n * even within the area; one locked to its order may still be reordered there.\n * Asked of the editor's own lock question with a move out to the end of the\n * page, which leaves only the area the block is in to answer.\n */\nfunction heldInPlace(editor: EditorState, id: string): boolean {\n  const found = editor.lockRefusalFor([\n    { kind: \"move\", id, to: { index: editor.document.nodes.length } },\n  ]);\n  // A slot locked to its order still lets it be reordered inside the slot. A\n  // Layers lock is not asked here: the drag starts and every place refuses it\n  // in the lock's words (`layersDrop`), so the author is told why.\n  return (\n    found !== undefined && !isLayersLockFacts(found) && found.lock !== \"insert\"\n  );\n}\n\n/** The row a press landed in, inside `host`: its block and its depth. */\nfunction pressedRow(\n  target: EventTarget,\n  host: HTMLElement\n): { id: string; depth: number } | null {\n  // Asked by node kind, so a row in another document still answers.\n  if (!isElement(target)) return null;\n  const row = target.closest('[role=\"treeitem\"]');\n  if (row === null || !host.contains(row)) return null;\n  const id = rowBlockId(row);\n  if (id === null) return null;\n  return { id, depth: Number(row.getAttribute(\"aria-level\") ?? \"1\") - 1 };\n}\n\n/**\n * Whether a drag may pick the block up. A block its area holds in place is\n * left alone: the press still selects it. A block a Layers lock holds, its own\n * or one inside or around it, is picked up so that the drag can say why it\n * will not land anywhere, as the canvas does.\n */\nfunction movable(editor: EditorState, id: string): boolean {\n  return !heldInPlace(editor, id);\n}\n\n/** A comparable spelling of what is drawn, so an unchanged aim draws nothing. */\nfunction drawnKey(drawn: LayersDrawn | null): string {\n  if (drawn === null) return \"\";\n  const { result } = drawn;\n  const why =\n    result.kind === \"refused\"\n      ? refusalAnnouncement(layersRefusalWording(result.refusal))\n      : \"\";\n  return [result.kind, drawn.top, drawn.left, why].join(\"\\u0000\");\n}\n\n/**\n * Wire pointer events on the element around the Layers tree to the drop rule.\n *\n * Returns handlers to spread onto that element and what to draw over it.\n */\nexport function useLayersDrag({\n  editor,\n  nesting,\n  definitions,\n  enabled,\n  onOpen,\n}: UseLayersDragOptions): LayersDrag {\n  const gesture = React.useRef<Gesture | null>(null);\n  const [draggingId, setDraggingId] = React.useState<string | null>(null);\n  const [drawn, setDrawn] = React.useState<LayersDrawn | null>(null);\n  const [announcement, setAnnouncement] = React.useState(\"\");\n\n  // Read at event time, so a handler bound on one render never acts on a\n  // document or an option a later render replaced.\n  const latest = React.useRef({\n    editor,\n    nesting,\n    definitions,\n    enabled,\n    onOpen,\n  });\n  latest.current = { editor, nesting, definitions, enabled, onOpen };\n\n  const stopResting = React.useCallback((drag: Gesture) => {\n    if (drag.resting !== null) window.clearTimeout(drag.resting.timer);\n    drag.resting = null;\n  }, []);\n\n  /** End the gesture and release what it holds, drawing nothing. */\n  const teardown = React.useCallback(() => {\n    const drag = gesture.current;\n    if (drag === null) return;\n    if (drag.frame !== null) cancelAnimationFrame(drag.frame);\n    if (drag.hold !== null) window.clearTimeout(drag.hold);\n    drag.release?.();\n    stopResting(drag);\n    if (drag.host.hasPointerCapture(drag.owner)) {\n      drag.host.releasePointerCapture(drag.owner);\n    }\n    gesture.current = null;\n  }, [stopResting]);\n\n  const reset = React.useCallback(() => {\n    teardown();\n    setDraggingId(null);\n    setDrawn(null);\n    // The region describes the drag, so it goes quiet when the drag ends; the\n    // next drag's reason is then a change it announces, even if identical.\n    setAnnouncement(\"\");\n  }, [teardown]);\n\n  /**\n   * Open a collapsed row the pointer rests on, after a short wait.\n   *\n   * Started once per row: a pointer moving within the same row keeps the\n   * timer it has rather than restarting it, or a hand that never holds\n   * perfectly still would never open anything.\n   */\n  const restOn = React.useCallback(\n    (drag: Gesture, row: LayersRow | undefined) => {\n      const opens =\n        row !== undefined &&\n        row.id !== drag.id &&\n        !row.expanded &&\n        row.canHoldChildren;\n      if (!opens) {\n        stopResting(drag);\n        return;\n      }\n      if (drag.resting?.id === row.id) return;\n      stopResting(drag);\n      const id = row.id;\n      drag.resting = {\n        id,\n        timer: window.setTimeout(() => {\n          if (gesture.current !== drag) return;\n          drag.resting = null;\n          drag.stale = true;\n          latest.current.onOpen(id);\n        }, LAYERS_OPEN_DELAY_MS),\n      };\n    },\n    [stopResting]\n  );\n\n  /** Re-aim the drag at where the pointer is now, and draw the answer. */\n  const aim = React.useCallback(\n    (drag: Gesture) => {\n      const { definitions: components, editor: current } = latest.current;\n      const tree = drag.host.querySelector(`.${LAYERS_TREE_CLASS}`);\n      const rows = measureRows(drag.host, drag.places, components);\n      const pointer = canvasContentPoint(drag.clientX, drag.clientY, drag.host);\n      // Outside the tree's own box is nowhere, even where a row the tree drew\n      // just beyond its scrolled edge would be under the pointer.\n      const within =\n        tree !== null && inside(canvasContentRect(tree, drag.host), pointer);\n      restOn(drag, within ? rowAt(rows, pointer.y) : undefined);\n      drag.result = within\n        ? layersDrop({\n            rows,\n            draggedId: drag.id,\n            pointer,\n            left: drag.left,\n            placement: {\n              document: drag.document,\n              sources: placementSources({\n                nesting: latest.current.nesting,\n                ...(components === undefined\n                  ? {}\n                  : { definitions: components }),\n              }),\n              lockRefusalFor: current.lockRefusalFor,\n              verdicts: drag.verdicts,\n            },\n          })\n        : { kind: \"none\" };\n\n      const result = drag.result;\n      const edges = containerEdges(drag.host);\n      const next: LayersDrawn | null =\n        result.kind === \"none\"\n          ? null\n          : {\n              result,\n              notice: {\n                top: edges.top + result.line.y - NOTICE_LIFT_PX,\n                left: edges.right + NOTICE_GAP_PX,\n              },\n              top: result.line.y,\n              left: depthStart(drag.host) + result.line.depth * LAYERS_DEPTH_PX,\n            };\n      setDrawn(previous =>\n        drawnKey(previous) === drawnKey(next) ? previous : next\n      );\n      const sentence =\n        result.kind === \"refused\"\n          ? refusalAnnouncement(layersRefusalWording(result.refusal))\n          : \"\";\n      // Spoken when the reason CHANGES, not on every move over the same\n      // refusal. Leaving a refused gap clears the region and so does the\n      // drag's end, so the same reason met again is a change, read again.\n      if (sentence !== drag.spoken) {\n        drag.spoken = sentence;\n        setAnnouncement(sentence);\n      }\n    },\n    [restOn]\n  );\n\n  /**\n   * Scroll the tree while the pointer rests near its top or bottom edge, and\n   * keep aiming: the rows move under a pointer that does not.\n   */\n  const pump = React.useCallback(() => {\n    const drag = gesture.current;\n    if (drag === null || !drag.active) return;\n    // The tree the drag is on was taken off the page — emptied, or the panel\n    // swapped it for its note — so there is nothing left to aim at, and a\n    // loop that kept running would hold a detached tree for ever.\n    if (!drag.host.isConnected) {\n      reset();\n      return;\n    }\n    const tree = drag.host.querySelector<HTMLElement>(`.${LAYERS_TREE_CLASS}`);\n    if (tree !== null) {\n      const edges = containerEdges(tree);\n      const step = autoscrollStep(drag.clientY, edges.top, edges.bottom);\n      if (step !== 0) tree.scrollTop += step;\n      // Whoever scrolled the tree — this loop, a wheel, a trackpad — the rows\n      // have moved under a pointer that has not, so the aim is read again.\n      // Compared with the offset last aimed at rather than with this frame's\n      // own step, which a scroll from outside never shows up in.\n      if (tree.scrollTop !== drag.seenScroll) {\n        drag.seenScroll = tree.scrollTop;\n        drag.stale = true;\n      }\n    }\n    if (drag.stale) {\n      drag.stale = false;\n      aim(drag);\n    }\n    drag.frame = requestAnimationFrame(pump);\n  }, [aim, reset]);\n\n  /**\n   * Turn a press into a drag: by distance for a mouse or a pen, by the hold\n   * for a finger. Either way the block is selected and the pointer captured\n   * only now, for the reason the canvas gives — capturing a press that stays\n   * a click would retarget the click away from the row.\n   */\n  const activate = React.useCallback(\n    (drag: Gesture) => {\n      drag.active = true;\n      drag.hold = null;\n      // A new drag starts quiet, whatever the last one left in the region —\n      // a refusal, or a move the editor did not make. Its own outcome is then\n      // a change from silence and is read out, even if it repeats the last.\n      setAnnouncement(\"\");\n      drag.host.setPointerCapture(drag.owner);\n      if (drag.touch) drag.release = holdPage(drag.host);\n      latest.current.editor.select(drag.id);\n      setDraggingId(drag.id);\n      drag.frame = requestAnimationFrame(pump);\n      aim(drag);\n    },\n    [aim, pump]\n  );\n\n  const onPointerDown = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      // The primary button only, and one gesture at a time.\n      if (event.button !== 0 || gesture.current?.active === true) return;\n      const { editor: current, enabled: allowed } = latest.current;\n      if (!allowed) return;\n      const pressed = pressedRow(event.target, event.currentTarget);\n      if (pressed === null || !movable(current, pressed.id)) return;\n      const { id, depth } = pressed;\n      gesture.current = {\n        owner: event.pointerId,\n        id,\n        host: event.currentTarget,\n        originX: event.clientX,\n        originY: event.clientY,\n        left:\n          canvasContentPoint(event.clientX, event.clientY, event.currentTarget)\n            .x -\n          depth * LAYERS_DEPTH_PX,\n        document: current.document,\n        places: placesIn(current.document),\n        verdicts: layersVerdictCache(),\n        active: false,\n        clientX: event.clientX,\n        clientY: event.clientY,\n        result: { kind: \"none\" },\n        frame: null,\n        resting: null,\n        stale: false,\n        spoken: \"\",\n        seenScroll:\n          event.currentTarget.querySelector(`.${LAYERS_TREE_CLASS}`)\n            ?.scrollTop ?? 0,\n        touch: event.pointerType === \"touch\",\n        hold: null,\n        release: null,\n      };\n      const drag = gesture.current;\n      if (drag.touch) {\n        drag.hold = window.setTimeout(() => {\n          if (gesture.current === drag && !drag.active) activate(drag);\n        }, LAYERS_TOUCH_HOLD_MS);\n      }\n    },\n    [activate]\n  );\n\n  const onPointerMove = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      const drag = gesture.current;\n      if (drag === null || drag.owner !== event.pointerId) return;\n      drag.clientX = event.clientX;\n      drag.clientY = event.clientY;\n      if (drag.active) {\n        aim(drag);\n        return;\n      }\n      const travelled = Math.hypot(\n        event.clientX - drag.originX,\n        event.clientY - drag.originY\n      );\n      if (drag.touch) {\n        // A finger that moves before the hold is scrolling: let it go, and\n        // the browser pans the list as it would have without this.\n        if (travelled > LAYERS_TOUCH_TOLERANCE_PX) reset();\n        return;\n      }\n      // The same threshold the canvas uses, so a click on a row stays a\n      // click and never commits a move to where the block already is.\n      if (travelled >= DEFAULT_ACTIVATION_PX) activate(drag);\n    },\n    [activate, aim, reset]\n  );\n\n  const onPointerUp = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      const drag = gesture.current;\n      if (drag === null || drag.owner !== event.pointerId) return;\n      const result = drag.result;\n      // ONE op, through the editor's own move: one undo step, refused by its\n      // apply as a keyboard move would be if anything changed under the drag.\n      // A refused or empty aim moves nothing, so the block stays where it was.\n      const applied =\n        drag.active && result.kind === \"drop\"\n          ? latest.current.editor.apply({\n              kind: \"move\",\n              id: drag.id,\n              to: result.to,\n              ...(result.dropSlotIfEmpty === undefined\n                ? {}\n                : { dropSlotIfEmpty: result.dropSlotIfEmpty }),\n            })\n          : undefined;\n      reset();\n      // A drop drawn as allowed that the store still refused is said, after\n      // the reset that quiets the region: a move that did not happen must not\n      // read like one that did.\n      if (applied === null) {\n        setAnnouncement(unmovedAnnouncement(drag.document, drag.id));\n      }\n    },\n    [reset]\n  );\n\n  const onPointerCancel = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      if (gesture.current?.owner !== event.pointerId) return;\n      reset();\n    },\n    [reset]\n  );\n\n  /*\n   * The browser took the pointer away — another element captured it, or the\n   * window lost it. The drag cannot hear its release any more, so it ends\n   * here rather than waiting for one. Only for an ACTIVE gesture of this\n   * pointer: the release this hook makes itself fires it after the gesture\n   * is already gone.\n   */\n  const onLostPointerCapture = React.useCallback(\n    (event: React.PointerEvent<HTMLElement>) => {\n      const drag = gesture.current;\n      if (drag === null || !drag.active) return;\n      if (drag.owner !== event.pointerId) return;\n      // The tree's OWN capture, and only that. A touch is captured by the row\n      // it lands on, and picking the row up moves the capture to the tree: the\n      // row reports losing it, and that event bubbles here. It is the drag\n      // taking hold, and ending the drag for it would end every touch drag.\n      if (event.target !== drag.host) return;\n      reset();\n    },\n    [reset]\n  );\n\n  /*\n   * The document changed under a drag — a Delete or an Undo pressed while the\n   * pointer is held. Everything the gesture judged was judged against the\n   * document it began on, and the dragged block may not exist any more, so\n   * the drag ends rather than dropping into a page it never saw.\n   */\n  React.useEffect(() => {\n    const drag = gesture.current;\n    if (drag !== null && drag.document !== editor.document) reset();\n  }, [editor.document, reset]);\n\n  /*\n   * The rules or the component definitions were replaced under a drag — the\n   * component library finishing its load, typically. The document is the\n   * same, so the gesture goes on, but every verdict it kept was reached with\n   * the old sources and the store will not ask again on release: they are\n   * dropped and the place under the pointer is judged afresh.\n   */\n  React.useEffect(() => {\n    const drag = gesture.current;\n    if (drag === null) return;\n    drag.verdicts = layersVerdictCache();\n    if (drag.active) aim(drag);\n  }, [definitions, nesting, aim]);\n\n  // A panel closed mid-drag must not leave a frame loop or a timer behind.\n  React.useEffect(() => teardown, [teardown]);\n\n  /*\n   * Escape abandons the drag. On the DOCUMENT and in the capture phase, as the\n   * canvas listens: the keyboard is wherever focus was when the drag began,\n   * and the editor's own Escape (clearing the selection) must not also run.\n   */\n  React.useEffect(() => {\n    if (draggingId === null) return;\n    const abandon = (event: KeyboardEvent): void => {\n      if (event.key !== \"Escape\") return;\n      event.preventDefault();\n      event.stopPropagation();\n      reset();\n    };\n    document.addEventListener(\"keydown\", abandon, true);\n    return () => {\n      document.removeEventListener(\"keydown\", abandon, true);\n    };\n  }, [draggingId, reset]);\n\n  return {\n    handlers: {\n      onPointerDown,\n      onPointerMove,\n      onPointerUp,\n      onPointerCancel,\n      onLostPointerCapture,\n    },\n    draggingId,\n    drawn,\n    announcement,\n    cancel: reset,\n  };\n}\n\n/**\n * The line where a dragged row would land, and why it cannot when it cannot.\n *\n * Drawn over the tree by the panel, in the coordinates of the element the\n * drag is on. Hidden from assistive technology: the reason is spoken through\n * the panel's live region, and a pointer gesture describes itself to anyone\n * who can see the line.\n */\nexport function LayersDropOverlay({\n  drawn,\n}: {\n  drawn: LayersDrawn | null;\n}): React.JSX.Element | null {\n  if (drawn === null) return null;\n  const { result } = drawn;\n  const refused = result.kind === \"refused\";\n  const wording = refused ? layersRefusalWording(result.refusal) : null;\n  return (\n    <>\n      <div\n        className=\"nx-layers-drop-line\"\n        data-refused={refused ? \"\" : undefined}\n        style={{ top: drawn.top, left: drawn.left }}\n        aria-hidden=\"true\"\n      />\n      {wording === null ? null : (\n        <PlacedRefusal\n          headline={wording.headline}\n          remedy={wording.remedy}\n          at={drawn.notice}\n        />\n      )}\n    </>\n  );\n}\n\n/**\n * A refused drop's reason, beside the panel rather than on it.\n *\n * Fixed in the window, level with the line, just past the panel's right edge,\n * so every row the author is aiming between stays readable. Fixed rather than\n * absolute so the panel's own clipping cannot cut it off; still drawn inside\n * the panel, so it keeps the editor's tokens and theme. Kept on screen by\n * moving it back inside the window by its own measured size.\n *\n * The one refusal notice the canvas draws too (`RefusalNotice`), placed here.\n */\nfunction PlacedRefusal({\n  headline,\n  remedy,\n  at,\n}: {\n  headline: string;\n  remedy: string | null;\n  at: LayersDrawn[\"notice\"];\n}): React.JSX.Element {\n  const element = React.useRef<HTMLDivElement | null>(null);\n  const [placed, setPlaced] = React.useState(at);\n  useIsomorphicLayoutEffect(() => {\n    const notice = element.current;\n    if (notice === null) return;\n    const right = window.innerWidth - notice.offsetWidth - NOTICE_MARGIN_PX;\n    const bottom = window.innerHeight - notice.offsetHeight - NOTICE_MARGIN_PX;\n    const left = Math.max(NOTICE_MARGIN_PX, Math.min(at.left, right));\n    const top = Math.max(NOTICE_MARGIN_PX, Math.min(at.top, bottom));\n    setPlaced(previous =>\n      previous.left === left && previous.top === top ? previous : { left, top }\n    );\n  }, [at.left, at.top, headline, remedy]);\n  return (\n    <RefusalNotice\n      ref={element}\n      className=\"nx-layers-drop-refusal\"\n      style={{ position: \"fixed\", top: placed.top, left: placed.left }}\n      headline={headline}\n      remedy={remedy}\n    />\n  );\n}\n","\"use client\";\n\n/**\n * Layers' rows for the regions of the page's layout, its header and footer,\n * which are not the page's blocks, and what Layers does while one of them is\n * edited in place.\n *\n * @module layers-regions\n */\nimport type { RegionArea } from \"@nextlyhq/blocks-engine\";\nimport { Lock } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { isHTMLElement } from \"../../canvas/dom-kind\";\nimport { EDITOR_WORDS } from \"../../editor-words\";\n\n/** The region Layers shows the blocks of while it is edited in place. */\nexport interface LayersEditedRegion {\n  /** Its name, \"Site header\". */\n  readonly label: string;\n}\n\n/**\n * The regions whose first row has had focus, by the editing session's own\n * value, so it moves there once as editing starts and not again when the\n * panel is closed and opened while the same region is edited.\n */\nconst focusedRegions = new WeakSet<LayersEditedRegion>();\n\n/** One region of the page's layout, as a row of its own in Layers. */\nexport interface LayersRegionRow {\n  readonly area: RegionArea;\n  /** The region's name, \"Site header\". */\n  readonly name: string;\n  /** Where it comes from, \"Main header & footer\". */\n  readonly origin: string;\n  /** Whether the region is the canvas's selection. */\n  readonly selected?: boolean;\n  /** Select the region, and show it on the canvas. */\n  readonly onActivate: () => void;\n}\n\n/** A region of the page's layout, as a row that is not one of the page's blocks. */\nexport function RegionRow({\n  row,\n}: {\n  row: LayersRegionRow;\n}): React.JSX.Element {\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-layers-region\"\n      data-nx-layers-region={row.area}\n      // Named whole, so it is announced as one sentence: what it is and where\n      // it comes from. Pressed while the region is selected.\n      aria-label={`${row.name}, ${row.origin}`}\n      aria-pressed={row.selected === true}\n      onClick={row.onActivate}\n    >\n      <Lock size={14} aria-hidden=\"true\" />\n      {/* A real space between name and origin, which the flex row does not\n          draw: the words drawn stay apart, so the name holds them. */}\n      <span className=\"nx-layers-region__name\">{row.name}</span>{\" \"}\n      <span className=\"nx-layers-region__origin\">{row.origin}</span>\n    </button>\n  );\n}\n\n/**\n * Focus the first row of the tree once per region edited in place, as\n * editing it starts: rows are drawn a frame after the panel, so it is asked\n * after paint.\n */\nfunction useFocusFirstRowOf(\n  region: LayersEditedRegion | undefined,\n  body: React.RefObject<HTMLDivElement | null>\n): void {\n  React.useEffect(() => {\n    if (region === undefined || focusedRegions.has(region)) return;\n    const row = body.current?.querySelector('[role=\"treeitem\"]');\n    if (!isHTMLElement(row)) return;\n    focusedRegions.add(region);\n    row.focus();\n  });\n}\n\n/** What Layers and its tree are called: \"Layers\", or \"Layers · Site header\". */\nexport function layersTitleOf(region: LayersEditedRegion | undefined): string {\n  return region === undefined\n    ? EDITOR_WORDS.layers\n    : `${EDITOR_WORDS.layers} · ${region.label}`;\n}\n\n/** What Layers says with no blocks to show, of the page or of the region. */\nexport function emptyNoteOf(region: LayersEditedRegion | undefined): string {\n  const whose = region === undefined ? \"This page\" : region.label;\n  return `${whose} has no blocks yet. Open Add in the rail to place one.`;\n}\n\n/**\n * Layers' heading while a region is edited in place, so the panel says whose\n * blocks it lists; none while the page's are, as before.\n */\nexport function EditedRegionHeading({\n  region,\n  title,\n}: {\n  region: LayersEditedRegion | undefined;\n  title: string;\n}): React.JSX.Element | null {\n  return region === undefined ? null : (\n    <h2 className=\"nx-layers-panel__heading\">{title}</h2>\n  );\n}\n\n/**\n * Layers' search, started afresh whenever the document it searches changes:\n * entering a region edited in place, or leaving it. Cleared in the render\n * that sees the change, so the region's rows are never drawn filtered by the\n * page's words, and the first of them is there to take focus.\n */\nfunction useSearchOf(\n  region: LayersEditedRegion | undefined\n): [string, (query: string) => void] {\n  const [query, setQuery] = React.useState(\"\");\n  const [searched, setSearched] = React.useState(region);\n  if (searched !== region) {\n    setSearched(region);\n    setQuery(\"\");\n  }\n  return [query, setQuery];\n}\n\n/**\n * What Layers keeps per document it shows: its search, started afresh on\n * entering or leaving a region edited in place, and the tree's element,\n * whose first row takes focus once as the region's editing starts.\n */\nexport function useEditedRegionLayers(region: LayersEditedRegion | undefined): {\n  query: string;\n  setQuery: (query: string) => void;\n  body: React.RefObject<HTMLDivElement | null>;\n} {\n  const [query, setQuery] = useSearchOf(region);\n  const body = React.useRef<HTMLDivElement | null>(null);\n  useFocusFirstRowOf(region, body);\n  return { query, setQuery, body };\n}\n","\"use client\";\n\n/**\n * The layers panel: the page as a tree, and the way to reach a block the canvas\n * cannot show.\n *\n * Decides nothing about the tree itself — `layers.ts` derives it, filters it and\n * says what has to open. This draws what that returns and owns one thing the\n * pure module cannot: which branches are expanded, which is state rather than\n * derivation.\n *\n * **The tree is `@nextlyhq/ui`'s `TreeView`, not one built here.** That\n * component exists for this control and says so: virtualized so a document of a\n * few thousand blocks costs a window rather than a tree, and flat\n * `role=\"treeitem\"` rows carrying `aria-level`/`aria-setsize`/`aria-posinset`\n * because virtualization makes the nested `role=\"group\"` markup impossible to\n * build. It also brings the APG keyboard model and typeahead. Reimplementing\n * any of that here would be a second answer to a question the design system has\n * already answered, and the accessibility half is the half that would rot.\n *\n * ## Three things open a branch, and they are not the same kind of thing\n *\n * The author clicks a twisty; a selection made on the canvas sits inside\n * collapsed containers; a search finds a match that is buried. Treating all\n * three as one derived union looks right and makes an ancestor of the selected\n * block IMPOSSIBLE TO CLOSE — the author collapses it, the next render puts it\n * straight back.\n *\n * So they are split by how long they should last. A selection opens its\n * ancestors ONCE, into the author's own set, and the author may close them\n * again. A search opens its matches' ancestors only while the query stands, so\n * clearing it returns the tree to what the author had open. Only the author's\n * set is stored.\n *\n * ## The panel says how to reorder, because nothing else does\n *\n * The bindings that move a block already work here — the tree holds focus and\n * the editor's own keystrokes act on the selection, so an author standing in\n * this panel can already reorder and nest without touching the canvas. Nothing\n * told them so, and a capability nobody can find reads exactly like a missing\n * one.\n *\n * The hint is DERIVED from the bindings rather than written beside them. A\n * retyped \"Alt+Up\" is correct until someone rebinds the keystroke, and then it\n * is a label that teaches a key which does nothing — with no test that can\n * fail, because the two are only related by having been typed by the same\n * person on the same day.\n *\n * It is also the tree's accessible description, not merely text near it. A\n * sighted author reads it because it sits under the tree; a screen-reader user\n * hears it on entering the tree, which is the moment the question arises.\n *\n * ## Rows can be dragged, through the same rule as everything else\n *\n * A row dragged by the pointer moves its block, and dragged to the right nests\n * it; `layers-drag` follows the gesture and `layers-drop` decides where it\n * lands and whether the placement rule and the locks allow it. Off while a\n * search filters the list, whose hidden neighbours a drop would land between.\n *\n * ## A row is a handle on its block\n *\n * Pointing at a row outlines its block on the canvas, and choosing one\n * scrolls the canvas to it. A row's eye hides its block on the device being\n * edited, and that device only; its padlock locks it. Both icons are for the\n * pointer, shown while the row is hovered and always while they say\n * something (hidden here, locked); the keyboard reaches the same verbs by F2,\n * the eye's and the lock's chords, and the row's menu, which also carries the\n * block verbs every other surface offers. A row renames in place.\n *\n * @module layers-panel\n */\n\nimport {\n  allBlocks,\n  findNode,\n  hiddenOnDevice,\n  registryNestingSource,\n  walkNodes,\n  type BlockDocument,\n  type BreakpointSet,\n  type ComponentLookup,\n  type NestingSource,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  TreeView,\n  chordMatches,\n  detectApplePlatform,\n  parseKeys,\n  type TreeNode,\n} from \"@nextlyhq/ui\";\nimport {\n  Braces,\n  Eye,\n  EyeOff,\n  Lock,\n  LockOpen,\n  SlidersHorizontal,\n  SquareDashed,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { BlockIconMark } from \"../../block-icon\";\nimport { DRAG_SOURCE_ATTRIBUTE } from \"../../canvas/canvas\";\nimport { useHoveredBlockSetter } from \"../../canvas/hovered-block\";\nimport type { MoveDirection } from \"../../canvas/keyboard-move\";\nimport { revealNode } from \"../../canvas/reveal-node\";\nimport type { EditorState } from \"../../editor-state\";\nimport { EDITOR_WORDS } from \"../../editor-words\";\nimport { FieldsOfDocument, useDraftFieldEdit } from \"../../field-edit\";\nimport { HAS_CUSTOM_CSS } from \"../../inspector/custom-css\";\nimport {\n  layersLockChangeable,\n  lockOp,\n  lockStatusOf,\n  lockViewOf,\n  renameOp,\n} from \"../../inspector/inspector\";\nimport { lockRefusalWording } from \"../../lock-refusal\";\nimport { refusalAnnouncement } from \"../../move-refusal\";\nimport type { BuilderOp } from \"../../op-vocabulary\";\nimport { deviceLabel } from \"../../shell/breakpoint-switcher\";\nimport { keyHint } from \"../../shell/key-hint\";\nimport { MOVE_KEYS, type SharedBlockVerbs } from \"../../shell/keyboard-actions\";\n\nimport {\n  EntryContentRowFact,\n  useEntryContentRows,\n  type EntryContentRowFacts,\n} from \"./entry-content-layers\";\nimport {\n  ROW_KEYS,\n  rowKeyAction,\n  hiddenDeviceNames,\n  listedNames,\n  toggleOnDeviceOp,\n  type RowKeyAction,\n} from \"./layer-row-actions\";\nimport { LayerRowMenu, type RowMenuItem } from \"./layer-row-menu\";\nimport { rowIdOf, RowShortcuts } from \"./layer-row-shortcuts\";\nimport {\n  ancestorIds,\n  filterLayers,\n  regionsTo,\n  slotRowsIn,\n  type SlotRow,\n  layerLabel,\n  layersOf,\n  UNNAMED_COMPONENT,\n  type ComponentTitleOf,\n  type LayerNode,\n} from \"./layers\";\nimport {\n  type LayersDrag,\n  LAYERS_TREE_CLASS,\n  LayersDropOverlay,\n  useLayersDrag,\n} from \"./layers-drag\";\nimport {\n  EditedRegionHeading,\n  emptyNoteOf,\n  layersTitleOf,\n  RegionRow,\n  useEditedRegionLayers,\n  type LayersEditedRegion,\n  type LayersRegionRow,\n} from \"./layers-regions\";\n\nexport interface LayersPanelProps {\n  /** The editor whose document this shows and whose selection it drives. */\n  editor: EditorState;\n  /**\n   * Whether the block-move keystrokes are bound for THIS editor.\n   *\n   * Owned by the host, which is the only place that can answer it. This panel\n   * is drawn in the shell's panel region while the keystrokes are registered by\n   * a component wrapping the shell's children, and those are sibling subtrees —\n   * so nothing readable from where this sits describes the bindings beside it.\n   * A host with two editors on one page has two answers, and only it knows\n   * which belongs to which.\n   *\n   * Defaults to `false`, so a panel told nothing says nothing: the legend is a\n   * claim that pressing something does something, and silence is the safe\n   * direction for a claim that cannot be checked from here.\n   */\n  moveHints?: boolean;\n  /**\n   * The nesting rules a dragged row is judged by. Defaults to the registry's,\n   * which is what the keyboard moves and the canvas default to.\n   */\n  nesting?: NestingSource;\n  /**\n   * The component definitions the canvas draws instances from, so a dragged\n   * instance is judged by what it draws, as its canvas drop is.\n   */\n  definitions?: ComponentLookup;\n  /**\n   * The regions of the page's layout, shown as rows of their own: a header\n   * above the page's blocks, a footer below them.\n   *\n   * Outside the tree on purpose. They are not the page's blocks, so they take\n   * no part in its block selection, its drag and drop, its locks or its\n   * visibility; each is one button an author reaches by Tab, and activating\n   * it selects the region, as a click on the canvas does.\n   */\n  regions?: readonly LayersRegionRow[];\n  /**\n   * A component's title by id, so a placement's row reads as what the author\n   * placed, and a search for that title finds it. The library holds the\n   * titles, and the host read it.\n   */\n  componentTitle?: ComponentTitleOf;\n  /**\n   * The site's breakpoints and the one being edited, which the eye hides a\n   * block on. Absent, rows offer no eye: hiding \"here\" needs a device.\n   */\n  device?: { breakpoints: BreakpointSet | undefined; id: string };\n  /**\n   * The canvas, as the frame draws it: its root element or the frame's\n   * document. A row chosen here scrolls its block into view there.\n   */\n  canvasRoot?: HTMLElement | Document | null;\n  /**\n   * The block verbs the host's verbs provider shares, for the row menu: the\n   * same verbs and reasons the toolbar and the canvas menu show. Absent, the\n   * menu offers the row's own verbs alone.\n   */\n  verbs?: SharedBlockVerbs;\n  /**\n   * Whether the panel sits inside a shortcut provider, so the row keystrokes\n   * (F2, the eye's and the lock's chords) register with it and Help lists\n   * them. Owned by the host, as `moveHints` is. Without one, the panel reads\n   * the keys on its own rows.\n   */\n  shortcuts?: boolean;\n  /**\n   * The region of the page's layout edited in place, while one is: `editor`\n   * is then the region's, and the panel is headed \"Layers · Site header\" in\n   * the region's own name. Focus moves to its first row once, as editing it\n   * starts, so a keyboard author lands on what they went in to edit.\n   * @experimental Settles with editing a header or footer in place.\n   */\n  editedRegion?: LayersEditedRegion;\n}\n\n/** One badge: an icon nobody has to see, and a word every reader gets. */\nfunction Badge({\n  icon,\n  text,\n  lock,\n  tooltip = false,\n}: {\n  icon: React.ReactNode;\n  text: string;\n  /** For a lock badge: the block's own lock, or one it is held by. */\n  lock?: \"own\" | \"inherited\";\n  /** Whether a pointer resting on the icon is told the words too. */\n  tooltip?: boolean;\n}): React.JSX.Element {\n  return (\n    <span\n      className=\"nx-layer-row__badge\"\n      {...(lock === undefined ? {} : { \"data-lock\": lock })}\n      {...(tooltip ? { title: text } : {})}\n    >\n      {/*\n        The icon is decorative and the word is the fact. A title attribute would\n        reach a pointer and nothing else, and an icon alone announces as an\n        image with no name — so the text ships and is clipped visually.\n      */}\n      <span aria-hidden=\"true\">{icon}</span>\n      <span className=\"nx-sr-only\">{text}</span>\n    </span>\n  );\n}\n\n/**\n * What each block type draws, by type.\n *\n * A layer node carries the block's TYPE and nothing about its definition —\n * `layersOf` reads a document, and a document does not hold editor metadata. So\n * the lookup happens here, where the registry is already reachable, rather than\n * by widening what the derivation returns.\n *\n * Read ONCE per mount, for the reason the insert panel gives for reading the\n * registry the same way: it is global mutable state with no change\n * notification, so there is nothing to subscribe to.\n */\nfunction iconsByType(): ReadonlyMap<string, string | undefined> {\n  return new Map(\n    allBlocks().map(definition => [definition.name, definition.editor?.icon])\n  );\n}\n\n/**\n * The mark a row draws: a placement's is the component mark whatever its\n * type's own icon, so it reads as a component beside the blocks around it.\n */\nfunction markOf(\n  node: LayerNode,\n  icons: ReadonlyMap<string, string | undefined>\n): string | undefined {\n  return node.component ? \"component\" : icons.get(node.type);\n}\n\n/**\n * The word as well as the mark, for a placement its component's title names:\n * the title alone would read as the block's own name. The fallback is already\n * that word, so it is not said twice.\n */\nfunction ComponentTag({ node }: { node: LayerNode }): React.JSX.Element | null {\n  if (!node.component || node.label === UNNAMED_COMPONENT) return null;\n  return <span className=\"nx-layer-row__tag\">component</span>;\n}\n\n/** What a row is drawn with beyond its own layer. */\ninterface RowView {\n  readonly icons: ReadonlyMap<string, string | undefined>;\n  readonly draggingId: string | null;\n  /** The row being renamed, which draws a field in place of its name. */\n  readonly renamingId: string | null;\n  /** The device the eye acts on, by name (\"Mobile\"); absent, no eye. */\n  readonly deviceName: string | undefined;\n  readonly onRenamed: (id: string, name: string | null) => void;\n  readonly onAct: (id: string, action: RowKeyAction) => void;\n  /** Each Entry content block's field, and whether it is gone, by id. */\n  readonly entryContent: ReadonlyMap<string, EntryContentRowFacts>;\n  /** The devices each block hidden somewhere is hidden on, by id: \"Tablet and Mobile\". */\n  readonly hiddenOn: ReadonlyMap<string, string>;\n}\n\n/** The page's save, as the admin binds it, in the shortcut grammar. */\nconst SAVE_CHORD = parseKeys(\"mod+s\")[0];\n\n/**\n * Whether a key press is the save chord, read by the shortcut manager's own\n * matcher, so Command on an Apple keyboard and Control elsewhere.\n */\nfunction isSaveChord(event: React.KeyboardEvent): boolean {\n  return (\n    SAVE_CHORD !== undefined &&\n    chordMatches(\n      SAVE_CHORD,\n      event.key,\n      event.nativeEvent,\n      detectApplePlatform()\n    )\n  );\n}\n\n/**\n * The field a row's name becomes while it is renamed.\n *\n * Its keys are its own: the tree reads arrows, Home, End and typed letters\n * for itself, and a field inside a row would otherwise lose every one of\n * them to the tree. Enter keeps the name and Escape keeps the old one; a\n * blur keeps what was typed, as leaving a field does everywhere else.\n *\n * The save chord alone goes on to the editor's shortcuts, so Save pressed\n * here saves the page; a keystroke begins the field's edit, so that save\n * writes the name being typed first, through the field's own blur.\n */\nfunction RenameField({\n  id,\n  label,\n  name,\n  onDone,\n}: {\n  id: string;\n  label: string;\n  /** The author's own name, which the field starts from; none, it is empty. */\n  name: string | undefined;\n  onDone: (name: string | null) => void;\n}): React.JSX.Element {\n  const field = React.useRef<HTMLInputElement | null>(null);\n  const finished = React.useRef(false);\n  React.useEffect(() => {\n    field.current?.focus();\n    field.current?.select();\n  }, []);\n  // Nothing changed is nothing to write: an unchanged field, or one left\n  // empty on a block that had no name of its own.\n  const finish = (typed: string | null): void => {\n    if (finished.current) return;\n    finished.current = true;\n    onDone(typed === null || typed.trim() === (name ?? \"\") ? null : typed);\n  };\n  const stop = (event: React.SyntheticEvent): void => event.stopPropagation();\n  const edit = useDraftFieldEdit();\n  return (\n    <input\n      ref={field}\n      className=\"nx-layer-row__rename\"\n      // The row's hook stays on what stands for the block while it is renamed.\n      data-nx-layer={id}\n      // The author's own name, as the inspector's rename starts from; the\n      // label it falls back to shows as the placeholder, never as a value a\n      // blur would store.\n      defaultValue={name ?? \"\"}\n      placeholder={label}\n      aria-label={`Rename ${label}`}\n      // A press inside the field is a caret, not a drag, a selection or the\n      // tree's own click.\n      onPointerDown={stop}\n      onClick={stop}\n      onDoubleClick={stop}\n      onChange={event => {\n        const typed = event.currentTarget;\n        edit.begin(() => {\n          typed.value = name ?? \"\";\n        });\n      }}\n      onKeyDown={event => {\n        if (!isSaveChord(event)) event.stopPropagation();\n        if (event.key === \"Enter\") {\n          event.preventDefault();\n          finish(event.currentTarget.value);\n        } else if (event.key === \"Escape\") {\n          event.preventDefault();\n          finish(null);\n        }\n      }}\n      onBlur={event => finish(event.currentTarget.value)}\n    />\n  );\n}\n\n/**\n * A row's eye or padlock. Pointer-only, so it is out of the Tab order and\n * hidden from assistive technology: the keyboard reaches the same verb by its\n * chord and the row's menu, and the row says hidden and locked in words.\n */\nfunction RowAction({\n  id,\n  action,\n  title,\n  pinned,\n  onAct,\n  children,\n}: {\n  id: string;\n  action: RowKeyAction;\n  title: string;\n  /** Shown at rest, not only on hover, because it states something true. */\n  pinned: boolean;\n  onAct: RowView[\"onAct\"];\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const stop = (event: React.SyntheticEvent): void => event.stopPropagation();\n  return (\n    <button\n      type=\"button\"\n      tabIndex={-1}\n      aria-hidden=\"true\"\n      className=\"nx-layer-row__action\"\n      data-action={action}\n      {...(pinned ? { \"data-pinned\": \"\" } : {})}\n      title={title}\n      // Neither a drag nor a selection of the row: the press is the action.\n      // Nor a focus: the row keeps it, so its keystrokes still reach it.\n      onPointerDown={stop}\n      onMouseDown={event => event.preventDefault()}\n      onDoubleClick={stop}\n      onClick={event => {\n        event.stopPropagation();\n        onAct(id, action);\n      }}\n    >\n      {children}\n    </button>\n  );\n}\n\n/**\n * A list's region as a row: \"Each entry\" or \"When empty\", with how many\n * blocks it holds. It names no block, so it is never dragged or renamed;\n * choosing it selects the list and shows that region on the canvas.\n */\nfunction slotRow(node: LayerNode, row: SlotRow, view: RowView): TreeNode {\n  const held = node.children.filter(child => child.slot === row.slot);\n  return {\n    id: row.rowId,\n    textValue: row.label,\n    label: (\n      <span className=\"nx-layer-row\" data-nx-layer-slot={row.slot}>\n        <SquareDashed\n          aria-hidden=\"true\"\n          size={14}\n          className=\"nx-layer-row__slot-mark\"\n        />\n        <span className=\"nx-layer-row__label\">{row.label}</span>\n        <span className=\"nx-layer-row__count\">\n          {held.length === 0\n            ? \"empty\"\n            : held.length === 1\n              ? \"1 block\"\n              : `${String(held.length)} blocks`}\n        </span>\n      </span>\n    ),\n    ...(held.length === 0\n      ? {}\n      : { children: held.map(child => rowOf(child, view)) }),\n  };\n}\n\n/** A layer as a row: its mark, its name, and what is true about it. */\nfunction rowOf(node: LayerNode, view: RowView): TreeNode {\n  if (node.slotRows !== undefined) {\n    return {\n      id: node.id,\n      textValue: node.label,\n      label: <LayerRow node={node} view={view} />,\n      children: node.slotRows.map(row => slotRow(node, row, view)),\n    };\n  }\n  return {\n    id: node.id,\n    // `textValue` carries the NAME alone even though the label renders badges\n    // beside it. Typeahead matches what an author would type, and a row whose\n    // searchable text included \"Locked\" would be reachable by typing a word\n    // that is not its name.\n    textValue: node.label,\n    label: <LayerRow node={node} view={view} />,\n    // Omitted for a block that holds nothing: the tree draws a twisty and an\n    // open/closed state for any row given a children list, empty or not, and\n    // a twisty that opens onto nothing is a control that does nothing.\n    ...(node.children.length === 0\n      ? {}\n      : {\n          children: node.children.map(child => rowOf(child, view)),\n        }),\n  };\n}\n\n/** A row's contents: its mark, its name or the field renaming it, and facts. */\nfunction LayerRow({\n  node,\n  view,\n}: {\n  node: LayerNode;\n  view: RowView;\n}): React.JSX.Element {\n  return (\n    <span\n      className=\"nx-layer-row\"\n      {...(node.component ? { \"data-component\": \"\" } : {})}\n      // Dimmed where the canvas shows nothing of it, with the word beside.\n      {...(node.hiddenHere === true || node.hiddenWith !== undefined\n        ? { \"data-hidden\": \"\" }\n        : {})}\n      // The block in hand, faded where it sits as the canvas fades its own\n      // drag source; the same attribute, so the two read as one gesture.\n      {...(node.id === view.draggingId ? { [DRAG_SOURCE_ATTRIBUTE]: \"\" } : {})}\n    >\n      <BlockIconMark icon={markOf(node, view.icons)} size={14} />\n      {node.id === view.renamingId ? (\n        // A name typed here is the document's, as a field in the block's\n        // settings is: unsaved work until it is written, and written first\n        // by a save made from the field.\n        <FieldsOfDocument.Provider value={true}>\n          <RenameField\n            id={node.id}\n            label={node.label}\n            name={node.name}\n            onDone={name => view.onRenamed(node.id, name)}\n          />\n        </FieldsOfDocument.Provider>\n      ) : (\n        /* `data-nx-layer` names the block a row stands for. Labels repeat —\n          every paragraph is \"Text\" — so it is the one stable way to find a\n          given block's row, the Layers counterpart of the canvas's\n          `data-nx-node`. */\n        <span className=\"nx-layer-row__label\" data-nx-layer={node.id}>\n          {node.label}\n        </span>\n      )}\n      <ComponentTag node={node} />\n      <EntryContentRowFact facts={view.entryContent.get(node.id)} />\n      <RowFacts node={node} hiddenOn={view.hiddenOn.get(node.id)} />\n      <NotQuotedFact node={node} />\n      <RowActions node={node} view={view} />\n    </span>\n  );\n}\n\n/**\n * That a block is marked never to be quoted in search: said, not drawn. The\n * canvas tags the block on hover, and this is where a screen reader hears it.\n */\nfunction NotQuotedFact({\n  node,\n}: {\n  node: LayerNode;\n}): React.JSX.Element | null {\n  return node.notQuoted === true ? (\n    <span className=\"nx-sr-only\">Not quoted in search</span>\n  ) : null;\n}\n\n/**\n * Whether the block is hidden on the device shown, or with the block around\n * it, in words on screen and read out.\n */\nfunction HiddenFact({\n  node,\n  hiddenOn,\n}: {\n  node: LayerNode;\n  hiddenOn: string | undefined;\n}): React.JSX.Element | null {\n  if (node.hiddenHere === true) {\n    // A word, on screen and read out: hidden on the device shown. A pointer\n    // resting on it is told every device it is hidden on.\n    return (\n      <span\n        className=\"nx-layer-row__hidden\"\n        {...(hiddenOn === undefined ? {} : { title: `Hidden on ${hiddenOn}` })}\n      >\n        Hidden\n      </span>\n    );\n  }\n  if (node.hiddenWith === undefined) return null;\n  // Hidden because the block around it is, which is where it is shown again:\n  // named, as an inherited lock names its block.\n  return (\n    <span className=\"nx-layer-row__hidden\" data-inherited=\"\">\n      Hidden with {node.hiddenWith}\n    </span>\n  );\n}\n\n/**\n * The eye-slash of a block hidden on a device other than the one shown,\n * naming the devices: the same reading Hide on and the canvas's stripes take.\n * None where the row already says it is hidden here or with its parent.\n */\nfunction DeviceHiddenFact({\n  node,\n  hiddenOn,\n}: {\n  node: LayerNode;\n  hiddenOn: string | undefined;\n}): React.JSX.Element | null {\n  if (!node.breakpointHidden) return null;\n  if (node.hiddenHere === true || node.hiddenWith !== undefined) return null;\n  return (\n    <Badge\n      icon={<EyeOff size={12} />}\n      text={\n        hiddenOn === undefined\n          ? \"Hidden at some screen sizes\"\n          : `Hidden on ${hiddenOn}`\n      }\n      tooltip\n    />\n  );\n}\n\n/** What is true about a block, each in words a screen reader reads. */\nfunction RowFacts({\n  node,\n  hiddenOn,\n}: {\n  node: LayerNode;\n  /** The devices the block is hidden on, \"Tablet and Mobile\", if any. */\n  hiddenOn: string | undefined;\n}): React.JSX.Element {\n  return (\n    <>\n      <HiddenFact node={node} hiddenOn={hiddenOn} />\n      {/* Both locks in the row's own ink, so each reads against the row in\n          every state it can be in. A lock held from a block around it is\n          quieter by weight, a thinner stroke, never by a fainter colour; both\n          say so in words, and the inherited one names the block to unlock. */}\n      {node.locked ? (\n        // The word, read out; the padlock pinned at the row's end is what\n        // the eye sees, at the stronger stroke.\n        <span className=\"nx-sr-only\" data-lock=\"own\">\n          Locked\n        </span>\n      ) : node.lockedBy === undefined ? null : (\n        <Badge\n          icon={<Lock size={12} strokeWidth={1.25} />}\n          text={`Locked by ${node.lockedBy}`}\n          lock=\"inherited\"\n        />\n      )}\n      <DeviceHiddenFact node={node} hiddenOn={hiddenOn} />\n      {node.conditional ? (\n        <Badge\n          icon={<SlidersHorizontal size={12} />}\n          text=\"Shown conditionally\"\n        />\n      ) : null}\n      {/* \"{ }\" for a block with custom CSS of its own, for everyone: only\n          that it has some, named for a screen reader and a resting pointer. */}\n      {node.customCss === true ? (\n        <Badge icon={<Braces size={12} />} text={HAS_CUSTOM_CSS} tooltip />\n      ) : null}\n    </>\n  );\n}\n\n/** The row's eye and padlock, at its right edge. */\nfunction RowActions({\n  node,\n  view,\n}: {\n  node: LayerNode;\n  view: RowView;\n}): React.JSX.Element {\n  return (\n    <span className=\"nx-layer-row__actions\">\n      <RowEye node={node} view={view} />\n      <RowPadlock node={node} view={view} />\n    </span>\n  );\n}\n\n/**\n * The row's eye. Not on a block a lock holds, which refuses the change, nor\n * on one hidden with the block around it, which is shown again there.\n */\nfunction RowEye({\n  node,\n  view,\n}: {\n  node: LayerNode;\n  view: RowView;\n}): React.JSX.Element | null {\n  const { deviceName } = view;\n  const offered =\n    deviceName !== undefined &&\n    !node.locked &&\n    node.lockedBy === undefined &&\n    node.hiddenWith === undefined;\n  if (!offered) return null;\n  const hidden = node.hiddenHere === true;\n  return (\n    <RowAction\n      id={node.id}\n      action=\"toggle-hidden\"\n      title={`${hidden ? \"Show\" : \"Hide\"} on ${deviceName}`}\n      pinned={hidden}\n      onAct={view.onAct}\n    >\n      {hidden ? <EyeOff size={14} /> : <Eye size={14} />}\n    </RowAction>\n  );\n}\n\n/** The row's padlock: the block's own lock; one held from around it is lifted there. */\nfunction RowPadlock({\n  node,\n  view,\n}: {\n  node: LayerNode;\n  view: RowView;\n}): React.JSX.Element | null {\n  if (node.lockedBy !== undefined) return null;\n  return (\n    <RowAction\n      id={node.id}\n      action=\"toggle-lock\"\n      title={node.locked ? \"Unlock\" : \"Lock\"}\n      pinned={node.locked}\n      onAct={view.onAct}\n    >\n      {node.locked ? (\n        <Lock size={14} strokeWidth={2.5} />\n      ) : (\n        <LockOpen size={14} />\n      )}\n    </RowAction>\n  );\n}\n\n/**\n * The short label each direction gets in the legend.\n *\n * The binding's own `description` is a SENTENCE — \"Move the selected block into\n * the container above it\" — because it is written to be announced after the\n * move happens, where the subject has to be named. Four of those stacked under\n * a tree is a paragraph rather than a legend, and it reads as prose to be\n * waded through rather than a key to be scanned.\n *\n * So the legend names the DIRECTION, which the binding table already carries as\n * an enum. That keeps this a projection of something the editor decided rather\n * than a second wording of it: total over `MoveDirection`, so a direction added\n * to the move rule fails to compile here instead of silently drawing nothing.\n *\n * One verb across all four, matching the arrow that runs them, so the pairs\n * read as opposites rather than as four unrelated commands.\n */\nconst DIRECTION_LABEL: Readonly<Record<MoveDirection, string>> = {\n  up: \"Move up\",\n  down: \"Move down\",\n  indent: \"Move in\",\n  outdent: \"Move out\",\n};\n\n/**\n * The drag's state as the panel draws it: absent with no drag, \"refused\"\n * while the place under the pointer refuses the block — which turns the\n * cursor to no-drop, as the canvas does — and empty otherwise.\n */\nfunction draggingState(drag: LayersDrag): string | undefined {\n  if (drag.draggingId === null) return undefined;\n  return drag.drawn?.result.kind === \"refused\" ? \"refused\" : \"\";\n}\n\n/**\n * The handlers the element around the tree carries for the rows: the row\n * under the pointer outlines its block on the canvas, the row's verbs by\n * keyboard for the row that has focus (the eye's and the lock's icons are\n * for the pointer alone), and a double-click renames.\n */\nfunction rowBodyHandlers({\n  hover,\n  apple,\n  act,\n  keys,\n}: {\n  hover: (id: string | null) => void;\n  apple: boolean;\n  act: (id: string, action: RowKeyAction) => void;\n  /** Whether to read the row keystrokes here. */\n  keys: boolean;\n}): Pick<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"onPointerOver\" | \"onPointerLeave\" | \"onKeyDown\" | \"onDoubleClick\"\n> {\n  return {\n    onPointerOver: event => hover(rowIdOf(event.target)),\n    onPointerLeave: () => hover(null),\n    onKeyDown: event => {\n      if (!keys) return;\n      const action = rowKeyAction(event, apple);\n      const id = action === null ? null : rowIdOf(event.target);\n      if (action === null || id === null) return;\n      event.preventDefault();\n      act(id, action);\n    },\n    onDoubleClick: event => {\n      const id = rowIdOf(event.target);\n      if (id !== null) act(id, \"rename\");\n    },\n  };\n}\n\n/**\n * The name of the nearest block around `id` hidden on the device being\n * edited, or `undefined` when none is.\n */\nfunction hiddenAround(\n  editor: EditorState,\n  id: string,\n  device: NonNullable<LayersPanelProps[\"device\"]>\n): string | undefined {\n  const around = ancestorIds(editor.document, id)\n    .map(each => findNode(editor.document.nodes, each))\n    .filter(\n      (node): node is NonNullable<typeof node> =>\n        node !== undefined &&\n        hiddenOnDevice(node.visibility, device.breakpoints, device.id)\n    );\n  const nearest = around[around.length - 1];\n  return nearest === undefined ? undefined : layerLabel(nearest);\n}\n\n/**\n * A row chosen here scrolls the canvas to its block, on every choice: a row\n * chosen again after the canvas was scrolled away scrolls back, though the\n * selection did not change. A frame later, once the selection has reached\n * the canvas: a hidden block is drawn only once it is selected.\n */\nfunction useRevealChosen(\n  canvasRoot: LayersPanelProps[\"canvasRoot\"]\n): (id: string) => void {\n  const latestCanvas = React.useRef(canvasRoot);\n  latestCanvas.current = canvasRoot;\n  return React.useCallback((id: string) => {\n    requestAnimationFrame(() => {\n      const root = latestCanvas.current;\n      if (root !== null && root !== undefined) revealNode(root, id);\n    });\n  }, []);\n}\n\n/**\n * The devices each block hidden somewhere is hidden on, by id, as one\n * phrase: \"Tablet and Mobile\". Read ONCE per document, not per row.\n */\nfunction hiddenOnByBlock(\n  document: BlockDocument,\n  breakpoints: BreakpointSet | undefined\n): ReadonlyMap<string, string> {\n  const hidden = new Map<string, string>();\n  walkNodes(document.nodes, node => {\n    if (node.visibility?.devices === undefined) return;\n    const names = hiddenDeviceNames(node.visibility, breakpoints);\n    if (names.length > 0) hidden.set(node.id, listedNames(names));\n  });\n  return hidden;\n}\n\n/**\n * The tree's rows, built again only when what a row draws changes: the\n * blocks shown, the drag, the row being renamed, the device, and each\n * block's Entry content field and the devices it is hidden on.\n */\nfunction useTreeRows(\n  roots: readonly LayerNode[],\n  {\n    document,\n    device,\n    draggingId,\n    rows,\n  }: {\n    document: BlockDocument;\n    device: LayersPanelProps[\"device\"];\n    draggingId: string | null;\n    rows: ReturnType<typeof useRowVerbs>;\n  }\n): TreeNode[] {\n  const icons = React.useMemo(iconsByType, []);\n  const entryContent = useEntryContentRows(document);\n  const hiddenOn = useHiddenOn(document, device);\n  const deviceName = deviceNameOf(device);\n  const { renamingId, onRenamed, act } = rows;\n  return React.useMemo(\n    () =>\n      roots.map(root =>\n        rowOf(root, {\n          icons,\n          draggingId,\n          renamingId,\n          deviceName,\n          onRenamed,\n          onAct: act,\n          entryContent,\n          hiddenOn,\n        })\n      ),\n    [\n      roots,\n      icons,\n      entryContent,\n      hiddenOn,\n      draggingId,\n      renamingId,\n      deviceName,\n      onRenamed,\n      act,\n    ]\n  );\n}\n\n/** {@link hiddenOnByBlock}, read again only when the page or the breakpoints change. */\nfunction useHiddenOn(\n  document: BlockDocument,\n  device: LayersPanelProps[\"device\"]\n): ReadonlyMap<string, string> {\n  const breakpoints = device?.breakpoints;\n  return React.useMemo(\n    () => hiddenOnByBlock(document, breakpoints),\n    [document, breakpoints]\n  );\n}\n\n/** The device the eye acts on, by the name the device buttons give it. */\nfunction deviceNameOf(device: LayersPanelProps[\"device\"]): string | undefined {\n  if (device === undefined) return undefined;\n  return deviceLabel(device.breakpoints, device.id) ?? device.id;\n}\n\n/**\n * The move legend's rows, from the binding table, so a rebound keystroke\n * moves the hint with it. A binding this cannot spell is dropped rather than\n * guessed at — see `keyHint` for why a wrong hint is worse than no hint.\n * None until the platform is known, or where the host binds no moves.\n */\nfunction moveHintsFor(\n  apple: boolean | null,\n  moveHints: boolean\n): { keys: string; shown: string; label: string; description: string }[] {\n  if (apple === null || !moveHints) return [];\n  return MOVE_KEYS.flatMap(({ keys, direction, description }) => {\n    const shown = keyHint(keys, apple);\n    return shown === null\n      ? []\n      : [{ keys, shown, label: DIRECTION_LABEL[direction], description }];\n  });\n}\n\n/** Whether the block is hidden on the device being edited. */\nfunction hiddenHere(\n  editor: EditorState,\n  id: string,\n  device: NonNullable<LayersPanelProps[\"device\"]>\n): boolean {\n  const node = findNode(editor.document.nodes, id);\n  return (\n    node !== undefined &&\n    hiddenOnDevice(node.visibility, device.breakpoints, device.id)\n  );\n}\n\n/**\n * Flip a block's visibility on the device being edited, answering what to\n * say, or `null` when nothing changed.\n */\nfunction toggleHidden(\n  editor: EditorState,\n  id: string,\n  device: LayersPanelProps[\"device\"]\n): string | null {\n  if (device === undefined) return null;\n  const wasHidden = hiddenHere(editor, id, device);\n  const op = toggleOnDeviceOp(editor.document, id, device);\n  if (op === null || editor.apply(op) === null) return null;\n  const name = deviceLabel(device.breakpoints, device.id) ?? device.id;\n  return wasHidden ? `Shown on ${name}.` : `Hidden on ${name}.`;\n}\n\n/** Lock or unlock a block, answering what to say, or `null` when nothing changed. */\nfunction toggleLock(editor: EditorState, id: string): string | null {\n  const node = findNode(editor.document.nodes, id);\n  if (node === undefined) return null;\n  const locking = node.locked !== true;\n  if (editor.apply(lockOp(id, locking)) === null) return null;\n  return locking ? \"Locked.\" : \"Unlocked.\";\n}\n\n/** Put focus back on a block's row, once a rename has ended. */\nfunction focusRow(scope: HTMLElement | null, id: string): void {\n  requestAnimationFrame(() => {\n    // This panel's rows only: a second editor on the page holds the same ids.\n    const rows = scope?.querySelectorAll<HTMLElement>('[role=\"treeitem\"]');\n    const row = Array.from(rows ?? []).find(each => rowIdOf(each) === id);\n    row?.focus();\n  });\n}\n\n/** What the row verbs give the panel. */\ninterface RowVerbs {\n  readonly renamingId: string | null;\n  readonly onRenamed: (id: string, name: string | null) => void;\n  readonly act: (id: string, action: RowKeyAction) => void;\n  /** The row menu's own items, for the row the menu was opened on. */\n  readonly menuItems: (id: string | null) => readonly RowMenuItem[];\n  /** What the last verb did, or why it was refused. */\n  readonly notice: string;\n}\n\n/**\n * Rename, the eye and the lock for one row, refused up front in the words\n * every lock refusal uses, so a verb the store would refuse says why instead\n * of doing nothing.\n */\nfunction useRowVerbs(\n  editor: EditorState,\n  device: LayersPanelProps[\"device\"],\n  scope: React.RefObject<HTMLElement | null>\n): RowVerbs {\n  const [renamingId, setRenamingId] = React.useState<string | null>(null);\n  const [notice, setNotice] = React.useState(\"\");\n  const latest = React.useRef({ editor, device });\n  latest.current = { editor, device };\n\n  /** Why the store would refuse `ops`, or `undefined` when it would not. */\n  const refusalOf = React.useCallback(\n    (ops: readonly BuilderOp[]): string | undefined => {\n      const found = latest.current.editor.lockRefusalFor(ops);\n      return found === undefined\n        ? undefined\n        : refusalAnnouncement(lockRefusalWording(found));\n    },\n    []\n  );\n\n  /** Why a verb may not run on `id`, or `undefined` when it may. */\n  const reasonFor = React.useCallback(\n    (id: string, action: RowKeyAction): string | undefined => {\n      const { editor: now, device: on } = latest.current;\n      switch (action) {\n        case \"rename\":\n          return refusalOf([renameOp(id, \"name\")]);\n        case \"toggle-hidden\": {\n          if (on === undefined) return \"\";\n          // Hidden with a block around it: changing this one shows nothing.\n          const around = hiddenAround(now, id, on);\n          if (around !== undefined) {\n            return `Hidden with ${around}. Show ${around} on this device to show it.`;\n          }\n          const op = toggleOnDeviceOp(now.document, id, on);\n          return op === null ? \"\" : refusalOf([op]);\n        }\n        case \"toggle-lock\": {\n          const status = lockStatusOf(now.document, id, lockViewOf(now));\n          if (status.inheritedFrom !== undefined && !status.layers) {\n            return `This block is inside ${status.inheritedFrom}, which is locked. Unlock ${status.inheritedFrom} to change it.`;\n          }\n          return layersLockChangeable(status)\n            ? undefined\n            : \"The area it sits in fixes this.\";\n        }\n      }\n    },\n    [refusalOf]\n  );\n\n  const act = React.useCallback(\n    (id: string, action: RowKeyAction): void => {\n      const reason = reasonFor(id, action);\n      if (reason !== undefined) {\n        setNotice(reason);\n        return;\n      }\n      setNotice(\"\");\n      if (action === \"rename\") {\n        setRenamingId(id);\n        return;\n      }\n      const { editor: now, device: on } = latest.current;\n      const said =\n        action === \"toggle-hidden\"\n          ? toggleHidden(now, id, on)\n          : toggleLock(now, id);\n      if (said !== null) setNotice(said);\n    },\n    [reasonFor]\n  );\n\n  const onRenamed = React.useCallback(\n    (id: string, name: string | null): void => {\n      setRenamingId(null);\n      focusRow(scope.current, id);\n      if (name === null) return;\n      latest.current.editor.apply(renameOp(id, name));\n    },\n    [scope]\n  );\n\n  const menuItems = React.useCallback(\n    (id: string | null): readonly RowMenuItem[] => {\n      const { editor: now, device: on } = latest.current;\n      if (id === null) return [];\n      const node = findNode(now.document.nodes, id);\n      if (node === undefined) return [];\n      const items: RowMenuItem[] = [\n        {\n          id: \"rename\",\n          label: \"Rename\",\n          reason: reasonFor(id, \"rename\"),\n          keys: ROW_KEYS.rename,\n          run: () => act(id, \"rename\"),\n        },\n      ];\n      if (on !== undefined) {\n        const name = deviceLabel(on.breakpoints, on.id) ?? on.id;\n        items.push({\n          id: \"toggle-hidden\",\n          label: hiddenHere(now, id, on)\n            ? `Show on ${name}`\n            : `Hide on ${name}`,\n          reason: reasonFor(id, \"toggle-hidden\"),\n          keys: ROW_KEYS[\"toggle-hidden\"],\n          run: () => act(id, \"toggle-hidden\"),\n        });\n      }\n      items.push({\n        id: \"toggle-lock\",\n        label: node.locked === true ? \"Unlock\" : \"Lock\",\n        reason: reasonFor(id, \"toggle-lock\"),\n        keys: ROW_KEYS[\"toggle-lock\"],\n        run: () => act(id, \"toggle-lock\"),\n      });\n      return items;\n    },\n    [act, reasonFor]\n  );\n\n  return { renamingId, onRenamed, act, menuItems, notice };\n}\n\nexport function LayersPanel({\n  editor,\n  moveHints = false,\n  nesting,\n  definitions,\n  regions,\n  componentTitle,\n  device,\n  canvasRoot,\n  verbs,\n  shortcuts = false,\n  // The region edited in place, while one is: see `layers-regions`.\n  ...region\n}: LayersPanelProps): React.JSX.Element {\n  const { editedRegion } = region;\n  // Its own search for each document Layers shows, and the tree's element,\n  // whose first row takes focus as a region's editing starts.\n  const { query, setQuery, body } = useEditedRegionLayers(region.editedRegion);\n  const [opened, setOpened] = React.useState<readonly string[]>([]);\n\n  // Memoised on what was supplied, so the drag is not handed a new rule\n  // source on every render.\n  const rules = React.useMemo(\n    () => nesting ?? registryNestingSource(),\n    [nesting]\n  );\n  const drag = useLayersDrag({\n    editor,\n    nesting: rules,\n    ...(definitions === undefined ? {} : { definitions }),\n    enabled: query.trim() === \"\",\n    // A collapsed row rested on during a drag opens into the author's own set,\n    // as a twisty click would, so it stays open after the drag ends.\n    onOpen: id =>\n      setOpened(previous =>\n        previous.includes(id) ? previous : [...previous, id]\n      ),\n  });\n\n  // The tree's own element (`body`, above): where a rename's focus returns,\n  // and where the row keystrokes are scoped.\n  const rows = useRowVerbs(editor, device, body);\n  const setHovered = useHoveredBlockSetter();\n  // Nothing stays pointed at once the panel goes, or the canvas would keep\n  // outlining a block no row is under.\n  React.useEffect(() => () => setHovered(null), [setHovered]);\n  // A drag's own marks say where the block will land, so the hover outline\n  // goes as the drag starts, though the pointer entered no other row.\n  React.useEffect(() => {\n    if (drag.draggingId !== null) setHovered(null);\n  }, [drag.draggingId, setHovered]);\n\n  const revealChosen = useRevealChosen(canvasRoot);\n  // What the panel and its tree are called: \"Layers\", or \"Layers · Site\n  // header\" while a region is edited in place.\n  const title = layersTitleOf(editedRegion);\n\n  // Recomputed each render rather than memoised. The tree is only valid against\n  // the document it was read from, and every edit replaces that document — a\n  // memo would need the document as its key and would therefore never hit.\n  const tree = layersOf(editor.document, componentTitle, device);\n  const search = filterLayers(tree, query);\n  // The region rows by their own ids, so choosing one is told from choosing\n  // a block by what the row is, never by how an id is spelled.\n  const regionRows = slotRowsIn(tree);\n\n  /*\n   * The document, read at effect time rather than depended on.\n   *\n   * The effect below must run when the SELECTION moves and not when the\n   * document changes. Listing the document as a dependency would re-open the\n   * selected block's ancestors after every edit, so a branch the author closed\n   * would spring back open the next time they typed in the inspector.\n   */\n  const documentRef = React.useRef(editor.document);\n  documentRef.current = editor.document;\n\n  /*\n   * A selection made elsewhere opens its ancestors ONCE.\n   *\n   * Written into state rather than merged into the expanded set at render.\n   * Derived, it could not be undone: the author collapses a branch, the union\n   * puts it straight back, and an ancestor of the selected block becomes\n   * impossible to close.\n   */\n  React.useEffect(() => {\n    const needed = [\n      ...ancestorIds(documentRef.current, editor.selectedId),\n      // And each list's region the selection sits in, drawn between them.\n      ...regionsTo(documentRef.current, editor.selectedId).map(\n        region => region.rowId\n      ),\n    ];\n    if (needed.length === 0) return;\n    setOpened(previous => {\n      const missing = needed.filter(id => !previous.includes(id));\n      // Returning the same array when nothing is missing is what stops this\n      // effect re-rendering forever: a new array every run is a new state value.\n      return missing.length === 0 ? previous : [...previous, ...missing];\n    });\n  }, [editor.selectedId]);\n\n  /*\n   * Search reveals TEMPORARILY, so its branches are unioned at render and never\n   * stored. Clearing the query returns the tree to what the author had open,\n   * which is what makes searching feel like looking rather than like editing.\n   */\n  const expandedIds = React.useMemo(\n    () => [...new Set([...opened, ...search.expand])],\n    [opened, search.expand]\n  );\n\n  const nodes = useTreeRows(search.roots, {\n    document: editor.document,\n    device,\n    draggingId: drag.draggingId,\n    rows,\n  });\n\n  /*\n   * Which keyboard is in front of the author, resolved AFTER mounting.\n   *\n   * `detectApplePlatform` reads `navigator`, which a server render does not\n   * have — it answers false there, so a server would emit `Alt` and the first\n   * browser render `⌥`, and React would find markup it did not produce and\n   * throw the subtree away. Held as `null` until it is known, so the legend is\n   * absent rather than briefly wrong: this module's whole rule is that a hint\n   * naming the wrong key is worse than no hint at all.\n   */\n  /*\n   * Per INSTANCE, not a module constant. A host may mount two editors on one\n   * page, and a fixed id would have both trees pointing at the same element —\n   * an ambiguous lookup, where assistive technology can read one panel's tree\n   * the other panel's description.\n   */\n  const hintId = React.useId();\n  const [apple, setApple] = React.useState<boolean | null>(null);\n  React.useEffect(() => {\n    setApple(detectApplePlatform());\n  }, []);\n\n  // Built from the binding table; see `moveHintsFor`.\n  const hints = React.useMemo(\n    () => moveHintsFor(apple, moveHints),\n    [apple, moveHints]\n  );\n\n  return (\n    <div className=\"nx-layers-panel\">\n      <EditedRegionHeading region={editedRegion} title={title} />\n      <div className=\"nx-layers-panel__search\">\n        <Input\n          value={query}\n          onChange={event => setQuery(event.target.value)}\n          placeholder={`Search ${EDITOR_WORDS.layers.toLowerCase()}`}\n          aria-label={`Search ${EDITOR_WORDS.layers.toLowerCase()}`}\n        />\n      </div>\n\n      {regions\n        ?.filter(row => row.area === \"header\")\n        .map(row => (\n          <RegionRow key={row.area} row={row} />\n        ))}\n\n      {tree.length === 0 ? (\n        <p className=\"nx-layers-panel__note\">{emptyNoteOf(editedRegion)}</p>\n      ) : nodes.length === 0 ? (\n        <p className=\"nx-layers-panel__note\">No blocks match “{query}”.</p>\n      ) : (\n        <LayerRowMenu\n          rowOf={rowIdOf}\n          selectedIds={editor.selection.ids}\n          select={id => editor.select(id, \"replace\")}\n          items={rows.menuItems}\n          verbs={verbs}\n          apple={apple}\n          // A touch's long press arms the row drag first; the menu claims it.\n          onOpen={drag.cancel}\n        >\n          <div\n            ref={body}\n            className=\"nx-layers-panel__body\"\n            data-nx-dragging={draggingState(drag)}\n            {...drag.handlers}\n            {...rowBodyHandlers({\n              hover: id =>\n                // Not during a drag, whose own marks say where it will land.\n                setHovered(drag.draggingId === null ? id : null),\n              apple: apple ?? false,\n              act: rows.act,\n              // Read by the shortcut manager instead where the host has one.\n              keys: !shortcuts,\n            })}\n          >\n            <TreeView\n              className={LAYERS_TREE_CLASS}\n              aria-label={title}\n              nodes={nodes}\n              selectedId={editor.selectedId}\n              // The panel shows what the canvas shows. Passing only the primary\n              // would leave two surfaces disagreeing about what is selected, on a\n              // screen where a delete acts on all of it.\n              selectedIds={editor.selection.ids}\n              // The tree's three gestures ARE the editor's three gestures: it\n              // reports which one a row's modifiers meant and the store's own rules\n              // decide what that does. A panel translating them itself would be a\n              // second grammar to keep in step.\n              onSelectedChange={(id, mode) => {\n                // A list's region names no block: choosing it selects the\n                // list, and shows that region on the canvas.\n                const region = regionRows.get(id);\n                if (region !== undefined) {\n                  editor.select(region.parentId, \"replace\");\n                  editor.showListEmpty?.(\n                    region.parentId,\n                    region.slot === \"empty\"\n                  );\n                  revealChosen(region.parentId);\n                  return;\n                }\n                // A block inside a list's region is drawn only while the\n                // list shows that region: each list above it is switched to\n                // the region it sits in first, so revealing finds it.\n                for (const around of regionsTo(editor.document, id)) {\n                  editor.showListEmpty?.(\n                    around.parentId,\n                    around.slot === \"empty\"\n                  );\n                }\n                editor.select(id, mode);\n                revealChosen(id);\n              }}\n              expandedIds={expandedIds}\n              // The tree reports the whole next set, which during a search includes\n              // branches only the search opened. Those are dropped before storing,\n              // so clearing the query collapses them again instead of baking a\n              // temporary reveal into what the author has open.\n              onExpandedChange={next =>\n                setOpened(next.filter(id => !search.expand.includes(id)))\n              }\n              // The hint is the tree's DESCRIPTION, so it is announced on entering\n              // the tree rather than only readable by someone who can see it below.\n              aria-describedby={hints.length === 0 ? undefined : hintId}\n            />\n            <LayersDropOverlay drawn={drag.drawn} />\n          </div>\n        </LayerRowMenu>\n      )}\n\n      {regions\n        ?.filter(row => row.area === \"footer\")\n        .map(row => (\n          <RegionRow key={row.area} row={row} />\n        ))}\n\n      {/*\n        Why a drop under the pointer is refused, or what a row verb did, spoken. Present from the first\n        render, since a region that appears with its first message is often not\n        announced at all. A `div` rather than the editor's `p` region, which is\n        the keyboard moves' own and sits elsewhere in the editor.\n      */}\n      <div role=\"status\" aria-live=\"polite\" className=\"nx-sr-only\">\n        {drag.announcement === \"\" ? rows.notice : drag.announcement}\n      </div>\n\n      {shortcuts ? <RowShortcuts scope={body} act={rows.act} /> : null}\n\n      {/*\n        What a row's verb did, or why it could not, on screen: a refused eye or\n        rename otherwise changes nothing visible. Read out by the panel's one\n        live region above, so it is not announced twice.\n      */}\n      <p aria-hidden=\"true\" className=\"nx-layers-panel__notice\">\n        {rows.notice}\n      </p>\n\n      {/*\n        Outside the empty and no-match branches deliberately: the bindings are\n        what an author reaches for once there ARE layers to move, and a page\n        with none has nothing to say this about.\n      */}\n      {tree.length === 0 || nodes.length === 0 || hints.length === 0 ? null : (\n        <ul className=\"nx-layers-panel__hint\" id={hintId}>\n          {hints.map(({ keys, shown, label, description }) => (\n            <li className=\"nx-layers-panel__hint-row\" key={keys}>\n              <span className=\"nx-layers-panel__hint-key\" aria-hidden=\"true\">\n                {shown}\n              </span>\n              {/*\n                The short label is what is DRAWN; the binding's own sentence is\n                what is read out, because a description announced without its\n                subject — \"Move in\" — says less than the sentence the shortcut\n                manager already carries for exactly this.\n              */}\n              <span className=\"nx-layers-panel__hint-label\" aria-hidden=\"true\">\n                {label}\n              </span>\n              <span className=\"nx-sr-only\">\n                {shown}: {description}\n              </span>\n            </li>\n          ))}\n        </ul>\n      )}\n    </div>\n  );\n}\n","/**\n * Small parts of the variables view, kept beside it: the button a Design\n * group's heading becomes when the group folds, the view's own search box\n * for a view no host searches for, what the view searches for, which groups\n * it lists, and its scrolling body.\n *\n * @module design-group-toggle\n */\nimport type { SiteTokenSet, TokenMode } from \"@nextlyhq/blocks-engine\";\nimport { Input } from \"@nextlyhq/ui\";\nimport { ChevronDown, Search } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { variableGroups, type VariableGroup } from \"./tokens-studio\";\n\n/**\n * A Design group's heading as the button that folds it, with how many it\n * holds. Exported so every Design group folds the same way, the ones other\n * panels draw included.\n */\nexport function GroupToggle({\n  heading,\n  count,\n  open,\n  onToggle,\n}: {\n  heading: string;\n  count: number;\n  open: boolean;\n  /** Absent while it cannot fold, as during a search. */\n  onToggle: (() => void) | undefined;\n}): React.JSX.Element {\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-vars__group-toggle\"\n      // Said as \"Colours, 12\", with the state its expanded flag gives.\n      aria-label={`${heading}, ${count}`}\n      aria-expanded={open}\n      aria-disabled={onToggle === undefined ? true : undefined}\n      onClick={onToggle}\n    >\n      <ChevronDown\n        aria-hidden=\"true\"\n        size={14}\n        className=\"nx-vars__group-chevron\"\n      />\n      {/* A real space between heading and count, which the flex row does not\n          draw: the words drawn stay apart, so the name holds them. */}\n      <span className=\"nx-vars__group-label\">{heading}</span>{\" \"}\n      <span className=\"nx-vars__group-count\">{count}</span>\n    </button>\n  );\n}\n\n/** A variables view's own search box, drawn only where no host searches for it. */\n/** What the view's own search box is drawn from. */\ninterface OwnSearchProps {\n  /** Whether it is drawn at all: not where a host keeps the search. */\n  shown: boolean;\n  query: string;\n  onQuery: (query: string) => void;\n}\n\nexport const OwnSearch: React.ForwardRefExoticComponent<\n  OwnSearchProps & React.RefAttributes<HTMLInputElement>\n> = React.forwardRef<HTMLInputElement, OwnSearchProps>(function OwnSearch(\n  { shown, query, onQuery },\n  ref\n) {\n  if (!shown) return null;\n  return (\n    <div className=\"nx-vars__search\">\n      <Search aria-hidden=\"true\" size={16} />\n      <Input\n        ref={ref}\n        type=\"search\"\n        aria-label=\"Search variables\"\n        placeholder=\"Search variables\"\n        value={query}\n        onChange={event => onQuery(event.target.value)}\n      />\n    </div>\n  );\n});\n\n/**\n * What the view searches for: the host's search where it keeps one, else\n * the view's own, with the needle both are matched by.\n */\nexport function useViewSearch(hostSearch: string | undefined): {\n  query: string;\n  needle: string;\n  /** Whether a search is on. */\n  searching: boolean;\n  setQuery: (query: string) => void;\n  /** Whether the view draws its own search box. */\n  own: boolean;\n} {\n  const [ownQuery, setQuery] = React.useState(\"\");\n  const query = hostSearch ?? ownQuery;\n  const needle = query.trim().toLowerCase();\n  return {\n    query,\n    needle,\n    searching: needle !== \"\",\n    setQuery,\n    own: hostSearch === undefined,\n  };\n}\n\n/** The groups of the variables, narrowed to the ones this view lists. */\nexport function useListedGroups(\n  tokens: SiteTokenSet | undefined,\n  mode: TokenMode,\n  listed: readonly VariableGroup[] | undefined\n): ReturnType<typeof variableGroups> {\n  return React.useMemo(\n    () =>\n      tokens === undefined\n        ? []\n        : variableGroups(tokens, mode).filter(\n            group => listed === undefined || listed.includes(group.group)\n          ),\n    [tokens, mode, listed]\n  );\n}\n\n/** A data attribute's value for a flag: present and empty, or absent. */\nexport function markOf(flag: boolean): \"\" | undefined {\n  return flag ? \"\" : undefined;\n}\n\n/** The view's scrolling body: its notes, the header's reports, its groups. */\nexport function ViewBody({\n  notes,\n  overlays,\n  adds,\n  children,\n}: {\n  notes: React.ReactNode;\n  overlays: React.ReactNode;\n  /** The adds of groups hidden while empty, after the groups. */\n  adds: React.ReactNode;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-vars__body\">\n      {notes}\n      {overlays}\n      {children}\n      {adds}\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * \"Clean up unused…\" on the Colours tab: every colour the site made that\n * nothing uses, listed ticked in a dialog, removed in one step.\n *\n * What is listed is the usage filter's own \"unused\" ({@link\n * cleanUpCandidates}), less the colours the open page uses, which may not be\n * saved yet. Built-in colours are never listed: they are never removed.\n *\n * The removal is the host's: it judges each colour again just before its\n * write, so one that became used since the list was read is kept and named\n * with where, and the rest go. The dialog then says what went and what\n * stayed; when all went, it closes.\n *\n * @module colour-cleanup\n */\nimport type { SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Checkbox,\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { colourHexOf } from \"../../styles/style-colour\";\n\nimport { colourOrder } from \"./colour-groups\";\nimport { cleanUpCandidates } from \"./colour-usage\";\nimport type { VariableEntry, VariableGroup } from \"./tokens-studio\";\nimport { swatchStyle } from \"./variable-swatch\";\nimport { usageState } from \"./variable-usage\";\nimport type { VariableUsageHere } from \"./variable-usage-view\";\n\n/**\n * One colour a clean-up kept, with why in words that name it and where it\n * is used.\n *\n * @experimental Settles with the Colours tab's clean-up.\n */\nexport interface ColourKept {\n  readonly id: string;\n  readonly name: string;\n  readonly reason: string;\n}\n\n/**\n * What a clean-up came to: the colours removed and the ones kept, by\n * identity; or why it could not be made at all.\n *\n * @experimental Settles with the Colours tab's clean-up.\n */\nexport type ColourCleanUpResult =\n  | {\n      readonly kind: \"done\";\n      readonly removed: readonly string[];\n      readonly kept: readonly ColourKept[];\n    }\n  | { readonly kind: \"refused\"; readonly reason: string };\n\n/**\n * The host's clean-up: remove these colours, each judged on its own.\n *\n * @experimental Settles with the Colours tab's clean-up.\n */\nexport type CleanUpColours = (\n  ids: readonly string[]\n) => Promise<ColourCleanUpResult>;\n\n/** \"1 colour\", \"2 colours\". */\nfunction coloursWord(count: number): string {\n  return `${count} ${count === 1 ? \"colour\" : \"colours\"}`;\n}\n\n/** One listed colour: its row, its identity and the swatch it shows. */\ninterface Listed {\n  readonly identity: string;\n  readonly label: string;\n  readonly light: string | undefined;\n}\n\n/**\n * The Colours tab's clean-up control and its dialog. Nothing where the view\n * lists no colours, the author may not change Design, or the host cannot\n * clean up.\n */\nexport function ColourCleanUp({\n  groups,\n  readOnly,\n  onCleanUp,\n  ...reading\n}: {\n  groups: readonly {\n    readonly group: VariableGroup;\n    readonly entries: readonly VariableEntry[];\n  }[];\n  readOnly: boolean;\n  onCleanUp: CleanUpColours | undefined;\n} & Omit<CleanUpReading, \"colours\">): React.JSX.Element | null {\n  const colours = groups.find(group => group.group === \"colours\");\n  if (readOnly || onCleanUp === undefined || colours === undefined) {\n    return null;\n  }\n  return (\n    <CleanUpDialog\n      reading={{ ...reading, colours: colours.entries }}\n      onCleanUp={onCleanUp}\n    />\n  );\n}\n\n/** What the dialog reads its list from. */\ninterface CleanUpReading {\n  readonly colours: readonly VariableEntry[];\n  readonly tokens: SiteTokenSet;\n  readonly usage: VariableUsageHere | undefined;\n  readonly usedOnPage: ReadonlySet<string> | undefined;\n  /** Whether a colour is built in: the site's code or the engine supplies it. */\n  readonly builtIn: (identity: string) => boolean;\n}\n\n/** The colours listed, in the panel's order, and whether more may come. */\nfunction listedOf(reading: CleanUpReading): {\n  listed: Listed[];\n  counting: boolean;\n} {\n  const byIdentity = new Map(\n    reading.colours.map(entry => [entry.row.identity, entry])\n  );\n  const ordered = colourOrder(reading.tokens).flatMap(identity => {\n    const entry = byIdentity.get(identity);\n    if (entry === undefined) return [];\n    const token = reading.tokens.tokens[entry.row.at];\n    return [\n      {\n        identity,\n        label: entry.label,\n        light:\n          token === undefined\n            ? undefined\n            : colourHexOf(token.values.light, undefined),\n      },\n    ];\n  });\n  return cleanUpCandidates(ordered, {\n    stateOf: identity => usageState(reading.usage?.reachOf(identity)),\n    builtIn: reading.builtIn,\n    onPage: reading.usedOnPage,\n  });\n}\n\n/** What the dialog shows once a clean-up kept some colours. */\ninterface Settled {\n  readonly removed: number;\n  readonly kept: readonly ColourKept[];\n}\n\nfunction CleanUpDialog({\n  reading,\n  onCleanUp,\n}: {\n  reading: CleanUpReading;\n  onCleanUp: CleanUpColours;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  // Unticked rather than ticked, so a colour listed once its count arrives\n  // is ticked as the rest are.\n  const [unticked, setUnticked] = React.useState<ReadonlySet<string>>(\n    new Set()\n  );\n  const [busy, setBusy] = React.useState(false);\n  const [refusal, setRefusal] = React.useState<string | undefined>(undefined);\n  const [settled, setSettled] = React.useState<Settled | undefined>(undefined);\n  const trigger = React.useRef<HTMLButtonElement>(null);\n  const { listed, counting } = listedOf(reading);\n  const chosen = listed\n    .filter(colour => !unticked.has(colour.identity))\n    .map(colour => colour.identity);\n\n  const show = (next: boolean): void => {\n    if (next) {\n      setUnticked(new Set());\n      setRefusal(undefined);\n      setSettled(undefined);\n    }\n    setOpen(next);\n  };\n  const remove = async (): Promise<void> => {\n    setBusy(true);\n    setRefusal(undefined);\n    const result = await onCleanUp(chosen);\n    setBusy(false);\n    if (result.kind === \"refused\") setRefusal(result.reason);\n    else if (result.kept.length === 0) setOpen(false);\n    else setSettled({ removed: result.removed.length, kept: result.kept });\n  };\n\n  return (\n    <>\n      <button\n        ref={trigger}\n        type=\"button\"\n        className=\"nx-colour-cleanup__open\"\n        onClick={() => show(true)}\n      >\n        Clean up unused…\n      </button>\n      <Dialog open={open} onOpenChange={show}>\n        <DialogContent\n          className=\"max-w-sm\"\n          data-colour-cleanup=\"\"\n          // Back to the control that opened it, which a click does not\n          // always focus first.\n          onCloseAutoFocus={event => {\n            event.preventDefault();\n            trigger.current?.focus();\n          }}\n        >\n          <DialogHeader>\n            <DialogTitle>Clean up unused colours</DialogTitle>\n            <DialogDescription>\n              Colours you made that nothing on the site uses. Untick any you\n              want to keep.\n            </DialogDescription>\n          </DialogHeader>\n          {settled === undefined ? (\n            <CleanUpChoices\n              listed={listed}\n              counting={counting}\n              unticked={unticked}\n              onTick={(identity, ticked) =>\n                setUnticked(current => toggled(current, identity, !ticked))\n              }\n              refusal={refusal}\n            />\n          ) : (\n            <CleanUpSettled settled={settled} />\n          )}\n          <DialogFooter>\n            {settled === undefined ? (\n              <>\n                <Button\n                  type=\"button\"\n                  variant=\"outline\"\n                  onClick={() => show(false)}\n                >\n                  Cancel\n                </Button>\n                <Button\n                  type=\"button\"\n                  variant=\"destructive\"\n                  disabled={busy || chosen.length === 0}\n                  aria-busy={busy || undefined}\n                  onClick={() => void remove()}\n                >\n                  {`Remove ${coloursWord(chosen.length)}`}\n                </Button>\n              </>\n            ) : (\n              <Button type=\"button\" onClick={() => show(false)}>\n                Done\n              </Button>\n            )}\n          </DialogFooter>\n        </DialogContent>\n      </Dialog>\n    </>\n  );\n}\n\n/** A set with one identity added or taken out. */\nfunction toggled(\n  set: ReadonlySet<string>,\n  identity: string,\n  present: boolean\n): ReadonlySet<string> {\n  const next = new Set(set);\n  if (present) next.add(identity);\n  else next.delete(identity);\n  return next;\n}\n\n/** The colours to remove, each ticked, and what the dialog has to say. */\nfunction CleanUpChoices({\n  listed,\n  counting,\n  unticked,\n  onTick,\n  refusal,\n}: {\n  listed: readonly Listed[];\n  counting: boolean;\n  unticked: ReadonlySet<string>;\n  onTick: (identity: string, ticked: boolean) => void;\n  refusal: string | undefined;\n}): React.JSX.Element {\n  const id = React.useId();\n  return (\n    <div className=\"nx-colour-cleanup\">\n      {counting ? (\n        <p className=\"nx-colour-cleanup__note\" role=\"status\">\n          Counting usage…\n        </p>\n      ) : null}\n      {listed.length === 0 && !counting ? (\n        <p className=\"nx-colour-cleanup__note\">\n          Every colour you made is in use.\n        </p>\n      ) : null}\n      {listed.length === 0 ? null : (\n        <ul className=\"nx-colour-cleanup__list\">\n          {listed.map(colour => (\n            <li key={colour.identity} className=\"nx-colour-cleanup__row\">\n              <Checkbox\n                id={`${id}-${colour.identity}`}\n                aria-label={colour.label}\n                checked={!unticked.has(colour.identity)}\n                onCheckedChange={checked =>\n                  onTick(colour.identity, checked === true)\n                }\n              />\n              <span\n                className=\"nx-vars__swatch nx-vars__swatch--main\"\n                aria-hidden=\"true\"\n                style={swatchStyle(colour.light)}\n              />\n              <label\n                className=\"nx-colour-cleanup__name\"\n                htmlFor={`${id}-${colour.identity}`}\n                title={colour.label}\n              >\n                {colour.label}\n              </label>\n            </li>\n          ))}\n        </ul>\n      )}\n      {refusal === undefined ? null : (\n        <p className=\"nx-colour-cleanup__alert\" role=\"alert\">\n          {refusal}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/** What a clean-up that kept some colours did: what went, and what stayed. */\nfunction CleanUpSettled({ settled }: { settled: Settled }): React.JSX.Element {\n  const one = settled.kept.length === 1;\n  return (\n    <div className=\"nx-colour-cleanup\" role=\"status\">\n      <p className=\"nx-colour-cleanup__note\">\n        {settled.removed === 0\n          ? \"No colour was removed.\"\n          : `Removed ${coloursWord(settled.removed)}.`}\n      </p>\n      <p className=\"nx-colour-cleanup__note\">\n        {one ? \"Kept, as it's in use now:\" : \"Kept, as they're in use now:\"}\n      </p>\n      <ul className=\"nx-colour-cleanup__list\">\n        {settled.kept.map(kept => (\n          <li key={kept.id} className=\"nx-colour-cleanup__kept\">\n            {kept.reason}\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * A name edited in place: its field takes focus with the name selected as it\n * opens, and the edit finishes once. Enter's own close takes the field away,\n * and the blur that follows must not keep or cancel a second time.\n *\n * @module in-place-field\n */\nimport * as React from \"react\";\n\nexport function useInPlaceField(): {\n  readonly field: React.RefObject<HTMLInputElement | null>;\n  /** Set once the edit has finished, kept or cancelled. */\n  readonly done: React.RefObject<boolean>;\n} {\n  const done = React.useRef(false);\n  const field = React.useRef<HTMLInputElement>(null);\n  React.useEffect(() => {\n    field.current?.focus();\n    field.current?.select();\n  }, []);\n  return { field, done };\n}\n","\"use client\";\n\n/**\n * The Colours tab's named groups as an author changes them: a group's name\n * renamed in place, its ⋯ menu (\"Rename group\", \"Remove group\"), \"+ New\n * group\", and dragging a colour onto a row or a group's heading.\n *\n * A new group holds no colour yet, and a group is the colours in it, so it\n * lives here, named, until a colour moves into it; from then on the colours\n * carry it. Every change writes only colours' display groups and the colour\n * order (`colour-groups`), never a code name, a value or the site's CSS.\n *\n * @module colour-group-ui\n */\nimport {\n  MAX_TOKEN_LABEL_LENGTH,\n  tokenLabelIssue,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { Ellipsis, Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport {\n  colourGroups,\n  moveColour,\n  placeColour,\n  removeColourGroup,\n  renameColourGroup,\n} from \"./colour-groups\";\nimport { useInPlaceField } from \"./in-place-field\";\n\n/** What the Colours tab's groups share: the set, its writes, and the drafts. */\nexport interface ColourGroupHost {\n  readonly tokens: SiteTokenSet;\n  readonly readOnly: boolean;\n  readonly commit: (next: SiteTokenSet) => void;\n  /** Groups made with \"+ New group\" that no colour is in yet. */\n  readonly pending: readonly string[];\n  /** The group whose name is being edited in place. */\n  readonly renaming: string | null;\n  readonly setRenaming: (name: string | null) => void;\n  /** The group whose ⋯ takes focus back once its rename is ended by a key. */\n  readonly refocus: string | null;\n  readonly setRefocus: (name: string | null) => void;\n  readonly addPending: () => void;\n  readonly renamePending: (from: string, to: string) => void;\n  readonly dropPending: (name: string) => void;\n  /** The colour being dragged, by identity. */\n  readonly dragging: string | null;\n  readonly setDragging: (identity: string | null) => void;\n  /**\n   * After a colour row moved by Alt+Up or Alt+Down, with the set the move\n   * made: the panel keeps the row shown and focused where it is drawn now.\n   */\n  readonly onMoved?: (\n    row: { readonly key: string; readonly identity: string },\n    next: SiteTokenSet\n  ) => void;\n}\n\nexport const ColourGroupHostContext: React.Context<\n  ColourGroupHost | undefined\n> = React.createContext<ColourGroupHost | undefined>(undefined);\n\n/** The name a new group starts with, unique among the groups there are. */\nfunction newGroupName(taken: readonly string[]): string {\n  const base = \"New group\";\n  if (!taken.includes(base)) return base;\n  let n = 2;\n  while (taken.includes(`${base} ${String(n)}`)) n += 1;\n  return `${base} ${String(n)}`;\n}\n\n/** The Colours tab's shared state, for its sections and rows. */\nexport function useColourGroupHost(\n  tokens: SiteTokenSet,\n  readOnly: boolean,\n  commit: (next: SiteTokenSet) => void\n): ColourGroupHost {\n  const [drafts, setDrafts] = React.useState<readonly string[]>([]);\n  const [renaming, setRenaming] = React.useState<string | null>(null);\n  const [refocus, setRefocus] = React.useState<string | null>(null);\n  const [dragging, setDragging] = React.useState<string | null>(null);\n  const real = colourGroups(tokens).map(group => group.name);\n  // A draft a colour has moved into is a group like any other now, so it is\n  // let go, not just hidden: kept, it would come back empty once that group\n  // is renamed or removed.\n  const pending = drafts.filter(name => !real.includes(name));\n  if (pending.length !== drafts.length) setDrafts(pending);\n  return {\n    tokens,\n    readOnly,\n    commit,\n    pending,\n    renaming,\n    setRenaming,\n    refocus,\n    setRefocus,\n    addPending: () => {\n      const name = newGroupName([...real, ...pending]);\n      setDrafts([...pending, name]);\n      setRenaming(name);\n    },\n    renamePending: (from, to) =>\n      setDrafts(pending.map(name => (name === from ? to : name))),\n    dropPending: name => setDrafts(pending.filter(draft => draft !== name)),\n    dragging,\n    setDragging,\n  };\n}\n\n/** The groups' names, real then drafts, as a colour may be moved into them. */\nexport function useColourGroupNames(): readonly string[] {\n  const host = React.useContext(ColourGroupHostContext);\n  if (host === undefined) return [];\n  return [\n    ...colourGroups(host.tokens).map(group => group.name),\n    ...host.pending,\n  ];\n}\n\n/** Where a drop lands a dragged colour: in a group, before a colour or last. */\nfunction drop(\n  host: ColourGroupHost,\n  group: string,\n  before: string | undefined\n): void {\n  const dragged = host.dragging;\n  host.setDragging(null);\n  if (dragged === null) return;\n  const next = placeColour(host.tokens, dragged, group, before);\n  if (next !== host.tokens) host.commit(next);\n}\n\n/** The group a colour is listed in. */\nfunction groupOf(tokens: SiteTokenSet, identity: string): string | undefined {\n  return colourGroups(tokens).find(group => group.identities.includes(identity))\n    ?.name;\n}\n\n/**\n * A colour row's move one place up or down the site's colour order, by\n * Alt+Up and Alt+Down; nothing for any other kind, which is not ordered.\n * The panel is told after, so the row keeps the focus where it is drawn.\n */\nexport function useColourRowMove(\n  row: {\n    readonly key: string;\n    readonly identity: string;\n    readonly kind: string;\n  },\n  tokens: SiteTokenSet,\n  onChange: (tokens: SiteTokenSet) => void\n): ((by: -1 | 1) => void) | undefined {\n  const host = React.useContext(ColourGroupHostContext);\n  if (row.kind !== \"color\") return undefined;\n  return by => {\n    const next = moveColour(tokens, row.identity, by);\n    onChange(next);\n    host?.onMoved?.(row, next);\n  };\n}\n\n/**\n * A colour row's drag: it can be picked up, and a colour dropped on it lands\n * before it, in its group. Nothing where the colours are read-only.\n */\nexport function useColourRowDrag(row: {\n  readonly identity: string;\n  /** A colour's row is dragged; any other kind is not ordered. */\n  readonly kind: string;\n}): React.LiHTMLAttributes<HTMLLIElement> {\n  const host = React.useContext(ColourGroupHostContext);\n  const { identity } = row;\n  if (row.kind !== \"color\" || host === undefined || host.readOnly) return {};\n  return {\n    draggable: true,\n    onDragStart: event => {\n      event.dataTransfer.effectAllowed = \"move\";\n      event.dataTransfer.setData(\"text/plain\", identity);\n      host.setDragging(identity);\n    },\n    onDragEnd: () => host.setDragging(null),\n    onDragOver: event => {\n      if (host.dragging === null) return;\n      event.preventDefault();\n      event.dataTransfer.dropEffect = \"move\";\n    },\n    onDrop: event => {\n      event.preventDefault();\n      event.stopPropagation();\n      const group = groupOf(host.tokens, identity);\n      if (group !== undefined) drop(host, group, identity);\n    },\n  };\n}\n\n/** A group heading's drop: a colour dropped on it goes to the group's end. */\nexport function useColourGroupDrop(\n  name: string\n): React.HTMLAttributes<HTMLDivElement> {\n  const host = React.useContext(ColourGroupHostContext);\n  if (host === undefined || host.readOnly) return {};\n  return {\n    onDragOver: event => {\n      if (host.dragging === null) return;\n      event.preventDefault();\n      event.dataTransfer.dropEffect = \"move\";\n    },\n    onDrop: event => {\n      event.preventDefault();\n      drop(host, name, undefined);\n    },\n  };\n}\n\n/**\n * A named group's heading: its name and count, or the field renaming it,\n * and its ⋯ menu.\n */\nexport function ColourGroupHead({\n  name,\n  children,\n}: {\n  name: string;\n  /** The heading as the panel draws it: the fold toggle with the count. */\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const host = React.useContext(ColourGroupHostContext);\n  if (host === undefined) return <>{children}</>;\n  if (host.renaming === name) return <GroupNameField host={host} name={name} />;\n  return (\n    <>\n      {children}\n      {host.readOnly ? null : <GroupMenu host={host} name={name} />}\n    </>\n  );\n}\n\n/** The group's ⋯: \"Rename group\" and \"Remove group\". */\nfunction GroupMenu({\n  host,\n  name,\n}: {\n  host: ColourGroupHost;\n  name: string;\n}): React.JSX.Element {\n  const pending = host.pending.includes(name);\n  const only = colourGroups(host.tokens).length < 2 && !pending;\n  const renamed = React.useRef(false);\n  const more = React.useRef<HTMLButtonElement>(null);\n  // A rename ended by Enter or Escape hands focus back here, where it began,\n  // under the name the group has now.\n  const { refocus, setRefocus } = host;\n  React.useEffect(() => {\n    if (refocus !== name) return;\n    more.current?.focus();\n    setRefocus(null);\n  }, [refocus, setRefocus, name]);\n  return (\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild>\n        <button\n          ref={more}\n          type=\"button\"\n          className=\"nx-vars__icon-button nx-vars__more nx-colour-group__more\"\n          aria-label={`More actions for group ${name}`}\n        >\n          <Ellipsis aria-hidden=\"true\" size={14} />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align=\"end\"\n        className=\"nx-vars__menu\"\n        // The name field takes focus; the menu does not take it back.\n        onCloseAutoFocus={event => {\n          if (!renamed.current) return;\n          renamed.current = false;\n          event.preventDefault();\n        }}\n      >\n        <DropdownMenuItem\n          onSelect={() => {\n            renamed.current = true;\n            host.setRenaming(name);\n          }}\n        >\n          Rename group\n        </DropdownMenuItem>\n        <DropdownMenuItem\n          disabled={only}\n          onSelect={() => {\n            if (pending) host.dropPending(name);\n            else host.commit(removeColourGroup(host.tokens, name));\n          }}\n        >\n          Remove group\n        </DropdownMenuItem>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/**\n * The name typed for a group, where it can be taken: not empty, storable as a\n * label, and no other group's. Otherwise nothing, and the old name stays.\n */\nfunction acceptedName(\n  host: ColourGroupHost,\n  name: string,\n  draft: string\n): string | undefined {\n  const next = draft.trim();\n  const taken = [\n    ...colourGroups(host.tokens).map(group => group.name),\n    ...host.pending,\n  ].filter(other => other !== name);\n  const refused = next === \"\" || tokenLabelIssue(next) !== undefined;\n  return refused || next === name || taken.includes(next) ? undefined : next;\n}\n\n/**\n * The group's name in place: Enter or leaving keeps it, Escape keeps the old\n * one. An empty name, or one another group has, keeps the old one too.\n */\nfunction GroupNameField({\n  host,\n  name,\n}: {\n  host: ColourGroupHost;\n  name: string;\n}): React.JSX.Element {\n  const [draft, setDraft] = React.useState(name);\n  const { field, done } = useInPlaceField();\n  // Ended by a key, focus goes back to the group's ⋯; by leaving the field,\n  // it stays where the author went.\n  const finish = (keep: boolean, byKey: boolean): void => {\n    if (done.current) return;\n    done.current = true;\n    host.setRenaming(null);\n    const next = keep ? acceptedName(host, name, draft) : undefined;\n    if (next !== undefined && host.pending.includes(name)) {\n      host.renamePending(name, next);\n    } else if (next !== undefined) {\n      host.commit(renameColourGroup(host.tokens, name, next));\n    }\n    if (byKey) host.setRefocus(next ?? name);\n  };\n  return (\n    <input\n      ref={field}\n      className=\"nx-colour-group__name-field\"\n      aria-label=\"Group name\"\n      autoComplete=\"off\"\n      spellCheck={false}\n      value={draft}\n      maxLength={MAX_TOKEN_LABEL_LENGTH}\n      onChange={event => setDraft(event.currentTarget.value)}\n      onBlur={() => finish(true, false)}\n      onKeyDown={event => {\n        // The Enter that confirms an input method's text is not the end of\n        // the name.\n        if (event.key === \"Enter\" && !event.nativeEvent.isComposing) {\n          event.preventDefault();\n          finish(true, true);\n        } else if (event.key === \"Escape\") {\n          event.preventDefault();\n          event.stopPropagation();\n          finish(false, true);\n        }\n      }}\n    />\n  );\n}\n\n/**\n * \"+ New group\", at the end of the Colours tab, drawn as the add rows are:\n * the plus as an icon beside the words.\n */\nexport function NewGroupButton(): React.JSX.Element | null {\n  const host = React.useContext(ColourGroupHostContext);\n  if (host === undefined || host.readOnly) return null;\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-vars__add-row nx-colour-group__new\"\n      onClick={host.addPending}\n    >\n      <Plus aria-hidden=\"true\" size={14} />\n      New group\n    </button>\n  );\n}\n","\"use client\";\n\n/**\n * The Colours tab's usage filter: \"All\", \"Unused\" and \"Used on this page\",\n * as pills above the colour list, \"All\" by default.\n *\n * \"Unused\" lists only what the site's count has shown unused, and says\n * \"Counting usage…\" while the count is not whole rather than guess; \"Used on\n * this page\" lists what the open page and its components use, as the host\n * reads them from the editor's document, so it follows unsaved edits.\n *\n * @module colour-usage-filter\n */\nimport { tokenIdentity, type SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { keepsColour, type ColourFilter } from \"./colour-usage\";\nimport type { VariableEntry, VariableGroup } from \"./tokens-studio\";\nimport { usageState, type UsageState } from \"./variable-usage\";\nimport type { VariableUsageHere } from \"./variable-usage-view\";\n\n/** The choices, in the order they are offered. */\nconst CHOICES: readonly { value: ColourFilter; label: string }[] = [\n  { value: \"all\", label: \"All\" },\n  { value: \"unused\", label: \"Unused\" },\n  { value: \"page\", label: \"Used on this page\" },\n];\n\ninterface Listed {\n  readonly group: VariableGroup;\n  readonly heading: string;\n  readonly entries: readonly VariableEntry[];\n}\n\n/**\n * The groups with the colours narrowed to the filter, and the filter to\n * draw above them; nothing to draw where the view lists no colours.\n */\nexport function useColourFilter<G extends Listed>({\n  shown,\n  tokens,\n  usage,\n  usedOnPage,\n  openKey,\n  hidden,\n}: {\n  shown: readonly G[];\n  /** The site's variables, whose change can make a colour used or unused. */\n  tokens: SiteTokenSet | undefined;\n  usage: VariableUsageHere | undefined;\n  usedOnPage: ReadonlySet<string> | undefined;\n  /** The row whose editor is open, listed whatever the filter. */\n  openKey: string | null;\n  /** The built-in colours the site hides, left out whatever the filter. */\n  hidden?: ReadonlySet<string>;\n}): { shown: readonly G[]; control: React.ReactNode } {\n  const [filter, setFilter] = React.useState<ColourFilter>(\"all\");\n  const colours = shown.find(group => group.group === \"colours\");\n  useCountsAfterChange(filter === \"unused\", usage, tokens);\n  if (colours === undefined) return { shown, control: null };\n  const stateOf = (entry: VariableEntry): UsageState =>\n    usageState(usage?.reachOf(entry.row.identity));\n  const keeps = (entry: VariableEntry): boolean =>\n    entry.row.key === openKey ||\n    (hidden?.has(entry.row.identity) !== true &&\n      keepsColour(\n        filter,\n        stateOf(entry),\n        usedOnPage?.has(entry.row.identity) === true\n      ));\n  const counting =\n    filter === \"unused\" &&\n    colours.entries.some(entry => stateOf(entry) === \"counting\");\n  return {\n    shown: shown.map(group =>\n      group === colours\n        ? { ...group, entries: group.entries.filter(keeps) }\n        : group\n    ),\n    control: (\n      <ColourUsageFilter\n        value={filter}\n        onChange={setFilter}\n        counting={counting}\n      />\n    ),\n  };\n}\n\n/** How long after a change of the variables the counts are read again. */\nconst RECOUNT_AFTER_MS = 800;\n\n/**\n * Reads the colours' counts again a moment after the site's variables change,\n * once Unused is chosen: an edit that names a colour through another\n * variable, or stops naming it, changes whether it is used, and the counts\n * say so once the change is saved. A change made under another filter is\n * kept as owed, and read when Unused is chosen.\n */\nfunction useCountsAfterChange(\n  unused: boolean,\n  usage: VariableUsageHere | undefined,\n  tokens: SiteTokenSet | undefined\n): void {\n  const seen = React.useRef(tokens);\n  const owed = React.useRef(false);\n  const latest = React.useRef(usage);\n  latest.current = usage;\n  React.useEffect(() => {\n    if (seen.current !== tokens) owed.current = true;\n    seen.current = tokens;\n    const read = latest.current;\n    if (!unused || !owed.current || read === undefined) return undefined;\n    // Every colour the site has, whatever a search lists now: a change can\n    // name, or stop naming, one the search hides.\n    const colours = (tokens?.tokens ?? [])\n      .filter(token => token.kind === \"color\")\n      .map(tokenIdentity);\n    const timer = window.setTimeout(() => {\n      owed.current = false;\n      void read.readAgain(colours);\n    }, RECOUNT_AFTER_MS);\n    return () => window.clearTimeout(timer);\n  }, [tokens, unused]);\n}\n\n/** The pills, a radio group the arrow keys move through, and its note. */\nfunction ColourUsageFilter({\n  value,\n  onChange,\n  counting,\n}: {\n  value: ColourFilter;\n  onChange: (value: ColourFilter) => void;\n  counting: boolean;\n}): React.JSX.Element {\n  const buttons = React.useRef(new Map<ColourFilter, HTMLButtonElement>());\n  const move = (by: -1 | 1): void => {\n    const at = CHOICES.findIndex(choice => choice.value === value);\n    const next = CHOICES[(at + by + CHOICES.length) % CHOICES.length];\n    if (next === undefined) return;\n    onChange(next.value);\n    buttons.current.get(next.value)?.focus();\n  };\n  return (\n    <div className=\"nx-usage-filter\">\n      <div\n        className=\"nx-usage-filter__choices\"\n        role=\"radiogroup\"\n        aria-label=\"Show colours\"\n        onKeyDown={event => {\n          const by = arrowStep(event.key);\n          if (by === undefined) return;\n          event.preventDefault();\n          move(by);\n        }}\n      >\n        {CHOICES.map(choice => (\n          <button\n            key={choice.value}\n            ref={button => {\n              if (button === null) buttons.current.delete(choice.value);\n              else buttons.current.set(choice.value, button);\n            }}\n            type=\"button\"\n            role=\"radio\"\n            className=\"nx-usage-filter__choice\"\n            aria-checked={choice.value === value}\n            // One stop in the tab order, on the choice made.\n            tabIndex={choice.value === value ? 0 : -1}\n            onClick={() => onChange(choice.value)}\n          >\n            {choice.label}\n          </button>\n        ))}\n      </div>\n      {counting ? (\n        <p className=\"nx-usage-filter__note\" role=\"status\">\n          Counting usage…\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\n/** Which way an arrow key moves through the choices, or none. */\nfunction arrowStep(key: string): -1 | 1 | undefined {\n  if (key === \"ArrowRight\" || key === \"ArrowDown\") return 1;\n  return key === \"ArrowLeft\" || key === \"ArrowUp\" ? -1 : undefined;\n}\n","\"use client\";\n\n/**\n * What the Colours tab lists while the site hides its unused built-in\n * colours, and the setting that ends the tab: the tab's usage filter with\n * the hidden colours left out, read by the one rule the pickers read too\n * ({@link hiddenColours}).\n *\n * @module colours-of-view\n */\nimport type { SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport {\n  BuiltInColoursSetting,\n  builtInColoursShown,\n  useHiddenReadAgain,\n} from \"./built-in-colours\";\nimport { hiddenColours } from \"./colour-usage\";\nimport { useColourFilter } from \"./colour-usage-filter\";\nimport type { VariableEntry, VariableGroup } from \"./tokens-studio\";\nimport { usageState } from \"./variable-usage\";\nimport type { VariableUsageHere } from \"./variable-usage-view\";\n\n/**\n * The built-in colours the view leaves out while the site hides them, read\n * by the one rule the pickers read too, and whether a listed built-in\n * colour's row says so. Their use is read again a moment after the site's\n * variables change, since a variable naming one makes it used.\n */\nfunction useHiddenOfView({\n  tokens,\n  groups,\n  usage,\n  builtIn,\n  usedOnPage,\n}: {\n  tokens: SiteTokenSet | undefined;\n  groups: Parameters<typeof colourIdentities>[0];\n  usage: VariableUsageHere | undefined;\n  /** Whether a colour is built in: the site's code or the engine supplies it. */\n  builtIn: (identity: string) => boolean;\n  usedOnPage: ReadonlySet<string> | undefined;\n}): { hidden: ReadonlySet<string>; marksBuiltIn: boolean } {\n  const shown = builtInColoursShown(tokens);\n  const colours = colourIdentities(groups);\n  useHiddenReadAgain(shown, tokens, colours.filter(builtIn), usage?.readAgain);\n  return {\n    hidden: hiddenColours(colours, {\n      shown,\n      stateOf: identity => usageState(usage?.reachOf(identity)),\n      builtIn,\n      onPage: usedOnPage,\n    }),\n    marksBuiltIn: !shown,\n  };\n}\n\n/**\n * The Colours tab's usage filter over the listed groups, leaving out the\n * built-in colours the site hides ({@link useHiddenOfView}), and those.\n */\nexport function useColoursOfView<\n  G extends Parameters<typeof useColourFilter>[0][\"shown\"][number],\n>({\n  groups,\n  builtIn,\n  ...filter\n}: Omit<Parameters<typeof useColourFilter<G>>[0], \"hidden\"> & {\n  groups: Parameters<typeof colourIdentities>[0];\n  builtIn: (identity: string) => boolean;\n}): ReturnType<typeof useColourFilter<G>> & {\n  hidden: ReadonlySet<string>;\n  marksBuiltIn: boolean;\n} {\n  const { hidden, marksBuiltIn } = useHiddenOfView({\n    tokens: filter.tokens,\n    groups,\n    usage: filter.usage,\n    builtIn,\n    usedOnPage: filter.usedOnPage,\n  });\n  return { ...useColourFilter({ ...filter, hidden }), hidden, marksBuiltIn };\n}\n\n/** The site's built-in colours setting, which ends the Colours tab. */\nexport function ColoursTabEnd({\n  groups,\n  ...setting\n}: React.ComponentProps<typeof BuiltInColoursSetting> & {\n  groups: readonly { readonly group: VariableGroup }[];\n}): React.JSX.Element | null {\n  if (!groups.some(group => group.group === \"colours\")) return null;\n  return <BuiltInColoursSetting {...setting} />;\n}\n\n/** The identities of the colours the view lists. */\nfunction colourIdentities(\n  groups: readonly {\n    readonly group: VariableGroup;\n    readonly entries: readonly VariableEntry[];\n  }[]\n): string[] {\n  return groups\n    .filter(group => group.group === \"colours\")\n    .flatMap(group => group.entries.map(entry => entry.row.identity));\n}\n","/**\n * \"Fluid…\" on a size: two sizes, \"On small screens\" and \"On large screens\",\n * the sentence that says what they make (\"16px at 360px, growing to 20px at\n * 1280px\"), and \"Make fluid\", which stores the size grown evenly between\n * them across the site's fluid range, with the two sizes kept beside it.\n *\n * Opened in place inside the variable's editor rather than as a second\n * popover over it, so it stays in the editor's one dialog for focus and for\n * a screen reader. A value written by hand opens on its nearest two sizes,\n * and making it fluid converts it.\n *\n * @module fluid-popover\n */\nimport { isFluidSize } from \"@nextlyhq/blocks-engine\";\nimport { Button, Input } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  DEFAULT_FLUID_RANGE,\n  lengthInPx,\n  nearestFluidSizes,\n  type FluidRangeWidths,\n  type FluidSizes,\n} from \"../../styles/fluid-size\";\n\n/** What a size field needs to offer \"Fluid…\". */\nexport interface FluidHook {\n  /** The sizes the value was made from, where it was made fluid. */\n  readonly sizes: FluidSizes | undefined;\n  /** The value as stored, to start from where it has no sizes. */\n  readonly value: string;\n  readonly onFluid: (sizes: FluidSizes) => void;\n  /** The site's fluid range. */\n  readonly range?: FluidRangeWidths;\n  /** Change the site's fluid range, from \"Change range\". */\n  readonly onRange?: (range: FluidRangeWidths) => void;\n}\n\n/** The sizes to start from: the stored ones, else the value's nearest. */\nfunction startingSizes(hook: FluidHook, range: FluidRangeWidths): FluidSizes {\n  if (hook.sizes !== undefined) return hook.sizes;\n  const nearest = nearestFluidSizes(hook.value, range);\n  if (nearest !== undefined) return nearest;\n  const fixed = lengthInPx(hook.value);\n  return fixed === undefined\n    ? { small: 16, large: 16 }\n    : { small: fixed, large: fixed };\n}\n\n/**\n * A typed size in px, or `undefined` for what is not one: the engine's one\n * bound, which a reader of stored sizes holds them to as well.\n */\nfunction sizeOf(text: string): number | undefined {\n  const value = Number(text.trim());\n  return text.trim() !== \"\" && isFluidSize(value) ? value : undefined;\n}\n\n/** \"Fluid…\", and its two sizes under it while it is open. */\nexport function FluidButton({ hook }: { hook: FluidHook }): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  return (\n    <>\n      <button\n        type=\"button\"\n        className=\"nx-vars__link nx-vars-editor__fluid\"\n        aria-expanded={open}\n        onClick={() => setOpen(current => !current)}\n      >\n        Fluid…\n      </button>\n      {open ? <FluidForm hook={hook} onDone={() => setOpen(false)} /> : null}\n    </>\n  );\n}\n\n/** The two sizes, what they make, and \"Make fluid\". */\nfunction FluidForm({\n  hook,\n  onDone,\n}: {\n  hook: FluidHook;\n  onDone: () => void;\n}): React.JSX.Element {\n  const range = hook.range ?? DEFAULT_FLUID_RANGE;\n  const start = startingSizes(hook, range);\n  const [small, setSmall] = React.useState(String(start.small));\n  const [large, setLarge] = React.useState(String(start.large));\n  const id = React.useId();\n  const sizes = { small: sizeOf(small), large: sizeOf(large) };\n  const ready =\n    sizes.small !== undefined && sizes.large !== undefined\n      ? { small: sizes.small, large: sizes.large }\n      : undefined;\n  return (\n    <div className=\"nx-fluid\" role=\"group\" aria-label=\"Fluid size\">\n      <div className=\"nx-fluid__sizes\">\n        <label className=\"nx-vars-editor__label\" htmlFor={`${id}-small`}>\n          On small screens\n        </label>\n        <Input\n          id={`${id}-small`}\n          inputMode=\"decimal\"\n          autoComplete=\"off\"\n          value={small}\n          onChange={event => setSmall(event.currentTarget.value)}\n        />\n        <label className=\"nx-vars-editor__label\" htmlFor={`${id}-large`}>\n          On large screens\n        </label>\n        <Input\n          id={`${id}-large`}\n          inputMode=\"decimal\"\n          autoComplete=\"off\"\n          value={large}\n          onChange={event => setLarge(event.currentTarget.value)}\n        />\n      </div>\n      <p className=\"nx-fluid__said\" role=\"status\">\n        {ready === undefined\n          ? \"Type two sizes in px.\"\n          : `${String(ready.small)}px at ${String(range.min)}px, growing to ${String(ready.large)}px at ${String(range.max)}px`}\n      </p>\n      {hook.onRange === undefined ? null : (\n        <RangeLink range={range} onRange={hook.onRange} />\n      )}\n      <Button\n        type=\"button\"\n        size=\"sm\"\n        variant=\"outline\"\n        className=\"nx-vars-editor__button\"\n        disabled={ready === undefined}\n        onClick={() => {\n          if (ready === undefined) return;\n          hook.onFluid(ready);\n          onDone();\n        }}\n      >\n        Make fluid\n      </Button>\n    </div>\n  );\n}\n\n/** \"Change range\", and the site's fluid range under it while it is open. */\nfunction RangeLink({\n  range,\n  onRange,\n}: {\n  range: FluidRangeWidths;\n  onRange: (range: FluidRangeWidths) => void;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  return (\n    <>\n      <button\n        type=\"button\"\n        className=\"nx-vars__link nx-fluid__range-link\"\n        aria-expanded={open}\n        onClick={() => setOpen(current => !current)}\n      >\n        Change range\n      </button>\n      {open ? (\n        <FluidRangeFields range={range} onRange={onRange} readOnly={false} />\n      ) : null}\n    </>\n  );\n}\n\n/** The range's two widths as the fields show them. */\ninterface RangeDrafts {\n  readonly min: string;\n  readonly max: string;\n}\n\n/**\n * The fields' typing, until the stored range changes underneath them (an\n * undo, another author's save), which replaces both.\n */\nfunction useRangeDrafts(\n  range: FluidRangeWidths\n): [RangeDrafts, React.Dispatch<React.SetStateAction<RangeDrafts>>] {\n  const stored = `${String(range.min)} ${String(range.max)}`;\n  const [drafts, setDrafts] = React.useState<RangeDrafts>(() =>\n    draftsOf(range)\n  );\n  const [shown, setShown] = React.useState(stored);\n  if (shown !== stored) {\n    setShown(stored);\n    setDrafts(draftsOf(range));\n  }\n  return [drafts, setDrafts];\n}\n\nfunction draftsOf(range: FluidRangeWidths): RangeDrafts {\n  return { min: String(range.min), max: String(range.max) };\n}\n\n/** The end whose own text is no width, or `undefined` when both are widths. */\nfunction unreadableEnd(next: {\n  min: number | undefined;\n  max: number | undefined;\n}): \"min\" | \"max\" | undefined {\n  if (next.min === undefined) return \"min\";\n  return next.max === undefined ? \"max\" : undefined;\n}\n\n/**\n * The site's fluid range: \"Smallest screen\" and \"Largest screen\", in px.\n * Each field commits when it is left or on Enter; a range whose smallest\n * screen is not the smaller is refused in its field, saying why, and not\n * written. The one control for the range, in the Type tab and from every\n * \"Fluid…\".\n */\nexport function FluidRangeFields({\n  range,\n  onRange,\n  readOnly,\n}: {\n  range: FluidRangeWidths;\n  onRange: (range: FluidRangeWidths) => void;\n  readOnly: boolean;\n}): React.JSX.Element {\n  const id = React.useId();\n  const [drafts, setDrafts] = useRangeDrafts(range);\n  const [refused, setRefused] = React.useState<\"min\" | \"max\" | undefined>();\n  // Both fields are read on either's commit, so the pair saved is the pair on\n  // screen: a refused width stays typed, and putting the other right saves\n  // both rather than the stored one beside it.\n  const commit = (end: \"min\" | \"max\"): void => {\n    const next = { min: sizeOf(drafts.min), max: sizeOf(drafts.max) };\n    if (\n      next.min === undefined ||\n      next.max === undefined ||\n      next.min >= next.max\n    ) {\n      setRefused(unreadableEnd(next) ?? end);\n      return;\n    }\n    setRefused(undefined);\n    if (next.min !== range.min || next.max !== range.max) {\n      onRange({ min: next.min, max: next.max });\n    }\n  };\n  const field = (end: \"min\" | \"max\", label: string): React.JSX.Element => (\n    <>\n      <label className=\"nx-vars-editor__label\" htmlFor={`${id}-${end}`}>\n        {label}\n      </label>\n      <Input\n        id={`${id}-${end}`}\n        inputMode=\"decimal\"\n        autoComplete=\"off\"\n        readOnly={readOnly}\n        value={drafts[end]}\n        aria-invalid={refused === end ? true : undefined}\n        aria-describedby={refused === end ? `${id}-said` : undefined}\n        onChange={event => {\n          const text = event.currentTarget.value;\n          setDrafts(current => ({ ...current, [end]: text }));\n        }}\n        onBlur={() => commit(end)}\n        onKeyDown={event => {\n          if (event.key === \"Enter\") commit(end);\n        }}\n      />\n    </>\n  );\n  return (\n    <div className=\"nx-fluid__range\" role=\"group\" aria-label=\"Fluid range\">\n      {field(\"min\", \"Smallest screen\")}\n      {field(\"max\", \"Largest screen\")}\n      {refused === undefined ? null : (\n        <p className=\"nx-fluid__said\" id={`${id}-said`} role=\"status\">\n          The smallest screen comes first, and both are widths in px.\n        </p>\n      )}\n    </div>\n  );\n}\n","/**\n * Commits the field that has focus in a variable or Site text editor, by\n * leaving it, as Tab would: each field commits on blur, synchronously. Called\n * before an editor closes, since a click outside closes it before the\n * field's own blur, and the value typed there would otherwise be lost.\n *\n * @module editor-field-commit\n */\nimport { isHTMLElement } from \"../../canvas/dom-kind\";\n\nexport function commitFocusedField(document: Document | undefined): void {\n  const active = document?.activeElement;\n  if (isHTMLElement(active) && active.closest(\".nx-vars-editor\")) {\n    active.blur();\n  }\n}\n","/**\n * A colour's contrast in the Design panel's words: the WCAG 2 ratio to two\n * decimals (\"4.83:1\"), and what it is good for. \"Readable as text\" from\n * 4.5:1, the threshold for body text; \"Large text only\" from 3:1, the one\n * for large text and for controls; \"Low contrast\" below. The ratio is the\n * engine's own, so a figure here agrees with every other contrast check.\n *\n * @module variable-contrast\n */\nimport { checkContrast, type ContrastLevel } from \"@nextlyhq/blocks-engine\";\n\n/** What a ratio is good for, in words. */\nexport type ContrastBand =\n  | \"Readable as text\"\n  | \"Large text only\"\n  | \"Low contrast\";\n\n/**\n * What each of the engine's levels means here, read from its verdict so the\n * thresholds have one home: AAA and AA are body text, AA-large is large\n * text, and below that is low.\n */\nconst BANDS: Readonly<Record<ContrastLevel, ContrastBand>> = {\n  AAA: \"Readable as text\",\n  AA: \"Readable as text\",\n  \"AA-large\": \"Large text only\",\n  fail: \"Low contrast\",\n};\n\n/** One pair's contrast, as the colour's editor says it. */\nexport interface ContrastLine {\n  /** The ratio to two decimals: \"4.83:1\". */\n  readonly ratio: string;\n  readonly band: ContrastBand;\n}\n\n/**\n * The contrast of `foreground` on `background`, or `undefined` when either\n * cannot be read as a colour (a `var()`, say): no figure is better than a\n * wrong one.\n */\nexport function contrastLine(\n  foreground: string,\n  background: string\n): ContrastLine | undefined {\n  const result = checkContrast(foreground, background);\n  if (result === undefined) return undefined;\n  return {\n    ratio: `${shownRatio(result.ratio)}:1`,\n    band: BANDS[result.level],\n  };\n}\n\n/**\n * The ratio to two places, rounded, except where rounding would carry it\n * over a threshold it does not meet: 4.497 shows as \"4.49\", not \"4.50\" beside\n * \"Large text only\".\n */\nfunction shownRatio(ratio: number): string {\n  const rounded = Math.round(ratio * 100) / 100;\n  const crosses = [4.5, 3].some(edge => ratio < edge && rounded >= edge);\n  return (crosses ? Math.floor(ratio * 100) / 100 : rounded).toFixed(2);\n}\n","/**\n * The parts of a variable's editor beside its name and values: its code\n * name with Copy, how widely it is used with where, and, for a colour, its\n * contrast with the site's Background and Text in light and in dark. Kept\n * apart from the editor, which lays them out.\n *\n * @module variable-popup-parts\n */\nimport {\n  tokenIdentity,\n  type SiteToken,\n  type SiteTokenSet,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport { Moon, Sun } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { contrastLine } from \"./variable-contrast\";\nimport { variableRemoval, variableStatus } from \"./variable-usage\";\nimport {\n  VariableUses,\n  type RemovedPart,\n  type VariableUsageHere,\n} from \"./variable-usage-view\";\n\n/** ☀ or ☾ beside \"Light\" or \"Dark\", for sight: the words name the field. */\nexport function ModeIcon({ mode }: { mode: TokenMode }): React.JSX.Element {\n  const Icon = mode === \"light\" ? Sun : Moon;\n  return (\n    <Icon\n      aria-hidden=\"true\"\n      size={12}\n      className=\"nx-vars-editor__mode-icon\"\n      data-mode-icon={mode}\n    />\n  );\n}\n\n/**\n * What the variable is for, in a line under its name: a built-in's own\n * description (\"The space a container puts between the blocks it holds.\"),\n * kept from the site's code where a stored override carries none.\n */\nexport function VariableDescription({\n  token,\n  supplied,\n}: {\n  token: SiteToken | undefined;\n  supplied: SiteToken | undefined;\n}): React.JSX.Element | null {\n  const description = token?.description ?? supplied?.description;\n  return description === undefined ? null : (\n    <p className=\"nx-vars-editor__description\">{description}</p>\n  );\n}\n\n/** How long \"Copied\" shows after the code name is copied. */\nconst COPIED_FOR_MS = 2000;\n\n/**\n * \"Code name: --site-…\" and its Copy button. A variable never saved shows\n * the code name its name would give it, so it changes as the name is\n * typed; a saved one keeps its code name through every rename, and says so.\n */\nexport function CodeName({\n  id,\n  property,\n  isNew,\n}: {\n  /** The line's id, which the name field is described by. */\n  id: string;\n  /** The custom property, `--site-color-brand`. */\n  property: string;\n  isNew: boolean;\n}): React.JSX.Element {\n  const [copied, setCopied] = React.useState(false);\n  React.useEffect(() => {\n    if (!copied) return undefined;\n    const timer = window.setTimeout(() => setCopied(false), COPIED_FOR_MS);\n    return () => window.clearTimeout(timer);\n  }, [copied]);\n  const copy = (): void => {\n    void navigator.clipboard?.writeText(property).then(\n      () => setCopied(true),\n      () => undefined\n    );\n  };\n  return (\n    <div className=\"nx-vars-editor__code-name\">\n      <p className=\"nx-vars-editor__code\" id={id}>\n        <span>Code name: </span>\n        <code>{property}</code>\n      </p>\n      <button\n        type=\"button\"\n        className=\"nx-vars__link nx-vars-editor__copy\"\n        aria-label=\"Copy code name\"\n        onClick={copy}\n      >\n        Copy\n      </button>\n      <span className=\"nx-vars-editor__copied\" role=\"status\">\n        {copied ? \"Copied\" : \"\"}\n      </span>\n      {isNew ? null : (\n        <p className=\"nx-vars-editor__hint\">\n          Stays the same when you rename, so CSS that uses it keeps working\n        </p>\n      )}\n    </div>\n  );\n}\n\n/**\n * How widely the variable is used, with where on request: the count in\n * words, then the places, listed as the reason Remove waits lists them.\n */\nexport function UsageLine({\n  parts,\n  usage,\n}: {\n  /** The variables behind the row: a type size and its line height are two. */\n  parts: readonly RemovedPart[];\n  usage: VariableUsageHere;\n}): React.JSX.Element {\n  const [listed, setListed] = React.useState(false);\n  // Counted together, as the row counts them.\n  const reach = usage.reachTogether(parts.map(part => part.identity));\n  // Only something used has places to list.\n  const used = variableRemoval(reach) === \"in-use\";\n  return (\n    <div\n      className=\"nx-vars-editor__usage\"\n      role=\"group\"\n      aria-label=\"Where it's used\"\n    >\n      <span className=\"nx-vars-editor__status\">{variableStatus(reach)}</span>\n      {used && !listed ? (\n        <button\n          type=\"button\"\n          className=\"nx-vars__link\"\n          onClick={() => setListed(true)}\n        >\n          Show where\n        </button>\n      ) : null}\n      {listed ? <VariableUses parts={parts} usage={usage} /> : null}\n    </div>\n  );\n}\n\n/** The two colours a colour is measured against, by identity. */\nconst PARTNERS = [\n  { identity: \"color.background\", name: \"On Background\", role: \"background\" },\n  { identity: \"color.text\", name: \"With Text\", role: \"foreground\" },\n] as const;\n\n/**\n * A colour's contrast with the site's Background and Text, in light and in\n * dark, each a ratio and what it is good for. A colour with no dark value\n * keeps its light one in dark mode while Background may change, so its\n * dark line says \"Same in dark mode\". Background is measured with Text\n * only, and Text on Background only; a pair that cannot be read says\n * nothing.\n */\nexport function ColourContrast({\n  token,\n  tokens,\n  suppliedOf,\n}: {\n  token: SiteToken;\n  tokens: SiteTokenSet;\n  suppliedOf: (identity: string) => SiteToken | undefined;\n}): React.JSX.Element | null {\n  const own = tokenIdentity(token);\n  const pairs = PARTNERS.flatMap(partner => {\n    if (partner.identity === own) return [];\n    const other =\n      tokens.tokens.find(\n        candidate => tokenIdentity(candidate) === partner.identity\n      ) ?? suppliedOf(partner.identity);\n    return other === undefined ? [] : [{ ...partner, other }];\n  });\n  if (pairs.length === 0) return null;\n  return (\n    <div\n      className=\"nx-vars-editor__contrast\"\n      role=\"group\"\n      aria-label=\"Contrast\"\n    >\n      <span className=\"nx-vars-editor__label\">Contrast</span>\n      {pairs.map(pair => (\n        <ContrastPair\n          key={pair.identity}\n          name={pair.name}\n          colour={token}\n          other={pair.other}\n          onTop={pair.role === \"background\"}\n        />\n      ))}\n    </div>\n  );\n}\n\n/** One partner's two lines: light, then dark. */\nfunction ContrastPair({\n  name,\n  colour,\n  other,\n  onTop,\n}: {\n  name: string;\n  colour: SiteToken;\n  other: SiteToken;\n  /** Whether the colour is drawn on the other, or the other on it. */\n  onTop: boolean;\n}): React.JSX.Element {\n  const same =\n    colour.values.dark === undefined && other.values.dark !== undefined;\n  return (\n    <div\n      className=\"nx-vars-editor__contrast-pair\"\n      role=\"group\"\n      aria-label={name}\n    >\n      <span className=\"nx-vars-editor__contrast-name\">{name}</span>\n      {([\"light\", \"dark\"] as const).map(mode => {\n        const mine = valueIn(colour, mode);\n        const theirs = valueIn(other, mode);\n        const line = onTop\n          ? contrastLine(mine, theirs)\n          : contrastLine(theirs, mine);\n        return (\n          <span\n            key={mode}\n            className=\"nx-vars-editor__contrast-line\"\n            data-mode={mode}\n            data-band={line?.band}\n          >\n            <ModeIcon mode={mode} />\n            <span className=\"nx-sr-only\">\n              {mode === \"light\" ? \"Light: \" : \"Dark: \"}\n            </span>\n            {line === undefined ? (\n              \"Can't be measured\"\n            ) : (\n              <>\n                <span className=\"nx-vars-editor__ratio\">{line.ratio}</span>{\" \"}\n                {line.band}\n              </>\n            )}\n            {mode === \"dark\" && same ? (\n              <span className=\"nx-vars-editor__same-dark\">\n                {\" \"}\n                · Same in dark mode\n              </span>\n            ) : null}\n          </span>\n        );\n      })}\n    </div>\n  );\n}\n\n/** A variable's value in a mode, dark following light where it has none. */\nfunction valueIn(token: SiteToken, mode: TokenMode): string {\n  return mode === \"dark\"\n    ? (token.values.dark ?? token.values.light)\n    : token.values.light;\n}\n","/**\n * What Remove and Reset act on for one variable's row: the stored variables\n * behind it (a type size and its line height are one row), which of them the\n * site's code supplies, and what Remove may do under the usage read. Shared\n * by the variable's editor and its row's ⋯ menu, so both offer the same\n * actions on the same parts.\n *\n * @module variable-removal\n */\nimport {\n  sameSiteToken,\n  type SiteToken,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { VARIABLE_LOSS_WORDS } from \"../../editor-words\";\n\nimport { removeToken, type VariableEntry } from \"./tokens-studio\";\nimport {\n  variableRemoval,\n  type VariableReach,\n  type VariableRemoval,\n} from \"./variable-usage\";\nimport type { VariableUsageHere } from \"./variable-usage-view\";\n\n/** What Reset and Remove act on, and what Remove may do. */\nexport interface RemovalPlan {\n  /** The halves the site's code supplies that the author changed. */\n  readonly changed: readonly Part[];\n  /** The halves the site added, which Remove takes away. */\n  readonly removable: readonly Part[];\n  /** What the confirm names: the variable, or the half that goes. */\n  readonly what: string;\n  /**\n   * What the refusal names: the variable, or the half that goes, as its\n   * heading says it (\"Body's line height\").\n   */\n  readonly named: string;\n  /** What the places would lose, by what goes: \"colour\", \"line height\". */\n  readonly loss: string;\n  /** Remove's own words: \"Remove\", or \"Remove line height\". */\n  readonly label: string;\n  /** The usage that gates Remove, where the host reads it. */\n  readonly gate: VariableUsageHere | undefined;\n  /**\n   * How widely what Remove takes away is used, together: a type size and\n   * its line height when both go, so either one in use refuses.\n   */\n  readonly reach: VariableReach | undefined;\n  readonly removal: VariableRemoval;\n}\n\n/** The plan for an entry's halves, under the usage the host read. */\nexport function removalPlan(\n  entry: VariableEntry,\n  parts: readonly Part[],\n  usage: VariableUsageHere | undefined\n): RemovalPlan {\n  const changed = parts.filter(\n    part =>\n      part.from !== undefined &&\n      (part.held === undefined || !sameSiteToken(part.held, part.from))\n  );\n  const removable = parts.filter(part => part.from === undefined);\n  const gate = removable.length === 0 ? undefined : usage;\n  const reach =\n    gate === undefined\n      ? undefined\n      : gate.reachTogether(removable.map(part => part.identity));\n  // The whole variable when every half is the site's own; otherwise only the\n  // half that is, named, since the other stays.\n  const halves = removable.map(part => part.name).join(\" and \");\n  const whole = removable.length === parts.length;\n  const [alone] = removable;\n  return {\n    changed,\n    removable,\n    what: whole ? entry.label : `${halves} of ${entry.label}`,\n    named: whole ? entry.label : `${entry.label}'s ${halves}`,\n    // A half going on its own loses what that half is; the whole, what the\n    // variable's kind is.\n    loss:\n      !whole && removable.length === 1 && alone !== undefined\n        ? alone.loss\n        : VARIABLE_LOSS_WORDS[entry.row.kind],\n    label: whole ? \"Remove\" : `Remove ${halves}`,\n    gate,\n    reach,\n    removal: variableRemoval(reach),\n  };\n}\n\n/** The set with each changed half put back to what the site's code supplies. */\nexport function resetParts(\n  tokens: SiteTokenSet,\n  changed: readonly Part[]\n): SiteTokenSet {\n  const next = [...tokens.tokens];\n  for (const part of changed) {\n    if (part.from !== undefined) next[part.at] = part.from;\n  }\n  return { ...tokens, tokens: next };\n}\n\n/** One stored variable behind an entry, with what the site's code supplies. */\nexport interface Part {\n  name: string;\n  /** The variable's identity, which its usage is read by. */\n  identity: string;\n  /** What a place would lose with this part alone. */\n  loss: string;\n  at: number;\n  held: SiteToken | undefined;\n  from: SiteToken | undefined;\n}\n\n/**\n * The variables behind an entry: the row and, for a type size, its line\n * height, which has no row of its own and is acted on from here or nowhere.\n */\nexport function partsOf(\n  entry: VariableEntry,\n  token: SiteToken,\n  tokens: SiteTokenSet,\n  suppliedOf: (identity: string) => SiteToken | undefined\n): Part[] {\n  const own: Part = {\n    name: \"size\",\n    identity: entry.row.identity,\n    loss: VARIABLE_LOSS_WORDS[entry.row.kind],\n    at: entry.row.at,\n    held: token,\n    from: suppliedOf(entry.row.identity),\n  };\n  if (entry.lineHeight === undefined) return [own];\n  return [\n    own,\n    {\n      name: \"line height\",\n      identity: entry.lineHeight.identity,\n      loss: VARIABLE_LOSS_WORDS.lineHeight,\n      at: entry.lineHeight.at,\n      held: tokens.tokens[entry.lineHeight.at],\n      from: suppliedOf(entry.lineHeight.identity),\n    },\n  ];\n}\n\n/** The set without these variables, the later positions first. */\nexport function withoutParts(\n  tokens: SiteTokenSet,\n  parts: readonly Part[]\n): SiteTokenSet {\n  return parts\n    .map(part => part.at)\n    .sort((a, b) => b - a)\n    .reduce(removeToken, tokens);\n}\n","\"use client\";\n\n/**\n * A shadow variable's Light or Dark value, built with the shadow control\n * rather than typed as one line of CSS.\n *\n * @module variable-shadow-value\n */\nimport type { SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { ShadowControl } from \"../../inspector/style-inspector/shadow-control\";\n\nimport { ModeIcon } from \"./variable-popup-parts\";\nimport type { ValueFieldProps } from \"./variable-value-controls\";\n\n/**\n * The site's variables, for a shadow's Colour: a value field is handed its\n * own value alone, and a shadow coloured by a colour variable names one.\n */\nexport const ShadowVariables: React.Context<SiteTokenSet | undefined> =\n  React.createContext<SiteTokenSet | undefined>(undefined);\n\n/**\n * The value under its mode's label. What it writes is the variable's own\n * declaration, shown on hover and, while \"Show CSS names\" is on, its custom\n * property inline.\n */\nexport function ShadowValue({\n  label,\n  value,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n  css,\n  mode = \"light\",\n}: ValueFieldProps): React.JSX.Element {\n  const tokens = React.useContext(ShadowVariables);\n  const property = css?.split(\":\")[0]?.trim();\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\">\n        <ModeIcon mode={mode} />\n        {label}\n      </span>\n      <ShadowControl\n        label={label}\n        value={value}\n        tokens={tokens}\n        readOnly={readOnly}\n        refusedBy={refusedBy}\n        writesOf={\n          property === undefined ? undefined : next => `${property}: ${next}`\n        }\n        names={property === undefined ? undefined : [property]}\n        onCommit={onCommit}\n        // The whole shadow drawn on the canvas as it is edited.\n        onPreview={onPreview}\n      />\n    </div>\n  );\n}\n","/**\n * The editor that opens beside a variable's row: its name, its values for\n * light and dark, and removing or resetting it.\n *\n * Drawn inside the row's popover, so it is a dialog of its own: Name takes\n * focus when it opens, Tab stays inside, and Escape closes it back to the row.\n * Every field commits on blur or Enter rather than per keystroke, because a\n * variable is read by the whole site and each commit is handed to the host to\n * store; the host may wait for the author to pause before it does.\n *\n * Read-only fields stay fields (`readOnly`, never `disabled`), so a value can\n * still be selected and copied by someone who may not change it.\n *\n * A value the variable cannot hold is refused here, said in words under the\n * fields, and left in its field to be corrected, rather than written for the\n * save to refuse and the field to go back to what it held.\n *\n * @module variable-editor\n */\nimport {\n  resolveTokenPrefix,\n  tokenCustomProperty,\n  tokenIdentity,\n  type SiteToken,\n  type SiteTokenSet,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button, ColorPicker, Input } from \"@nextlyhq/ui\";\nimport { Undo2 } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { colourHexOf } from \"../../styles/style-colour\";\n\nimport { FluidButton, type FluidHook } from \"./fluid-popover\";\nimport { useRecentColours } from \"./recent-colours\";\nimport { siteTextUseWords } from \"./site-text-rows\";\nimport {\n  clearDarkValue,\n  labelNewVariable,\n  fluidRangeOf,\n  setFluidRange,\n  setFluidSize,\n  relabelToken,\n  variableLabelIssue,\n  writeTokenValue,\n  type TokenValueWrite,\n  type VariableEntry,\n} from \"./tokens-studio\";\nimport {\n  CodeName,\n  ColourContrast,\n  ModeIcon,\n  UsageLine,\n  VariableDescription,\n} from \"./variable-popup-parts\";\nimport {\n  partsOf,\n  removalPlan,\n  resetParts,\n  withoutParts,\n  type RemovalPlan,\n} from \"./variable-removal\";\nimport { ShadowValue, ShadowVariables } from \"./variable-shadow-value\";\nimport { swatchStyle } from \"./variable-swatch\";\nimport type { VariableRemoval } from \"./variable-usage\";\nimport { VariableRefusal, type VariableUsageHere } from \"./variable-usage-view\";\nimport {\n  LineHeightHint,\n  LineHeightInput,\n  SizeInput,\n  useDraft,\n  unwritableValue,\n  valueFieldFor,\n  variableCss,\n  VariablePreview,\n  type ValueFieldProps,\n} from \"./variable-value-controls\";\n\nexport interface VariableEditorProps {\n  entry: VariableEntry;\n  tokens: SiteTokenSet;\n  /**\n   * The site code's own version of a variable, by identity, when it supplies\n   * one. Asked for the row and for a type size's paired line height.\n   */\n  suppliedOf: (identity: string) => SiteToken | undefined;\n  readOnly: boolean;\n  onChange: (tokens: SiteTokenSet) => void;\n  /** The variable was removed; the popover's row no longer exists. */\n  onRemoved: () => void;\n  /**\n   * How widely the variable is used, where the host reads it: said beside\n   * Remove, which refuses in place while it is used. Absent: Remove confirms\n   * as it always has.\n   */\n  usage?: VariableUsageHere;\n  /**\n   * Opened by the row's Remove: the removal starts as the editor opens, so\n   * its confirm, or why it cannot go ahead, is what the author meets.\n   */\n  removing?: boolean;\n  /**\n   * Never saved: just added or copied. Its code name follows its name as it\n   * is typed, until the editor closes and it is saved under one.\n   */\n  isNew?: boolean;\n}\n\nexport function VariableEditor({\n  entry,\n  tokens,\n  suppliedOf,\n  readOnly,\n  onChange,\n  onRemoved,\n  usage,\n  removing = false,\n  isNew = false,\n}: VariableEditorProps): React.JSX.Element {\n  const id = React.useId();\n  const { row } = entry;\n  const token = tokens.tokens[row.at];\n  const [nameIssue, setNameIssue] = React.useState<string | undefined>();\n  const [name, setName] = useDraft(entry.label);\n  const { writeValue, previewValue, refusals, note } = useValueWrites(\n    tokens,\n    onChange\n  );\n\n  const commitName = (value: string): void => {\n    if (readOnly || value.trim() === entry.label) {\n      setNameIssue(undefined);\n      return;\n    }\n    const issue = variableLabelIssue(tokens, row.at, value);\n    setNameIssue(issue);\n    if (issue === undefined) onChange(relabelToken(tokens, row.at, value));\n  };\n\n  const saidId = `${id}-said`;\n  const refused: Refused = { fields: refusals, describedBy: saidId };\n\n  const said = saidUnder({ nameIssue, refusals, note, entry });\n\n  return (\n    <div\n      className=\"nx-vars-editor__body\"\n      // Spell-check off for every field in the editor, the colour picker's\n      // hex field included: its names and values are code-like words and\n      // colour codes, which a spell-checker underlines as misspelt. Set once\n      // here, since every field below inherits it.\n      spellCheck={false}\n    >\n      <div className=\"nx-vars-editor__field\">\n        <label className=\"nx-vars-editor__label\" htmlFor={`${id}-name`}>\n          Name\n        </label>\n        <Input\n          id={`${id}-name`}\n          // No list of earlier entries over a name being typed.\n          autoComplete=\"off\"\n          value={name}\n          onChange={event => setName(event.currentTarget.value)}\n          readOnly={readOnly}\n          aria-invalid={nameIssue === undefined ? undefined : true}\n          aria-describedby={said.length > 0 ? `${id}-said` : `${id}-code`}\n          onBlur={event => commitName(event.currentTarget.value)}\n          onKeyDown={event => {\n            if (event.key === \"Enter\") commitName(event.currentTarget.value);\n          }}\n        />\n        <CodeName\n          id={`${id}-code`}\n          property={codeNameOf(tokens, row.at, name, isNew)}\n          isNew={isNew}\n        />\n      </div>\n      <VariableDescription token={token} supplied={suppliedOf(row.identity)} />\n      {token === undefined ? null : (\n        <Values\n          entry={entry}\n          token={token}\n          tokens={tokens}\n          readOnly={readOnly}\n          onChange={onChange}\n          write={writeValue}\n          preview={previewValue}\n          refused={refused}\n        />\n      )}\n      <EditorDetails\n        entry={entry}\n        token={token}\n        tokens={tokens}\n        suppliedOf={suppliedOf}\n        usage={usage}\n      />\n      {said.length > 0 ? (\n        <p className=\"nx-vars-editor__issue\" id={saidId} role=\"status\">\n          {said.join(\" \")}\n        </p>\n      ) : null}\n      {readOnly || token === undefined ? null : (\n        <Actions\n          entry={entry}\n          token={token}\n          tokens={tokens}\n          suppliedOf={suppliedOf}\n          onChange={onChange}\n          onRemoved={onRemoved}\n          usage={usage}\n          removing={removing}\n        />\n      )}\n    </div>\n  );\n}\n\n/**\n * What is said under the fields, in order: why the name was refused, why a\n * value was (once each: two fields refused for the same reason say it\n * once), what a write changed beyond its own field, and what the engine\n * reports about the variable and its line height.\n */\nfunction saidUnder({\n  nameIssue,\n  refusals,\n  note,\n  entry,\n}: {\n  nameIssue: string | undefined;\n  refusals: ReadonlyMap<string, { readonly message: string }>;\n  note: string | undefined;\n  entry: VariableEntry;\n}): string[] {\n  return [\n    ...(nameIssue === undefined ? [] : [nameIssue]),\n    ...new Set([...refusals.values()].map(refusal => refusal.message)),\n    ...(note === undefined ? [] : [note]),\n    ...entry.row.issues,\n    ...(entry.lineHeight?.issues ?? []),\n  ];\n}\n\n/**\n * What the editor says about the variable below its values: how widely it\n * is used, where the host reads it, and, for a colour, its contrast.\n */\nfunction EditorDetails({\n  entry,\n  token,\n  tokens,\n  suppliedOf,\n  usage,\n}: {\n  entry: VariableEntry;\n  token: SiteToken | undefined;\n  tokens: SiteTokenSet;\n  suppliedOf: (identity: string) => SiteToken | undefined;\n  usage: VariableUsageHere | undefined;\n}): React.JSX.Element {\n  return (\n    <>\n      {usage === undefined || token === undefined ? null : (\n        // The parts Remove acts on, so a type size's line height is counted\n        // and listed under its own name, as it is there.\n        <UsageLine\n          parts={partsOf(entry, token, tokens, suppliedOf)}\n          usage={usage}\n        />\n      )}\n      {token?.kind === \"color\" ? (\n        <ColourContrast token={token} tokens={tokens} suppliedOf={suppliedOf} />\n      ) : null}\n    </>\n  );\n}\n\n/**\n * The custom property a variable is written under. For one never saved, the\n * one its name as typed would give it, so it follows each keystroke; a\n * saved variable's never changes.\n */\nfunction codeNameOf(\n  tokens: SiteTokenSet,\n  at: number,\n  typed: string,\n  isNew: boolean\n): string {\n  const named = isNew ? labelNewVariable(tokens, at, typed) : tokens;\n  const token = named.tokens[at];\n  if (token === undefined) return \"\";\n  const { prefix } = resolveTokenPrefix(tokens.prefix);\n  return tokenCustomProperty(tokenIdentity(token), prefix);\n}\n\n/**\n * The value fields' one write, and what it leaves said under the fields: the\n * fields holding a refused value, and a note about what a write changed\n * beyond its own field. Also the fields' preview, judged as the write is.\n */\nfunction useValueWrites(\n  tokens: SiteTokenSet,\n  onChange: (tokens: SiteTokenSet) => void\n): {\n  writeValue: ValueWrite;\n  previewValue: ValuePreview;\n  refusals: ReadonlyMap<string, RefusedValue>;\n  note: string | undefined;\n} {\n  // Each field holding a refused value, with why and with the value the field\n  // stored when it was refused: that field is marked and the reason said under\n  // the fields until THAT field is corrected, whatever else is committed.\n  const [recorded, setRefusals] = React.useState<\n    ReadonlyMap<string, RefusedValue>\n  >(() => new Map());\n  // A refusal lasts only while its field stores what it did when refused. A\n  // control that replaces or removes the value (Use light value, Reset, an\n  // undo) also replaces what the field shows, so its refusal goes with it.\n  const refusals = liveRefusals(recorded, tokens);\n  if (refusals.size !== recorded.size) setRefusals(refusals);\n  const refuse = (at: number, mode: TokenMode, message?: string): void =>\n    setRefusals(current => {\n      const key = fieldKey(at, mode);\n      if (current.get(key)?.message === message) return current;\n      const next = new Map(current);\n      if (message === undefined) next.delete(key);\n      else next.set(key, { message, held: tokens.tokens[at]?.values[mode] });\n      return next;\n    });\n  // What a write changed beyond its own field, said until the next write.\n  // It lasts, as a refusal does, only while the variable holds what that\n  // write left: Add dark values, Reset or an undo that changes it ends it.\n  const [noted, setNote] = React.useState<WriteNote>();\n  const note =\n    noted !== undefined &&\n    JSON.stringify(tokens.tokens[noted.at]?.values) === noted.values\n      ? noted.text\n      : undefined;\n  if (noted !== undefined && note === undefined) setNote(undefined);\n\n  /*\n   * Every value field writes through here, so a refusal is decided once. The\n   * value it already holds writes nothing and clears a message, which is how\n   * putting back what was there before a refusal reads as fixing it.\n   */\n  const writeValue: ValueWrite = (at, mode, value) => {\n    const next = value.trim();\n    if (tokens.tokens[at]?.values[mode] === next) {\n      refuse(at, mode);\n      return;\n    }\n    const written = valueWritten(tokens, at, mode, next);\n    if (\"issue\" in written) {\n      refuse(at, mode, written.issue);\n      return;\n    }\n    refuse(at, mode);\n    setNote(\n      written.note === undefined\n        ? undefined\n        : {\n            text: written.note,\n            at,\n            values: JSON.stringify(written.tokens.tokens[at]?.values),\n          }\n    );\n    onChange(written.tokens);\n  };\n  const previewValue = useValuePreview(tokens);\n  return { writeValue, previewValue, refusals, note };\n}\n\n/**\n * What a value would write: refused where it is typed when the site's\n * stylesheet would not write it, a value that would load a file among them,\n * rather than at the save. The one judgement a write and a preview share.\n */\nfunction valueWritten(\n  tokens: SiteTokenSet,\n  at: number,\n  mode: TokenMode,\n  next: string\n): TokenValueWrite {\n  const token = tokens.tokens[at];\n  const unwritable =\n    token === undefined ? undefined : unwritableValue(tokens, token, next);\n  if (unwritable !== undefined) return { issue: unwritable };\n  return writeTokenValue(tokens, at, mode, next);\n}\n\n/**\n * The value fields' preview: each value a field is given that its write\n * would take is handed to the host to draw, and one it would refuse, such as\n * half a colour, is not, so the canvas keeps the last valid value. `null`\n * ends it, drawing what is stored again; said once, and said when the editor\n * goes away mid-edit too, so nothing unwritten stays drawn.\n */\nfunction useValuePreview(tokens: SiteTokenSet): ValuePreview {\n  const host = React.useContext(VariablePreview);\n  // The host drawing an edit under way, while one is.\n  const drawing = React.useRef<typeof host>(undefined);\n  React.useEffect(\n    () => () => {\n      drawing.current?.(null);\n      drawing.current = undefined;\n    },\n    []\n  );\n  return (at, mode, text) => {\n    if (text === null) {\n      const drew = drawing.current;\n      drawing.current = undefined;\n      drew?.(null);\n      return;\n    }\n    const next = text.trim();\n    if (host === undefined || next === \"\") return;\n    // The stored value typed back is drawn as stored.\n    const written =\n      tokens.tokens[at]?.values[mode] === next\n        ? { tokens }\n        : valueWritten(tokens, at, mode, next);\n    if (\"issue\" in written) return;\n    drawing.current = host;\n    host(written.tokens);\n  };\n}\n\n/** Writes one variable's value for one mode, or says why it cannot. */\ntype ValueWrite = (at: number, mode: TokenMode, value: string) => void;\n\n/**\n * Draws one variable's value for one mode before it is written, or, given\n * `null`, ends the drawing.\n */\ntype ValuePreview = (at: number, mode: TokenMode, text: string | null) => void;\n\n/** A note a write left, and what its variable held once written, as JSON. */\ninterface WriteNote {\n  text: string;\n  at: number;\n  values: string;\n}\n\n/** A refused value's reason, and what its field stored when it was refused. */\ninterface RefusedValue {\n  message: string;\n  held: string | undefined;\n}\n\n/**\n * The refusals still about what their fields store; the same map when every\n * one is, so a render that changes nothing sets no state.\n */\nfunction liveRefusals(\n  recorded: ReadonlyMap<string, RefusedValue>,\n  tokens: SiteTokenSet\n): ReadonlyMap<string, RefusedValue> {\n  const live = [...recorded].filter(([key, refusal]) => {\n    const [at, mode] = key.split(\":\");\n    const values = tokens.tokens[Number(at)]?.values;\n    return (mode === \"dark\" ? values?.dark : values?.light) === refusal.held;\n  });\n  return live.length === recorded.size ? recorded : new Map(live);\n}\n\n/** One value field: a stored variable's position and a mode. */\nfunction fieldKey(at: number, mode: TokenMode): string {\n  return `${String(at)}:${mode}`;\n}\n\n/** The fields holding a refused value, and the reason's element to point at. */\ninterface Refused {\n  fields: ReadonlyMap<string, RefusedValue>;\n  describedBy: string;\n}\n\n/** The marking a field takes while it holds a refused value, or none. */\nfunction refusalAt(\n  refused: Refused,\n  at: number,\n  mode: TokenMode\n): string | undefined {\n  return refused.fields.has(fieldKey(at, mode))\n    ? refused.describedBy\n    : undefined;\n}\n\n/** The value fields a variable's kind calls for. */\nfunction Values({\n  entry,\n  token,\n  tokens,\n  readOnly,\n  onChange,\n  write,\n  preview,\n  refused,\n}: {\n  entry: VariableEntry;\n  token: SiteToken;\n  tokens: SiteTokenSet;\n  readOnly: boolean;\n  onChange: (tokens: SiteTokenSet) => void;\n  write: ValueWrite;\n  preview: ValuePreview;\n  refused: Refused;\n}): React.JSX.Element {\n  const { row, lineHeight } = entry;\n  const pair = (at: number, held: SiteToken): React.JSX.Element => (\n    // A shadow's Colour offers the site's colour variables.\n    <ShadowVariables.Provider value={tokens}>\n      <ModeValues\n        token={held}\n        cssOf={value => variableCss(tokens, held, value)}\n        readOnly={readOnly}\n        onCommit={(mode, value) => write(at, mode, value)}\n        onPreview={(mode, text) => preview(at, mode, text)}\n        onClear={() => onChange(clearDarkValue(tokens, at))}\n        refusedIn={mode => refusalAt(refused, at, mode)}\n        fluid={fluidHookOf({ token: held, tokens, at, onChange, readOnly })}\n      />\n    </ShadowVariables.Provider>\n  );\n  const lineToken =\n    lineHeight === undefined ? undefined : tokens.tokens[lineHeight.at];\n  if (lineHeight === undefined || lineToken === undefined) {\n    return pair(row.at, token);\n  }\n  return (\n    <TypePair\n      size={token}\n      sizeAt={row.at}\n      line={lineToken}\n      lineAt={lineHeight.at}\n      tokens={tokens}\n      readOnly={readOnly}\n      onChange={onChange}\n      write={write}\n      preview={preview}\n      refused={refused}\n    />\n  );\n}\n\n/** \"Fluid…\" for a type size's size, where it can be changed. */\nfunction TypeSizeFluid({\n  size,\n  sizeAt,\n  tokens,\n  onChange,\n  readOnly,\n}: {\n  size: SiteToken;\n  sizeAt: number;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n}): React.JSX.Element | null {\n  const hook = fluidHookOf({\n    token: size,\n    tokens,\n    at: sizeAt,\n    onChange,\n    readOnly,\n  });\n  return hook === undefined ? null : <FluidButton hook={hook} />;\n}\n\n/**\n * A type size and its line height, laid out as one pair so the editor stays\n * short: the two Light values side by side, then either one \"Same as light\"\n * line with one action for both, or the two Dark values side by side with one\n * action to drop both.\n */\nfunction TypePair({\n  size,\n  sizeAt,\n  line,\n  lineAt,\n  tokens,\n  readOnly,\n  onChange,\n  write,\n  preview,\n  refused,\n}: {\n  size: SiteToken;\n  sizeAt: number;\n  line: SiteToken;\n  lineAt: number;\n  tokens: SiteTokenSet;\n  readOnly: boolean;\n  onChange: (tokens: SiteTokenSet) => void;\n  write: ValueWrite;\n  preview: ValuePreview;\n  refused: Refused;\n}): React.JSX.Element {\n  const hasDark =\n    size.values.dark !== undefined || line.values.dark !== undefined;\n  const halves = [\n    { name: \"Size\", at: sizeAt, token: size },\n    { name: \"Line height\", at: lineAt, token: line },\n  ];\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <div className=\"nx-vars-editor__pair\">\n        <span aria-hidden=\"true\" />\n        {halves.map(half => (\n          <span\n            key={half.name}\n            className=\"nx-vars-editor__label\"\n            aria-hidden=\"true\"\n          >\n            {half.name}\n          </span>\n        ))}\n        <span className=\"nx-vars-editor__label\" aria-hidden=\"true\">\n          Light\n        </span>\n        {halves.map(half => (\n          <HalfInput\n            key={half.name}\n            half={half.name}\n            label={`${half.name}, light`}\n            value={half.token.values.light}\n            readOnly={readOnly}\n            refusedBy={refusalAt(refused, half.at, \"light\")}\n            onCommit={value => write(half.at, \"light\", value)}\n            onPreview={text => preview(half.at, \"light\", text)}\n            css={variableCss(tokens, half.token, half.token.values.light)}\n          />\n        ))}\n        {hasDark ? (\n          <>\n            <span className=\"nx-vars-editor__label\" aria-hidden=\"true\">\n              Dark\n            </span>\n            {halves.map(half => (\n              <div key={half.name} className=\"nx-vars-editor__cell\">\n                <HalfInput\n                  half={half.name}\n                  label={`${half.name}, dark`}\n                  value={half.token.values.dark ?? \"\"}\n                  placeholder={half.token.values.light}\n                  css={variableCss(\n                    tokens,\n                    half.token,\n                    half.token.values.dark ?? half.token.values.light\n                  )}\n                  readOnly={readOnly}\n                  refusedBy={refusalAt(refused, half.at, \"dark\")}\n                  onCommit={value => write(half.at, \"dark\", value)}\n                  onPreview={text => preview(half.at, \"dark\", text)}\n                />\n                {/* Each half returns to following light on its own; the\n                    action for both is below. */}\n                {readOnly || half.token.values.dark === undefined ? null : (\n                  <button\n                    type=\"button\"\n                    className=\"nx-vars__icon-button nx-vars-editor__cell-action\"\n                    aria-label={`Use light ${half.name.toLowerCase()}`}\n                    title={`Use light ${half.name.toLowerCase()}`}\n                    onClick={() => onChange(clearDarkValue(tokens, half.at))}\n                  >\n                    <Undo2 aria-hidden=\"true\" size={14} />\n                  </button>\n                )}\n              </div>\n            ))}\n          </>\n        ) : null}\n      </div>\n      <LineHeightHint\n        value={line.values.light}\n        mode=\"light\"\n        readOnly={readOnly}\n        onCommit={value => write(lineAt, \"light\", value)}\n      />\n      {/* \"Fluid…\" for the size: a type size is where a fluid size is most\n          wanted. */}\n      <TypeSizeFluid\n        size={size}\n        sizeAt={sizeAt}\n        tokens={tokens}\n        onChange={onChange}\n        readOnly={readOnly}\n      />\n      {line.values.dark === undefined ? null : (\n        <LineHeightHint\n          value={line.values.dark}\n          mode=\"dark\"\n          readOnly={readOnly}\n          onCommit={value => write(lineAt, \"dark\", value)}\n        />\n      )}\n      {hasDark ? (\n        readOnly ||\n        halves.some(half => half.token.values.dark === undefined) ? null : (\n          <Button\n            type=\"button\"\n            variant=\"outline\"\n            size=\"sm\"\n            className=\"nx-vars-editor__button nx-vars-editor__inline-action\"\n            onClick={() =>\n              onChange(clearDarkValue(clearDarkValue(tokens, sizeAt), lineAt))\n            }\n          >\n            Remove dark value\n          </Button>\n        )\n      ) : null}\n    </div>\n  );\n}\n\n/**\n * One half of a type size's pair: the size with its unit menu, or the line\n * height as a multiple of the text size.\n */\nfunction HalfInput({\n  half,\n  ...field\n}: {\n  half: string;\n  label: string;\n  value: string;\n  placeholder?: string;\n  readOnly: boolean;\n  refusedBy: string | undefined;\n  onCommit: (value: string) => void;\n  /** Draws the half's value before it is written; `null` ends it. */\n  onPreview: (text: string | null) => void;\n  css: string;\n}): React.JSX.Element {\n  return half === \"Size\" ? (\n    <SizeInput {...field} />\n  ) : (\n    <LineHeightInput {...field} />\n  );\n}\n\n/**\n * \"Fluid…\" for a size that can be changed: what it needs to read the\n * value's sizes and to store a size made fluid from two. Nothing for any\n * other kind, or where the variables are read-only.\n */\nfunction fluidHookOf({\n  token,\n  tokens,\n  at,\n  onChange,\n  readOnly,\n}: {\n  token: SiteToken;\n  tokens: SiteTokenSet;\n  at: number;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n}): FluidHook | undefined {\n  if (readOnly || token.kind !== \"dimension\") return undefined;\n  const range = fluidRangeOf(tokens);\n  return {\n    sizes: token.fluid,\n    value: token.values.light,\n    range,\n    onFluid: sizes => onChange(setFluidSize(tokens, at, sizes, range)),\n    onRange: next => onChange(setFluidRange(tokens, next)),\n  };\n}\n\n/**\n * One variable's Light value, then its Dark value, for every kind: a colour\n * with its swatch and picker, anything else as text.\n */\nfunction ModeValues({\n  token,\n  cssOf,\n  readOnly,\n  onCommit,\n  onPreview,\n  onClear,\n  refusedIn,\n  fluid,\n}: {\n  token: SiteToken;\n  /** The CSS a value of this variable writes. */\n  cssOf: (value: string) => string;\n  readOnly: boolean;\n  onCommit: (mode: TokenMode, value: string) => void;\n  /** Draws a mode's value before it is written; `null` ends it. */\n  onPreview: (mode: TokenMode, text: string | null) => void;\n  onClear: () => void;\n  /** The reason's element while a mode's field holds a refused value. */\n  refusedIn: (mode: TokenMode) => string | undefined;\n  /** \"Fluid…\" on a size's light value, where it can be changed. */\n  fluid: FluidHook | undefined;\n}): React.JSX.Element {\n  const Field = fieldFor(token);\n  return (\n    <>\n      <Field\n        label=\"Light\"\n        value={token.values.light}\n        readOnly={readOnly}\n        refusedBy={refusedIn(\"light\")}\n        onCommit={value => onCommit(\"light\", value)}\n        onPreview={text => onPreview(\"light\", text)}\n        css={cssOf(token.values.light)}\n        mode=\"light\"\n      />\n      {fluid === undefined ? null : <FluidButton hook={fluid} />}\n      <DarkValue\n        token={token}\n        cssOf={cssOf}\n        readOnly={readOnly}\n        refusedBy={refusedIn(\"dark\")}\n        onCommit={value => onCommit(\"dark\", value)}\n        onPreview={text => onPreview(\"dark\", text)}\n        onAdd={() => onCommit(\"dark\", token.values.light)}\n        onClear={onClear}\n      />\n    </>\n  );\n}\n\n/**\n * The field a variable's values are edited with: a colour's swatch and\n * picker, a shadow's layers, and every other kind's own field.\n */\nfunction fieldFor(\n  token: SiteToken\n): (props: ValueFieldProps) => React.JSX.Element {\n  if (token.kind === \"color\") return ColourValue;\n  return token.kind === \"shadow\" ? ShadowValue : valueFieldFor(token);\n}\n\n/**\n * A colour: a swatch that opens the picker inline, and its hex field.\n *\n * The picker sits inside this popover rather than in a second one, so focus\n * stays in one dialog. What it composes is held as a draft and written once,\n * when the picker is closed or this editor goes away, so dragging across it\n * is one save rather than one per pointer move. Given `onPreview`, each move\n * and each colour typed is drawn on the canvas meanwhile, and the drawing\n * ends before the one write.\n *\n * Its picker lists the author's Recent colours, as a block's does; a colour\n * written here, typed or picked, joins them.\n */\nexport function ColourValue({\n  label,\n  value,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n  mode = \"light\",\n}: {\n  label: string;\n  value: string;\n  readOnly: boolean;\n  /** The id of the reason, while this field holds a value that was refused. */\n  refusedBy?: string | undefined;\n  onCommit: (value: string) => void;\n  /** Draws a colour before it is written; `null` ends it. */\n  onPreview?: ((text: string | null) => void) | undefined;\n  /** Which mode's value this is, drawn ☀ or ☾ beside the label. */\n  mode?: TokenMode | undefined;\n}): React.JSX.Element {\n  const id = React.useId();\n  const [picking, setPicking] = React.useState(false);\n  const [text, setText] = useDraft(value);\n  const draft = React.useRef<string | null>(null);\n  // What the picker shows while a gesture is under way, handed back to it as\n  // its colour so each step builds on the last; written only when it closes.\n  const [shown, setShown] = React.useState<string | null>(null);\n  const [recentColours, remember] = useRecentColours();\n  const latest = React.useRef({ value, onCommit, onPreview, remember });\n  React.useEffect(() => {\n    latest.current = { value, onCommit, onPreview, remember };\n  });\n  const flush = React.useCallback((): void => {\n    const pending = draft.current;\n    draft.current = null;\n    latest.current.onPreview?.(null);\n    if (pending !== null && pending !== latest.current.value) {\n      latest.current.onCommit(pending);\n      latest.current.remember(pending);\n    }\n  }, []);\n  // A picker still open when the popover closes writes what it showed.\n  React.useEffect(() => flush, [flush]);\n  // The value it holds commits too while a refusal is shown: putting it\n  // back is how a refused value is corrected, and clears the refusal.\n  const commit = (typed: string): boolean => {\n    onPreview?.(null);\n    const next = typed.trim();\n    const writes =\n      !readOnly && next !== \"\" && (next !== value || refusedBy !== undefined);\n    if (writes) onCommit(next);\n    return writes;\n  };\n  // A typed colour joins Recent colours; text that is none is refused.\n  const commitTyped = (typed: string): void => {\n    if (commit(typed) && isColour(typed.trim())) remember(typed.trim());\n  };\n  // A recent colour is one choice, written as it is listed, as on a block,\n  // and moves to the front even where it is already the value.\n  const pickRecent = (colour: string): void => {\n    draft.current = null;\n    setShown(null);\n    setText(colour);\n    setPicking(false);\n    commit(colour);\n    remember(colour);\n  };\n  const { hex, paint, invalid, said } = colourFieldState(\n    text.trim(),\n    value,\n    shown\n  );\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <label className=\"nx-vars-editor__label\" htmlFor={id}>\n        <ModeIcon mode={mode} />\n        {label}\n      </label>\n      <div className=\"nx-vars-editor__colour\">\n        {readOnly ? (\n          <span\n            className=\"nx-vars__swatch\"\n            aria-hidden=\"true\"\n            data-invalid={invalid ? \"\" : undefined}\n            style={swatchStyle(paint)}\n          />\n        ) : (\n          <button\n            type=\"button\"\n            className=\"nx-vars__swatch nx-vars-editor__swatch\"\n            data-invalid={invalid ? \"\" : undefined}\n            aria-label={`Pick the ${label.toLowerCase()} colour${said}`}\n            aria-expanded={picking}\n            style={swatchStyle(paint)}\n            onClick={() => {\n              if (picking) {\n                flush();\n                setShown(null);\n              }\n              setPicking(open => !open);\n            }}\n          />\n        )}\n        <Input\n          id={id}\n          className=\"nx-vars-editor__mono\"\n          // A value, not words: no list of earlier entries over the field.\n          autoComplete=\"off\"\n          aria-invalid={refusedBy === undefined && !invalid ? undefined : true}\n          aria-describedby={refusedBy}\n          value={text}\n          onChange={event => {\n            setText(event.currentTarget.value);\n            // Typing takes over from a picker gesture: its colour is no\n            // longer shown, and closing the picker writes nothing over the\n            // typed text.\n            draft.current = null;\n            setShown(null);\n            if (!readOnly) onPreview?.(event.currentTarget.value);\n          }}\n          readOnly={readOnly}\n          onBlur={event => commitTyped(event.currentTarget.value)}\n          onKeyDown={event => {\n            if (event.key === \"Enter\") commitTyped(event.currentTarget.value);\n          }}\n        />\n      </div>\n      {picking ? (\n        <ColorPicker\n          className=\"nx-vars-editor__picker\"\n          // A value the picker cannot read starts it from white, not from\n          // black, which it would claim the value is; opaque, so a colour\n          // picked from there is seen.\n          color={hex ?? NO_COLOUR}\n          showAlpha\n          recentColors={[...recentColours]}\n          onRecentSelect={pickRecent}\n          onColorChange={next => {\n            draft.current = next;\n            setShown(next);\n            onPreview?.(next);\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/** Where the picker starts for a value it cannot read: white. */\nconst NO_COLOUR = \"#ffffff\";\n\n/**\n * What a colour field shows for the text in it: the colour the picker reads,\n * what the swatch paints, and whether the text is no colour at all.\n *\n * The swatch follows what is typed, so a value that is not a colour shows as\n * one at once, rather than as the last colour or as black. It is painted only\n * with a colour resolved here (`colourHexOf`), as every swatch is: `var()`,\n * `currentcolor` or `inherit` painted in the panel would take the panel's\n * colours rather than the site's. A colour the browser reads but this package\n * cannot resolve (`oklch()`, a named colour, a variable) leaves the swatch\n * empty and unmarked; only text no browser reads as a colour is marked\n * invalid, and said so in the swatch button's name. While a picker gesture is\n * under way, the picker's colour is what is shown, and the text is not judged.\n */\nfunction colourFieldState(\n  typed: string,\n  value: string,\n  shown: string | null\n): {\n  hex: string | undefined;\n  paint: string | undefined;\n  invalid: boolean;\n  said: string;\n} {\n  const current = typed === \"\" ? value : typed;\n  const invalid = shown === null && typed !== \"\" && !isColour(current);\n  const hex = shown ?? colourHexOf(current, undefined);\n  return {\n    hex,\n    paint: hex,\n    invalid,\n    said: invalid ? \" (not a valid colour)\" : \"\",\n  };\n}\n\n/**\n * Whether `text` is a colour: one this package reads, or the browser does.\n * The one answer both the field's invalid mark and Recent colours read.\n */\nfunction isColour(text: string): boolean {\n  return colourHexOf(text, undefined) !== undefined || isCssColour(text);\n}\n\n/**\n * Whether the browser reads `text` as a CSS colour: any colour a stylesheet\n * takes, beyond the hex and `rgb()` the picker reads. False where the\n * browser cannot say.\n */\nfunction isCssColour(text: string): boolean {\n  const css = globalThis.CSS as { supports?: unknown } | undefined;\n  return typeof css?.supports === \"function\"\n    ? CSS.supports(\"color\", text)\n    : false;\n}\n\n/** The dark value: its field, or a line saying it follows light. */\n/** The kinds a dark value is offered on; one already held is kept on any. */\nconst DARK_KINDS: ReadonlySet<string> = new Set([\"color\", \"shadow\"]);\n\nfunction DarkValue({\n  token,\n  cssOf,\n  readOnly,\n  refusedBy,\n  onCommit,\n  onPreview,\n  onAdd,\n  onClear,\n}: {\n  token: SiteToken;\n  cssOf: (value: string) => string;\n  readOnly: boolean;\n  refusedBy: string | undefined;\n  onCommit: (value: string) => void;\n  onPreview: (text: string | null) => void;\n  onAdd: () => void;\n  onClear: () => void;\n}): React.JSX.Element | null {\n  const dark = token.values.dark;\n  if (dark === undefined) {\n    // Offered on what reads differently in dark mode, colours and shadows;\n    // a size or a duration has no reason to change with the mode.\n    if (!DARK_KINDS.has(token.kind)) return null;\n    return (\n      <div className=\"nx-vars-editor__field\">\n        <span className=\"nx-vars-editor__label\">\n          <ModeIcon mode=\"dark\" />\n          Dark\n        </span>\n        <div className=\"nx-vars-editor__same\">\n          <span>Same as light</span>\n          {readOnly ? null : (\n            // Outlined, so the action reads as one at rest, not only on hover.\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              size=\"sm\"\n              className=\"nx-vars-editor__button\"\n              onClick={onAdd}\n            >\n              Add dark value\n            </Button>\n          )}\n        </div>\n      </div>\n    );\n  }\n  const Field = fieldFor(token);\n  return (\n    <>\n      <Field\n        label=\"Dark\"\n        value={dark}\n        readOnly={readOnly}\n        refusedBy={refusedBy}\n        onCommit={onCommit}\n        onPreview={onPreview}\n        css={cssOf(dark)}\n        mode=\"dark\"\n      />\n      {readOnly ? null : (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button nx-vars-editor__inline-action\"\n          onClick={onClear}\n        >\n          Remove dark value\n        </Button>\n      )}\n    </>\n  );\n}\n\n/**\n * Reset and Remove, each half of a type size by its own provenance.\n *\n * A half the site's code supplies can be reset when the author changed it,\n * and cannot be removed: the stored tier holds overrides, so removing it would\n * merge straight back on the next read. A half the site added can be removed,\n * behind a confirm naming it. A type size can be one of each, so both actions\n * can show at once.\n *\n * Where the host reads how widely the variable is used, its own half says so\n * beside Remove, and Remove, still pressable, opens why it cannot go ahead\n * while the variable is used or not counted yet, in place of the confirm.\n */\nfunction Actions({\n  entry,\n  token,\n  tokens,\n  suppliedOf,\n  onChange,\n  onRemoved,\n  usage,\n  removing,\n}: {\n  entry: VariableEntry;\n  token: SiteToken;\n  tokens: SiteTokenSet;\n  suppliedOf: (identity: string) => SiteToken | undefined;\n  onChange: (tokens: SiteTokenSet) => void;\n  onRemoved: () => void;\n  usage: VariableUsageHere | undefined;\n  removing: boolean;\n}): React.JSX.Element | null {\n  const plan = removalPlan(\n    entry,\n    partsOf(entry, token, tokens, suppliedOf),\n    usage\n  );\n  // A Site text row pointing at what Remove takes away holds it: the row\n  // would lose its size on every page, so the removal is refused here as\n  // the server refuses it, naming the row.\n  const heldBy = siteTextUseWords(\n    tokens,\n    plan.removable.map(part => part.identity)\n  );\n  const { step, setStep, remove } = useRemoveStep(plan, removing, heldBy);\n  const shown = shownStep(step, plan.removal);\n  if (shown === \"held\" && heldBy !== undefined) {\n    return (\n      <HeldRemoval\n        plan={plan}\n        heldBy={heldBy}\n        onReset={() => onChange(resetParts(tokens, plan.changed))}\n        onRemove={remove}\n      />\n    );\n  }\n  if (shown === \"confirm\" && plan.removable.length > 0) {\n    return (\n      <ConfirmRemove\n        what={plan.what}\n        focused={removing}\n        onKeep={() => setStep(\"idle\")}\n        onRemove={() => {\n          onChange(withoutParts(tokens, plan.removable));\n          onRemoved();\n        }}\n      />\n    );\n  }\n  if (plan.changed.length === 0 && plan.removable.length === 0) return null;\n  return (\n    <>\n      <ActionRow\n        plan={plan}\n        checking={shown === \"checking\"}\n        onReset={() => onChange(resetParts(tokens, plan.changed))}\n        onRemove={remove}\n      />\n      {shown === \"refused\" &&\n      plan.gate !== undefined &&\n      plan.reach !== undefined ? (\n        <VariableRefusal\n          name={plan.named}\n          loss={plan.loss}\n          parts={plan.removable}\n          reach={plan.reach}\n          usage={plan.gate}\n        />\n      ) : null}\n    </>\n  );\n}\n\n/**\n * Remove refused because a Site text row uses what it takes away: the row\n * named, and what to do first.\n */\nfunction HeldRemoval({\n  plan,\n  heldBy,\n  onReset,\n  onRemove,\n}: {\n  plan: RemovalPlan;\n  heldBy: string;\n  onReset: () => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <>\n      <ActionRow\n        plan={plan}\n        checking={false}\n        onReset={onReset}\n        onRemove={onRemove}\n      />\n      <p className=\"nx-vars-editor__issue\" role=\"status\">\n        {`${plan.named} is used by ${heldBy}, so it can't be removed. Point that row at another type size first.`}\n      </p>\n    </>\n  );\n}\n\n/** How widely it is used, then Reset and Remove, as the plan offers them. */\nfunction ActionRow({\n  plan,\n  checking,\n  onReset,\n  onRemove,\n}: {\n  plan: RemovalPlan;\n  /** Whether Remove is reading where it is used again before it answers. */\n  checking: boolean;\n  onReset: () => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-vars-editor__actions\">\n      {/* How widely it is used is said above; here only that Remove is\n          reading it again. */}\n      <span className=\"nx-vars-editor__status\" role=\"status\">\n        {checking ? \"Checking where it's used…\" : \"\"}\n      </span>\n      {plan.changed.length === 0 ? null : (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button\"\n          onClick={onReset}\n        >\n          Reset\n        </Button>\n      )}\n      {/* Pressable while the variable is used, too: it says why it waits. */}\n      {plan.removable.length === 0 ? null : (\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button nx-vars-editor__remove\"\n          onClick={onRemove}\n        >\n          {plan.label}\n        </Button>\n      )}\n    </div>\n  );\n}\n\n/**\n * Where Remove has got to: nothing yet, reading where it is used again, its\n * confirm, or why it cannot.\n */\ntype RemoveStep = \"idle\" | \"checking\" | \"confirm\" | \"refused\" | \"held\";\n\n/**\n * Remove's steps. Counts read earlier may say a variable is used when it no\n * longer is, so a Remove they would refuse first reads what it takes away\n * again, saying so, and answers on the fresh counts: the refusal, or the\n * confirm once nothing uses it. Nothing stale is shown while it reads; a\n * read that fails answers on the counts already kept.\n */\nfunction useRemoveStep(\n  plan: RemovalPlan,\n  removing: boolean,\n  /** The Site text rows holding what Remove takes away, in words, if any. */\n  heldBy: string | undefined\n): {\n  step: RemoveStep;\n  setStep: (step: RemoveStep) => void;\n  remove: () => void;\n} {\n  const [step, setStep] = React.useState<RemoveStep>(\"idle\");\n  const { gate, removal, removable } = plan;\n  const remove = (): void => {\n    if (heldBy !== undefined) {\n      setStep(\"held\");\n      return;\n    }\n    if (!refuses(removal) || gate === undefined) {\n      setStep(\"confirm\");\n      return;\n    }\n    setStep(\"checking\");\n    const answer = (): void =>\n      setStep(current => (current === \"checking\" ? \"refused\" : current));\n    gate.readAgain(removable.map(part => part.identity)).then(answer, answer);\n  };\n  // Started once, as the editor opens for the row's Remove; the latest\n  // `remove` through a ref, so the start does not repeat with each render.\n  const start = React.useRef(remove);\n  start.current = remove;\n  React.useEffect(() => {\n    if (removing) start.current();\n  }, [removing]);\n  return { step, setStep, remove };\n}\n\n/** Whether Remove opens why it cannot go ahead rather than the confirm. */\nfunction refuses(removal: VariableRemoval): boolean {\n  return removal === \"in-use\";\n}\n\n/**\n * The step shown: the confirm once a refused removal no longer refuses, as\n * when a count finds the variable unused, since the author asked to remove.\n */\nfunction shownStep(step: RemoveStep, removal: VariableRemoval): RemoveStep {\n  return step === \"refused\" && !refuses(removal) ? \"confirm\" : step;\n}\n\n/** Remove's confirm, naming what goes. */\nfunction ConfirmRemove({\n  what,\n  focused,\n  onKeep,\n  onRemove,\n}: {\n  what: string;\n  /** Takes focus, on Keep, as the row's Remove opened it. */\n  focused: boolean;\n  onKeep: () => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  const keep = React.useRef<HTMLButtonElement>(null);\n  React.useEffect(() => {\n    if (focused) keep.current?.focus();\n  }, [focused]);\n  return (\n    <div\n      className=\"nx-vars-editor__confirm\"\n      role=\"group\"\n      aria-label={`Remove ${what}`}\n    >\n      <p>\n        Remove <strong>{what}</strong>? Any block using it loses that style. The\n        page still renders.\n      </p>\n      <div className=\"nx-vars-editor__actions\">\n        <Button\n          ref={keep}\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button\"\n          onClick={onKeep}\n        >\n          Keep\n        </Button>\n        <Button\n          type=\"button\"\n          variant=\"destructive\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button\"\n          onClick={onRemove}\n        >\n          Remove {what}\n        </Button>\n      </div>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * Design → Type → \"Site text\": one row each for Body, the six headings,\n * Links, Buttons and Captions, set once for every page.\n *\n * Each row previews sample text in its current look beside its pair\n * (\"28 / 1.2\"), and opens a popup beside the panel, as a variable's row\n * does. A text row is pointed at a type size, which sets its size and line\n * height together, or given a typed size (with the unit menu or \"Fluid…\")\n * and a line height, or left as \"Your site's own\", which writes nothing.\n * The Links row has a colour, a colour on hover and when it is underlined.\n *\n * Every edit is a new token set handed to the host, as a variable edit is,\n * so it saves, merges and undoes the same way. What a row writes is said on\n * hover and, while \"Show CSS names\" is on, under the row.\n *\n * @module site-text-panel\n */\nimport {\n  fluidValue,\n  isTokenRef,\n  SITE_TEXT_UNDERLINES,\n  tokenRef,\n  type SiteTextEntry,\n  type SiteTextMap,\n  type SiteTextRole,\n  type SiteTextUnderline,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type TokenMode,\n  type NamedClass,\n  STYLE_CATALOG,\n  textStylesOf,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button, Popover, PopoverContent, PopoverTrigger } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { EDITOR_WORDS } from \"../../editor-words\";\nimport { CssHint, CssNamesLine } from \"../../inspector/css-hint\";\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\nimport { lineHeightFromText } from \"../../styles/style-folded\";\n\nimport { commitFocusedField } from \"./editor-field-commit\";\nimport { FluidButton, type FluidHook } from \"./fluid-popover\";\nimport {\n  pairWords,\n  SITE_OWN_WORDS,\n  siteTextRowViews,\n  siteTextWrites,\n  typeSizeChoices,\n  withRowTextStyle,\n  withSiteTextRow,\n  withTypeSize,\n  type SiteTextRowView,\n  type TypeSizeChoice,\n} from \"./site-text-rows\";\nimport { fluidRangeOf, setFluidRange } from \"./tokens-studio\";\nimport { VariableChoice } from \"./variable-choice\";\nimport { ColourValue } from \"./variable-editor\";\nimport {\n  CloseVariableEditor,\n  LineHeightInput,\n  SizeInput,\n} from \"./variable-value-controls\";\n\n/** What the section is handed: the set, how to change it, and the mode shown. */\nexport interface SiteTextSectionProps {\n  readonly tokens: SiteTokenSet;\n  readonly onChange: (tokens: SiteTokenSet) => void;\n  readonly readOnly: boolean;\n  readonly mode: TokenMode;\n  /** The rows the site's code supplies, which Reset returns a row to. */\n  readonly supplied?: SiteTextMap | undefined;\n  /**\n   * The site's class library, whose text styles a row may follow\n   * (\"Heading 1 uses Display\"). Absent: none is offered.\n   */\n  readonly classes?: readonly NamedClass[] | undefined;\n}\n\n/** The words each underline is offered by. */\nconst UNDERLINE_WORDS: Readonly<Record<SiteTextUnderline, string>> = {\n  always: \"Always\",\n  hover: \"On hover\",\n  never: \"Never\",\n};\n\n/** The CSS properties a row writes, for the \"Show CSS names\" line. */\nfunction cssNamesOf(role: SiteTextRole): string[] {\n  return role === \"link\"\n    ? [\"color\", \"text-decoration\"]\n    : [\"font-size\", \"line-height\"];\n}\n\n/** The sample text every row previews its look with. */\nconst SAMPLE = \"The quick survey\";\n\n/** The sizes a row's preview is drawn between, in px, so every row fits. */\nconst PREVIEW_PX = { min: 11, max: 20 } as const;\n\n/** A row's preview size: its text's size, scaled into the row's bounds. */\nfunction previewPx(row: SiteTextRowView): number {\n  const px = row.px ?? 16;\n  return Math.min(PREVIEW_PX.max, Math.max(PREVIEW_PX.min, px * 0.55));\n}\n\n/** What a row says beside its name: its pair, a link's look, or its site's own. */\nfunction rowWords(row: SiteTextRowView): string {\n  if (row.role !== \"link\" || row.pair === SITE_OWN_WORDS) return row.pair;\n  const underline = row.entry?.underline;\n  return underline === undefined\n    ? \"Colour\"\n    : `Underline ${UNDERLINE_WORDS[underline].toLowerCase()}`;\n}\n\n/** The Site text section, for the Type tab. */\nexport function SiteTextSection({\n  tokens,\n  onChange,\n  readOnly,\n  mode,\n  supplied,\n  classes,\n}: SiteTextSectionProps): React.JSX.Element {\n  const id = React.useId();\n  const rows = siteTextRowViews(tokens, mode, classes);\n  return (\n    <section className=\"nx-vars__group nx-site-text\" aria-labelledby={id}>\n      <div className=\"nx-vars__group-head\">\n        <h3 className=\"nx-vars__group-name\" id={id}>\n          {EDITOR_WORDS.siteText}\n        </h3>\n      </div>\n      <ul className=\"nx-vars__list\">\n        {rows.map(row => (\n          <SiteTextRow\n            key={row.role}\n            row={row}\n            tokens={tokens}\n            onChange={onChange}\n            readOnly={readOnly}\n            mode={mode}\n            resetTo={supplied?.[row.role]}\n            classes={classes}\n          />\n        ))}\n      </ul>\n    </section>\n  );\n}\n\n/** One row: its button, what it writes, and its popup. */\nfunction SiteTextRow({\n  row,\n  tokens,\n  onChange,\n  readOnly,\n  mode,\n  resetTo,\n  classes,\n}: {\n  row: SiteTextRowView;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n  mode: TokenMode;\n  resetTo: SiteTextEntry | undefined;\n  classes: readonly NamedClass[] | undefined;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const namesId = React.useId();\n  const words = rowWords(row);\n  const heading = /^h[1-6]$/.test(row.role);\n  return (\n    <PopupRow open={open} onOpen={setOpen}>\n      <div className=\"nx-vars__line\">\n        <CssHint writes={siteTextWrites(tokens, row.role, row.entry, classes)}>\n          <PopoverTrigger asChild>\n            <button\n              type=\"button\"\n              className=\"nx-vars__row nx-site-text__row\"\n              data-site-text={row.role}\n              data-open={open ? \"\" : undefined}\n            >\n              <span\n                className=\"nx-vars__name\"\n                title={row.label}\n                aria-hidden=\"true\"\n              >\n                {row.label}\n              </span>\n              <span\n                className=\"nx-site-text__preview\"\n                aria-hidden=\"true\"\n                style={{\n                  fontSize: `${String(previewPx(row))}px`,\n                  fontWeight: heading ? 700 : 400,\n                }}\n              >\n                {SAMPLE}\n              </span>\n              <span className=\"nx-vars__chip\" title={words} aria-hidden=\"true\">\n                {words}\n              </span>\n              {/* The row's name, in one element, named with its section so\n                  \"Body\" here is never taken for a type size of the same name\n                  in the list below. Text rather than an aria-label, which\n                  would have to hold every drawn word, the sample included. */}\n              <span className=\"nx-sr-only\">\n                {row.follows === undefined\n                  ? `${EDITOR_WORDS.siteText}: ${row.label}, ${words}`\n                  : `${EDITOR_WORDS.siteText}: ${row.label} uses ${row.follows.name}`}\n              </span>\n            </button>\n          </PopoverTrigger>\n        </CssHint>\n      </div>\n      <CssNamesLine id={namesId} names={cssNamesOf(row.role)} />\n      <PopoverContent\n        side=\"right\"\n        align=\"start\"\n        sideOffset={12}\n        collisionPadding={8}\n        className=\"nx-vars-editor nx-site-text__editor\"\n        aria-label={`${readOnly ? \"\" : \"Edit \"}${row.label}`}\n      >\n        <CloseVariableEditor.Provider value={() => setOpen(false)}>\n          <SiteTextEditor\n            row={row}\n            tokens={tokens}\n            onChange={onChange}\n            readOnly={readOnly}\n            mode={mode}\n            resetTo={resetTo}\n            classes={classes}\n          />\n        </CloseVariableEditor.Provider>\n      </PopoverContent>\n    </PopupRow>\n  );\n}\n\n/**\n * A Design row with a popup beside the panel: the row's line and its popup\n * inside, and what follows the row (a refusal) after it. A field still being\n * typed in commits before the popup closes. Shared by Site text's rows and\n * the text styles'.\n */\nexport function PopupRow({\n  open,\n  onOpen,\n  after,\n  children,\n}: {\n  open: boolean;\n  onOpen: (open: boolean) => void;\n  after?: React.ReactNode;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <li className=\"nx-vars__item\" data-open={open ? \"\" : undefined}>\n      <Popover\n        open={open}\n        onOpenChange={next => {\n          if (!next) commitFocusedField(globalThis.document);\n          onOpen(next);\n        }}\n        modal\n      >\n        {children}\n      </Popover>\n      {after}\n    </li>\n  );\n}\n\n/** A row's popup: a link's colours and underline, or a text row's size. */\nfunction SiteTextEditor(props: {\n  row: SiteTextRowView;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n  mode: TokenMode;\n  /** The row the site's code supplies, or none: the built-in one. */\n  resetTo: SiteTextEntry | undefined;\n  /** The site's classes, whose text styles a text row may follow. */\n  classes: readonly NamedClass[] | undefined;\n}): React.JSX.Element {\n  const { row, tokens, onChange, readOnly, resetTo } = props;\n  return (\n    <div className=\"nx-vars-editor__body\" spellCheck={false}>\n      <p className=\"nx-vars-editor__label nx-site-text__title\">{row.label}</p>\n      {row.role === \"link\" ? (\n        <LinkFields {...props} />\n      ) : (\n        <SizeFields {...props} />\n      )}\n      {readOnly || !row.stated ? null : (\n        <div className=\"nx-vars-editor__actions\">\n          <Button\n            type=\"button\"\n            variant=\"outline\"\n            size=\"sm\"\n            className=\"nx-vars-editor__button\"\n            // Back to the code's row where it supplies one, else the built-in.\n            onClick={() => onChange(withSiteTextRow(tokens, row.role, resetTo))}\n          >\n            Reset\n          </Button>\n        </div>\n      )}\n    </div>\n  );\n}\n\n/**\n * Which way a text row is set: a type size's identity, \"custom\" for a typed\n * size, or \"own\" for the site's own.\n */\ntype SizeWay = string;\n\n/** The way a text style is chosen by, beside a type size's identity. */\nconst TEXT_STYLE_WAY = \"text:\";\n\n/** The way a row's values say it is set. */\nfunction wayOf(row: SiteTextRowView): SizeWay {\n  if (row.follows !== undefined) return `${TEXT_STYLE_WAY}${row.follows.id}`;\n  const size = row.entry?.fontSize;\n  if (isTokenRef(size)) return size.$token;\n  return size === undefined && row.entry?.lineHeight === undefined\n    ? \"own\"\n    : \"custom\";\n}\n\n/** A text row's size: a type size, \"Custom size\", or \"Your site's own\". */\nfunction SizeFields({\n  row,\n  tokens,\n  onChange,\n  readOnly,\n  mode,\n  classes,\n}: {\n  row: SiteTextRowView;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n  mode: TokenMode;\n  classes: readonly NamedClass[] | undefined;\n}): React.JSX.Element {\n  const name = React.useId();\n  const choices = typeSizeChoices(tokens, mode);\n  // The text styles the row may follow in place of a size of its own.\n  const followable = textStylesOf(classes);\n  const stored = wayOf(row);\n  // \"Custom size\" chosen shows its fields before anything is typed.\n  const [typing, setTyping] = React.useState(false);\n  const way = typing && stored !== \"custom\" ? \"custom\" : stored;\n  const pick = (next: SizeWay): void => {\n    setTyping(next === \"custom\");\n    if (next === \"custom\") return;\n    if (next.startsWith(TEXT_STYLE_WAY)) {\n      onChange(\n        withRowTextStyle(tokens, row.role, next.slice(TEXT_STYLE_WAY.length))\n      );\n      return;\n    }\n    onChange(\n      next === \"own\"\n        ? withSiteTextRow(tokens, row.role, {})\n        : withTypeSize(tokens, row.role, next)\n    );\n  };\n  const options: readonly { value: SizeWay; label: string }[] = [\n    { value: \"own\", label: SITE_OWN_WORDS },\n    ...choices.map(choice => ({\n      value: choice.size,\n      label: `${choice.name} · ${choice.pair}`,\n    })),\n    { value: \"custom\", label: \"Custom size\" },\n    ...followable.map(style => ({\n      value: `${TEXT_STYLE_WAY}${style.id}`,\n      label: `Text style: ${sharedStyleName(style)}`,\n    })),\n  ];\n  return (\n    <>\n      <fieldset className=\"nx-site-text__sizes\">\n        <legend className=\"nx-vars-editor__label\">Type size</legend>\n        {options.map(option => (\n          <label key={option.value} className=\"nx-site-text__option\">\n            <input\n              type=\"radio\"\n              name={name}\n              value={option.value}\n              checked={way === option.value}\n              disabled={readOnly}\n              onChange={() => pick(option.value)}\n            />\n            <span>{option.label}</span>\n          </label>\n        ))}\n      </fieldset>\n      {way === \"custom\" ? (\n        <TypedSize\n          row={row}\n          tokens={tokens}\n          onChange={onChange}\n          readOnly={readOnly}\n          choices={choices}\n        />\n      ) : null}\n    </>\n  );\n}\n\n/** A plain value as a field shows it. */\nfunction plain(value: unknown): string {\n  return typeof value === \"string\" || typeof value === \"number\"\n    ? String(value)\n    : \"\";\n}\n\n/** A typed size, with its unit menu and \"Fluid…\", and a typed line height. */\nfunction TypedSize({\n  row,\n  tokens,\n  onChange,\n  readOnly,\n}: {\n  row: SiteTextRowView;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n  choices: readonly TypeSizeChoice[];\n}): React.JSX.Element {\n  // Typing a size of its own takes the row off a text style it followed.\n  const { textStyle: _followed, ...own } = row.entry ?? {};\n  const entry: SiteTextEntry = isTokenRef(own.fontSize) ? {} : own;\n  const write = (next: SiteTextEntry): void =>\n    onChange(withSiteTextRow(tokens, row.role, next));\n  const range = fluidRangeOf(tokens);\n  const size = plain(entry.fontSize);\n  const fluid: FluidHook = {\n    sizes: entry.fluid,\n    value: size,\n    range,\n    onFluid: sizes =>\n      write({ ...entry, fontSize: fluidValue(sizes, range), fluid: sizes }),\n    onRange: next => onChange(setFluidRange(tokens, next)),\n  };\n  return (\n    <div className=\"nx-vars-editor__field nx-site-text__typed\">\n      <SizeInput\n        label=\"Size\"\n        value={size}\n        readOnly={readOnly}\n        onCommit={value => {\n          const { fluid: _made, ...rest } = entry;\n          write({ ...rest, fontSize: value });\n        }}\n        css={`\n          font-size: ${size};\n        `}\n      />\n      {readOnly ? null : <FluidButton hook={fluid} />}\n      <LineHeightInput\n        label=\"Line height\"\n        value={plain(entry.lineHeight)}\n        readOnly={readOnly}\n        onCommit={value => {\n          const typed = lineHeightFromText(value);\n          if (typeof typed !== \"string\" && typeof typed !== \"number\") return;\n          write({ ...entry, lineHeight: typed });\n        }}\n      />\n      <p className=\"nx-site-text__said\">\n        {pairWords(size, plain(entry.lineHeight))}\n      </p>\n    </div>\n  );\n}\n\n/** The catalog's leaf for a text colour, which offers the colour variables. */\nconst COLOUR_LEAF: StyleLeaf | undefined = (() => {\n  const entry = STYLE_CATALOG.find(each => each.property === \"color\");\n  const shape = entry?.shape;\n  return shape !== undefined && \"cssProperty\" in shape ? shape : undefined;\n})();\n\n/** The Links row: its colour, its colour on hover, and its underline. */\nfunction LinkFields({\n  row,\n  tokens,\n  onChange,\n  readOnly,\n}: {\n  row: SiteTextRowView;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n  mode: TokenMode;\n}): React.JSX.Element {\n  const name = React.useId();\n  const entry = row.entry ?? {};\n  const write = (next: SiteTextEntry): void =>\n    onChange(withSiteTextRow(tokens, \"link\", next));\n  return (\n    <>\n      <LinkColour\n        label=\"Colour\"\n        value={entry.color}\n        tokens={tokens}\n        readOnly={readOnly}\n        onValue={color => write({ ...entry, color })}\n      />\n      <LinkColour\n        label=\"Colour on hover\"\n        value={entry.hoverColor}\n        tokens={tokens}\n        readOnly={readOnly}\n        onValue={hoverColor => write({ ...entry, hoverColor })}\n      />\n      <fieldset className=\"nx-site-text__sizes\" aria-label=\"Underline\">\n        <legend className=\"nx-vars-editor__label\">Underline</legend>\n        {SITE_TEXT_UNDERLINES.map(underline => (\n          <label key={underline} className=\"nx-site-text__option\">\n            <input\n              type=\"radio\"\n              name={name}\n              value={underline}\n              checked={entry.underline === underline}\n              disabled={readOnly}\n              onChange={() => write({ ...entry, underline })}\n            />\n            <span>{UNDERLINE_WORDS[underline]}</span>\n          </label>\n        ))}\n      </fieldset>\n    </>\n  );\n}\n\n/** One of a link's colours: typed or picked, or a colour variable. */\nfunction LinkColour({\n  label,\n  value,\n  tokens,\n  readOnly,\n  onValue,\n}: {\n  label: string;\n  value: SiteTextEntry[\"color\"];\n  tokens: SiteTokenSet;\n  readOnly: boolean;\n  onValue: (value: SiteTextEntry[\"color\"]) => void;\n}): React.JSX.Element {\n  const held = isTokenRef(value) ? value.$token : undefined;\n  return (\n    <div className=\"nx-site-text__colour\">\n      {held === undefined ? (\n        <ColourValue\n          label={label}\n          value={plain(value)}\n          readOnly={readOnly}\n          onCommit={onValue}\n        />\n      ) : (\n        <p className=\"nx-vars-editor__field\">\n          <span className=\"nx-vars-editor__label\">{label}</span>\n          <span className=\"nx-vars-editor__mono\">{held}</span>\n        </p>\n      )}\n      {readOnly || COLOUR_LEAF === undefined ? null : (\n        <VariableChoice\n          leaf={COLOUR_LEAF}\n          tokens={tokens}\n          current={held}\n          label={label}\n          onPick={identity => onValue(tokenRef(identity))}\n        />\n      )}\n    </div>\n  );\n}\n","/**\n * Which variable's editor the Design panel has open, what opening, adding,\n * duplicating and closing one does, and each editor's commit, which settles\n * once the author's work on it has ended. Kept beside the panel that uses it,\n * in a file of its own so the panel stays within the size its folder allows.\n *\n * @module tokens-panel-open-variable\n */\nimport { tokenIdentity, type SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { inColourGroup } from \"./colour-groups\";\nimport { commitFocusedField } from \"./editor-field-commit\";\nimport {\n  addVariable,\n  duplicateVariable,\n  labelNewVariable,\n  type VariableEntry,\n} from \"./tokens-studio\";\nimport type { OnAdd } from \"./variable-adds\";\n\n/** An add, with the named group of colours whose list its add row ends. */\nexport type OnAddTo = (\n  what: Parameters<OnAdd>[0],\n  from: Parameters<OnAdd>[1],\n  group?: string\n) => void;\n\n/**\n * Each editor's commit, settling where the author's work has already ended,\n * and a settle when the view goes away.\n *\n * Going away ends the author's work here as closing an editor does: a tab\n * change or the panel closing. An edit committed by an editor that is\n * already closed, such as a colour picker writing what it held as it\n * unmounts, comes after the settle its closing made, so it settles again\n * rather than wait for a pause the author has already ended.\n */\nfunction useCommitsSettled(\n  onChange: (tokens: SiteTokenSet) => void,\n  onSettle: (() => void) | undefined,\n  openKey: string | null\n): (key: string) => (next: SiteTokenSet) => void {\n  // The latest callback, so the effect runs only on unmount rather than on\n  // every render that hands a new one.\n  const settle = React.useRef(onSettle);\n  settle.current = onSettle;\n  // Which editor is open as of the latest render, and whether the panel is\n  // still mounted: read when an editor commits, which it may do as it goes\n  // away, after the close or the unmount has already settled.\n  const openNow = React.useRef(openKey);\n  openNow.current = openKey;\n  const mounted = React.useRef(true);\n  React.useEffect(() => {\n    mounted.current = true;\n    return () => {\n      mounted.current = false;\n      settle.current?.();\n    };\n  }, []);\n  return key => next => {\n    onChange(next);\n    if (!mounted.current || openNow.current !== key) settle.current?.();\n  };\n}\n\n/**\n * Which variable's editor is open, what opening and closing one does, and\n * each editor's commit, which settles once the editor has closed.\n *\n * A variable added from a \"+\" opens straight away, and is \"fresh\" until its\n * editor closes: nothing can reference it yet, so its code name may still\n * follow the name it was given, which happens on close. The row is keyed by\n * that code name, so focus is put back on it once it has re-rendered.\n */\nexport function useOpenVariable({\n  tokens,\n  onChange,\n  currentTokens,\n  onSettle,\n}: {\n  tokens: SiteTokenSet | undefined;\n  onChange: (tokens: SiteTokenSet) => void;\n  currentTokens: () => SiteTokenSet | undefined;\n  /** The author is done with a variable; see `TokensPanelProps.onSettle`. */\n  onSettle: (() => void) | undefined;\n}): {\n  /** The panel's element, which rows are found in to be focused. */\n  root: React.RefObject<HTMLDivElement | null>;\n  openKey: string | null;\n  /** The row just added, while its editor is open; a search keeps it. */\n  fresh: string | null;\n  toggle: (key: string, open: boolean) => void;\n  add: OnAddTo;\n  duplicate: (entry: VariableEntry) => void;\n  forget: (key: string) => void;\n  /** Each row editor's commit; see {@link useCommitsSettled}. */\n  commitFrom: (key: string) => (next: SiteTokenSet) => void;\n  /** Focuses a row once it is drawn, as after a move to another group. */\n  focus: (key: string) => void;\n} {\n  const root = React.useRef<HTMLDivElement>(null);\n  const [openKey, setOpenKey] = React.useState<string | null>(null);\n  const [focusKey, setFocusKey] = React.useState<string | null>(null);\n  const fresh = React.useRef(new Set<string>());\n  const [freshOpen, setFreshOpen] = React.useState<string | null>(null);\n  // What was pressed to add a variable: where focus goes back to when the\n  // new row is not drawn once its editor closes, as under a search it does\n  // not match.\n  const origin = React.useRef<HTMLElement | null>(null);\n  // Focus a row after its key changed under it (a just-added variable named\n  // after its label) or after the editor closed onto a new row.\n  React.useEffect(() => {\n    if (focusKey === null) return;\n    const find = (): HTMLElement | null | undefined =>\n      root.current?.querySelector<HTMLElement>(\n        `[data-variable-key=\"${CSS.escape(focusKey)}\"]`\n      );\n    const row = find();\n    if (row) {\n      row.focus();\n      // A row drawn anew, as one moved into another group is, has its button\n      // replaced once just after it mounts, as its editor's anchor registers.\n      // Focus follows the new one, unless it has gone elsewhere since.\n      window.setTimeout(() => {\n        const owner = row.ownerDocument;\n        if (row.isConnected || owner.activeElement !== owner.body) return;\n        find()?.focus();\n      }, 0);\n    } else if (origin.current?.isConnected === true) origin.current.focus();\n    setFocusKey(null);\n  }, [focusKey, tokens]);\n\n  // A variable just added is brought into view before its editor is placed\n  // beside it: added at the end of a long list, it would otherwise open its\n  // editor below the window, far from the \"+\" pressed.\n  React.useLayoutEffect(() => {\n    if (openKey === null || !fresh.current.has(openKey)) return;\n    root.current\n      ?.querySelector<HTMLElement>(\n        `[data-variable-key=\"${CSS.escape(openKey)}\"]`\n      )\n      ?.scrollIntoView({ block: \"nearest\" });\n  }, [openKey, tokens]);\n\n  // A variable just made, new or a copy, opens; its code name follows its\n  // name until the editor closes.\n  const opened = (made: { tokens: SiteTokenSet; at: number }): void => {\n    const added = made.tokens.tokens[made.at];\n    if (added === undefined) return;\n    onChange(made.tokens);\n    const key = tokenIdentity(added);\n    fresh.current.add(key);\n    setFreshOpen(key);\n    setOpenKey(key);\n  };\n\n  // The search is kept: the new row is added where the author is, in the\n  // named group of colours its add row ends.\n  const add: OnAddTo = (what, from, group) => {\n    origin.current = from;\n    const made = addVariable(currentTokens() ?? tokens, what);\n    opened({ ...made, tokens: inColourGroup(made.tokens, made.at, group) });\n  };\n\n  const duplicate = (entry: VariableEntry): void => {\n    const set = currentTokens() ?? tokens;\n    if (set === undefined) return;\n    origin.current = null;\n    opened(duplicateVariable(set, entry.row.at, entry.label));\n  };\n\n  const close = (key: string): void => {\n    // A field still being typed in commits first, as leaving it does: a\n    // click outside closes the editor before the field's own blur, and the\n    // name typed there would otherwise miss the code name made below.\n    commitFocusedField(root.current?.ownerDocument);\n    setOpenKey(null);\n    setFreshOpen(null);\n    // Settled after the renaming below, so a just-added variable's code name\n    // is part of what is persisted with the rest of its edit.\n    if (fresh.current.delete(key)) {\n      const named = namedAfterLabel(currentTokens(), key);\n      if (named !== undefined) onChange(named.tokens);\n      // Its row once drawn again, or what added it where a search hides it.\n      setFocusKey(named?.key ?? key);\n    }\n    onSettle?.();\n  };\n\n  const forget = (key: string): void => {\n    fresh.current.delete(key);\n    setOpenKey(null);\n    setFreshOpen(null);\n    onSettle?.();\n  };\n\n  const toggle = (key: string, open: boolean): void => {\n    if (open) setOpenKey(key);\n    else close(key);\n  };\n\n  const commitFrom = useCommitsSettled(onChange, onSettle, openKey);\n  return {\n    root,\n    openKey,\n    fresh: freshOpen,\n    toggle,\n    add,\n    duplicate,\n    forget,\n    commitFrom,\n    focus: setFocusKey,\n  };\n}\n\n/**\n * A just-added variable given a code name made from the name the author gave\n * it, with the row key it now has; nothing when it has no name of its own or\n * the code name would not change.\n */\nfunction namedAfterLabel(\n  set: SiteTokenSet | undefined,\n  key: string\n): { tokens: SiteTokenSet; key: string } | undefined {\n  if (set === undefined) return undefined;\n  const at = set.tokens.findIndex(token => tokenIdentity(token) === key);\n  const token = set.tokens[at];\n  if (token?.label === undefined) return undefined;\n  const named = labelNewVariable(set, at, token.label);\n  const renamed = named.tokens[at];\n  if (renamed === undefined || renamed.name === token.name) return undefined;\n  return { tokens: named, key: tokenIdentity(renamed) };\n}\n","/**\n * How a variable is added from the Design panel: the add rows each list ends\n * with (\"+ Add colour\", \"+ Add spacing\"…), each adding one kind or, for the\n * other values, offering a short menu of kinds, and an empty group's line.\n * Kept beside the variables view, which draws them.\n *\n * @module variable-adds\n */\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { Plus } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { NewVariable, VariableGroup } from \"./tokens-studio\";\n\n/** One add row: its words, and the kinds it adds (a menu for several). */\nexport interface AddRowSpec {\n  readonly label: string;\n  readonly options: readonly [NewVariable, string][];\n}\n\n/** What each group's list ends with, and what an empty group says. */\nexport const ADDS: Readonly<\n  Record<VariableGroup, { rows: readonly AddRowSpec[]; empty: string }>\n> = {\n  colours: {\n    rows: [{ label: \"Add colour\", options: [[\"colour\", \"Colour\"]] }],\n    empty: \"No colours yet.\",\n  },\n  type: {\n    rows: [{ label: \"Add type size\", options: [[\"type size\", \"Type size\"]] }],\n    empty: \"No type sizes yet.\",\n  },\n  spacing: {\n    rows: [{ label: \"Add spacing\", options: [[\"spacing\", \"Spacing\"]] }],\n    empty: \"No spacing yet.\",\n  },\n  radius: {\n    rows: [{ label: \"Add radius\", options: [[\"radius\", \"Radius\"]] }],\n    empty: \"No radii yet.\",\n  },\n  shadows: {\n    rows: [{ label: \"Add shadow\", options: [[\"shadow\", \"Shadow\"]] }],\n    empty: \"No shadows yet.\",\n  },\n  // The site's one content width, built in: nothing to add beside it.\n  content: { rows: [], empty: \"\" },\n  fonts: {\n    rows: [\n      { label: \"Add font\", options: [[\"fontFamily\", \"Font\"]] },\n      { label: \"Add font weight\", options: [[\"fontWeight\", \"Font weight\"]] },\n    ],\n    empty: \"No font or weight variables yet.\",\n  },\n  other: {\n    rows: [\n      {\n        label: \"Add value\",\n        options: [\n          [\"dimension\", \"Size\"],\n          [\"number\", \"Number\"],\n          [\"duration\", \"Duration\"],\n          [\"custom\", \"Custom value\"],\n        ],\n      },\n    ],\n    empty: \"\",\n  },\n};\n\n/** An empty group's one line, above its add rows. */\nexport function EmptyGroup({ text }: { text: string }): React.JSX.Element {\n  return <p className=\"nx-vars__empty\">{text}</p>;\n}\n\n/**\n * What an add row reports: the kind to add, and the add row's own button,\n * where focus goes back to when the new row is not drawn once its editor\n * closes. The button rather than whatever has focus: chosen from a menu,\n * focus is on an item that goes with the menu.\n */\nexport type OnAdd = (what: NewVariable, from: HTMLElement | null) => void;\n\n/** A group's add rows, at the end of its list. */\nexport function AddRows({\n  group,\n  onAdd,\n}: {\n  group: VariableGroup;\n  onAdd: OnAdd;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-vars__add-rows\">\n      {ADDS[group].rows.map(spec => (\n        <AddRow key={spec.label} spec={spec} onAdd={onAdd} />\n      ))}\n    </div>\n  );\n}\n\n/** \"+ Add colour\": a button for one kind, a menu for several. */\nfunction AddRow({\n  spec,\n  onAdd,\n}: {\n  spec: AddRowSpec;\n  onAdd: OnAdd;\n}): React.JSX.Element {\n  const trigger = React.useRef<HTMLButtonElement>(null);\n  const face = (\n    <>\n      <Plus aria-hidden=\"true\" size={14} />\n      {spec.label}\n    </>\n  );\n  const [only] = spec.options;\n  if (spec.options.length === 1 && only !== undefined) {\n    return (\n      <button\n        type=\"button\"\n        className=\"nx-vars__add-row\"\n        onClick={event => onAdd(only[0], event.currentTarget)}\n      >\n        {face}\n      </button>\n    );\n  }\n  return (\n    // Not modal: a modal menu marks the panel around it aria-hidden while\n    // its rows stay focusable (axe: aria-hidden-focus).\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild>\n        <button ref={trigger} type=\"button\" className=\"nx-vars__add-row\">\n          {face}\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align=\"start\" className=\"nx-vars__menu\">\n        {spec.options.map(([what, label]) => (\n          <DropdownMenuItem\n            key={what}\n            onSelect={() => onAdd(what, trigger.current)}\n          >\n            {label}\n          </DropdownMenuItem>\n        ))}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n","\"use client\";\n\n/**\n * A colour row's moves in its ⋯ menu: Move up, Move down, and Move to\n * group…, which lists the site's other named groups. Each one writes only the\n * colour's display group and the colour order, never its code name or value.\n *\n * @module colour-move-items\n */\nimport type { SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuSub,\n  DropdownMenuSubContent,\n  DropdownMenuSubTrigger,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { ColourGroupHostContext, useColourGroupNames } from \"./colour-group-ui\";\nimport { colourGroups, moveColour, moveColourToGroup } from \"./colour-groups\";\n\n/** Where a colour sits: whether anything is above it, or below it. */\nfunction edgesOf(\n  tokens: SiteTokenSet,\n  identity: string\n): { first: boolean; last: boolean; group: string | undefined } {\n  const flat = colourGroups(tokens).flatMap(group =>\n    group.identities.map(id => ({ id, group: group.name }))\n  );\n  const at = flat.findIndex(entry => entry.id === identity);\n  return {\n    first: at <= 0,\n    last: at === -1 || at === flat.length - 1,\n    group: flat[at]?.group,\n  };\n}\n\nexport function ColourMoveItems({\n  row,\n  tokens,\n  onChange,\n}: {\n  row: { readonly key: string; readonly identity: string };\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n}): React.JSX.Element {\n  const { identity } = row;\n  const host = React.useContext(ColourGroupHostContext);\n  // Each move tells the panel after, so the row keeps the focus where it is\n  // drawn now, in another group as well.\n  const moved = (next: SiteTokenSet): void => {\n    onChange(next);\n    host?.onMoved?.(row, next);\n  };\n  const { first, last, group } = edgesOf(tokens, identity);\n  // The groups there are, and any new one no colour is in yet.\n  const named = useColourGroupNames();\n  const others = (\n    named.length > 0\n      ? named\n      : colourGroups(tokens).map(candidate => candidate.name)\n  ).filter(name => name !== group);\n  return (\n    <>\n      <DropdownMenuSeparator />\n      <DropdownMenuItem\n        disabled={first}\n        onSelect={() => moved(moveColour(tokens, identity, -1))}\n      >\n        Move up\n      </DropdownMenuItem>\n      <DropdownMenuItem\n        disabled={last}\n        onSelect={() => moved(moveColour(tokens, identity, 1))}\n      >\n        Move down\n      </DropdownMenuItem>\n      {others.length === 0 ? null : (\n        <DropdownMenuSub>\n          <DropdownMenuSubTrigger>Move to group…</DropdownMenuSubTrigger>\n          <DropdownMenuSubContent className=\"nx-vars__menu\">\n            {others.map(name => (\n              <DropdownMenuItem\n                key={name}\n                onSelect={() =>\n                  moved(moveColourToGroup(tokens, identity, name))\n                }\n              >\n                {name}\n              </DropdownMenuItem>\n            ))}\n          </DropdownMenuSubContent>\n        </DropdownMenuSub>\n      )}\n    </>\n  );\n}\n","/**\n * A variable row's ⋯ menu: Rename, Duplicate, a colour's moves, the dark\n * value, and Remove or, for a variable the site's code supplies, Reset to\n * built-in.\n *\n * Remove opens the row's editor at its confirm rather than removing from the\n * menu, so the one removal there is, with its check of where the variable\n * is used, is the one that runs. The menu is told when an item hands focus\n * to something else (the name field, an editor) so closing it does not take\n * focus back to the ⋯.\n *\n * @module variable-row-menu\n */\nimport type { SiteToken, SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { Ellipsis } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ColourMoveItems } from \"./colour-move-items\";\nimport {\n  clearDarkValue,\n  setTokenValue,\n  type VariableEntry,\n} from \"./tokens-studio\";\nimport { partsOf, removalPlan, resetParts } from \"./variable-removal\";\nimport type { VariableUsageHere } from \"./variable-usage-view\";\n\n/** What the row does for the menu's items that leave the menu. */\nexport interface RowMenuActions {\n  /** Edit the name in place in the row. */\n  readonly onRename: () => void;\n  /** Add a copy right below, and open it. */\n  readonly onDuplicate: () => void;\n  /** Open the row's editor; `removing` starts its Remove. */\n  readonly onEdit: (removing: boolean) => void;\n}\n\n/** The kinds a dark value is offered on: what reads differently in dark. */\nconst DARK_KINDS: ReadonlySet<string> = new Set([\"color\", \"shadow\"]);\n\nexport function RowMenu({\n  entry,\n  token,\n  tokens,\n  suppliedOf,\n  usage,\n  label,\n  open,\n  onOpenChange,\n  onChange,\n  actions,\n}: {\n  entry: VariableEntry;\n  token: SiteToken;\n  tokens: SiteTokenSet;\n  suppliedOf: (identity: string) => SiteToken | undefined;\n  usage: VariableUsageHere | undefined;\n  /** The row's name as it is read, for the ⋯ button's own name. */\n  label: string;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  onChange: (tokens: SiteTokenSet) => void;\n  actions: RowMenuActions;\n}): React.JSX.Element {\n  const plan = removalPlan(\n    entry,\n    partsOf(entry, token, tokens, suppliedOf),\n    usage\n  );\n  // Set by an item that moves focus elsewhere, read as the menu closes.\n  const handingOff = React.useRef(false);\n  const handOff = (then: () => void) => () => {\n    handingOff.current = true;\n    then();\n  };\n  const at = entry.row.at;\n  const dark = token.values.dark !== undefined;\n  const builtIn = plan.removable.length === 0;\n  return (\n    // Not modal: a modal menu marks the panel around it aria-hidden while\n    // its rows stay focusable (axe: aria-hidden-focus).\n    <DropdownMenu modal={false} open={open} onOpenChange={onOpenChange}>\n      <DropdownMenuTrigger asChild>\n        <button\n          type=\"button\"\n          className=\"nx-vars__icon-button nx-vars__more\"\n          aria-label={`More actions for ${label}`}\n        >\n          <Ellipsis aria-hidden=\"true\" size={14} />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align=\"end\"\n        className=\"nx-vars__menu\"\n        onCloseAutoFocus={event => {\n          if (!handingOff.current) return;\n          handingOff.current = false;\n          event.preventDefault();\n        }}\n      >\n        <DropdownMenuItem onSelect={handOff(actions.onRename)}>\n          Rename\n        </DropdownMenuItem>\n        <DropdownMenuItem onSelect={handOff(actions.onDuplicate)}>\n          Duplicate\n        </DropdownMenuItem>\n        {entry.row.kind === \"color\" ? (\n          <ColourMoveItems\n            row={entry.row}\n            tokens={tokens}\n            onChange={onChange}\n          />\n        ) : null}\n        {dark ? (\n          // Offered on any kind that holds one, as an import can leave on\n          // a size, so it can be taken away; it is used until it is.\n          <DropdownMenuItem\n            onSelect={() => onChange(clearDarkValue(tokens, at))}\n          >\n            Remove dark value\n          </DropdownMenuItem>\n        ) : DARK_KINDS.has(entry.row.kind) ? (\n          <DropdownMenuItem\n            onSelect={handOff(() => {\n              // Starts as light, so nothing changes until the author picks\n              // the dark value in the editor that opens.\n              onChange(setTokenValue(tokens, at, \"dark\", token.values.light));\n              actions.onEdit(false);\n            })}\n          >\n            Add dark value\n          </DropdownMenuItem>\n        ) : null}\n        {builtIn ? null : (\n          <DropdownMenuItem onSelect={handOff(() => actions.onEdit(true))}>\n            {plan.label}\n          </DropdownMenuItem>\n        )}\n        {plan.changed.length === 0 && !builtIn ? null : (\n          <DropdownMenuItem\n            disabled={plan.changed.length === 0}\n            onSelect={() => onChange(resetParts(tokens, plan.changed))}\n          >\n            Reset to built-in\n          </DropdownMenuItem>\n        )}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n","/**\n * One variable's row in the Design panel: a swatch, a type specimen or a\n * kind icon, its name, a value chip for what is not a colour, and a ⋯ menu.\n * The row opens the variable's editor beside it; F2 or the menu's Rename\n * edits the name in place in the row, and Shift+F10 or the menu key opens\n * the menu, as they do in a file list.\n *\n * A colour shows one swatch, split corner to corner, light at the top left\n * and dark at the bottom right, where its dark value differs. How widely a\n * variable is used is said in the row's tooltip and in its name to a screen\n * reader, not drawn on the row.\n *\n * @module variable-row\n */\nimport {\n  tokenIdentity,\n  type SiteToken,\n  type SiteTokenSet,\n  type TokenKind,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Input,\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@nextlyhq/ui\";\nimport { Braces, Bold, Hash, Ruler, Timer, Type } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { DESKTOP_PREVIEW_WIDTH } from \"../../canvas/canvas-width\";\nimport { fluidRange, pxAtWidth } from \"../../styles/fluid-size\";\nimport { colourHexOf } from \"../../styles/style-colour\";\nimport { lengthInPx, variableValueText } from \"../../styles/style-variables\";\n\nimport { useColourRowDrag, useColourRowMove } from \"./colour-group-ui\";\nimport { markOf } from \"./design-group-toggle\";\nimport { useInPlaceField } from \"./in-place-field\";\nimport {\n  lengthFamilyOf,\n  relabelToken,\n  variableGroupOf,\n  variableLabelIssue,\n  type VariableEntry,\n} from \"./tokens-studio\";\nimport { VariableEditor, type VariableEditorProps } from \"./variable-editor\";\nimport { RowMenu, type RowMenuActions } from \"./variable-row-menu\";\nimport { swatchStyle } from \"./variable-swatch\";\nimport { variableCountWords, type VariableReach } from \"./variable-usage\";\nimport { CountTip, type VariableUsageHere } from \"./variable-usage-view\";\nimport { CloseVariableEditor } from \"./variable-value-controls\";\n\nexport interface VariableRowProps {\n  entry: VariableEntry;\n  tokens: SiteTokenSet;\n  mode: TokenMode;\n  suppliedOf: (identity: string) => SiteToken | undefined;\n  readOnly: boolean;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  onChange: (tokens: SiteTokenSet) => void;\n  onRemoved: () => void;\n  /** Adds a copy right below, and opens it. */\n  onDuplicate: () => void;\n  /**\n   * Just added or copied and never saved, while its editor is open: its\n   * editor's code name follows its name as it is typed. `marked` while a\n   * search would hide it, so it shows marked \"New\" in a narrowed list.\n   */\n  fresh?: { readonly marked: boolean } | undefined;\n  /** How widely it is used, where the host reads it. */\n  usage: VariableUsageHere | undefined;\n  /** Every variable the row stands for, together, once read. */\n  reach: VariableReach | undefined;\n  /**\n   * Marked \"Built-in\": a built-in colour still listed while the site hides\n   * the ones it does not use, so the author can tell why it stayed.\n   */\n  builtIn?: boolean;\n}\n\n/**\n * One variable: a button that opens its editor beside the row, and its ⋯.\n *\n * The button's name is the plain name followed by the values in words and\n * how widely it is used, so a screen reader hears what the swatch shows.\n */\nexport function VariableRow({\n  entry,\n  tokens,\n  mode,\n  suppliedOf,\n  readOnly,\n  open,\n  onOpenChange,\n  onChange,\n  onRemoved,\n  onDuplicate,\n  fresh,\n  usage,\n  reach,\n  builtIn = false,\n}: VariableRowProps): React.JSX.Element {\n  const token = tokens.tokens[entry.row.at];\n  const [removing, setRemoving] = React.useState(false);\n  const [renaming, setRenaming] = React.useState(false);\n  const [menuOpen, setMenuOpen] = React.useState(false);\n  const button = React.useRef<HTMLButtonElement>(null);\n  const opened = closingEndsRemove(setRemoving, onOpenChange);\n  const handOff = useHandOff(opened);\n  const shown = shownName(entry);\n  const changing = !readOnly && token !== undefined;\n  // A colour row moves with Alt+Up and Alt+Down.\n  const move = useColourRowMove(entry.row, tokens, onChange);\n  const onKeyDown = rowKeys(changing, {\n    rename: setRenaming,\n    menu: setMenuOpen,\n    move,\n  });\n  // A colour row can be dragged to another place in the colour order.\n  const drag = useColourRowDrag(entry.row);\n  return (\n    <li className=\"nx-vars__item\" data-open={markOf(open)} {...drag}>\n      <Popover open={open} onOpenChange={opened} modal>\n        {/* The editor opens beside the whole row, the ⋯ with it. */}\n        <PopoverAnchor asChild>\n          <div className=\"nx-vars__line\">\n            <RowNameOrField\n              renaming={renaming}\n              onRenamed={() => setRenaming(false)}\n              entry={entry}\n              token={token}\n              tokens={tokens}\n              mode={mode}\n              reach={reach}\n              marked={fresh?.marked === true}\n              builtIn={builtIn}\n              open={open}\n              quiet={open || menuOpen}\n              button={button}\n              onChange={onChange}\n              onKeyDown={onKeyDown}\n            />\n            <RowActions\n              changing={changing}\n              entry={entry}\n              token={token}\n              tokens={tokens}\n              suppliedOf={suppliedOf}\n              usage={usage}\n              label={shown}\n              open={menuOpen}\n              onOpenChange={setMenuOpen}\n              onChange={onChange}\n              actions={menuActionsOf({\n                setRenaming,\n                setRemoving,\n                onDuplicate,\n                onOpenChange,\n              })}\n            />\n          </div>\n        </PopoverAnchor>\n        <RowEditor\n          entry={entry}\n          tokens={tokens}\n          suppliedOf={suppliedOf}\n          readOnly={readOnly}\n          onChange={onChange}\n          onRemoved={onRemoved}\n          removing={removing}\n          isNew={fresh !== undefined}\n          usage={usage}\n          handOff={handOff}\n        />\n      </Popover>\n    </li>\n  );\n}\n\n/**\n * What the row's ⋯ menu does: rename in place, copy, and open the editor,\n * at its remove step where asked.\n */\nfunction menuActionsOf(row: {\n  setRenaming: (renaming: boolean) => void;\n  setRemoving: (removing: boolean) => void;\n  onDuplicate: () => void;\n  onOpenChange: (open: boolean) => void;\n}): RowMenuActions {\n  return {\n    onRename: () => row.setRenaming(true),\n    onDuplicate: row.onDuplicate,\n    onEdit: startRemove => {\n      row.setRemoving(startRemove);\n      row.onOpenChange(true);\n    },\n  };\n}\n\n/** The row's ⋯ menu, where its variable can be changed; nothing otherwise. */\nfunction RowActions({\n  changing,\n  token,\n  ...menu\n}: Omit<React.ComponentProps<typeof RowMenu>, \"token\"> & {\n  changing: boolean;\n  token: SiteToken | undefined;\n}): React.JSX.Element | null {\n  if (!changing || token === undefined) return null;\n  return <RowMenu token={token} {...menu} />;\n}\n\n/**\n * The row's button, which opens its editor: named by the visible name, then\n * the values the swatch shows, so a screen reader hears both and speech\n * input still matches; its tooltip says how widely it is used.\n */\nfunction RowTrigger({\n  entry,\n  token,\n  tokens,\n  mode,\n  reach,\n  marked,\n  builtIn,\n  open,\n  quiet,\n  button,\n  onKeyDown,\n}: {\n  entry: VariableEntry;\n  token: SiteToken | undefined;\n  tokens: SiteTokenSet;\n  mode: TokenMode;\n  reach: VariableReach | undefined;\n  marked: boolean;\n  /** Marked \"Built-in\"; see {@link VariableRowProps.builtIn}. */\n  builtIn: boolean;\n  open: boolean;\n  /** The tooltip stays closed: the editor or the menu is open. */\n  quiet: boolean;\n  button: React.RefObject<HTMLButtonElement | null>;\n  onKeyDown: ((event: React.KeyboardEvent) => void) | undefined;\n}): React.JSX.Element {\n  return (\n    <CountTip reach={reach} quiet={quiet}>\n      <PopoverTrigger asChild>\n        <button\n          ref={button}\n          type=\"button\"\n          className=\"nx-vars__row\"\n          data-variable-key={entry.row.key}\n          data-kind={entry.row.kind}\n          // Drawn as chosen while its editor is open. Its own mark: the\n          // row's tooltip sets `data-state` too, over the popover's.\n          data-open={markOf(open)}\n          onKeyDown={onKeyDown}\n        >\n          <RowFace\n            entry={entry}\n            token={token}\n            tokens={tokens}\n            mode={mode}\n            marked={marked}\n            builtIn={builtIn}\n          />\n          {/* The row's whole name, in one element: its visible name first,\n              then what the hidden swatch and chips show. Text rather than an\n              aria-label, which must hold every drawn word, the decorative\n              ones included; one element, so no browser puts a space before\n              its commas. */}\n          <span className=\"nx-sr-only\">\n            {rowLabel({\n              entry,\n              token,\n              tokens,\n              mode,\n              reach,\n              marked,\n              builtIn,\n            })}\n          </span>\n        </button>\n      </PopoverTrigger>\n    </CountTip>\n  );\n}\n\n/** The variable's editor, in the popover beside its row. */\nfunction RowEditor({\n  handOff,\n  usage,\n  ...editor\n}: Omit<VariableEditorProps, \"usage\"> & {\n  usage: VariableUsageHere | undefined;\n  handOff: ReturnType<typeof useHandOff>;\n}): React.JSX.Element {\n  return (\n    <PopoverContent\n      side=\"right\"\n      align=\"start\"\n      sideOffset={12}\n      // Kept inside the window, clear of its edges.\n      collisionPadding={8}\n      className=\"nx-vars-editor\"\n      aria-label={`${editor.readOnly ? \"\" : \"Edit \"}${editor.entry.label}`}\n      onCloseAutoFocus={handOff.onCloseAutoFocus}\n    >\n      <CloseVariableEditor.Provider value={handOff.close}>\n        <VariableEditor\n          {...editor}\n          {...(usage === undefined ? {} : { usage })}\n        />\n      </CloseVariableEditor.Provider>\n    </PopoverContent>\n  );\n}\n\n/**\n * A row's own keys, as a file list has them: F2 renames in place, and\n * Shift+F10 or the menu key opens its ⋯ menu. None on a row that cannot\n * change.\n */\nfunction rowKeys(\n  changing: boolean,\n  on: {\n    /** Starts renaming in place; called with `true`. */\n    rename: (renaming: true) => void;\n    /** Opens the row's ⋯ menu; called with `true`. */\n    menu: (open: true) => void;\n    /** A colour's move one place up or down, by Alt+Up and Alt+Down. */\n    move?: ((by: -1 | 1) => void) | undefined;\n  }\n): ((event: React.KeyboardEvent) => void) | undefined {\n  if (!changing) return undefined;\n  return event => {\n    const by = moveBy(event);\n    if (by !== undefined && on.move !== undefined) {\n      event.preventDefault();\n      on.move(by);\n      return;\n    }\n    const menu =\n      event.key === \"ContextMenu\" || (event.key === \"F10\" && event.shiftKey);\n    if (event.key !== \"F2\" && !menu) return;\n    event.preventDefault();\n    if (menu) on.menu(true);\n    else on.rename(true);\n  };\n}\n\n/** Which way Alt+Up or Alt+Down moves a row, or nothing for any other key. */\nfunction moveBy(event: React.KeyboardEvent): -1 | 1 | undefined {\n  if (!event.altKey) return undefined;\n  if (event.key === \"ArrowUp\") return -1;\n  return event.key === \"ArrowDown\" ? 1 : undefined;\n}\n\n/**\n * The row's name as a screen reader hears it: the visible name, \"new\" while\n * it is marked so, the values the swatch shows, and how widely it is used.\n */\nfunction rowLabel({\n  entry,\n  token,\n  tokens,\n  mode,\n  reach,\n  marked,\n  builtIn,\n}: {\n  entry: VariableEntry;\n  token: SiteToken | undefined;\n  tokens: SiteTokenSet;\n  mode: TokenMode;\n  reach: VariableReach | undefined;\n  marked: boolean;\n  builtIn: boolean;\n}): string {\n  const fresh = marked ? \", new\" : \"\";\n  const supplied = builtIn ? \", built-in\" : \"\";\n  return `${shownName(entry)}${fresh}${supplied}${describe(entry, token, tokens, mode)}${countWords(reach)}`;\n}\n\n/**\n * What the row draws: its preview, its name, and its value, or \"New\" in\n * the value's place while the editor beside it shows the value.\n */\nfunction RowFace({\n  entry,\n  token,\n  tokens,\n  mode,\n  marked,\n  builtIn,\n}: {\n  entry: VariableEntry;\n  token: SiteToken | undefined;\n  tokens: SiteTokenSet;\n  mode: TokenMode;\n  marked: boolean;\n  builtIn: boolean;\n}): React.JSX.Element {\n  return (\n    <>\n      <RowLead entry={entry} token={token} tokens={tokens} mode={mode} />\n      <RowName entry={entry} />\n      {builtIn ? (\n        <span className=\"nx-vars__built-in\" aria-hidden=\"true\">\n          Built-in\n        </span>\n      ) : null}\n      {marked ? (\n        <span className=\"nx-vars__new\" aria-hidden=\"true\">\n          New\n        </span>\n      ) : (\n        <RowTail entry={entry} token={token} tokens={tokens} mode={mode} />\n      )}\n    </>\n  );\n}\n\n/**\n * The row's name, and its kind where another row shares the name: drawn\n * only, since the row's screen-reader name starts with the same words.\n */\nfunction RowName({ entry }: { entry: VariableEntry }): React.JSX.Element {\n  return (\n    <span className=\"nx-vars__name\" aria-hidden=\"true\">\n      {entry.label}\n      {entry.kindWord === undefined ? null : (\n        <span className=\"nx-vars__name-kind\">{` · ${entry.kindWord}`}</span>\n      )}\n    </span>\n  );\n}\n\n/**\n * The name, edited in place in the row. Enter or leaving the field keeps\n * it, Escape cancels; Enter and Escape hand focus back to the row. A name\n * that cannot be used keeps the field open on Enter, saying why; leaving\n * the field then cancels, so nothing half-typed is kept. The code name\n * stays as it is, so CSS that uses it keeps working.\n */\nfunction RenameField({\n  entry,\n  token,\n  tokens,\n  onChange,\n  onDone,\n  row,\n}: {\n  entry: VariableEntry;\n  token: SiteToken;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  onDone: () => void;\n  row: React.RefObject<HTMLButtonElement | null>;\n}): React.JSX.Element {\n  const id = React.useId();\n  const [name, setName] = React.useState(entry.label);\n  const [issue, setIssue] = React.useState<string | undefined>();\n  // Once: Enter's own close takes the field away, and the blur that follows\n  // must not keep or cancel a second time.\n  const { field, done } = useInPlaceField();\n  const finish = (refocus: boolean): void => {\n    done.current = true;\n    onDone();\n    // Back on the row once it is drawn again in the field's place.\n    if (refocus) window.setTimeout(() => row.current?.focus(), 0);\n  };\n  const keep = (refocus: boolean): boolean => {\n    if (name.trim() === entry.label) {\n      finish(refocus);\n      return true;\n    }\n    const refused = variableLabelIssue(tokens, entry.row.at, name);\n    if (refused !== undefined) {\n      setIssue(refused);\n      return false;\n    }\n    onChange(relabelToken(tokens, entry.row.at, name));\n    finish(refocus);\n    return true;\n  };\n  const said = `${id}-said`;\n  return (\n    <span className=\"nx-vars__rename\">\n      <RowLead entry={entry} token={token} tokens={tokens} mode=\"light\" />\n      <Input\n        ref={field}\n        className=\"nx-vars__rename-field\"\n        aria-label={`Name of ${entry.label}`}\n        autoComplete=\"off\"\n        spellCheck={false}\n        value={name}\n        aria-invalid={issue === undefined ? undefined : true}\n        aria-describedby={issue === undefined ? undefined : said}\n        onChange={event => {\n          setName(event.currentTarget.value);\n          setIssue(undefined);\n        }}\n        onKeyDown={event => {\n          if (event.key === \"Enter\") {\n            event.preventDefault();\n            keep(true);\n          } else if (event.key === \"Escape\") {\n            // Only the field: the canvas keeps its selection.\n            event.preventDefault();\n            event.stopPropagation();\n            finish(true);\n          }\n        }}\n        onBlur={() => {\n          if (done.current) return;\n          if (!keep(false)) finish(false);\n        }}\n      />\n      {issue === undefined ? null : (\n        <span className=\"nx-vars__rename-issue\" id={said} role=\"status\">\n          {issue}\n        </span>\n      )}\n    </span>\n  );\n}\n\n/**\n * A colour's one swatch: its light value, split corner to corner with its\n * dark value at the bottom right where the two differ. An unwritten colour,\n * which the page does not carry, draws the empty swatch.\n */\nfunction ColourSwatch({\n  entry,\n  token,\n}: {\n  entry: VariableEntry;\n  token: SiteToken | undefined;\n}): React.JSX.Element {\n  const written = entry.row.written && token !== undefined;\n  const light = written\n    ? colourHexOf(token.values.light, undefined)\n    : undefined;\n  const dark =\n    written && token.values.dark !== undefined\n      ? colourHexOf(token.values.dark, undefined)\n      : undefined;\n  const split =\n    light !== undefined &&\n    dark !== undefined &&\n    light.toLowerCase() !== dark.toLowerCase();\n  return (\n    <span\n      className=\"nx-vars__swatch nx-vars__swatch--main\"\n      aria-hidden=\"true\"\n      data-split={split ? \"\" : undefined}\n      style={{\n        ...swatchStyle(light),\n        ...(split ? { \"--nx-swatch-dark\": dark } : {}),\n      }}\n    />\n  );\n}\n\n/**\n * The row's button, or while it is renamed in place, the name field that\n * takes its place.\n */\nfunction RowNameOrField({\n  renaming,\n  onRenamed,\n  onChange,\n  ...row\n}: React.ComponentProps<typeof RowTrigger> & {\n  renaming: boolean;\n  onRenamed: () => void;\n  onChange: (tokens: SiteTokenSet) => void;\n}): React.JSX.Element {\n  const { entry, token, tokens, button } = row;\n  if (!renaming || token === undefined) return <RowTrigger {...row} />;\n  return (\n    <RenameField\n      entry={entry}\n      token={token}\n      tokens={tokens}\n      onChange={onChange}\n      onDone={onRenamed}\n      row={button}\n    />\n  );\n}\n\n/** The editor's open change, a close leaving the remove step behind. */\nfunction closingEndsRemove(\n  setRemoving: (removing: boolean) => void,\n  onOpenChange: (open: boolean) => void\n): (open: boolean) => void {\n  return open => {\n    if (!open) setRemoving(false);\n    onOpenChange(open);\n  };\n}\n\n/**\n * Closing a row's editor for a control that sends the author elsewhere: the\n * editor closes without handing focus back to the row, which would take it\n * from the place the author was sent to.\n */\nfunction useHandOff(onOpenChange: (open: boolean) => void): {\n  close: () => void;\n  onCloseAutoFocus: (event: Event) => void;\n} {\n  const handingOff = React.useRef(false);\n  const close = React.useCallback(() => {\n    handingOff.current = true;\n    onOpenChange(false);\n  }, [onOpenChange]);\n  const onCloseAutoFocus = React.useCallback((event: Event) => {\n    if (!handingOff.current) return;\n    handingOff.current = false;\n    event.preventDefault();\n  }, []);\n  return { close, onCloseAutoFocus };\n}\n\n/** The row's count in words, after its name and values, once it is read. */\nfunction countWords(reach: VariableReach | undefined): string {\n  return reach === undefined ? \"\" : `. ${variableCountWords(reach)}`;\n}\n\n/**\n * The row's name as it is read: its label, and its kind when another row is\n * shown under the same name.\n */\nfunction shownName(entry: VariableEntry): string {\n  return entry.kindWord === undefined\n    ? entry.label\n    : `${entry.label} · ${entry.kindWord}`;\n}\n\n/** The value a variable shows for the preview mode, falling back to light. */\nfunction valueFor(token: SiteToken | undefined, mode: TokenMode): string {\n  if (token === undefined) return \"\";\n  return mode === \"dark\"\n    ? (token.values.dark ?? token.values.light)\n    : token.values.light;\n}\n\n/** The row's leading preview: a swatch, a type specimen, or a kind icon. */\nfunction RowLead({\n  entry,\n  token,\n  tokens,\n  mode,\n}: {\n  entry: VariableEntry;\n  token: SiteToken | undefined;\n  tokens: SiteTokenSet;\n  mode: TokenMode;\n}): React.JSX.Element {\n  const kind = entry.row.kind;\n  if (kind === \"color\") return <ColourSwatch entry={entry} token={token} />;\n  if (entry.row.name.startsWith(\"font-size.\")) {\n    return (\n      <span\n        className=\"nx-vars__specimen\"\n        aria-hidden=\"true\"\n        style={{\n          fontSize: `${String(specimenSize(valueFor(token, mode)))}px`,\n          fontFamily: siteFamily(tokens, mode),\n        }}\n      >\n        Aa\n      </span>\n    );\n  }\n  // A radius draws a square with that radius on its corners.\n  if (lengthFamilyOf(entry.row) === \"radius\") {\n    return (\n      <span\n        className=\"nx-vars__kind\"\n        aria-hidden=\"true\"\n        data-variable-icon=\"radius\"\n      >\n        <span\n          className=\"nx-vars__radius\"\n          style={{ borderRadius: valueFor(token, mode) }}\n        />\n      </span>\n    );\n  }\n  const Icon = KIND_ICONS[kind];\n  return (\n    <span\n      className=\"nx-vars__kind\"\n      aria-hidden=\"true\"\n      data-variable-icon={lengthFamilyOf(entry.row) ?? kind}\n    >\n      {kind === \"shadow\" ? (\n        <span\n          className=\"nx-vars__shadow\"\n          style={{ boxShadow: valueFor(token, mode) }}\n        />\n      ) : (\n        <Icon size={14} />\n      )}\n    </span>\n  );\n}\n\nconst KIND_ICONS: Readonly<\n  Record<TokenKind, React.ComponentType<{ size?: number }>>\n> = {\n  color: Hash,\n  dimension: Ruler,\n  fontFamily: Type,\n  fontWeight: Bold,\n  number: Hash,\n  shadow: Hash,\n  duration: Timer,\n  custom: Braces,\n};\n\n/**\n * The specimen's drawn size: the type size scaled into the row, so a heading\n * still reads larger than body text without growing the row.\n */\nfunction specimenSize(value: string): number {\n  // Read through the inspector's own reading of a length, so a type size is\n  // measured the same way in both places; a value it cannot measure is drawn\n  // at body size, as before.\n  const px = lengthInPx(value) ?? 16;\n  return Math.min(18, Math.max(11, Math.round(10 + px * 0.2)));\n}\n\n/** The site's body font, when it names a family this panel can draw. */\nfunction siteFamily(tokens: SiteTokenSet, mode: TokenMode): string | undefined {\n  // By identity, the one a rename leaves alone: the body font keeps drawing\n  // after an author renames it.\n  const body = tokens.tokens.find(\n    token => tokenIdentity(token) === \"font.body\"\n  );\n  const family = valueFor(body, mode);\n  return family === \"\" || /var\\s*\\(/i.test(family) ? undefined : family;\n}\n\n/** The row's trailing value chip; none on a colour row. */\nfunction RowTail({\n  entry,\n  token,\n  mode,\n}: {\n  entry: VariableEntry;\n  token: SiteToken | undefined;\n  tokens: SiteTokenSet;\n  mode: TokenMode;\n}): React.JSX.Element | null {\n  // A colour's one swatch says its values; nothing follows its name.\n  if (token === undefined || entry.row.kind === \"color\") return null;\n  const own = valueFor(token, mode);\n  const words = tailWords(entry, own);\n  const chip = (\n    <span\n      className=\"nx-vars__chip\"\n      aria-hidden=\"true\"\n      // The whole value on hover when the chip says it in other words, as\n      // \"Fluid · 16–20px\" does; the row's name says it to a screen reader.\n      title={words === chipText(entry, own, \"raw\") ? undefined : own}\n    >\n      {words}\n    </span>\n  );\n  if (\n    variableGroupOf(entry.row) !== \"spacing\" ||\n    entry.row.kind !== \"dimension\"\n  ) {\n    return chip;\n  }\n  // A spacing draws a bar as long as it is at the desktop width.\n  const px = pxAtWidth(own, DESKTOP_PREVIEW_WIDTH);\n  return (\n    <span className=\"nx-vars__tail\" aria-hidden=\"true\">\n      {px === undefined ? null : (\n        <span\n          className=\"nx-vars__bar\"\n          style={{ width: `${String(Math.round(px))}px` }}\n        />\n      )}\n      {chip}\n    </span>\n  );\n}\n\n/**\n * What the value chip says: a fluid length's range (\"Fluid · 16–20px\"),\n * the content width in px, as the block panel's Boxed option measures it,\n * or the value in the picker's words.\n */\nfunction tailWords(entry: VariableEntry, own: string): string {\n  const range = fluidRange(own);\n  if (range !== undefined && entry.lineHeight === undefined) {\n    return `Fluid · ${String(Math.round(range.minPx))}–${String(Math.round(range.maxPx))}px`;\n  }\n  if (variableGroupOf(entry.row) === \"content\") {\n    const px = pxAtWidth(own, DESKTOP_PREVIEW_WIDTH);\n    if (px !== undefined) return `${String(Math.round(px))}px`;\n  }\n  return chipText(entry, own);\n}\n\n/**\n * \"16 / 26\" for a type size with its line height, or the value itself, in\n * the picker's words: \"Fluid\" for a length that changes with the page, whose\n * whole `clamp()` crowded the name out of the row. `raw` keeps the value as\n * written, to tell whether the words shortened it.\n */\nfunction chipText(\n  entry: VariableEntry,\n  own: string,\n  form: \"words\" | \"raw\" = \"words\"\n): string {\n  const text =\n    form === \"raw\"\n      ? own\n      : variableValueText({ kind: entry.row.kind, value: own });\n  if (entry.lineHeight === undefined) return text;\n  return `${bare(text)} / ${bare(entry.lineHeight.value)}`;\n}\n\n/** A px value without its unit, as designers write a type scale. */\nfunction bare(value: string): string {\n  return value.trim().replace(/^(-?\\d*\\.?\\d+)px$/, \"$1\");\n}\n\n/** The row's values in words, for the button's accessible name. */\nfunction describe(\n  entry: VariableEntry,\n  token: SiteToken | undefined,\n  tokens: SiteTokenSet,\n  mode: TokenMode\n): string {\n  if (token === undefined) return \"\";\n  // A colour row shows both its swatches, so both values are said whatever\n  // the preview; every other row shows the preview mode's value, so that is\n  // the one said, read through the same projection the row draws with.\n  if (entry.row.kind === \"color\") {\n    const dark = token.values.dark;\n    return `, light ${token.values.light}, dark ${dark ?? \"same as light\"}`;\n  }\n  if (entry.lineHeight !== undefined) {\n    const line = valueFor(tokens.tokens[entry.lineHeight.at], mode);\n    return `, size ${valueFor(token, mode)}, line height ${line}`;\n  }\n  return `, ${valueFor(token, mode)}`;\n}\n","/**\n * How widely some variables are used together, as one count: a font's\n * variables, or a type size and its line height. A page naming two of them\n * is one place, not two, so where the host can count the documents each\n * once ({@link VariablesAccess.usageTogether}), a group's documents are its\n * count; elsewhere, they are the variables' added up, as before.\n *\n * A group is read once each of its variables is, and read again whenever\n * any of them is: two reads can say the same numbers of two variables while\n * the pages they share have changed. The host's count stands only for the\n * reads it was made from. Until it is read for them, and where it fails,\n * the group is added up, which says rightly whether anything uses it, so a\n * removal is never offered for a group in use while its count is read.\n *\n * @module variable-together-reads\n */\nimport * as React from \"react\";\n\nimport { idsKey, idsOf } from \"./usage-reads\";\nimport {\n  combinedReach,\n  reachTogether,\n  type VariableReach,\n  type VariablesAccess,\n  type VariablesTogether,\n} from \"./variable-usage\";\n\n/** The most groups, and the most variables they name in all, one read asks about. */\nconst TOGETHER_READ_SIZE = 50;\n\n/** A group as it is asked about: its variables once each, in one order. */\nfunction groupOf(identities: readonly string[]): string[] {\n  return [...new Set(identities)].sort();\n}\n\n/**\n * The groups in reads of at most {@link TOGETHER_READ_SIZE} groups naming\n * at most as many variables in all. A group larger than a read is left out:\n * its documents stay added up.\n */\nexport function togetherBatches(\n  groups: readonly (readonly string[])[]\n): string[][][] {\n  const batches: string[][][] = [];\n  let batch: string[][] = [];\n  let named = new Set<string>();\n  for (const group of groups) {\n    if (group.length > TOGETHER_READ_SIZE) continue;\n    const joined = new Set([...named, ...group]);\n    if (\n      batch.length === TOGETHER_READ_SIZE ||\n      joined.size > TOGETHER_READ_SIZE\n    ) {\n      batches.push(batch);\n      batch = [];\n      named = new Set(group);\n    } else {\n      named = joined;\n    }\n    batch.push([...group]);\n  }\n  if (batch.length > 0) batches.push(batch);\n  return batches;\n}\n\n/** What a group's read kept: the variables' usage it was read under, and its answer. */\ninterface Kept {\n  readonly stamp: string;\n  readonly value: VariablesTogether | \"failed\";\n}\n\n/** Each read's answer for a variable, numbered as first seen. */\nconst answerNumbers = new WeakMap<VariableReach, number>();\nlet answersSeen = 0;\n\n/**\n * Which read a variable's usage came from: each read answers with its own\n * object, so two reads saying the same numbers are told apart.\n */\nfunction answerNumber(reach: VariableReach): number {\n  const known = answerNumbers.get(reach);\n  if (known !== undefined) return known;\n  answersSeen += 1;\n  answerNumbers.set(reach, answersSeen);\n  return answersSeen;\n}\n\n/** The reads a group's variables' usage came from, as one value. */\nfunction stampOf(\n  group: readonly string[],\n  values: ReadonlyMap<string, VariableReach>\n): string {\n  return JSON.stringify(\n    group.map(id => {\n      const reach = values.get(id);\n      return reach === undefined ? null : answerNumber(reach);\n    })\n  );\n}\n\n/** Every group's answer, read a batch at a time; a batch that fails, failed. */\nasync function readGroups(\n  read: NonNullable<VariablesAccess[\"usageTogether\"]>,\n  due: readonly (readonly [string[], string])[],\n  signal: AbortSignal\n): Promise<Map<string, Kept>> {\n  const stamps = new Map(due.map(([group, stamp]) => [idsKey(group), stamp]));\n  const kept = new Map<string, Kept>();\n  for (const batch of togetherBatches(due.map(([group]) => group))) {\n    const answers = await read(batch, signal).catch(() => undefined);\n    batch.forEach((group, at) => {\n      const key = idsKey(group);\n      kept.set(key, {\n        stamp: stamps.get(key) ?? \"\",\n        value: answers?.[at] ?? \"failed\",\n      });\n    });\n  }\n  return kept;\n}\n\n/**\n * The groups due a read, with the usage of their variables each is read\n * under: those whose variables are all read and whose last read, if any,\n * was under other usage.\n */\nfunction dueGroups(\n  groups: readonly string[][],\n  values: ReadonlyMap<string, VariableReach>,\n  kept: ReadonlyMap<string, Kept>\n): (readonly [string[], string])[] {\n  return groups.flatMap(group => {\n    if (!group.every(id => values.has(id))) return [];\n    const stamp = stampOf(group, values);\n    return kept.get(idsKey(group))?.stamp === stamp\n      ? []\n      : [[group, stamp] as const];\n  });\n}\n\n/**\n * How widely some variables are used together, for the groups a screen\n * shows: answers a group's reach from its variables' `values`, with the\n * host's count of their documents together where it has one for the reads\n * in hand. Otherwise, and for a group not asked about here, it is added up.\n * A single variable is its own reach.\n *\n * @param access - The host's usage reads; none reads nothing\n * @param groups - The groups the screen shows, each the variables in it\n * @param values - Each variable's usage, as read by identity\n */\nexport function useReachTogether(\n  access: VariablesAccess | undefined,\n  groups: readonly (readonly string[])[],\n  values: ReadonlyMap<string, VariableReach>\n): (identities: readonly string[]) => VariableReach | undefined {\n  const read = access?.usageTogether;\n  const wantedKey = idsKey(\n    [\n      ...new Set(\n        groups\n          .map(groupOf)\n          // One variable is its own count; more than a read holds, added up.\n          .filter(\n            group => group.length > 1 && group.length <= TOGETHER_READ_SIZE\n          )\n          .map(idsKey)\n      ),\n    ].sort()\n  );\n  const wanted = React.useMemo(() => new Set(idsOf(wantedKey)), [wantedKey]);\n  const [kept, setKept] = React.useState<ReadonlyMap<string, Kept>>(\n    () => new Map()\n  );\n  const due = dueGroups([...wanted].map(idsOf), values, kept);\n  // One string, so the read follows what is due and nothing else.\n  const dueKey = JSON.stringify(due);\n  React.useEffect(() => {\n    if (read === undefined) return;\n    const asked = JSON.parse(dueKey) as [string[], string][];\n    if (asked.length === 0) return;\n    const controller = new AbortController();\n    void readGroups(read, asked, controller.signal).then(answers => {\n      if (!controller.signal.aborted) {\n        setKept(current => new Map([...current, ...answers]));\n      }\n    });\n    return () => controller.abort();\n  }, [read, dueKey]);\n  return React.useCallback(\n    (identities: readonly string[]): VariableReach | undefined => {\n      const group = groupOf(identities);\n      const reaches = group.map(id => values.get(id));\n      const key = idsKey(group);\n      if (read === undefined || !wanted.has(key)) {\n        return combinedReach(reaches);\n      }\n      // The host's count only for the reads it was made from.\n      const held = kept.get(key);\n      const current =\n        held !== undefined &&\n        held.value !== \"failed\" &&\n        held.stamp === stampOf(group, values);\n      return current\n        ? reachTogether(reaches, held.value)\n        : combinedReach(reaches);\n    },\n    [read, wanted, kept, values]\n  );\n}\n","/**\n * What the Styles tab's block style actions write: a new block style made\n * from the ★ style's values, a copy of one, the ★ moved, and a built-in style\n * hidden or shown again. Each is the site's whole class list after the\n * action, so the host stores it through the one writer every class write\n * joins, or why it can't be.\n *\n * A rename keeps the style's id and its class name, so every document\n * wearing it keeps resolving; only the name the author reads changes.\n *\n * @module block-style-plans\n * @experimental Settles with the Styles tab's Block styles.\n */\n\nimport {\n  isDefaultLook,\n  isLook,\n  ownLooksRead,\n  MAX_NAMED_CLASS_NAME_LENGTH,\n  MAX_TOKEN_LABEL_LENGTH,\n  newId,\n  starredLooksOf,\n  tokenLabelIssue,\n  type NamedClass,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { usableSiteClasses } from \"./class-library\";\nimport { sharedStyleName, sharedStyleSlug } from \"./shared-style-library\";\n\n/** A block style action's answer: the classes to store and the style it made, or why not. */\nexport type BlockStylePlan =\n  | {\n      readonly ok: true;\n      readonly classes: NamedClass[];\n      /** The style the action made. */\n      readonly id: string;\n    }\n  | { readonly ok: false; readonly reason: string };\n\n/** What a block style no longer on the site is told. */\nconst BLOCK_STYLE_GONE = \"This block style is no longer on the site.\";\n\n/** A block type's ★ style as the page draws it, or `undefined` while its own style is. */\nfunction starredStyleOf(\n  library: readonly NamedClass[],\n  blockType: string\n): NamedClass | undefined {\n  return starredLooksOf(usableSiteClasses(library)).get(blockType);\n}\n\n/** The part of a block style's class name its type gives: `button`, `acme-hero`. */\nfunction typeSlug(blockType: string): string {\n  return blockType.startsWith(\"core/\")\n    ? blockType.slice(\"core/\".length)\n    : blockType.replace(\"/\", \"-\");\n}\n\n/**\n * The class name a block style of this type takes from its name, as the\n * built-in ones are written (`button-outline`), cut to the longest a class\n * name may be.\n */\nfunction blockStyleSlug(blockType: string, name: string): string {\n  const words = sharedStyleSlug(name);\n  if (words === \"\") return \"\";\n  return `${typeSlug(blockType)}-${words}`\n    .slice(0, MAX_NAMED_CLASS_NAME_LENGTH)\n    .replace(/-+$/, \"\");\n}\n\n/** Whether another style of the block type has this name, in any case. */\nfunction nameHeld(\n  library: readonly NamedClass[],\n  blockType: string,\n  label: string,\n  except: string | undefined\n): boolean {\n  return library.some(\n    entry =>\n      entry.id !== except &&\n      isLook(entry) &&\n      entry.blockType === blockType &&\n      sharedStyleName(entry).toLowerCase() === label.toLowerCase()\n  );\n}\n\n/** Why a name can't be a block style's, or `undefined`: none, or one unwritable. */\nfunction labelRefusal(blockType: string, label: string): string | undefined {\n  if (label === \"\") return \"A block style needs a name.\";\n  const issue = tokenLabelIssue(label);\n  if (issue !== undefined) return issue.replace(\"A label\", \"A name\");\n  if (blockStyleSlug(blockType, label) === \"\") {\n    return \"Use at least one letter or digit in the name.\";\n  }\n  return undefined;\n}\n\n/** What a name another style of the type has is told. */\nfunction heldWords(blockTitle: string, label: string): string {\n  return `${blockTitle} already has a style named “${label}”. Choose another name.`;\n}\n\n/**\n * Why a name can't be a new block style of this type, or `undefined`: its\n * name, or the class name it gives, is another style's.\n */\nfunction nameRefusal(\n  library: readonly NamedClass[],\n  blockType: string,\n  label: string,\n  blockTitle: string\n): string | undefined {\n  const refused = labelRefusal(blockType, label);\n  if (refused !== undefined) return refused;\n  const slug = blockStyleSlug(blockType, label);\n  if (\n    nameHeld(library, blockType, label, undefined) ||\n    library.some(entry => entry.slug === slug)\n  ) {\n    return heldWords(blockTitle, label);\n  }\n  return undefined;\n}\n\n/**\n * The next position in the library: after every style, so the new one is\n * last. Text styles are placed the same way.\n */\nexport function nextOrderIndex(library: readonly NamedClass[]): number {\n  return (\n    library.reduce(\n      (max, entry) =>\n        Number.isFinite(entry.orderIndex)\n          ? Math.max(max, entry.orderIndex)\n          : max,\n      -1\n    ) + 1\n  );\n}\n\n/**\n * The block style a block can wear with this id, or `undefined`: none is on\n * the site, or the id is a block's own style, which no block wears.\n */\nfunction wornStyleOf(\n  library: readonly NamedClass[],\n  id: string\n): NamedClass | undefined {\n  const source = library.find(entry => entry.id === id && isLook(entry));\n  return source === undefined || isDefaultLook(source) ? undefined : source;\n}\n\n/**\n * A block's own style, which stores the site's edits to its base: the one\n * the compiler reads for the type, where a library holds more than one.\n */\nfunction ownStyleOf(\n  library: readonly NamedClass[],\n  blockType: string\n): NamedClass | undefined {\n  return ownLooksRead(library).find(entry => entry.blockType === blockType);\n}\n\n/**\n * A class name no style in the library has: the one given, or, where a long\n * name was cut to the same one, that one cut further with `-2`, `-3`… on it.\n * Text styles take theirs the same way.\n */\nexport function unusedSlug(\n  library: readonly NamedClass[],\n  slug: string\n): string {\n  const taken = new Set(library.map(entry => entry.slug));\n  if (!taken.has(slug)) return slug;\n  for (let count = 2; ; count += 1) {\n    const end = `-${count}`;\n    const next = `${slug.slice(0, MAX_NAMED_CLASS_NAME_LENGTH - end.length).replace(/-+$/, \"\")}${end}`;\n    if (!taken.has(next)) return next;\n  }\n}\n\n/** A style the site made, for a block type, with the styles given. */\nfunction siteStyle(\n  library: readonly NamedClass[],\n  blockType: string,\n  label: string,\n  styles: NamedClass[\"styles\"],\n  mintId: () => string\n): NamedClass {\n  return {\n    id: mintId(),\n    slug: unusedSlug(library, blockStyleSlug(blockType, label)),\n    label,\n    orderIndex: nextOrderIndex(library),\n    blockType,\n    // A copy, so an edit to the new style never edits the one it came from.\n    styles: structuredClone(styles),\n  };\n}\n\n/**\n * A new block style for a block type, named by the author, made from the ★\n * style's values: the ★ style's own when one is chosen, else the site's\n * edits to the block's own style, so it starts out looking as a block of\n * that type does until a style is picked.\n */\nexport function newBlockStylePlan(\n  library: readonly NamedClass[],\n  blockType: string,\n  name: string,\n  blockTitle: string,\n  mintId: () => string = newId\n): BlockStylePlan {\n  const label = name.trim();\n  const refusal = nameRefusal(library, blockType, label, blockTitle);\n  if (refusal !== undefined) return { ok: false, reason: refusal };\n  const from =\n    starredStyleOf(library, blockType) ?? ownStyleOf(library, blockType);\n  const entry = siteStyle(\n    library,\n    blockType,\n    label,\n    from?.styles ?? {},\n    mintId\n  );\n  return { ok: true, classes: [...library, entry], id: entry.id };\n}\n\n/** The most copies of one style a copy's name counts to. */\nconst MAX_COPIES = 999;\n\n/**\n * The first \"<name> copy\", \"<name> copy 2\"… no style of the type is named,\n * the name cut so the longest of them is still a name a style may have; or\n * `undefined` once every count is taken. Its class name is made free apart,\n * so two copies of a long name cut to one class name both have one.\n */\nfunction copyName(\n  library: readonly NamedClass[],\n  blockType: string,\n  name: string\n): string | undefined {\n  return firstCopyName(\n    name,\n    candidate =>\n      labelRefusal(blockType, candidate) === undefined &&\n      !nameHeld(library, blockType, candidate, undefined)\n  );\n}\n\n/**\n * The first \"<name> copy\", \"<name> copy 2\"… that `free` accepts, the name\n * cut so the longest of them is still a name a style may have; or\n * `undefined` once every count is taken. A text style's copy is named so too.\n */\nexport function firstCopyName(\n  name: string,\n  free: (candidate: string) => boolean\n): string | undefined {\n  const room = MAX_TOKEN_LABEL_LENGTH - ` copy ${MAX_COPIES}`.length;\n  const base = name.slice(0, room).trimEnd();\n  for (let count = 1; count <= MAX_COPIES; count += 1) {\n    const candidate = count === 1 ? `${base} copy` : `${base} copy ${count}`;\n    if (free(candidate)) return candidate;\n  }\n  return undefined;\n}\n\n/**\n * A copy of a block style, built-in or the site's own, as a style the site\n * made: its values, under the next free \"copy\" name, with none of its marks\n * (★, hidden, locked).\n */\nexport function duplicateBlockStylePlan(\n  library: readonly NamedClass[],\n  id: string,\n  blockTitle: string,\n  mintId: () => string = newId\n): BlockStylePlan {\n  const source = wornStyleOf(library, id);\n  if (source === undefined) return { ok: false, reason: BLOCK_STYLE_GONE };\n  const blockType = source.blockType as string;\n  const label = copyName(library, blockType, sharedStyleName(source));\n  if (label === undefined) {\n    return {\n      ok: false,\n      reason: `${blockTitle} has as many copies of “${sharedStyleName(source)}” as a name can count. Rename one first.`,\n    };\n  }\n  const entry = siteStyle(library, blockType, label, source.styles, mintId);\n  return { ok: true, classes: [...library, entry], id: entry.id };\n}\n\n/**\n * A block style the site made, renamed: its name only. Its id and class name\n * stay, so every document wearing it keeps resolving.\n */\nexport function renameBlockStylePlan(\n  library: readonly NamedClass[],\n  id: string,\n  name: string,\n  blockTitle: string\n): BlockStylePlan {\n  const source = wornStyleOf(library, id);\n  if (source === undefined) return { ok: false, reason: BLOCK_STYLE_GONE };\n  // A lock holds a style's name as well as its values.\n  if (source.locked === true) {\n    return {\n      ok: false,\n      reason: `${sharedStyleName(source)} is locked, so it can't be renamed.`,\n    };\n  }\n  const blockType = source.blockType as string;\n  const label = name.trim();\n  const refused =\n    labelRefusal(blockType, label) ??\n    (nameHeld(library, blockType, label, id)\n      ? heldWords(blockTitle, label)\n      : undefined);\n  if (refused !== undefined) return { ok: false, reason: refused };\n  return {\n    ok: true,\n    classes: library.map(entry =>\n      entry === source ? { ...entry, label } : entry\n    ),\n    id,\n  };\n}\n\n/** A class with one mark set or taken off: present as `true`, never `false`. */\nfunction withMark(\n  entry: NamedClass,\n  mark: \"starred\" | \"hidden\",\n  on: boolean\n): NamedClass {\n  const { [mark]: _was, ...rest } = entry;\n  return on ? { ...rest, [mark]: true } : rest;\n}\n\n/**\n * The library with ★ on one block style of a type, or given back to the\n * block's own style (`id` `null`): every other style of the type loses it,\n * so one style per type carries ★.\n */\nexport function withDefaultBlockStyle(\n  library: readonly NamedClass[],\n  blockType: string,\n  id: string | null\n): NamedClass[] {\n  return library.map(entry => {\n    if (!isLook(entry) || entry.blockType !== blockType) return entry;\n    const starred = entry.id === id && !isDefaultLook(entry);\n    if ((entry.starred === true) === starred) return entry;\n    return withMark(entry, \"starred\", starred);\n  });\n}\n\n/** The library with one block style hidden, or shown again. */\nexport function withHiddenBlockStyle(\n  library: readonly NamedClass[],\n  id: string,\n  hidden: boolean\n): NamedClass[] {\n  return library.map(entry =>\n    entry.id === id && isLook(entry) && (entry.hidden === true) !== hidden\n      ? withMark(entry, \"hidden\", hidden)\n      : entry\n  );\n}\n","/**\n * What the design-token export and import carry beyond the variables: the\n * site's text styles, its Site text rows, colour order, fluid range and\n * built-in colours setting, and which fonts a file uses that the site lacks.\n *\n * The engine writes and reads all of it (`tokensToDtcg`, `dtcgToTokens`);\n * this is the policy around it, as `tokens-transfer` is for the variables:\n * an import MERGES, so a Site text row the file doesn't state keeps the\n * site's, and a text style the site has is changed by its id rather than\n * added beside it; and nothing is applied that the site would refuse to\n * store, said in the author's words instead.\n *\n * @module tokens-transfer-extras\n */\nimport {\n  breakpointContexts,\n  forEachStyleValues,\n  isTextStyle,\n  usableNamedClasses,\n  type BreakpointSet,\n  sameJsonValue,\n  SITE_TEXT_LABELS,\n  SITE_TEXT_ROLES,\n  remapTokenReferences,\n  type DtcgSiteData,\n  type FontFaceDef,\n  type ModesRead,\n  type NamedClass,\n  type SiteToken,\n  type SiteTokenSet,\n  type TokenRemap,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { ClassListEdit } from \"../../styles/block-style-actions\";\nimport { nextOrderIndex } from \"../../styles/block-style-plans\";\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\n\nimport { readStack } from \"./font-library\";\n\n/** What a file's text styles would do to the site's. */\nexport interface TextStylesPlan {\n  /** Text styles the site doesn't have. */\n  readonly added: readonly NamedClass[];\n  /** Text styles the site has, by id, that the file changes. */\n  readonly updated: readonly NamedClass[];\n  /** Text styles the site has exactly as the file does. */\n  readonly unchanged: readonly NamedClass[];\n}\n\n/** What an import carries beyond the variables, as planned. */\nexport interface ImportExtras {\n  /** The site's own design data the file keeps, if any. */\n  readonly site?: DtcgSiteData;\n  readonly textStyles: TextStylesPlan;\n  /**\n   * The font families the file's variables, text styles and Site text\n   * name first that the site has no font file for, in the order met.\n   */\n  readonly missingFonts: readonly string[];\n}\n\n/** What the site holds that an import is planned against. */\nexport interface ImportContext {\n  /**\n   * The site's classes, whose text styles a file's are matched with.\n   * Absent: nothing here can store text styles, so a file's are not\n   * imported, and the preview says so.\n   */\n  readonly textStyles?: readonly NamedClass[];\n  /**\n   * The faces the site loads. Absent: not known, so no font is listed as\n   * missing.\n   */\n  readonly faces?: readonly FontFaceDef[];\n  /**\n   * The site's breakpoints. A text style's values for one the site doesn't\n   * define would never be drawn, so they are left out, and the preview says\n   * which. Absent: not known, so every value is kept.\n   */\n  readonly breakpoints?: BreakpointSet;\n}\n\n/**\n * The file's tokens that merge into a site variable under its id rather\n * than their own (a variable renamed here to the code name the file uses):\n * each one's identity in the file to the id it takes, and the site's\n * prefix, which a `var()` naming one is written with. The engine's\n * {@link TokenRemap}, which a page or component transfer reads through too.\n */\nexport type Adoption = TokenRemap;\n\n/**\n * What an import carries beyond the variables, planned against the site:\n * its site data, its text styles and the fonts it names that the site\n * lacks. Text styles are stored by the host's class writer; where there is\n * none (`context.textStyles` absent) the file's are not imported, and that\n * is said in `refused` rather than counted as imported and dropped. What\n * they and the Site text rows name follows the variables they merge into\n * (`adoption`), and a row following a text style that isn't imported keeps\n * the site's own.\n */\nexport function importExtras(\n  read: Pick<ModesRead, \"tokens\" | \"textStyles\" | \"site\">,\n  context: ImportContext,\n  refused: string[],\n  adoption?: Adoption\n): ImportExtras {\n  // Their values only: a name is the author's words, whatever it reads.\n  const fileStyles = (read.textStyles ?? []).map(style => ({\n    ...style,\n    styles: followingAdoption(style.styles, adoption),\n  }));\n  const fileSite = siteFollowingAdoption(read.site, adoption);\n  if (context.textStyles === undefined && fileStyles.length > 0) {\n    refused.push(\n      fileStyles.length === 1\n        ? \"The file's text style wasn't imported: text styles can only be imported from the editor's Design panel.\"\n        : `The file's ${String(fileStyles.length)} text styles weren't imported: text styles can only be imported from the editor's Design panel.`\n    );\n  }\n  const textStyles = planTextStyles(\n    context.textStyles === undefined ? undefined : fileStyles,\n    context.textStyles ?? [],\n    refused,\n    context.breakpoints\n  );\n  const site = withRowsItCanFollow(fileSite, fileStyles, {\n    library: context.textStyles,\n    plan: textStyles,\n    refused,\n  });\n  return {\n    ...(site === undefined ? {} : { site }),\n    textStyles,\n    missingFonts:\n      context.faces === undefined\n        ? []\n        : missingFonts(read.tokens, fileStyles, fileSite, context.faces),\n  };\n}\n\n/**\n * The file's site data with what it names following the variables they\n * merge into: its rows as {@link followingAdoption} reads them, and each\n * colour in its order, which names a variable by identity.\n */\nfunction siteFollowingAdoption(\n  site: DtcgSiteData | undefined,\n  adoption: Adoption | undefined\n): DtcgSiteData | undefined {\n  if (site === undefined) return undefined;\n  const read = followingAdoption(site, adoption);\n  return read.order === undefined || adoption === undefined\n    ? read\n    : { ...read, order: read.order.map(id => adoption.ids.get(id) ?? id) };\n}\n\n/**\n * A file's text style or site data with each variable it names by an\n * adopted identity, by `$token` or through `var()` of its custom property,\n * pointed at the id that variable takes here: the engine's one remap, built\n * once per import.\n */\nexport function followingAdoption<T>(\n  value: T,\n  adoption: Adoption | undefined\n): T {\n  return adoption === undefined ? value : remapTokenReferences(value, adoption);\n}\n\n/**\n * The file's site data without the Site text rows that would follow a text\n * style the site won't have: one of the file's the import doesn't store,\n * or, where the site's styles are known, any the site doesn't hold. Such a\n * row would follow nothing, so the site's own row is kept, and `refused`\n * names it.\n */\nfunction withRowsItCanFollow(\n  site: DtcgSiteData | undefined,\n  fileStyles: readonly NamedClass[],\n  against: {\n    /** The site's classes, or `undefined` where they aren't known. */\n    library: readonly NamedClass[] | undefined;\n    plan: TextStylesPlan;\n    refused: string[];\n  }\n): DtcgSiteData | undefined {\n  if (site?.siteText === undefined) return site;\n  const { plan, library } = against;\n  const held = new Set(\n    [\n      ...(library ?? []).filter(isTextStyle),\n      ...plan.added,\n      ...plan.updated,\n      ...plan.unchanged,\n    ].map(style => style.id)\n  );\n  const named = new Map(\n    fileStyles.map(style => [style.id, sharedStyleName(style)])\n  );\n  // Where the site's styles aren't known, only the file's own can be judged.\n  const judged = (id: string): boolean =>\n    !held.has(id) && (library !== undefined || named.has(id));\n  const rows: Record<string, unknown> = { ...site.siteText };\n  for (const role of SITE_TEXT_ROLES) {\n    const followed = site.siteText[role]?.textStyle;\n    if (followed === undefined || !judged(followed)) continue;\n    delete rows[role];\n    const name = named.get(followed);\n    against.refused.push(\n      name === undefined\n        ? `Site text: ${SITE_TEXT_LABELS[role]} kept this site's own settings, because the text style it follows isn't on this site.`\n        : `Site text: ${SITE_TEXT_LABELS[role]} kept this site's own settings, because the text style it follows in the file, “${name}”, wasn't imported.`\n    );\n  }\n  const { siteText: _all, ...rest } = site;\n  return Object.keys(rows).length === 0 ? rest : { ...rest, siteText: rows };\n}\n\n/** A file's text styles sorted against the site's, with what is refused. */\nfunction planTextStyles(\n  incoming: readonly NamedClass[] | undefined,\n  library: readonly NamedClass[],\n  refused: string[],\n  breakpoints?: BreakpointSet\n): TextStylesPlan {\n  const plan: Record<keyof TextStylesPlan, NamedClass[]> = {\n    added: [],\n    updated: [],\n    unchanged: [],\n  };\n  const site: SiteStyles = {\n    library,\n    byId: new Map(library.map(entry => [entry.id, entry])),\n    known:\n      breakpoints === undefined\n        ? undefined\n        : new Set(breakpointContexts(breakpoints).map(entry => entry.id)),\n    // Which of the site's classes are drawn now: an import that would stop\n    // one being drawn is refused, as the site's own save would refuse it.\n    drawn: usableNamedClasses(library).map(entry => entry.id),\n  };\n  for (const file of incoming ?? []) {\n    const verdict = textStyleVerdict(file, site, plan);\n    if (verdict.kind === \"refused\") {\n      refused.push(verdict.why);\n      continue;\n    }\n    plan[verdict.kind].push(verdict.style);\n    refused.push(...verdict.notes);\n  }\n  return plan;\n}\n\n/** What a file's text style is planned against: the site's own styles. */\ninterface SiteStyles {\n  readonly library: readonly NamedClass[];\n  readonly byId: ReadonlyMap<string, NamedClass>;\n  /** The site's breakpoint ids, or `undefined` where they aren't known. */\n  readonly known: ReadonlySet<string> | undefined;\n  /** The ids of the site's classes drawn now. */\n  readonly drawn: readonly string[];\n}\n\n/** Where one of a file's text styles goes, or why it doesn't. */\ntype TextStyleVerdict =\n  | { readonly kind: \"refused\"; readonly why: string }\n  | {\n      readonly kind: keyof TextStylesPlan;\n      readonly style: NamedClass;\n      /** What was left out of it, said in the preview. */\n      readonly notes: readonly string[];\n    };\n\n/**\n * One of a file's text styles judged against the site: refused where the\n * site would refuse to store it (an id another kind of style holds, a lock\n * set here, a name or code name taken), else added, updated or unchanged,\n * with the lock this site gives it and without values for breakpoints the\n * site lacks.\n */\nfunction textStyleVerdict(\n  file: NamedClass,\n  site: SiteStyles,\n  planned: { added: readonly NamedClass[]; updated: readonly NamedClass[] }\n): TextStyleVerdict {\n  const name = sharedStyleName(file);\n  const held = site.byId.get(file.id);\n  if (held !== undefined && !isTextStyle(held)) {\n    return {\n      kind: \"refused\",\n      why: `“${name}” was not imported: a style on this site that isn't a text style has the same id.`,\n    };\n  }\n  const notes: string[] = [];\n  // One the site has keeps its place among the site's styles.\n  const placed =\n    held === undefined ? file : { ...file, orderIndex: held.orderIndex };\n  const style = withSiteLock(\n    withinBreakpoints(placed, site.known, name, notes),\n    held\n  );\n  if (held !== undefined && sameJsonValue(held, style)) {\n    return { kind: \"unchanged\", style, notes };\n  }\n  const why = refusalOf(style, name, held, site, planned);\n  if (why !== undefined) return { kind: \"refused\", why };\n  return { kind: held === undefined ? \"added\" : \"updated\", style, notes };\n}\n\n/** Why the site would refuse to store a changed text style, if it would. */\nfunction refusalOf(\n  style: NamedClass,\n  name: string,\n  held: NamedClass | undefined,\n  site: SiteStyles,\n  planned: { added: readonly NamedClass[]; updated: readonly NamedClass[] }\n): string | undefined {\n  // A lock holds on the site that set it: a style locked here is left as\n  // it is until someone unlocks it, as every other write leaves it.\n  if (held?.locked === true) {\n    return `“${name}” is locked on this site, so the file's version was not imported. Unlock it first.`;\n  }\n  const clash = site.library.find(\n    entry =>\n      entry.id !== style.id &&\n      isTextStyle(entry) &&\n      (sharedStyleName(entry).toLowerCase() === name.toLowerCase() ||\n        entry.slug === style.slug)\n  );\n  if (clash !== undefined) {\n    return `There is already a text style named “${sharedStyleName(clash)}” on this site, so “${name}” was not imported.`;\n  }\n  if (drawnTogether(site, planned, style, held === undefined)) {\n    return undefined;\n  }\n  const owner = site.library.find(\n    entry => entry.id !== style.id && entry.slug === style.slug\n  );\n  return owner === undefined\n    ? `“${name}” was not imported: this site couldn't draw it beside its own styles.`\n    : `“${name}” was not imported: a style on this site already uses its code name, “${style.slug}”.`;\n}\n\n/**\n * Whether the site's classes with `style` taken as well are all still\n * drawn, `style` among them: read by the compiler's own claim rules\n * (`usableNamedClasses`), so a code name another style holds, of any kind,\n * is caught as the site's save would catch it.\n */\nfunction drawnTogether(\n  site: SiteStyles,\n  planned: { added: readonly NamedClass[]; updated: readonly NamedClass[] },\n  style: NamedClass,\n  isNew: boolean\n): boolean {\n  const trial = textStylesEdit({\n    added: isNew ? [...planned.added, style] : planned.added,\n    updated: isNew ? planned.updated : [...planned.updated, style],\n    unchanged: [],\n  })(site.library);\n  if (!(\"classes\" in trial)) return false;\n  const now = new Set(usableNamedClasses(trial.classes).map(entry => entry.id));\n  return [\n    ...site.drawn,\n    ...planned.added.map(entry => entry.id),\n    style.id,\n  ].every(id => now.has(id));\n}\n\n/**\n * A text style with the lock this site gives it: a new one arrives unlocked\n * (a lock is set on each site, through its own route), and one the site has\n * keeps the site's lock as it is.\n */\nfunction withSiteLock(\n  style: NamedClass,\n  held: NamedClass | undefined\n): NamedClass {\n  const rest: NamedClass = { ...style };\n  delete rest.locked;\n  return held?.locked === true ? { ...rest, locked: true } : rest;\n}\n\n/**\n * A text style without its values for breakpoints the site doesn't define,\n * nor the fluid sizes they were made from, each one left out said in\n * `notes`. Unchanged where the site's breakpoints aren't known.\n */\nfunction withinBreakpoints(\n  style: NamedClass,\n  known: ReadonlySet<string> | undefined,\n  name: string,\n  notes: string[]\n): NamedClass {\n  if (known === undefined) return style;\n  const left = new Set<string>();\n  const styles: Record<string, unknown> = {};\n  for (const [state, byBreakpoint] of Object.entries(style.styles)) {\n    if (byBreakpoint === null || typeof byBreakpoint !== \"object\") {\n      styles[state] = byBreakpoint;\n      continue;\n    }\n    const kept: Record<string, unknown> = {};\n    for (const [breakpoint, values] of Object.entries(byBreakpoint)) {\n      if (known.has(breakpoint)) kept[breakpoint] = values;\n      else left.add(breakpoint);\n    }\n    styles[state] = kept;\n  }\n  if (left.size === 0) return style;\n  for (const breakpoint of left) {\n    notes.push(\n      `“${name}”'s values for the “${breakpoint}” breakpoint were left out: this site has no such breakpoint.`\n    );\n  }\n  return withoutFluidSizesAt({ ...style, styles }, left);\n}\n\n/**\n * A text style without the fluid sizes of the breakpoints `left`, whose\n * values were left out: sizes beside no size would be taken for the ones a\n * size typed there later was made from.\n */\nfunction withoutFluidSizesAt(\n  style: NamedClass,\n  left: ReadonlySet<string>\n): NamedClass {\n  const { fluidSizes, ...rest } = style;\n  const sizes = Object.entries(fluidSizes ?? {}).filter(\n    ([breakpoint]) => !left.has(breakpoint)\n  );\n  return sizes.length === 0\n    ? rest\n    : { ...rest, fluidSizes: Object.fromEntries(sizes) };\n}\n\n/**\n * The class edit that stores a planned import's text styles, composed\n * against the site's classes at the moment it is stored: one it has, by id,\n * is replaced where it stands, and a new one is added after every class.\n */\nexport function textStylesEdit(plan: TextStylesPlan): ClassListEdit {\n  return existing => {\n    const replaced = new Map(plan.updated.map(style => [style.id, style]));\n    const classes = existing.map(entry =>\n      isTextStyle(entry) ? (replaced.get(entry.id) ?? entry) : entry\n    );\n    const held = new Set(classes.map(entry => entry.id));\n    let next = nextOrderIndex(classes);\n    // An update whose style was removed meanwhile is stored as new, so what\n    // the import says it stored is stored.\n    for (const style of [...plan.added, ...plan.updated]) {\n      if (held.has(style.id)) continue;\n      classes.push({ ...style, orderIndex: next });\n      next += 1;\n    }\n    return { classes };\n  };\n}\n\n/** How many text styles a planned import stores. */\nexport function textStylesTaken(plan: TextStylesPlan): number {\n  return plan.added.length + plan.updated.length;\n}\n\n/**\n * The site's set with a file's own design data laid over it: each Site text\n * row the file states replaces the site's, and the rest stay; the order, the\n * fluid range and the built-in colours setting are the file's where it\n * states them.\n */\nexport function withSiteData(\n  into: SiteTokenSet,\n  site: DtcgSiteData | undefined\n): SiteTokenSet {\n  if (site === undefined) return into;\n  return {\n    ...into,\n    ...(site.siteText === undefined\n      ? {}\n      : { siteText: { ...into.siteText, ...site.siteText } }),\n    ...(site.order === undefined ? {} : { order: site.order }),\n    ...(site.fluidRange === undefined ? {} : { fluidRange: site.fluidRange }),\n    ...(site.builtInColoursShown === undefined\n      ? {}\n      : { builtInColoursShown: site.builtInColoursShown }),\n  };\n}\n\n/** Whether laying a file's design data over the site's changes anything. */\nexport function siteDataChanges(\n  into: SiteTokenSet,\n  site: DtcgSiteData | undefined\n): boolean {\n  if (site === undefined) return false;\n  const after = withSiteData(into, site);\n  return (\n    !sameJsonValue(after.siteText ?? null, into.siteText ?? null) ||\n    !sameJsonValue(after.order ?? null, into.order ?? null) ||\n    !sameJsonValue(after.fluidRange ?? null, into.fluidRange ?? null) ||\n    after.builtInColoursShown !== into.builtInColoursShown\n  );\n}\n\n/**\n * What a file's design data is, line by line, for the import's preview:\n * \"Site text: Body, Heading 2\", \"Colour order\", \"Fluid range: 320–1440px\".\n */\nexport function siteDataLines(site: DtcgSiteData | undefined): string[] {\n  if (site === undefined) return [];\n  const lines: string[] = [];\n  if (site.siteText !== undefined) {\n    const rows = SITE_TEXT_ROLES.filter(role =>\n      Object.hasOwn(site.siteText ?? {}, role)\n    ).map(role => SITE_TEXT_LABELS[role]);\n    if (rows.length > 0) lines.push(`Site text: ${rows.join(\", \")}`);\n  }\n  if (site.order !== undefined) lines.push(\"The order of your colours\");\n  if (site.fluidRange !== undefined) {\n    lines.push(\n      `Fluid sizes grow from ${String(site.fluidRange.min)}px to ${String(site.fluidRange.max)}px wide`\n    );\n  }\n  if (site.builtInColoursShown !== undefined) {\n    lines.push(\n      site.builtInColoursShown\n        ? \"Built-in colours are shown\"\n        : \"Built-in colours are hidden\"\n    );\n  }\n  return lines;\n}\n\n/**\n * The families a file's fonts name first that none of the site's faces\n * provides: from its font variables (light and dark), its text styles and\n * its Site text rows. A generic family (`serif`) and a font through\n * `var()` are never missing.\n */\nfunction missingFonts(\n  tokens: readonly SiteToken[],\n  textStyles: readonly NamedClass[],\n  site: DtcgSiteData | undefined,\n  faces: readonly FontFaceDef[]\n): string[] {\n  const values: string[] = [];\n  for (const token of tokens) {\n    if (token.kind !== \"fontFamily\") continue;\n    values.push(token.values.light);\n    if (token.values.dark !== undefined) values.push(token.values.dark);\n  }\n  for (const style of textStyles) {\n    forEachStyleValues(style.styles, (_breakpoint, styleValues) => {\n      const family = (styleValues as { fontFamily?: unknown } | undefined)\n        ?.fontFamily;\n      if (typeof family === \"string\") values.push(family);\n    });\n  }\n  for (const row of Object.values(site?.siteText ?? {})) {\n    if (typeof row?.fontFamily === \"string\") values.push(row.fontFamily);\n  }\n  const missing = new Map<string, string>();\n  for (const value of values) {\n    const first = readStack(value, faces).firstChoice;\n    if (first?.source !== \"not-provided\") continue;\n    const key = first.family.toLowerCase();\n    if (!missing.has(key)) missing.set(key, first.family);\n  }\n  return [...missing.values()];\n}\n","/**\n * The list \"What wasn't exported\" shows after an export: each variable or\n * text style a file did not write as other tools read it, what happened to\n * it, and why, in an author's words rather than the engine's.\n *\n * @module tokens-transfer-gaps\n */\nimport {\n  tokenDisplayLabel,\n  type NamedClass,\n  type SiteToken,\n  type SiteTokenSet,\n  type TokenKind,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { DESIGN_ACTION_WORDS } from \"../../editor-words\";\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\n\n/** One variable a file did not write as other tools read it, and why. */\nexport interface ExportGap {\n  /** Its code name; absent for a report that names no variable. */\n  readonly name?: string;\n  /** The name an author sees it by. */\n  readonly label?: string;\n  /**\n   * `kept`: written only as Nextly data, which Nextly reads back exactly and\n   * other tools skip. `left-out`: not in the file at all. `without-data`: in\n   * the file with its value, but without vendor data a file cannot hold.\n   */\n  readonly outcome: \"kept\" | \"left-out\" | \"without-data\";\n  /** Why, in plain words. */\n  readonly why: string;\n}\n\n/** Why the token file keeps a text style only as Nextly data. */\nexport const TEXT_STYLE_KEPT_WHY =\n  \"Design tools can't read this text style as it is written.\";\n\n/**\n * A text style in \"What wasn't exported\", under its name, apart from every\n * variable's code name by the group the file writes text styles under.\n */\nexport function textStyleGap(\n  style: NamedClass,\n  outcome: ExportGap[\"outcome\"],\n  why: string\n): ExportGap {\n  return {\n    name: `textStyles.${style.slug}`,\n    label: sharedStyleName(style),\n    outcome,\n    why,\n  };\n}\n\n/**\n * An export's report as the list \"What wasn't exported\" shows: each variable\n * by its name, what happened to it, and why, in plain words.\n *\n * Each engine sentence starts with the quoted code name of the variable it is\n * about, which is how it is matched to its variable; one naming none (a whole\n * file that could not be written) keeps its words and names no variable.\n */\nexport function gapsOf(\n  tokens: SiteTokenSet,\n  skipped: readonly string[],\n  kept: readonly string[],\n  lost: readonly string[] = []\n): ExportGap[] {\n  const byName = new Map(tokens.tokens.map(token => [token.name, token]));\n  const gaps: ExportGap[] = [\n    ...skipped.map(message => gapNamedBy(tokens, message, \"left-out\")),\n    ...lost.map(message => gapNamedBy(tokens, message, \"without-data\")),\n  ];\n  for (const name of kept) {\n    const token = byName.get(name);\n    if (token === undefined) continue;\n    gaps.push({\n      name,\n      label: tokenDisplayLabel(token),\n      outcome: \"kept\",\n      why: KEPT_WHY[token.kind],\n    });\n  }\n  return gaps;\n}\n\n/** One engine sentence as a row of the list, under the variable it names. */\nfunction gapNamedBy(\n  tokens: SiteTokenSet,\n  message: string,\n  outcome: ExportGap[\"outcome\"]\n): ExportGap {\n  const token = aboutWhich(tokens.tokens, message);\n  if (token === undefined) return { outcome, why: message };\n  return {\n    name: token.name,\n    label: tokenDisplayLabel(token),\n    outcome,\n    why: plainWhy(message.slice(token.name.length + 3)),\n  };\n}\n\n/**\n * The variable an engine sentence is about: the one whose quoted code name\n * opens it. The longest such name wins, so `\"space.4\"` is not read as being\n * about a variable called `space`.\n */\nexport function aboutWhich(\n  tokens: readonly SiteToken[],\n  message: string\n): SiteToken | undefined {\n  let found: SiteToken | undefined;\n  for (const token of tokens) {\n    if (!message.startsWith(`\"${token.name}\" `)) continue;\n    if (found === undefined || token.name.length > found.name.length) {\n      found = token;\n    }\n  }\n  return found;\n}\n\n/**\n * Why a file left a variable out, in an author's words, from the rest of the\n * engine's sentence after the variable's name.\n *\n * The engine's sentences are written for a developer reading a report (\"token\n * name\", \"vendor data\"); a designer reading the list needs what the tool takes\n * instead. A sentence not listed here keeps the engine's words, with \"token\"\n * said as \"variable\", so a reason added there later still reads.\n */\nfunction plainWhy(rest: string): string {\n  for (const [pattern, words] of PLAIN_WHY) {\n    const match = pattern.exec(rest);\n    if (match !== null) return typeof words === \"string\" ? words : words(match);\n  }\n  const sentence = rest\n    .replace(/,? so it was (?:not exported|left out of the Figma files)/, \"\")\n    .replace(/ It was left out of the Figma files\\.$/, \"\")\n    .replace(/\\btokens?\\b/g, word =>\n      word === \"token\" ? \"variable\" : \"variables\"\n    );\n  return `It ${sentence}`;\n}\n\nconst PLAIN_WHY: readonly (readonly [\n  RegExp,\n  string | ((match: RegExpExecArray) => string),\n])[] = [\n  [/^is a shadow\\./, DESIGN_ACTION_WORDS.figmaStyles],\n  [\n    /^carries vendor data that a file cannot hold/,\n    \"It holds data from another tool that a file can't store, so the file has its value but not that data. Importing the file back treats it as a new variable.\",\n  ],\n  [\n    /^is a size Figma cannot read/,\n    \"Figma takes sizes in px or rem, and fluid sizes that end in px or rem.\",\n  ],\n  [\n    /^is a colour Figma cannot read/,\n    \"Figma takes colours written as hex or rgb().\",\n  ],\n  [\n    /^is not a list of font names Figma can read/,\n    \"Figma takes a font as a list of font names.\",\n  ],\n  [/^names no font family Figma can read/, \"It names no font Figma can use.\"],\n  [\n    /^is a font weight Figma cannot read/,\n    \"Figma takes a font weight as a number, normal or bold.\",\n  ],\n  [/^is not a plain number/, \"Figma takes a plain number here.\"],\n  [/^is a duration Figma cannot read/, \"Figma takes durations in ms or s.\"],\n  [\n    /^sits where another variable's group is/,\n    \"Another variable's group already uses this name.\",\n  ],\n  [/^is nested too deeply/, \"Its code name has too many parts.\"],\n  [\n    /^is written under more than (\\d+) characters/,\n    match => `Its code name is longer than ${match[1] ?? \"\"} characters.`,\n  ],\n  [/^is not a token name/, \"Its code name can't be written to a file.\"],\n  [\n    /^has an id that is not a token name/,\n    \"Its stored id can't be written to a file. Its value is still here in Nextly.\",\n  ],\n  [\n    /^is exported more than once/,\n    \"Another variable has the same code name, so only one was written.\",\n  ],\n  [\n    /^cannot be exported, because \"([^\"]+)\" is already a token/,\n    match =>\n      `\"${match[1] ?? \"\"}\" is a variable, so nothing can sit under its name.`,\n  ],\n  [\n    /^carries vendor data that a file cannot hold/,\n    \"Data another tool stored on it can't be written to a file. Imported back, it would arrive as a new variable.\",\n  ],\n];\n\n/**\n * Why the token file keeps a variable only as Nextly data, by its kind: the\n * format types a value of that kind only in some forms, and this one is not\n * among them.\n */\nexport const KEPT_WHY: Readonly<Record<TokenKind, string>> = {\n  color: \"Design tools can't read this colour as it is written.\",\n  dimension: \"Design tools take sizes in px or rem only.\",\n  fontFamily: \"Design tools can't read this font list as it is written.\",\n  fontWeight: \"Design tools can't read this font weight as it is written.\",\n  number: \"Design tools can't read this number as it is written.\",\n  shadow: \"Design tools can't read a shadow from this file.\",\n  duration: \"Design tools take durations in ms or s only.\",\n  custom: \"A custom value has no type design tools read.\",\n};\n","/**\n * What of an import's text styles and Site text can land, judged against\n * the variables the merge actually takes. A file's variable can be refused\n * (a name another variable here holds under another id); a text style or\n * a row using it would then read nothing, and the site's guard refuses a\n * text style naming a variable it doesn't hold, which would refuse the\n * whole class save. So each is left out instead, the site's own row kept,\n * and named; the rest still land. So is a text style naming, by `$token`, a\n * variable neither the file nor the site holds, which the same guard\n * refuses.\n *\n * @module tokens-transfer-reach\n */\nimport {\n  resolveSiteTokens,\n  resolveTokenPrefix,\n  SITE_TEXT_LABELS,\n  SITE_TEXT_ROLES,\n  siteTextUses,\n  tokenCustomProperty,\n  tokenIdentity,\n  type DtcgSiteData,\n  type NamedClass,\n  type SiteTextMap,\n  type SiteTextRole,\n  type SiteToken,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\n\nimport type { ImportExtras } from \"./tokens-transfer-extras\";\n\n/**\n * The import's extras without the text styles and Site text rows that use\n * one of the file's variables `merged` doesn't hold, nor the rows following\n * a text style left out; each named in `refused`.\n */\nexport function reachingVariables(\n  extras: ImportExtras,\n  incoming: readonly SiteToken[],\n  merged: SiteTokenSet,\n  refused: string[]\n): ImportExtras {\n  const prefix = resolveTokenPrefix(merged.prefix).prefix;\n  const keys = (token: SiteToken): string[] => [\n    tokenIdentity(token),\n    tokenCustomProperty(tokenIdentity(token), prefix),\n  ];\n  // By identity: a property another variable here also writes doesn't\n  // make the file's variable land.\n  const landed = new Set(merged.tokens.map(tokenIdentity));\n  const owners = new Map(\n    incoming.flatMap(token => keys(token).map(key => [key, token] as const))\n  );\n  // The name of a variable of the file's that didn't land, for a key.\n  const missing = (key: string): string | undefined => {\n    const owner = owners.get(key);\n    return owner === undefined || landed.has(tokenIdentity(owner))\n      ? undefined\n      : owner.name;\n  };\n  // Every variable the site will hold, its built-in ones included, as the\n  // site's guard judges a text style's `$token` against them.\n  const held = new Set(resolveSiteTokens(merged).tokens.map(tokenIdentity));\n  // A `$token` naming no variable of the file's or the site's. A `var()`\n  // property is CSS the site draws or not, and no guard judges it.\n  const unknown = (key: string): boolean =>\n    !key.startsWith(\"--\") && !owners.has(key) && !held.has(key);\n  const left = new Map<string, string>();\n  const keep = (style: NamedClass): boolean => {\n    const keys = keysUsed(style.styles);\n    const name = keys.map(missing).find(found => found !== undefined);\n    const nowhere = name === undefined ? keys.find(unknown) : undefined;\n    if (name === undefined && nowhere === undefined) return true;\n    left.set(style.id, sharedStyleName(style));\n    refused.push(\n      name === undefined\n        ? `“${sharedStyleName(style)}” was not imported: a variable it uses, “${nowhere ?? \"\"}”, isn't on this site or in the file.`\n        : `“${sharedStyleName(style)}” was not imported: a variable it uses, “${name}”, wasn't imported.`\n    );\n    return false;\n  };\n  const { textStyles } = extras;\n  const kept = {\n    added: textStyles.added.filter(keep),\n    updated: textStyles.updated.filter(keep),\n    unchanged: textStyles.unchanged,\n  };\n  const { site: before, ...rest } = extras;\n  const site = rowsThatReach(before, missing, left, refused);\n  return { ...rest, textStyles: kept, ...(site === undefined ? {} : { site }) };\n}\n\n/**\n * The site data without the rows that follow a text style left out\n * (`left`, by id) or use a variable that didn't land, each named.\n */\nfunction rowsThatReach(\n  site: DtcgSiteData | undefined,\n  missing: (key: string) => string | undefined,\n  left: ReadonlyMap<string, string>,\n  refused: string[]\n): DtcgSiteData | undefined {\n  if (site?.siteText === undefined) return site;\n  const why = reasonsByRow(site.siteText, missing, left);\n  if (why.size === 0) return site;\n  const rows: Record<string, unknown> = { ...site.siteText };\n  for (const [role, reason] of why) {\n    delete rows[role];\n    refused.push(\n      `Site text: ${SITE_TEXT_LABELS[role]} kept this site's own settings, because ${reason}.`\n    );\n  }\n  const { siteText: _all, ...rest } = site;\n  return Object.keys(rows).length === 0 ? rest : { ...rest, siteText: rows };\n}\n\n/** Why each row that can't land can't: the text style or the variable. */\nfunction reasonsByRow(\n  rows: SiteTextMap,\n  missing: (key: string) => string | undefined,\n  left: ReadonlyMap<string, string>\n): Map<SiteTextRole, string> {\n  const why = new Map<SiteTextRole, string>();\n  for (const role of SITE_TEXT_ROLES) {\n    const style = left.get(rows[role]?.textStyle ?? \"\");\n    if (style === undefined) continue;\n    why.set(\n      role,\n      `the text style it follows in the file, “${style}”, wasn't imported`\n    );\n  }\n  for (const [key, roles] of siteTextUses(rows)) {\n    const name = missing(key);\n    if (name === undefined) continue;\n    for (const role of roles.filter(entry => !why.has(entry))) {\n      why.set(role, `a variable it uses, “${name}”, wasn't imported`);\n    }\n  }\n  return why;\n}\n\n/** The variables a text style's values name: `$token` ids and `var()` properties. */\nfunction keysUsed(value: unknown): string[] {\n  if (typeof value === \"string\") {\n    return [...value.matchAll(/var\\(\\s*(--[A-Za-z0-9_-]+)/g)].map(\n      match => match[1] ?? \"\"\n    );\n  }\n  if (Array.isArray(value)) return value.flatMap(keysUsed);\n  if (value === null || typeof value !== \"object\") return [];\n  return Object.entries(value).flatMap(([key, entry]) =>\n    key === \"$token\" && typeof entry === \"string\" ? [entry] : keysUsed(entry)\n  );\n}\n","/**\n * Taking a token table out of this site, and bringing one in.\n *\n * A thin layer over the engine's `tokensToDtcg` and `dtcgToTokens`, which do\n * the conversion and already do the hard half of it: they REPORT what they\n * could not carry rather than dropping it in silence. That report is the whole\n * value of the pair — a designer handed a file with three tokens missing has no\n * way to know, and the ones that go missing are the interesting ones — so\n * everything here is arranged so the caller cannot accidentally throw it away.\n *\n * ## Import MERGES, and merges on identity\n *\n * A file adds tokens and changes the ones it names; it never removes what it\n * does not mention. Replacing the table would silently delete tokens that\n * blocks across the site still reference, with the page still rendering and no\n * error anywhere — an outcome nothing here could undo.\n *\n * Merged on IDENTITY rather than on name, because that is what a reference\n * stores and what every other tier merge in this system keys on. Keyed on the\n * name, a file naming a token the site has renamed would arrive as a second\n * entry beside it, and the two would collide on the one custom property they\n * both compose.\n *\n * ## A partial file imports partially\n *\n * The engine maps seven `$type`s and the format defines more — `typography`,\n * `transition`, `gradient` and the rest have no kind here — so a file exported\n * from a design tool usually contains entries this site cannot hold. Refusing\n * the whole file for them would mean import almost never succeeds, and the\n * author could not repair it without editing the file by hand. What comes in is\n * what fits; what did not is named, with the engine's own reason.\n *\n * @module tokens-transfer\n */\nimport {\n  isPlainRecord,\n  dtcgToTokens,\n  emitTokenBlocks,\n  modeFilesToTokens,\n  NEXTLY_EXTENSION,\n  resolverToTokens,\n  resolveTokenPrefix,\n  sameSiteToken,\n  tokensToFigma,\n  tokensToResolver,\n  tokenCustomProperty,\n  tokenDisplayLabel,\n  tokenIdentity,\n  tokensToDtcg,\n  isTextStyle,\n  classesAcrossFluidRange,\n  DEFAULT_FLUID_RANGE,\n  type DtcgSiteData,\n  type ModesRead,\n  type NamedClass,\n  type SiteToken,\n  type SiteTextMap,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { DESIGN_ACTION_WORDS } from \"../../editor-words\";\nimport type { ClassListEdit } from \"../../styles/block-style-actions\";\n\nimport { labelClashes, setFluidRange } from \"./tokens-studio\";\nimport {\n  followingAdoption,\n  importExtras,\n  type Adoption,\n  siteDataChanges,\n  textStylesEdit,\n  textStylesTaken,\n  withSiteData,\n  type ImportContext,\n  type ImportExtras,\n} from \"./tokens-transfer-extras\";\nimport {\n  aboutWhich,\n  gapsOf,\n  KEPT_WHY,\n  TEXT_STYLE_KEPT_WHY,\n  textStyleGap,\n  type ExportGap,\n} from \"./tokens-transfer-gaps\";\nimport { reachingVariables } from \"./tokens-transfer-reach\";\n\nexport type { ExportGap } from \"./tokens-transfer-gaps\";\n\n/** What an import did, or why it could not begin. */\nexport type ImportResult =\n  | {\n      readonly ok: true;\n      /** The whole table, with the file merged into it. */\n      readonly tokens: SiteTokenSet;\n      /** How many tokens the file contributed, added or changed. */\n      readonly imported: number;\n      /** What the file held that this site cannot, in the engine's words. */\n      readonly skipped: readonly string[];\n      /** How many text styles the import stores, through {@link classes}. */\n      readonly textStyles?: number;\n      /**\n       * The class edit that stores the file's text styles, for the host's\n       * one class writer. Absent when there are none to store.\n       */\n      readonly classes?: ClassListEdit;\n      /**\n       * The file's Site text rows the import takes, which a host storing it\n       * in steps lays over the rows as they are by then.\n       */\n      readonly rows?: SiteTextMap;\n    }\n  | {\n      readonly ok: false;\n      /** Why nothing could be read at all. */\n      readonly error: string;\n      /** Anything the engine said on the way, which may explain the refusal. */\n      readonly skipped: readonly string[];\n    };\n\n/**\n * A design-token document merged into the table this site already has.\n *\n * The text is parsed HERE rather than handed to the engine as a string, because\n * \"this is not JSON\" and \"this is JSON but not a token document\" are different\n * failures with different repairs — one is a corrupt or truncated file, the\n * other is the wrong file — and a single message covering both sends the author\n * to look in the wrong place.\n */\nexport function importDtcg(text: string, into: SiteTokenSet): ImportResult {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(text) as unknown;\n  } catch {\n    return {\n      ok: false,\n      error:\n        \"That file is not valid JSON, so nothing in it could be read. It may be truncated or may not be a token file at all.\",\n      skipped: [],\n    };\n  }\n\n  let read: ReturnType<typeof dtcgToTokens>;\n  try {\n    read = dtcgToTokens(parsed);\n  } catch {\n    /*\n     * The conversion walks the document recursively, so a deeply nested one —\n     * a few thousand groups, which is tens of kilobytes of file — exhausts the\n     * stack. A `RangeError` is not something a caller can act on, and this is\n     * the import BOUNDARY: everything past it is a panel that would let the\n     * rejection escape into a discarded promise, showing nothing and stopping\n     * silently. Turned into the refusal every other failure here returns.\n     */\n    return {\n      ok: false,\n      error:\n        \"That file is nested too deeply to read. A design-token file groups its tokens a few levels deep; this one goes thousands.\",\n      skipped: [],\n    };\n  }\n  // Everything the file held that this site did not keep is the READER's to say,\n  // at the point it passes each part over, so it is carried through whole\n  // rather than supplemented by a second look at the same document.\n  const skipped = read.issues.map(issue => issue.message);\n  if (read.tokens.length === 0) {\n    return {\n      ok: false,\n      error:\n        \"No tokens in that file could be used by this site. Nothing was changed.\",\n      skipped,\n    };\n  }\n  const merged = mergeById(into, read.tokens);\n  return {\n    ok: true,\n    tokens: merged.tokens,\n    // What SURVIVED, not what the file held. A file can name one token twice —\n    // two entries carrying one identity — and only the last of them lands, so\n    // counting the file's entries would claim an arrival that did not happen.\n    imported: merged.landed,\n    skipped: [...skipped, ...merged.refused],\n  };\n}\n\n/** One chosen file, as text. */\nexport interface ImportFile {\n  readonly name: string;\n  readonly text: string;\n}\n\n/** A token the file and the site both hold, with values that clash. */\nexport interface ImportConflict {\n  readonly identity: string;\n  readonly mine: SiteToken;\n  readonly imported: SiteToken;\n  /** Each field the two state differently, in words, for the preview. */\n  readonly fields: readonly ConflictField[];\n}\n\n/** One field a conflict differs in: the site's value and the file's. */\nexport interface ConflictField {\n  readonly field: string;\n  readonly mine: string;\n  readonly imported: string;\n}\n\n/** What an import WOULD do, shown to the author before anything changes. */\nexport type ImportPlan =\n  | {\n      readonly ok: true;\n      /** Tokens the site does not have. */\n      readonly added: readonly SiteToken[];\n      /**\n       * Tokens the file changes without contradicting the site: a dark value,\n       * a label or a description the site's token lacks, or another tool's\n       * data on it.\n       */\n      readonly changed: readonly SiteToken[];\n      readonly unchanged: readonly SiteToken[];\n      /** Tokens whose values clash, each settled by the author: keep or use. */\n      readonly conflicts: readonly ImportConflict[];\n      /**\n       * Names the import would give to more than one variable. Applying such\n       * an import is refused, so the preview says which before it is tried.\n       */\n      readonly labelClashes: readonly string[];\n      /** What the files held that this site cannot, in the engine's words. */\n      readonly skipped: readonly string[];\n      /** Every token read, in file order, for {@link applyImport}. */\n      readonly incoming: readonly SiteToken[];\n      /** What the files carry beyond the variables. */\n      readonly extras: ImportExtras;\n    }\n  | {\n      readonly ok: false;\n      readonly error: string;\n      readonly skipped: readonly string[];\n    };\n\n/** The author's answer to one conflict. */\nexport type ConflictChoice = \"keep\" | \"use\";\n\n/**\n * The files an author chose, read and compared with the site, changing nothing.\n *\n * Three shapes are read: a theme (resolver) file with the token files it\n * names, one file per mode as Figma exports them, or a single token file.\n * Aliases are resolved by the engine as each file is read.\n */\nexport function planImport(\n  files: readonly ImportFile[],\n  into: SiteTokenSet,\n  context: ImportContext = {}\n): ImportPlan {\n  const parsed: { name: string; document: unknown }[] = [];\n  for (const file of files) {\n    try {\n      parsed.push({\n        name: file.name,\n        document: JSON.parse(file.text) as unknown,\n      });\n    } catch {\n      return {\n        ok: false,\n        error: `${file.name} is not valid JSON, so nothing was imported. It may be truncated or may not be a token file at all.`,\n        skipped: [],\n      };\n    }\n  }\n  let read: ModesRead;\n  try {\n    read = readChosen(parsed);\n  } catch {\n    // The reader walks the file recursively; see `importDtcg`.\n    return {\n      ok: false,\n      error:\n        \"That file is nested too deeply to read. A design-token file groups its tokens a few levels deep; this one goes thousands.\",\n      skipped: [],\n    };\n  }\n  const skipped = read.issues.map(entry => entry.message);\n  const refusedStyles: string[] = [];\n  const adopted = adoptedIds(read.tokens, into);\n  const adoption: Adoption = {\n    ids: adopted,\n    // The file's variables and this site's: a reference may name either.\n    identities: [\n      ...new Set([...read.tokens, ...into.tokens].map(tokenIdentity)),\n    ],\n    from: resolveTokenPrefix(read.site?.prefix).prefix,\n    to: resolveTokenPrefix(into.prefix).prefix,\n  };\n  // The file's own values name each other through `var()` too (a shadow\n  // its colour), so they follow the same map as its text styles and rows.\n  const tokens = read.tokens.map(token => ({\n    ...token,\n    values: followingAdoption(token.values, adoption),\n  }));\n  const extras = importExtras(\n    withTextStylesAcrossRangeOf(read, into),\n    context,\n    refusedStyles,\n    adoption\n  );\n  const { textStyles } = extras;\n  const carriesMore =\n    read.site !== undefined ||\n    textStyles.added.length +\n      textStyles.updated.length +\n      textStyles.unchanged.length >\n      0;\n  if (read.tokens.length === 0 && !carriesMore) {\n    return {\n      ok: false,\n      error:\n        \"No variables in those files could be used by this site. Nothing was changed.\",\n      skipped: [...skipped, ...refusedStyles],\n    };\n  }\n  // One entry per identity, chosen once, so the preview shows exactly what\n  // applying will merge: the last of two entries sharing an identity, with\n  // the first reported.\n  const dropped: string[] = [];\n  const unique = [...oneEach(withStoredIds(tokens, adopted), dropped).values()];\n  // Rows using a variable the merge would refuse keep the site's own,\n  // judged against every incoming variable taken; applying judges again\n  // against what the author's choices take.\n  const rowsLeft: string[] = [];\n  const reached = reachingVariables(\n    extras,\n    unique,\n    mergeById(withFluidRangeOf(into, extras.site), unique).tokens,\n    rowsLeft\n  );\n  return {\n    ok: true,\n    skipped: [...skipped, ...refusedStyles, ...dropped, ...rowsLeft],\n    ...planned(unique, into),\n    extras: reached,\n  };\n}\n\n/**\n * The site's variables with its own fluid sizes remade across the fluid\n * range a file states, as the site's own range change remakes them, so a\n * size the file doesn't restate keeps matching the range stored with it.\n * Unchanged where the file states no range, or the site's own.\n */\nfunction withFluidRangeOf(\n  into: SiteTokenSet,\n  site: DtcgSiteData | undefined\n): SiteTokenSet {\n  const range = site?.fluidRange;\n  if (range === undefined) return into;\n  const current = into.fluidRange ?? DEFAULT_FLUID_RANGE;\n  if (current.min === range.min && current.max === range.max) return into;\n  return setFluidRange(into, range);\n}\n\n/**\n * The file's text styles with each fluid size made again across this site's\n * fluid range, where the file states no range and this site's is another.\n *\n * A file states the range of the site that wrote it, unless that site used\n * the default one. The engine keeps a text style's fluid sizes only beside\n * the size they make across that range (`dtcgToTokens`), and an import that\n * states a range brings it here, so the sizes go on making the size. A file\n * that states none leaves this site's range as it is: each such size is made\n * again across it from its sizes, as this site's own text styles are, so the\n * style follows the range here too. The server would make it again on\n * arrival anyway, as it does for every save that sets new fluid sizes; made\n * here, the preview shows what is stored.\n */\nfunction withTextStylesAcrossRangeOf(\n  read: ModesRead,\n  into: SiteTokenSet\n): ModesRead {\n  if (read.textStyles === undefined || read.site?.fluidRange !== undefined) {\n    return read;\n  }\n  const across = classesAcrossFluidRange(\n    read.textStyles,\n    DEFAULT_FLUID_RANGE,\n    into.fluidRange ?? DEFAULT_FLUID_RANGE\n  );\n  return across === read.textStyles\n    ? read\n    : { ...read, textStyles: [...across] };\n}\n\n/**\n * The file's tokens sorted against the site, with the names the import would\n * give to more than one variable if every conflict took the file's side.\n */\nfunction planned(\n  incoming: readonly SiteToken[],\n  into: SiteTokenSet\n): ReturnType<typeof sortAgainst> & { labelClashes: string[] } {\n  const sorted = sortAgainst(incoming, into);\n  return {\n    ...sorted,\n    labelClashes: newLabelClashes(\n      into,\n      mergeById(into, sorted.incoming).tokens\n    ),\n  };\n}\n\n/**\n * Names shown for more than one variable once an import is merged, other than\n * those the site already shared before it: a name a site already uses twice\n * is not the import's doing.\n */\nfunction newLabelClashes(before: SiteTokenSet, after: SiteTokenSet): string[] {\n  const had = new Set(labelClashes(before).map(name => name.toLowerCase()));\n  return labelClashes(after).filter(name => !had.has(name.toLowerCase()));\n}\n\n/** Which reader the chosen files call for. */\nfunction readChosen(\n  parsed: readonly { name: string; document: unknown }[]\n): ModesRead {\n  const theme = parsed.find(file => isThemeFile(file.document));\n  if (theme !== undefined) {\n    const others = new Map(\n      parsed\n        .filter(file => file !== theme)\n        .map(file => [file.name, file.document])\n    );\n    return resolverToTokens(theme.document, others);\n  }\n  if (parsed.length > 1) return modeFilesToTokens(parsed);\n  return dtcgToTokens(parsed[0]?.document);\n}\n\n/** A DTCG Resolver document: it resolves sets and modifiers in an order. */\nfunction isThemeFile(document: unknown): boolean {\n  return (\n    isPlainRecord(document) &&\n    typeof document.version === \"string\" &&\n    Array.isArray(document.resolutionOrder)\n  );\n}\n\n/** The file's tokens sorted by how they meet the site's, matched on identity. */\nfunction sortAgainst(\n  incoming: readonly SiteToken[],\n  into: SiteTokenSet\n): Pick<\n  Extract<ImportPlan, { ok: true }>,\n  \"added\" | \"changed\" | \"unchanged\" | \"conflicts\" | \"incoming\"\n> {\n  const mine = new Map(into.tokens.map(token => [tokenIdentity(token), token]));\n  const added: SiteToken[] = [];\n  const changed: SiteToken[] = [];\n  const unchanged: SiteToken[] = [];\n  const conflicts: ImportConflict[] = [];\n  const laid: SiteToken[] = [];\n  for (const stated of incoming) {\n    const identity = tokenIdentity(stated);\n    const held = mine.get(identity);\n    // What applying would store: the file's token laid onto the site's.\n    const imported = held === undefined ? stated : laidOnto(held, stated);\n    laid.push(imported);\n    if (held === undefined) {\n      added.push(imported);\n      continue;\n    }\n    const fields = conflictFields(held, imported);\n    if (fields.length > 0) {\n      conflicts.push({ identity, mine: held, imported, fields });\n    } else if (sameSiteToken(held, imported)) {\n      // Asked of the token applying would store, with the engine's one\n      // comparison, vendor data included: another tool's metadata arriving\n      // is a change, and a field the file merely leaves out is not.\n      unchanged.push(imported);\n    } else changed.push(imported);\n  }\n  return { added, changed, unchanged, conflicts, incoming: laid };\n}\n\n/**\n * A file's token laid onto the site's: a field the file states replaces the\n * stored one, and an optional field it leaves out (a dark value, a label, a\n * description, another tool's data) keeps the stored value rather than being\n * deleted by an import that never mentioned it.\n */\nfunction laidOnto(held: SiteToken, stated: SiteToken): SiteToken {\n  const dark = stated.values.dark ?? held.values.dark;\n  // The sizes a fluid size was made from belong to its value: a file that\n  // changes the value without them leaves a size typed by hand.\n  const fluid =\n    stated.fluid ??\n    (stated.values.light === held.values.light ? held.fluid : undefined);\n  return {\n    ...keptOptional(held, stated),\n    name: stated.name,\n    kind: stated.kind,\n    values:\n      dark === undefined\n        ? { light: stated.values.light }\n        : { light: stated.values.light, dark },\n    ...(fluid === undefined ? {} : { fluid }),\n  };\n}\n\n/** The optional fields a file's token may leave out, and the site's keep. */\nconst OPTIONAL_FIELDS = [\n  \"id\",\n  \"label\",\n  \"group\",\n  \"description\",\n  \"extensions\",\n  \"unreadExtension\",\n] as const;\n\n/** Each optional field the file states, else the site's, else none. */\nfunction keptOptional(\n  held: SiteToken,\n  stated: SiteToken\n): Pick<SiteToken, (typeof OPTIONAL_FIELDS)[number]> {\n  const kept: Partial<Record<(typeof OPTIONAL_FIELDS)[number], unknown>> = {};\n  for (const field of OPTIONAL_FIELDS) {\n    const value = stated[field] ?? held[field];\n    if (value !== undefined) kept[field] = value;\n  }\n  return kept as Pick<SiteToken, (typeof OPTIONAL_FIELDS)[number]>;\n}\n\n/**\n * The file's tokens, each one that states no id given the id of the site's\n * variable it names.\n *\n * A file from another tool, Figma's above all, carries names only. A variable\n * renamed here keeps its old name as its id, so matching that file by identity\n * would read the renamed variable as new and then refuse it for taking the\n * name. A token the file gives no id is matched by name instead, unless its\n * name is itself another variable's identity, which a stated identity wins.\n */\nfunction withStoredIds(\n  incoming: readonly SiteToken[],\n  adopted: ReadonlyMap<string, string>\n): SiteToken[] {\n  return incoming.map(token => {\n    const id = token.id === undefined ? adopted.get(token.name) : undefined;\n    return id === undefined ? token : { ...token, id };\n  });\n}\n\n/**\n * Which of the file's tokens take a site variable's id (see\n * {@link withStoredIds}): each one's identity in the file, its name, to the\n * id it takes here. What the file's text styles and Site text name by that\n * identity follows the same map, so they reach the variable it merged into.\n */\nfunction adoptedIds(\n  incoming: readonly SiteToken[],\n  into: SiteTokenSet\n): Map<string, string> {\n  const identities = new Set(into.tokens.map(tokenIdentity));\n  const byName = new Map(into.tokens.map(token => [token.name, token]));\n  const adopted = new Map<string, string>();\n  for (const token of incoming) {\n    if (token.id !== undefined || identities.has(token.name)) continue;\n    const held = byName.get(token.name)?.id;\n    if (held !== undefined) adopted.set(token.name, held);\n  }\n  return adopted;\n}\n\n/** Whether both sides state something and the statements differ. */\nfunction differs(\n  mine: string | undefined,\n  theirs: string | undefined\n): boolean {\n  return mine !== undefined && theirs !== undefined && mine !== theirs;\n}\n\n/**\n * Each field the site's variable and the file's state differently. Kind, code\n * name and light value always count; dark value, name and description count\n * only where both state one, since one side leaving a field unset is the file\n * filling it in rather than contradicting it.\n */\nfunction conflictFields(mine: SiteToken, imported: SiteToken): ConflictField[] {\n  const fields: ConflictField[] = [];\n  const note = (field: string, a: string | undefined, b: string | undefined) =>\n    fields.push({ field, mine: a ?? \"none\", imported: b ?? \"none\" });\n  if (mine.kind !== imported.kind) note(\"Kind\", mine.kind, imported.kind);\n  if (mine.name !== imported.name) note(\"Code name\", mine.name, imported.name);\n  if (mine.values.light !== imported.values.light) {\n    note(\"Light\", mine.values.light, imported.values.light);\n  }\n  if (differs(mine.values.dark, imported.values.dark)) {\n    note(\"Dark\", mine.values.dark, imported.values.dark);\n  }\n  if (differs(mine.label, imported.label)) {\n    note(\"Name\", mine.label, imported.label);\n  }\n  if (differs(mine.description, imported.description)) {\n    note(\"Description\", mine.description, imported.description);\n  }\n  return fields;\n}\n\n/**\n * A planned import applied to the site's tokens as they are NOW.\n *\n * A conflict the author chose to keep is left as the site has it; every other\n * token from the files is merged in, an unanswered conflict taking the file's\n * side. `into` is asked for at apply time rather than taken from the plan,\n * because the author may have edited a variable while the preview was open.\n */\nexport function applyImport(\n  plan: Extract<ImportPlan, { ok: true }>,\n  into: SiteTokenSet,\n  choices: ReadonlyMap<string, ConflictChoice>\n): ImportResult {\n  // Only what changes the site is applied and counted: a variable the file\n  // holds unchanged, or a conflict kept as the site has it, is no change, and\n  // merging it would spend a save and claim an arrival that did not happen.\n  const standing = new Set([\n    ...plan.unchanged.map(tokenIdentity),\n    ...plan.conflicts\n      .filter(conflict => choices.get(conflict.identity) === \"keep\")\n      .map(conflict => conflict.identity),\n  ]);\n  const taken = plan.incoming.filter(\n    token => !standing.has(tokenIdentity(token))\n  );\n  const styles = textStylesTaken(plan.extras.textStyles);\n  const siteChanges = siteDataChanges(into, plan.extras.site);\n  if (taken.length === 0 && styles === 0 && !siteChanges) {\n    return {\n      ok: false,\n      error:\n        \"Nothing in those files would change this site's design, so nothing was changed.\",\n      skipped: plan.skipped,\n    };\n  }\n  const merged = mergeById(withFluidRangeOf(into, plan.extras.site), taken);\n  // Judged again against what the author's choices take.\n  const rowsLeft: string[] = [];\n  const reached = reachingVariables(\n    plan.extras,\n    plan.incoming,\n    merged.tokens,\n    rowsLeft\n  );\n  const stored = textStylesTaken(reached.textStyles);\n  // Refused rather than saved: two variables under one name cannot be told\n  // apart in the panel, and the site's own edits are held to the same rule.\n  const clashing = newLabelClashes(into, merged.tokens);\n  if (clashing.length > 0) {\n    return {\n      ok: false,\n      error: `This import would give two variables the same name: ${clashing\n        .map(name => `\"${name}\"`)\n        .join(\n          \", \"\n        )}. Keep this site's version of one of them, or rename one first.`,\n      skipped: plan.skipped,\n    };\n  }\n  return {\n    ok: true,\n    // The site's own design data laid over the merged variables, so the two\n    // save, merge and undo as one edit.\n    tokens: withSiteData(merged.tokens, reached.site),\n    imported: merged.landed,\n    skipped: [...plan.skipped, ...merged.refused, ...rowsLeft],\n    ...(reached.site?.siteText === undefined\n      ? {}\n      : { rows: reached.site.siteText }),\n    ...(stored === 0\n      ? {}\n      : {\n          textStyles: stored,\n          classes: textStylesEdit(reached.textStyles),\n        }),\n  };\n}\n\n/**\n * The table with `incoming` layered over it, matched on identity.\n *\n * Order is preserved for what was already there, and new tokens are appended,\n * so an import does not reshuffle a table the author has been reading. A token\n * the file names keeps its POSITION and takes the file's content.\n */\nfunction mergeById(\n  into: SiteTokenSet,\n  incoming: readonly SiteToken[]\n): { tokens: SiteTokenSet; landed: number; refused: string[] } {\n  const refused: string[] = [];\n  const wanted = oneEach(incoming, refused);\n\n  /*\n   * Conflicts are judged against the table as it WOULD be with everything\n   * applied, not against a destination mutated entry by entry.\n   *\n   * Incrementally, the answer depends on the order the file happens to list its\n   * tokens: a file renaming `a` to `beta` and `b` to `gamma` imports both if\n   * `b` comes first and only one if `a` does, because `beta` is still taken at\n   * the moment `a` is considered. Coordinated renames are ordinary — a design\n   * tool emits them whenever someone reorganises a palette — and half-applying\n   * one is worse than refusing it, because the half that lands is a rename the\n   * author did not ask for on its own.\n   *\n   * Judged REPEATEDLY, because a refusal can free what it was blocking: a token\n   * whose only clash is with another incoming token that must itself be refused\n   * is perfectly importable once that one is gone. One pass would discard it for\n   * a conflict that does not survive the pass. Each round removes at least one\n   * token, so this terminates in at most as many rounds as the file has tokens,\n   * and in practice in one.\n   */\n  const taken = new Map(wanted);\n  resolveClashes(into, taken, refused);\n\n  return {\n    tokens: { ...into, tokens: applyAll(into.tokens, taken) },\n    landed: taken.size,\n    refused,\n  };\n}\n\n/**\n * One incoming token per identity, with the duplicates named.\n *\n * A file can name one token twice. `dtcgToTokens` returns both, because two\n * DTCG paths are two entries — but they compose one custom property here, so\n * only the last can be carried forward. Reported rather than dropped in\n * silence: two tokens going in and one arriving is precisely the loss this\n * feature exists to show.\n *\n * The message names which of the two was DROPPED and never says the other\n * landed, because this choice is made before any clash is judged and the\n * survivor can still be refused afterwards. Claiming it arrived produced a\n * report that contradicted itself on the same import — \"only `taken` was\n * taken\" beside \"`taken` was not imported\".\n */\nfunction oneEach(\n  incoming: readonly SiteToken[],\n  refused: string[]\n): Map<string, SiteToken> {\n  const wanted = new Map<string, SiteToken>();\n  for (const token of incoming) {\n    const identity = tokenIdentity(token);\n    const first = wanted.get(identity);\n    if (first !== undefined) {\n      refused.push(\n        `\"${first.name}\" and \"${token.name}\" are one token in that file — both carry the identity \"${identity}\" — so \"${first.name}\" was dropped in favour of \"${token.name}\".`\n      );\n    }\n    wanted.set(identity, token);\n  }\n  return wanted;\n}\n\n/**\n * The destination with every wanted token applied, replacing or appending.\n *\n * The destination is indexed ONCE rather than searched per incoming token. A\n * scan inside the loop makes the whole import quadratic, and it runs on the\n * main thread while the studio is open: measured at roughly 1.3 seconds for\n * five thousand tokens, 4.7 for ten thousand and 18 for twenty thousand, with\n * the editor unresponsive throughout. A design system that large is unusual and\n * a generated one is not.\n */\nfunction applyAll(\n  base: readonly SiteToken[],\n  wanted: ReadonlyMap<string, SiteToken>\n): SiteToken[] {\n  const tokens = [...base];\n  const at = new Map<string, number>();\n  tokens.forEach((token, index) => {\n    // First wins, matching the emitter: where a table already holds two entries\n    // under one identity, a replacement lands on the one that would be written.\n    if (!at.has(tokenIdentity(token))) at.set(tokenIdentity(token), index);\n  });\n  for (const [identity, token] of wanted) {\n    const index = at.get(identity);\n    if (index === undefined) {\n      at.set(identity, tokens.length);\n      tokens.push(token);\n    } else {\n      tokens[index] = token;\n    }\n  }\n  return tokens;\n}\n\n/**\n * Where every proposed row sits, so a refusal can be judged without a rescan.\n *\n * Refusing a rename does not remove its row — it puts the STORED row back, and\n * that row's own name can collide with something still accepted. Judging that\n * by re-reading the whole table once per refusal is quadratic, and a file whose\n * renames form a long chain is exactly the shape that makes it so: measured at\n * 24ms for 250 tokens, 70 for 500, 269 for 1000 and 1082 for 2000, on the main\n * thread with the studio open.\n *\n * Indexed instead, because the consequences of a refusal are LOCAL: it can only\n * disturb the keys the restored row occupies. A custom property is composed\n * from the identity, which a refusal does not change, so those cannot cascade\n * at all and are settled once.\n */\ninterface Placement {\n  /** identity -> the row currently proposed for it. */\n  readonly row: Map<string, SiteToken>;\n  /** an exact name -> the identities holding it. */\n  readonly named: Map<string, Set<string>>;\n  /** a group path -> the identities whose name is nested below it. */\n  readonly below: Map<string, Set<string>>;\n  /** a composed custom property -> the identities composing it. */\n  readonly property: Map<string, Set<string>>;\n}\n\n/** Every group path a name passes through on its way to its last segment. */\nfunction ancestorsOf(name: string): string[] {\n  const segments = name.split(\".\");\n  const found: string[] = [];\n  for (let cut = 1; cut < segments.length; cut++) {\n    found.push(segments.slice(0, cut).join(\".\"));\n  }\n  return found;\n}\n\nfunction hold(index: Map<string, Set<string>>, key: string, who: string): void {\n  const held = index.get(key);\n  if (held === undefined) index.set(key, new Set([who]));\n  else held.add(who);\n}\n\nfunction release(\n  index: Map<string, Set<string>>,\n  key: string,\n  who: string\n): void {\n  const held = index.get(key);\n  if (held === undefined) return;\n  held.delete(who);\n  if (held.size === 0) index.delete(key);\n}\n\n/** Put a row into every index that can report a conflict about it. */\nfunction occupy(at: Placement, token: SiteToken): void {\n  const identity = tokenIdentity(token);\n  at.row.set(identity, token);\n  hold(at.named, token.name, identity);\n  for (const above of ancestorsOf(token.name)) hold(at.below, above, identity);\n  // The prefix is the same string in front of every property, so it can neither\n  // create a collision nor prevent one — the same reason the studio's own\n  // collision check composes without it.\n  hold(at.property, tokenCustomProperty(identity, \"\"), identity);\n}\n\n/** Take a row back out of every index, leaving its identity unplaced. */\nfunction vacate(at: Placement, identity: string): void {\n  const token = at.row.get(identity);\n  if (token === undefined) return;\n  at.row.delete(identity);\n  release(at.named, token.name, identity);\n  for (const above of ancestorsOf(token.name)) {\n    release(at.below, above, identity);\n  }\n  release(at.property, tokenCustomProperty(identity, \"\"), identity);\n}\n\n/** One key some rows are fighting over, and which pass may settle it. */\ninterface Key {\n  readonly kind: \"name\" | \"property\";\n  readonly value: string;\n}\n\n/**\n * Who is fighting over one key, and what each of them should be told.\n *\n * A name carries TWO constraints and a row can break both at once, so the\n * wording is per participant rather than per key: two rows with the same name\n * are duplicates, and a row named `brand` beside one named `brand.main` asks\n * `brand` to be a token and a group at the same time.\n */\nfunction contestAt(\n  at: Placement,\n  key: Key\n): { holders: Set<string>; say: (identity: string) => string } | undefined {\n  if (key.kind === \"property\") {\n    const holders = at.property.get(key.value);\n    if (holders === undefined || holders.size < 2) return undefined;\n    return {\n      holders,\n      say: identity =>\n        `\"${at.row.get(identity)?.name ?? identity}\" and another token here both become \"${key.value}\", so it was not imported. Two tokens cannot share one custom property.`,\n    };\n  }\n  const same = at.named.get(key.value) ?? new Set<string>();\n  const nested = at.below.get(key.value) ?? new Set<string>();\n  const duplicated = same.size > 1;\n  const straddled = same.size > 0 && nested.size > 0;\n  if (!duplicated && !straddled) return undefined;\n  return {\n    holders: new Set([...same, ...nested]),\n    say: identity =>\n      same.has(identity) && duplicated\n        ? `\"${key.value}\" is already the name of a different token on this site, so it was not imported. Rename one of them and try again.`\n        : `\"${at.row.get(identity)?.name ?? identity}\" cannot be imported beside \"${key.value}\", which is a token on this site too. A design-token file writes \"${key.value}\" as either a token or a group holding others, never both, so a file exported with these two would lose one of them.`,\n  };\n}\n\n/**\n * Refuse one incoming row, put the site's own back, and say where to look next.\n *\n * The restored row is not going to move again — it is what the site already\n * had — so every conflict it creates is a forced one, which is why the cascade\n * never has to revisit the mutual pass.\n */\nfunction revert(\n  at: Placement,\n  taken: Map<string, SiteToken>,\n  stored: ReadonlyMap<string, SiteToken>,\n  identity: string,\n  work: Key[]\n): void {\n  taken.delete(identity);\n  vacate(at, identity);\n  const back = stored.get(identity);\n  if (back === undefined) return;\n  occupy(at, back);\n  work.push({ kind: \"name\", value: back.name });\n  for (const above of ancestorsOf(back.name)) {\n    work.push({ kind: \"name\", value: above });\n  }\n}\n\n/**\n * Settle every conflict of ONE kind reachable from a worklist.\n *\n * `forced` means at least one row in the fight cannot move: the destination is\n * not going to give the name up, so the refusal is unavoidable. Anything else\n * is incoming rows clashing only with EACH OTHER, and those are left until the\n * forced ones have finished, because a forced refusal can free a name and make\n * a mutual clash disappear. Refusing both halves first would discard an import\n * that a moment later had nothing wrong with it.\n */\nfunction settle(\n  at: Placement,\n  taken: Map<string, SiteToken>,\n  stored: ReadonlyMap<string, SiteToken>,\n  refused: string[],\n  mode: \"forced\" | \"mutual\",\n  work: Key[]\n): void {\n  while (work.length > 0) {\n    const key = work.pop();\n    if (key === undefined) continue;\n    const fight = contestAt(at, key);\n    if (fight === undefined) continue;\n    // Only INCOMING rows can be refused. A clash the destination already had is\n    // not this file's doing, and refusing the import for it would leave an\n    // author unable to bring anything in until they had repaired something\n    // else entirely.\n    const movable = [...fight.holders].filter(identity => taken.has(identity));\n    if (movable.length === 0) continue;\n    if (movable.length < fight.holders.size !== (mode === \"forced\")) continue;\n    for (const identity of movable) {\n      refused.push(fight.say(identity));\n      revert(at, taken, stored, identity, work);\n    }\n  }\n}\n\n/** Every key some rows are currently fighting over. */\nfunction contestedKeys(at: Placement): Key[] {\n  const found: Key[] = [];\n  for (const [value, holders] of at.named) {\n    if (holders.size > 1 || at.below.has(value)) {\n      found.push({ kind: \"name\", value });\n    }\n  }\n  for (const [value, holders] of at.property) {\n    if (holders.size > 1) found.push({ kind: \"property\", value });\n  }\n  return found;\n}\n\n/**\n * Remove from `taken` every incoming token the result could not hold, naming it.\n *\n * Three passes, and the order between them is the whole point. Forced refusals\n * first, because they are unavoidable and can FREE a name that some other\n * incoming token was only blocked by. Then the mutual ones, which by that point\n * are tokens clashing with each other and nothing else — a file that\n * contradicts itself, where there is no ground to prefer either, so both are\n * refused and both are named. Then forced once more, because a mutual refusal\n * also puts a stored row back.\n *\n * A fourth pass cannot be needed. Refusing a token only ever ADDS an immovable\n * row to a key, so any conflict that appears afterwards has an immovable\n * participant and is forced by construction; and freeing a key never creates a\n * conflict at all.\n */\nfunction resolveClashes(\n  into: SiteTokenSet,\n  taken: Map<string, SiteToken>,\n  refused: string[]\n): void {\n  const stored = new Map<string, SiteToken>();\n  for (const token of into.tokens) {\n    // First wins, matching the emitter and `applyAll`: where a table already\n    // holds one identity twice, the row the emitter would write is the row\n    // this judges.\n    const identity = tokenIdentity(token);\n    if (!stored.has(identity)) stored.set(identity, token);\n  }\n  const at: Placement = {\n    row: new Map(),\n    named: new Map(),\n    below: new Map(),\n    property: new Map(),\n  };\n  for (const token of applyAll(into.tokens, taken)) {\n    if (!at.row.has(tokenIdentity(token))) occupy(at, token);\n  }\n  settle(at, taken, stored, refused, \"forced\", contestedKeys(at));\n  settle(at, taken, stored, refused, \"mutual\", contestedKeys(at));\n  settle(at, taken, stored, refused, \"forced\", contestedKeys(at));\n}\n\n/** A file this site can hand to another tool, and what it could not carry. */\nexport interface ExportResult {\n  readonly text: string;\n  /** The file name to offer, which is part of the artefact rather than chrome. */\n  readonly filename: string;\n  /**\n   * What the file holds, in words, for the message that says it was saved: a\n   * file name alone does not tell an author which file holds what.\n   */\n  readonly label: string;\n  readonly mime: string;\n  /** Tokens the format could not represent, in the engine's words. */\n  readonly skipped: readonly string[];\n  /**\n   * The same report in the author's words, one entry per variable, with the\n   * variables the file keeps only as Nextly data beside the ones it left out:\n   * the list \"What wasn't exported\" shows.\n   */\n  readonly gaps: readonly ExportGap[];\n}\n\n/**\n * The site's tokens as a design-token document.\n *\n * Pretty-printed rather than minified: the artefact is read by people and lands\n * in version control, where a diff over one line per token is the difference\n * between a reviewable change and an opaque one.\n */\nexport function exportDtcg(\n  tokens: SiteTokenSet,\n  classes: readonly NamedClass[] = []\n): ExportResult {\n  let skipped: string[];\n  let refused: string[];\n  let lost: string[];\n  let text: string;\n  let kept: readonly string[];\n  let stylesKept: readonly NamedClass[];\n  try {\n    /*\n     * EVERY step that reads the vendor data is inside this guard, the\n     * conversion included. Each was moved in separately after being found to\n     * touch the same untrusted values one step earlier than the last: the\n     * write reaches them through `JSON.stringify`, the preflight walks them\n     * first, and `tokensToDtcg` SPREADS `token.extensions` before either runs,\n     * so an enumerable getter that throws is read there. The boundary is the\n     * whole export rather than any one of its steps, which is what stops a\n     * line added later from landing outside it.\n     */\n    const textStyles = classes.filter(isTextStyle);\n    const { document, issues, keptTextStyles } = tokensToDtcg(tokens, {\n      textStyles,\n    });\n    // Kept apart for the list: a variable the engine refused is not in the\n    // file, while one whose vendor data cannot be written still is.\n    refused = issues.map(issue => issue.message);\n    lost = unwritable(tokens);\n    skipped = [...refused, ...lost];\n    kept = carriedNames(document);\n    stylesKept = textStyles.filter(style => keptTextStyles.includes(style.id));\n    text = `${JSON.stringify(document, null, 2)}\\n`;\n  } catch {\n    /*\n     * `SiteToken.extensions` is `Record<string, unknown>` and carries vendor\n     * data untouched, which is what the format asks for — and a site's own\n     * TypeScript config can put a `bigint`, a cycle or a throwing `toJSON` in\n     * there. `tokensToDtcg` copies it faithfully and `JSON.stringify` then\n     * throws, out of a click handler, so nothing downloads and nothing is\n     * said.\n     *\n     * Answered with an empty artefact and a reason rather than a throw: the\n     * caller downloads what it is given, so a file that cannot be written has\n     * to arrive here as a report.\n     */\n    const skipped = [\n      \"This site's tokens carry vendor data that cannot be written to a file — a value JSON has no form for, such as a very large number or a structure that refers to itself. Nothing was exported.\",\n    ];\n    return {\n      text: \"\",\n      filename: \"tokens.json\",\n      label: \"variables\",\n      mime: \"application/json\",\n      /*\n       * The engine's own issues are absent here deliberately: the conversion\n       * that produces them is inside the guard, so a failure during it leaves\n       * nothing to report but this. Naming issues from a conversion that did\n       * not finish would be reporting a list nobody produced.\n       */\n      skipped,\n      gaps: gapsOf(tokens, skipped, []),\n    };\n  }\n  return {\n    text,\n    filename: \"tokens.json\",\n    label: \"variables\",\n    mime: \"application/json\",\n    skipped,\n    gaps: [\n      ...gapsOf(tokens, refused, kept, lost),\n      ...stylesKept.map(style =>\n        textStyleGap(style, \"kept\", TEXT_STYLE_KEPT_WHY)\n      ),\n    ],\n  };\n}\n\n/**\n * The variables a token file holds only in Nextly's own extension: the ones\n * the format has no type for, written exactly so Nextly reads them back, and\n * skipped by every other tool. The engine writes them without a report, since\n * nothing is lost to Nextly, so they are read off the document it wrote.\n */\nfunction carriedNames(document: Record<string, unknown>): string[] {\n  const root = document[\"$extensions\"];\n  const own = isPlainRecord(root) ? root[NEXTLY_EXTENSION] : undefined;\n  // `variables` is the file format's key for them, which Nextly's importer\n  // reads back; a key in the files people keep, so it does not move.\n  const carried = isPlainRecord(own) ? own[\"variables\"] : undefined;\n  return isPlainRecord(carried) ? Object.keys(carried) : [];\n}\n\n/** The file name a DTCG export is saved under, and its theme file's. */\nconst DTCG_FILE = \"variables.tokens.json\";\nconst THEME_FILE = \"variables.resolver.json\";\n\n/**\n * The DTCG export: the token file, and beside it a theme file when any\n * variable has a dark value, so a tool reading the standard finds the modes.\n */\nexport function exportDtcgWithTheme(\n  tokens: SiteTokenSet,\n  classes: readonly NamedClass[] = []\n): ExportResult[] {\n  const main = { ...exportDtcg(tokens, classes), filename: DTCG_FILE };\n  if (\n    main.text === \"\" ||\n    !tokens.tokens.some(token => token.values.dark !== undefined)\n  ) {\n    return [main];\n  }\n  const theme = tokensToResolver(tokens, DTCG_FILE);\n  const themeSkipped = theme.issues.map(entry => entry.message);\n  return [\n    main,\n    {\n      text: `${JSON.stringify(theme.resolver, null, 2)}\\n`,\n      filename: THEME_FILE,\n      // It holds the dark values the format can type, which a file name\n      // ending in \"resolver\" does not say; the token file's extension holds\n      // every dark value exactly.\n      label: \"dark values in a theme file\",\n      mime: \"application/json\",\n      skipped: themeSkipped,\n      gaps: [\n        ...gapsOf(tokens, themeSkipped, []),\n        ...darkValuesKept(tokens, theme.resolver, themeSkipped, main.gaps),\n      ],\n    },\n  ];\n}\n\n/**\n * The variables whose dark value only the token file's Nextly data holds.\n *\n * The engine writes a dark value the format has no type for into the token\n * file's own extension and leaves it out of the theme file without a report,\n * since Nextly reads it back exactly. A variable whose light value IS typed\n * is in the token file as other tools read it, so nothing else names it, yet\n * those tools have no dark value for it and use the light one in dark mode.\n * Read off the theme file the engine wrote rather than worked out again here,\n * so what this names is what the file holds. A variable the token file\n * already names, or the theme file refused, is not named a second time.\n */\nfunction darkValuesKept(\n  tokens: SiteTokenSet,\n  resolver: unknown,\n  skipped: readonly string[],\n  named: readonly ExportGap[]\n): ExportGap[] {\n  const written = darkDocumentOf(resolver);\n  const elsewhere = new Set<string>(\n    named.flatMap(gap => (gap.name === undefined ? [] : [gap.name]))\n  );\n  for (const message of skipped) {\n    const token = aboutWhich(tokens.tokens, message);\n    if (token !== undefined) elsewhere.add(token.name);\n  }\n  return tokens.tokens.flatMap(token =>\n    token.values.dark === undefined ||\n    elsewhere.has(token.name) ||\n    holdsTokenAt(written, token.name)\n      ? []\n      : [\n          {\n            name: token.name,\n            label: tokenDisplayLabel(token),\n            outcome: \"kept\" as const,\n            why: `${DARK_KEPT_WHY} ${KEPT_WHY[token.kind]}`,\n          },\n        ]\n  );\n}\n\n/** What a dark value kept only as Nextly data means for other tools. */\nconst DARK_KEPT_WHY =\n  \"Its dark value is kept for Nextly only, so design tools use its light value in dark mode.\";\n\n/** The token tree a theme file gives its `dark` context, if it has one. */\nfunction darkDocumentOf(resolver: unknown): unknown {\n  const modifiers = isPlainRecord(resolver) ? resolver[\"modifiers\"] : undefined;\n  if (!isPlainRecord(modifiers)) return undefined;\n  for (const modifier of Object.values(modifiers)) {\n    const contexts = isPlainRecord(modifier) ? modifier[\"contexts\"] : undefined;\n    const dark = isPlainRecord(contexts) ? contexts[\"dark\"] : undefined;\n    if (Array.isArray(dark)) return dark[0];\n  }\n  return undefined;\n}\n\n/** Whether a token tree holds a token at a dotted name's path. */\nfunction holdsTokenAt(tree: unknown, name: string): boolean {\n  let node = tree;\n  for (const segment of name.split(\".\")) {\n    if (!isPlainRecord(node) || !Object.hasOwn(node, segment)) return false;\n    node = node[segment];\n  }\n  return isPlainRecord(node) && \"$value\" in node;\n}\n\n/**\n * The For Figma export: one file per mode, each holding every variable, as\n * Figma's variables import asks. What Figma cannot hold is named once, on the\n * light file: shadows and text styles among it, which Figma keeps as effect\n * styles and text styles, built on the variables the files hold.\n */\nexport function exportForFigma(\n  tokens: SiteTokenSet,\n  classes: readonly NamedClass[] = []\n): ExportResult[] {\n  const textStyles = classes.filter(isTextStyle);\n  return ([\"light\", \"dark\"] as const).map(mode => {\n    const made = tokensToFigma(tokens, mode);\n    const empty = Object.keys(made.document).length === 0;\n    const skipped =\n      mode === \"light\" ? made.issues.map(entry => entry.message) : [];\n    return {\n      text: empty ? \"\" : `${JSON.stringify(made.document, null, 2)}\\n`,\n      filename: `${mode}.tokens.json`,\n      label: `${mode} mode`,\n      mime: \"application/json\",\n      skipped,\n      gaps: [\n        ...gapsOf(tokens, skipped, []),\n        ...(mode === \"light\"\n          ? textStyles.map(style =>\n              textStyleGap(style, \"left-out\", DESIGN_ACTION_WORDS.figmaStyles)\n            )\n          : []),\n      ],\n    };\n  });\n}\n\n/**\n * Tokens whose vendor data will not survive being written, named.\n *\n * A THROWING value is caught where the file is built. This is the quieter case:\n * `JSON.stringify` succeeds and drops things on the way — a function, a symbol,\n * an `undefined`, a `toJSON` returning nothing — so the check cannot be \"did it\n * throw\". Everything it drops it drops SILENTLY, and one of the things riding\n * in `$extensions` is this system's own record of a token's stable identity and\n * exact CSS. Lose that and the file stops being round-trippable: importing it\n * back gives the token a new identity, and every document referencing the old\n * one stops resolving.\n *\n * Asked as \"is this made only of things a file can hold\" rather than by writing\n * it and comparing what comes back. The ALLOWLIST is the sound direction here:\n * what JSON can carry is closed and fixed by its grammar, while what it cannot\n * grows with the language — a check built from the second list goes quiet about\n * whatever was added since someone last looked at it.\n */\nfunction unwritable(tokens: SiteTokenSet): string[] {\n  const lost: string[] = [];\n  for (const token of tokens.tokens) {\n    // BOTH halves of what rides in `$extensions`, because they reach the file\n    // by the same route and fail the same way: `tokensToDtcg` spreads each into\n    // an object `JSON.stringify` then writes. A `toJSON` inside either is the\n    // worst of it — spread into a block, it replaces that whole block, and for\n    // the preserved half the block it replaces is this system's own record of\n    // the token's identity and exact CSS.\n    const carried = [token.extensions, token.unreadExtension].filter(\n      part => part !== undefined\n    );\n    if (carried.every(part => holdsOnlyJson(part))) continue;\n    lost.push(\n      `\"${token.name}\" carries vendor data that a file cannot hold, so the exported token is missing it. Importing this file back would give that token a different identity.`\n    );\n  }\n  return lost;\n}\n\n/**\n * Whether a value is made only of what a JSON file can carry.\n *\n * `toJSON` counts as cannot: it means the written form is something other than\n * the value, so what a reader gets back is not what was stored — which is the\n * loss being looked for, whether or not the substitute is itself writable.\n *\n * A non-finite number is refused for the same reason rather than as pedantry:\n * `NaN` and the infinities are written as `null`, so the value silently becomes\n * a different one.\n */\nfunction holdsOnlyJson(value: unknown, seen = new Set<unknown>()): boolean {\n  if (isJsonLeaf(value)) return true;\n  if (typeof value !== \"object\" || value === null) return false;\n  /*\n   * A cycle is not something a file can hold either, but it is reported where\n   * writing THROWS rather than here — so what this needs from it is only not to\n   * follow it forever. Without the set this walk recurses until the stack goes,\n   * which is the failure it was written to prevent, one level up.\n   */\n  if (seen.has(value)) return true;\n  seen.add(value);\n  /*\n   * `toJSON` BEFORE the branch below, because it belongs to any object: an\n   * array can carry one exactly as a record can, and `JSON.stringify` calls it\n   * either way. Asked inside the record branch it was never reached for an\n   * array, which returned as soon as its own elements checked out — so `[1, 2]`\n   * with a `toJSON` returning `[9]` was written as `[9]` and reported as\n   * nothing lost. The written form being something OTHER than the value is the\n   * loss being looked for, whether or not the substitute is itself writable.\n   */\n  if (typeof (value as { toJSON?: unknown }).toJSON === \"function\") {\n    return false;\n  }\n  if (Array.isArray(value)) {\n    /*\n     * Index by index rather than through `every`, which SKIPS holes. A sparse\n     * array has none of its missing elements visited, so it passes vacuously\n     * while `JSON.stringify` writes each hole as `null` — vendor data coming\n     * back CHANGED rather than missing, which is the one shape a walk over the\n     * values it can SEE cannot notice.\n     *\n     * Reading the index is all it takes: a hole reads as `undefined`, which is\n     * not a leaf and not an object, so the same call that judges every other\n     * element refuses it. An explicit `undefined` is refused with it, and\n     * rightly — `JSON.stringify` turns that into `null` too.\n     */\n    for (let index = 0; index < value.length; index++) {\n      if (!holdsOnlyJson(value[index], seen)) return false;\n    }\n    return true;\n  }\n  return recordHoldsJson(value, seen);\n}\n\n/**\n * Whether a non-array object is what it appears to be, contents included.\n *\n * Its own question because an object can MISREPRESENT itself in a way an array\n * cannot, and it is answered before any of its contents matter: a `Map` or a\n * `Set` has no own enumerable keys, so walking its values finds nothing and it\n * looks perfectly safe — and `JSON.stringify` writes it as `{}`, erasing\n * everything it held. That is the trap the engine's own `isPlainRecord` exists\n * for, and the reason it reads the prototype rather than counting keys.\n */\nfunction recordHoldsJson(value: object, seen: Set<unknown>): boolean {\n  if (!isPlainRecord(value)) return false;\n  return Object.values(value).every(item => holdsOnlyJson(item, seen));\n}\n\n/**\n * Whether a value is one a JSON file can carry as it stands.\n *\n * The closed half of the question, asked apart from the walk because it is\n * fixed by the grammar and the walk is not: strings, booleans, finite numbers\n * and null, and nothing else. A non-finite number is refused rather than\n * accepted as pedantry — `NaN` and the infinities are written as `null`, so the\n * value silently becomes a different one.\n */\nfunction isJsonLeaf(value: unknown): boolean {\n  if (value === null) return true;\n  if (typeof value === \"string\" || typeof value === \"boolean\") return true;\n  return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * The site's variables as the CSS a page reads them from, light and dark,\n * under the site's prefix: what \"Copy CSS variables\" hands a developer.\n *\n * Emitted by `emitTokenBlocks` under `:root`, the call the site sheet makes\n * for its variable blocks, so the copy is those blocks byte for byte rather\n * than a second rendering that agrees today and drifts. Variables only: the\n * sheet's other rules (the content width, block defaults) are not variables.\n *\n * Copy only. Reading CSS back would need a parser nothing in this system has,\n * and a token table recovered from custom properties would have lost every\n * token's kind, which is what decides where it may be used.\n */\nexport function variableCss(tokens: SiteTokenSet): {\n  readonly css: string;\n  /**\n   * What the writer left out, in its own words: a variable whose CSS name\n   * another already took, or a prefix it could not use. Named to the author,\n   * so a copy that is missing a variable never reads as complete.\n   */\n  readonly skipped: readonly string[];\n} {\n  const { css, issues } = emitTokenBlocks(tokens, \":root\");\n  // Empty stays empty: a lone newline would be copied and confirmed, telling\n  // an author their variables were copied when nothing was.\n  return {\n    css: css === \"\" ? \"\" : `${css}\\n`,\n    skipped: issues.map(issue => issue.message),\n  };\n}\n","/**\n * The import preview's \"Fonts this site doesn't have\": each font the file\n * uses that no font file on the site provides, with \"Add from Google Fonts\"\n * for one the catalogue has. Fonts travel by name only, so the import never\n * adds one by itself; adding goes through the catalogue's own add, the one\n * the Fonts screen uses, and a font the catalogue lacks is uploaded there.\n *\n * @module variables-transfer-fonts\n */\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { DESIGN_ACTION_WORDS as WORDS } from \"../../editor-words\";\n\nimport type { CatalogueFamilyView, FontCatalogue } from \"./font-catalogue-view\";\n\n/** Where one missing font stands. */\ntype Standing =\n  | { readonly kind: \"idle\" }\n  | { readonly kind: \"adding\" }\n  | { readonly kind: \"added\" }\n  | { readonly kind: \"refused\"; readonly why: string };\n\n/**\n * The cuts an add asks for: the regular and bold where the family has them,\n * else its first, in its default script and its upright style, or its first\n * where it has none. A variable family is added whole.\n */\nfunction firstCuts(family: CatalogueFamilyView): {\n  weights: readonly number[] | \"variable\";\n  styles: CatalogueFamilyView[\"styles\"];\n  subsets: readonly string[];\n} {\n  const styles: CatalogueFamilyView[\"styles\"] = family.styles.includes(\"normal\")\n    ? [\"normal\"]\n    : family.styles.slice(0, 1);\n  if (family.variable)\n    return { weights: \"variable\", styles, subsets: [family.defSubset] };\n  const both = family.weights.filter(\n    weight => weight === 400 || weight === 700\n  );\n  const first = family.weights[0];\n  return {\n    weights: both.length > 0 ? both : first === undefined ? [] : [first],\n    styles,\n    subsets: [family.defSubset],\n  };\n}\n\n/** What the import reads the catalogue with: its families, and its add. */\nexport type ImportCatalogue = Pick<FontCatalogue, \"load\" | \"add\">;\n\nexport function MissingFonts({\n  families,\n  catalogue,\n}: {\n  /** The missing families, as the file names them. */\n  families: readonly string[];\n  catalogue?: ImportCatalogue;\n}): React.JSX.Element {\n  const [offered, setOffered] = React.useState<\n    ReadonlyMap<string, CatalogueFamilyView>\n  >(() => new Map());\n  const [standing, setStanding] = React.useState<ReadonlyMap<string, Standing>>(\n    () => new Map()\n  );\n  React.useEffect(() => {\n    if (catalogue === undefined) return undefined;\n    const reading = new AbortController();\n    catalogue.load(reading.signal).then(\n      ({ families: listed }) => {\n        if (reading.signal.aborted) return;\n        setOffered(\n          new Map(listed.map(family => [family.family.toLowerCase(), family]))\n        );\n      },\n      () => undefined\n    );\n    return () => reading.abort();\n  }, [catalogue]);\n\n  const add = async (name: string, family: CatalogueFamilyView) => {\n    if (catalogue === undefined) return;\n    const set = (next: Standing) =>\n      setStanding(held => new Map(held).set(name, next));\n    set({ kind: \"adding\" });\n    const cuts = firstCuts(family);\n    const refusal = await catalogue.add({\n      id: family.id,\n      weights: cuts.weights,\n      styles: cuts.styles,\n      subsets: cuts.subsets,\n    });\n    set(\n      refusal === undefined\n        ? { kind: \"added\" }\n        : { kind: \"refused\", why: refusal }\n    );\n  };\n\n  return (\n    <section className=\"nx-vars-import__section\">\n      <h3>{WORDS.missingFonts}</h3>\n      <ul className=\"nx-vars-import__fonts\">\n        {families.map(name => {\n          const family = offered.get(name.toLowerCase());\n          const now = standing.get(name) ?? { kind: \"idle\" };\n          return (\n            <li key={name} className=\"nx-vars-import__font\">\n              <span className=\"nx-vars-import__font-name\">{name}</span>\n              {family === undefined ? (\n                <span className=\"nx-vars-import__font-note\">\n                  {WORDS.uploadFont}\n                </span>\n              ) : now.kind === \"added\" ? (\n                <span className=\"nx-vars-import__font-note\" role=\"status\">\n                  {WORDS.fontAdded}\n                </span>\n              ) : (\n                <Button\n                  type=\"button\"\n                  size=\"sm\"\n                  variant=\"outline\"\n                  disabled={now.kind === \"adding\"}\n                  aria-label={`${WORDS.addFromGoogle}: ${name}`}\n                  onClick={() => void add(name, family)}\n                >\n                  {WORDS.addFromGoogle}\n                </Button>\n              )}\n              {now.kind === \"refused\" ? (\n                <span className=\"nx-vars-import__font-note\" role=\"alert\">\n                  {now.why}\n                </span>\n              ) : null}\n            </li>\n          );\n        })}\n      </ul>\n    </section>\n  );\n}\n","/**\n * The Design panel's ⋯ menu (\"More design actions\"): bringing variables in\n * from design-token files, taking them out, and copying them as CSS.\n *\n * The menu sits in the Design panel's header. Importing opens the system's\n * file chooser through a hidden file input, so the visible control is a menu\n * item like every other and the keyboard reaches it the same way. Nothing is\n * applied until the author has seen what the files would change and confirmed\n * it, settling each conflict as they go. A message about values an import\n * refused stays until the author dismisses it, since it names what did not\n * arrive.\n *\n * An import carries more than the variables: the file's text styles, its\n * Site text rows, colour order, fluid range and built-in colours setting,\n * each listed in the preview and stored through the host's own writers (the\n * text styles through its one class writer). The fonts the file uses that\n * the site has no file for are listed too, with \"Add from Google Fonts\" for\n * a font the catalogue has.\n *\n * Exports write files straight away: the design token file (with a theme file\n * beside it when there are dark values), or one file per mode for Figma. A\n * short toast says what was written; what the files did not carry is one\n * click away, in \"What wasn't exported\", rather than in a box that stays.\n * \"Copy CSS variables\" puts the site's variable blocks on the clipboard.\n *\n * @module variables-transfer\n */\nimport {\n  resolveTokenPrefix,\n  sameJsonValue,\n  tokenDisplayLabel,\n  type BreakpointSet,\n  type NamedClass,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n  toast,\n  TooltipProvider,\n} from \"@nextlyhq/ui\";\nimport { Ellipsis } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport { DESIGN_ACTION_WORDS as WORDS } from \"../../editor-words\";\nimport type {\n  ClassListEdit,\n  EditClasses,\n} from \"../../styles/block-style-actions\";\nimport { sharedStyleName } from \"../../styles/shared-style-library\";\n\nimport { FontChoicesContext, type FontChoices } from \"./font-family-field\";\nimport {\n  applyImport,\n  exportDtcgWithTheme,\n  exportForFigma,\n  planImport,\n  variableCss,\n  type ConflictChoice,\n  type ExportGap,\n  type ExportResult,\n  type ImportPlan,\n} from \"./tokens-transfer\";\nimport { siteDataLines, type ImportContext } from \"./tokens-transfer-extras\";\nimport { MissingFonts, type ImportCatalogue } from \"./variables-transfer-fonts\";\n\ntype ReadyPlan = Extract<ImportPlan, { ok: true }>;\n\n/** One of the menu's exports: what it makes, and how its toast names it. */\ninterface ExportKind {\n  make: (\n    set: SiteTokenSet,\n    classes: readonly NamedClass[]\n  ) => readonly ExportResult[];\n  /** The toast's opening words, before the files it names. */\n  done: string;\n  /** How the files' labels are joined in the toast. */\n  join: string;\n  /** Where the list of what was not exported says it comes from. */\n  from: string;\n}\n\nconst DTCG_EXPORT: ExportKind = {\n  make: exportDtcgWithTheme,\n  done: \"Design tokens exported\",\n  // \"variables, and dark values in a theme file\": the second is a phrase\n  // of its own, so a comma keeps the two apart.\n  join: \", and \",\n  from: \"From the design token files. A value kept for Nextly only is in the file as Nextly data: Nextly reads it back, and other design tools skip it.\",\n};\n\nconst FIGMA_EXPORT: ExportKind = {\n  make: exportForFigma,\n  done: \"Exported for Figma\",\n  join: \" and \",\n  from: \"From the Figma files.\",\n};\n\n/** What \"What wasn't exported\" lists, and which export it is about. */\ninterface NotExported {\n  gaps: readonly ExportGap[];\n  from: string;\n}\n\n/** How long an export's toast stays when it offers its list: time to reach it. */\nconst WITH_LIST_MS = 10_000;\n\nexport interface VariablesTransfer {\n  /** The header's ⋯ menu, with its hidden file input. */\n  menu: React.JSX.Element;\n  /**\n   * The import preview and the list of what an export left out. Both are\n   * dialogs drawn over the editor, so where a host mounts this draws nothing.\n   */\n  overlays: React.JSX.Element;\n}\n\n/**\n * What a host's variables write made at once stored: all of it, some of it\n * (the site refused some variables and the host stored the rest), with the\n * reason the rest was refused, or none of it.\n */\nexport type VariablesStored =\n  | { readonly stored: \"all\" }\n  | { readonly stored: \"part\"; readonly why?: string | undefined }\n  | { readonly stored: \"none\" };\n\n/**\n * A host's answer as a {@link VariablesStored}: a host answering a boolean\n * says all or nothing.\n */\nfunction asStored(answer: boolean | VariablesStored): VariablesStored {\n  if (answer === true) return { stored: \"all\" };\n  if (answer === false) return { stored: \"none\" };\n  return answer;\n}\n\n/**\n * The transfer controls and their state.\n *\n * `currentTokens` is asked at the moment a set is needed rather than captured,\n * because reading files is asynchronous and an author can edit a variable\n * while it runs; merging into an earlier set would undo that edit.\n */\nexport function useVariablesTransfer({\n  onChange,\n  currentTokens,\n  readOnly,\n  currentClasses,\n  onEditClasses,\n  storeTokensNow,\n  catalogue,\n  breakpoints,\n}: {\n  onChange: (tokens: SiteTokenSet) => void;\n  currentTokens: () => SiteTokenSet | undefined;\n  readOnly: boolean;\n  /**\n   * The site's classes as they are now, whose text styles an export writes\n   * and an import is matched with. Absent: none are exported or imported.\n   */\n  currentClasses?: () => readonly NamedClass[] | undefined;\n  /** The host's one class writer, which an import's text styles are stored through. */\n  onEditClasses?: EditClasses;\n  /**\n   * The host's variables write made at once rather than at the author's\n   * pause, answering what it stored: `true` or `false` for all or none, or a\n   * {@link VariablesStored} where the host can say it stored only some. An\n   * import's text styles name its variables, and the site refuses a text\n   * style naming a variable it doesn't hold yet, so those are stored first\n   * through this. Absent, like `onEditClasses`: an import brings in no text\n   * styles.\n   */\n  storeTokensNow?: (tokens: SiteTokenSet) => Promise<boolean | VariablesStored>;\n  /** The Google Fonts catalogue, which a missing font is added from. */\n  catalogue?: ImportCatalogue;\n  /**\n   * The site's breakpoints, once read: a file's text style values for one\n   * the site lacks are left out of an import, and the preview says so.\n   */\n  breakpoints?: BreakpointSet;\n}): VariablesTransfer {\n  // The site's fonts, from the host's Design frame: a font the file names\n  // and none of these provide is listed as missing.\n  const fonts = React.useContext(FontChoicesContext);\n  const [plan, setPlan] = React.useState<ReadyPlan | null>(null);\n  const [notExported, setNotExported] = React.useState<NotExported | null>(\n    null\n  );\n  const input = React.useRef<HTMLInputElement>(null);\n  // Where focus goes back to when the list closes: the toast that opened it\n  // has gone by then.\n  const trigger = React.useRef<HTMLButtonElement>(null);\n  // The callbacks as they are now, published at commit, for reads that\n  // outlive the render that started them.\n  const latest = React.useRef({\n    onChange,\n    currentTokens,\n    currentClasses,\n    onEditClasses,\n    storeTokensNow,\n    breakpoints,\n  });\n  React.useLayoutEffect(() => {\n    latest.current = {\n      onChange,\n      currentTokens,\n      currentClasses,\n      onEditClasses,\n      storeTokensNow,\n      breakpoints,\n    };\n  });\n  // Which read is the current one: a later choice supersedes an earlier read\n  // still in flight, and a read finishing after the panel has gone is ignored.\n  const reads = React.useRef(0);\n  React.useLayoutEffect(\n    () => () => {\n      reads.current = -1;\n    },\n    []\n  );\n  // The toast whose button opens the list. The list is this panel's state,\n  // so when the panel goes the toast goes with it: left behind, its button\n  // would open nothing, then or after the panel comes back.\n  const listed = React.useRef<string | number | null>(null);\n  React.useEffect(\n    () => () => {\n      if (listed.current !== null) toast.dismiss(listed.current);\n    },\n    []\n  );\n\n  const refuse = (headline: string, detail: readonly string[] = []): void =>\n    sayUntilDismissed(\"error\", headline, detail);\n\n  const read = async (files: readonly File[]): Promise<void> => {\n    const mine = reads.current + 1;\n    reads.current = mine;\n    let texts: { name: string; text: string }[];\n    try {\n      texts = await Promise.all(\n        files.map(async file => ({ name: file.name, text: await file.text() }))\n      );\n    } catch {\n      if (mine === reads.current) {\n        refuse(\n          \"Those files could not be read. They may have been moved or renamed since you chose them.\"\n        );\n      }\n      return;\n    }\n    if (mine !== reads.current) return;\n    const into = latest.current.currentTokens();\n    if (into === undefined) {\n      refuse(\"This site's variables are not loaded, so nothing was imported.\");\n      return;\n    }\n    const planned = planImport(\n      texts,\n      into,\n      importContext(latest.current, fonts)\n    );\n    if (!planned.ok) {\n      refuse(planned.error, planned.skipped);\n      return;\n    }\n    setPlan(planned);\n  };\n\n  const apply = (choices: ReadonlyMap<string, ConflictChoice>): void => {\n    if (plan === null) return;\n    setPlan(null);\n    const into = latest.current.currentTokens();\n    if (into === undefined) {\n      refuse(\"This site's variables are not loaded, so nothing was imported.\");\n      return;\n    }\n    const result = applyImport(plan, into, choices);\n    if (!result.ok) {\n      refuse(result.error, result.skipped);\n      return;\n    }\n    // What the toast says once the import is stored: only what arrived.\n    const done = (textStyles: number): void => {\n      const imported = importedWords(result.imported, textStyles);\n      if (result.skipped.length === 0) {\n        toast(imported);\n        return;\n      }\n      // Refused in part: what did not arrive is named, and stays named\n      // until the author has read it.\n      const refused = result.skipped.length;\n      sayUntilDismissed(\n        \"warning\",\n        `${imported} ${counted(refused, \"value was\", \"values were\")} refused:`,\n        result.skipped\n      );\n    };\n    const { onEditClasses: edit, storeTokensNow: storeNow } = latest.current;\n    if (storeNow === undefined) {\n      latest.current.onChange(result.tokens);\n      done(result.textStyles ?? 0);\n      return;\n    }\n    if (result.classes === undefined || edit === undefined) {\n      // No text styles to store after them, but the variables still go\n      // through the write that answers what it stored, so a save the site\n      // takes in part is said as that rather than counted as whole.\n      void storeVariables(storeNow, result.tokens, refuse).then(stored => {\n        if (stored) done(result.textStyles ?? 0);\n      });\n      return;\n    }\n    void importInSteps({\n      variables: withSiteRowsOf(result.tokens, into, result.rows),\n      classes: result.classes,\n      // The rows laid over the variables as they are by then, so an edit\n      // made meanwhile isn't lost.\n      rows: () => withRows(latest.current.currentTokens() ?? into, result.rows),\n      writers: { storeNow, edit, onChange: latest.current.onChange },\n      refuse,\n    }).then(stored => {\n      // \"nothing\" was said by the step that stopped.\n      if (stored !== \"nothing\") {\n        done(stored === \"all\" ? (result.textStyles ?? 0) : 0);\n      }\n    });\n  };\n\n  const send = (kind: ExportKind): void => {\n    const set = latest.current.currentTokens();\n    if (set === undefined) {\n      toast.error(\n        \"This site's variables are not loaded, so nothing was exported.\"\n      );\n      return;\n    }\n    const made = kind.make(set, latest.current.currentClasses?.() ?? []);\n    const written = made.filter(file => file.text !== \"\");\n    for (const file of written) download(file);\n    const gaps = oncePerVariable(made.flatMap(file => file.gaps));\n    const list =\n      gaps.length === 0\n        ? {}\n        : {\n            duration: WITH_LIST_MS,\n            action: {\n              label: WORDS.notExported,\n              onClick: () => {\n                // Focus back on the menu first. The toaster returns focus to\n                // where it came from as focus leaves it, and would otherwise\n                // do so after the list has taken it, out from under the list.\n                trigger.current?.focus();\n                setNotExported({ gaps, from: kind.from });\n              },\n            },\n          };\n    const shown =\n      written.length === 0\n        ? toast.error(\n            set.tokens.length === 0\n              ? \"No file was written: this site has no variables to write.\"\n              : \"No file was written.\",\n            list\n          )\n        : // Each file named in words, so an author knows which file holds\n          // what without opening it, and how many files to look for.\n          toast(\n            `${kind.done}: ${written.map(file => file.label).join(kind.join)} (${counted(\n              written.length,\n              \"file\",\n              \"files\"\n            )})`,\n            list\n          );\n    listed.current = gaps.length === 0 ? null : shown;\n  };\n\n  const copy = (): void => {\n    const set = latest.current.currentTokens();\n    if (set === undefined) {\n      toast.error(\n        \"This site's variables are not loaded, so nothing was copied.\"\n      );\n      return;\n    }\n    const { css, skipped } = variableCss(set);\n    if (css === \"\") {\n      toast.error(\"This site has no variables to copy.\");\n      return;\n    }\n    const named = `named ${resolveTokenPrefix(set.prefix).prefix}\\u2026`;\n    const said = set.tokens.some(token => token.values.dark !== undefined)\n      ? `CSS variables copied: light and dark values, ${named}`\n      : `CSS variables copied, ${named}`;\n    const refused = (): void => {\n      toast.error(\n        \"The CSS variables couldn't be copied: this browser didn't allow the copy.\"\n      );\n    };\n    // The editor's own clipboard: a page may not be allowed to write to it.\n    const clipboard: Clipboard | undefined =\n      typeof navigator === \"undefined\" ? undefined : navigator.clipboard;\n    if (clipboard === undefined) {\n      refused();\n      return;\n    }\n    void clipboard.writeText(css).then(() => {\n      if (skipped.length === 0) {\n        toast(said);\n        return;\n      }\n      // Copied in part: what is missing is named, and stays named until the\n      // author has read it, as an import refused in part is.\n      sayUntilDismissed(\n        \"warning\",\n        `${said}. ${counted(skipped.length, \"variable was\", \"variables were\")} left out:`,\n        skipped\n      );\n    }, refused);\n  };\n\n  const menu = (\n    <>\n      <TooltipProvider delayDuration={300}>\n        {/* Not modal: it opens the file chooser and the import preview from\n            inside, and a modal menu would hide the rest of the editor from\n            assistive technology while leaving it focusable. */}\n        <DropdownMenu modal={false}>\n          {/* The tooltip is the button's only visible name, as on every icon\n              button beside the canvas; no browser tooltip. */}\n          <ChromeTooltip content={WORDS.more}>\n            <DropdownMenuTrigger asChild>\n              <button\n                ref={trigger}\n                type=\"button\"\n                className=\"nx-vars__icon-button\"\n                aria-label={WORDS.more}\n              >\n                <Ellipsis aria-hidden=\"true\" size={16} />\n              </button>\n            </DropdownMenuTrigger>\n          </ChromeTooltip>\n          <DropdownMenuContent align=\"end\" className=\"nx-vars__menu\">\n            {readOnly ? null : (\n              <>\n                <DropdownMenuItem onSelect={() => input.current?.click()}>\n                  {WORDS.importTokens}\n                </DropdownMenuItem>\n                <DropdownMenuSeparator />\n              </>\n            )}\n            {/* The format is drawn as a quieter hint, and said after the\n                name: every word drawn is in the name, so someone who says\n                what they see reaches the item. */}\n            <DropdownMenuItem\n              aria-label={`${WORDS.exportTokens}, ${WORDS.exportTokensHint}`}\n              className=\"nx-design-more__item\"\n              onSelect={() => send(DTCG_EXPORT)}\n            >\n              <span>{WORDS.exportTokens}</span>\n              <span className=\"nx-design-more__hint\">\n                {WORDS.exportTokensHint}\n              </span>\n            </DropdownMenuItem>\n            <DropdownMenuItem onSelect={() => send(FIGMA_EXPORT)}>\n              {WORDS.exportFigma}\n            </DropdownMenuItem>\n            <DropdownMenuSeparator />\n            <DropdownMenuItem onSelect={copy}>{WORDS.copyCss}</DropdownMenuItem>\n          </DropdownMenuContent>\n        </DropdownMenu>\n      </TooltipProvider>\n      {readOnly ? null : (\n        <input\n          ref={input}\n          type=\"file\"\n          multiple\n          className=\"nx-sr-only\"\n          // Opened only from the menu's \"Import design tokens…\", so it is\n          // kept out of the tab order and out of the accessibility tree: one\n          // way to import, not a second bare file control beside the menu.\n          tabIndex={-1}\n          aria-hidden=\"true\"\n          aria-label=\"Choose variable files to import\"\n          accept=\".json,.tokens,.tokens.json,application/json\"\n          onChange={event => {\n            const files = [...(event.target.files ?? [])];\n            // Cleared so choosing the same files again fires again.\n            event.target.value = \"\";\n            if (files.length > 0) void read(files);\n          }}\n        />\n      )}\n    </>\n  );\n\n  const overlays = (\n    <>\n      {notExported === null ? null : (\n        <NotExportedList\n          list={notExported}\n          onClose={() => setNotExported(null)}\n          returnTo={trigger}\n        />\n      )}\n      {plan === null ? null : (\n        <ImportPreview\n          plan={plan}\n          onCancel={() => setPlan(null)}\n          onApply={apply}\n          {...(catalogue === undefined ? {} : { catalogue })}\n        />\n      )}\n    </>\n  );\n\n  return { menu, overlays };\n}\n\n/**\n * What the chosen files would change, before anything does.\n *\n * Counts first, then the conflicts, each with its own choice, then what the\n * files hold that this site cannot (listed, not dropped silently).\n */\nfunction ImportPreview({\n  plan,\n  onCancel,\n  onApply,\n  catalogue,\n}: {\n  plan: ReadyPlan;\n  onCancel: () => void;\n  onApply: (choices: ReadonlyMap<string, ConflictChoice>) => void;\n  catalogue?: ImportCatalogue;\n}): React.JSX.Element {\n  const [choices, setChoices] = React.useState<Map<string, ConflictChoice>>(\n    () => new Map()\n  );\n  const styles = plan.extras.textStyles;\n  const counts = [\n    count(plan.added.length, \"to add\"),\n    count(plan.changed.length, \"to update\"),\n    count(plan.unchanged.length, \"unchanged\"),\n    count(plan.conflicts.length, \"to settle\"),\n    count(\n      styles.added.length + styles.updated.length,\n      styles.added.length + styles.updated.length === 1\n        ? \"text style\"\n        : \"text styles\"\n    ),\n  ].filter(part => part !== \"\");\n  const alsoInFile = siteDataLines(plan.extras.site);\n  return (\n    <Dialog\n      open\n      onOpenChange={open => {\n        if (!open) onCancel();\n      }}\n    >\n      <DialogContent className=\"nx-vars-import\">\n        <DialogHeader>\n          <DialogTitle>Import variables</DialogTitle>\n          <DialogDescription>{counts.join(\" · \")}</DialogDescription>\n        </DialogHeader>\n        <div className=\"nx-vars-import__body\">\n          <NameList title=\"New\" names={plan.added.map(tokenDisplayLabel)} />\n          <NameList\n            title=\"Updated (a dark value, a name or a note this site lacks, or another tool's data)\"\n            names={plan.changed.map(tokenDisplayLabel)}\n          />\n          <NameList\n            title={WORDS.textStyles}\n            names={[...styles.added, ...styles.updated].map(sharedStyleName)}\n          />\n          {alsoInFile.length === 0 ? null : (\n            <section className=\"nx-vars-import__section\">\n              <h3>{WORDS.alsoInFile}</h3>\n              <ul className=\"nx-vars-import__skipped\">\n                {alsoInFile.map(line => (\n                  <li key={line}>{line}</li>\n                ))}\n              </ul>\n            </section>\n          )}\n          {plan.extras.missingFonts.length === 0 ? null : (\n            <MissingFonts\n              families={plan.extras.missingFonts}\n              {...(catalogue === undefined ? {} : { catalogue })}\n            />\n          )}\n          {plan.conflicts.length === 0 ? null : (\n            <section className=\"nx-vars-import__section\">\n              <h3>Different from this site</h3>\n              <ul className=\"nx-vars-import__conflicts\">\n                {plan.conflicts.map(conflict => {\n                  const name = tokenDisplayLabel(conflict.mine);\n                  const choice = choices.get(conflict.identity) ?? \"use\";\n                  return (\n                    <li key={conflict.identity}>\n                      <span className=\"nx-vars-import__name\">{name}</span>\n                      {/* Every field that differs, so a conflict over a\n                          dark value or a name says which and how. */}\n                      <dl className=\"nx-vars-import__fields\">\n                        {conflict.fields.map(field => (\n                          <div key={field.field}>\n                            <dt>{field.field}</dt>\n                            <dd className=\"nx-vars-import__values\">\n                              {`${field.mine} → ${field.imported}`}\n                            </dd>\n                          </div>\n                        ))}\n                      </dl>\n                      <div\n                        className=\"nx-vars__seg\"\n                        role=\"radiogroup\"\n                        aria-label={`${name}: keep or use`}\n                      >\n                        {([\"keep\", \"use\"] as const).map(option => (\n                          <button\n                            key={option}\n                            type=\"button\"\n                            role=\"radio\"\n                            aria-checked={choice === option}\n                            onClick={() =>\n                              setChoices(held =>\n                                new Map(held).set(conflict.identity, option)\n                              )\n                            }\n                          >\n                            {option === \"keep\" ? \"Keep mine\" : \"Use imported\"}\n                          </button>\n                        ))}\n                      </div>\n                    </li>\n                  );\n                })}\n              </ul>\n            </section>\n          )}\n          {plan.labelClashes.length === 0 ? null : (\n            <section className=\"nx-vars-import__section\">\n              <h3>Names used twice</h3>\n              <ul className=\"nx-vars-import__skipped\">\n                {plan.labelClashes.map(name => (\n                  <li key={name}>\n                    {`Two variables would be called \"${name}\". Keep this site's version of one, or rename one before importing.`}\n                  </li>\n                ))}\n              </ul>\n            </section>\n          )}\n          {plan.skipped.length === 0 ? null : (\n            <section className=\"nx-vars-import__section\">\n              <h3>Skipped</h3>\n              <ul className=\"nx-vars-import__skipped\">\n                {plan.skipped.map((line, at) => (\n                  <li key={`${String(at)}-${line}`}>{line}</li>\n                ))}\n              </ul>\n            </section>\n          )}\n        </div>\n        <DialogFooter>\n          <Button type=\"button\" variant=\"outline\" onClick={onCancel}>\n            Cancel\n          </Button>\n          <Button type=\"button\" onClick={() => onApply(choices)}>\n            Import\n          </Button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n\n/**\n * An import's variables stored through the host's write that answers what\n * it stored, answering whether ALL were. Anything less is said here: none\n * as \"nothing was imported\", and a save the site took in part as `partly`\n * (some variables are stored, so \"nothing\" would be untrue) with the reason\n * the rest was refused.\n */\nasync function storeVariables(\n  storeNow: (tokens: SiteTokenSet) => Promise<boolean | VariablesStored>,\n  tokens: SiteTokenSet,\n  refuse: (headline: string, detail?: readonly string[]) => void,\n  partly = \"Only some of the variables were saved.\"\n): Promise<boolean> {\n  const stored = asStored(await storeNow(tokens).catch(() => false));\n  if (stored.stored === \"none\") {\n    refuse(\"The variables weren't saved, so nothing was imported.\");\n  }\n  if (stored.stored === \"part\") {\n    refuse(partly, stored.why === undefined ? [] : [stored.why]);\n  }\n  return stored.stored === \"all\";\n}\n\n/**\n * An import with text styles, stored in three steps, each a step of the\n * history: the variables (and the site's other design data) first, since\n * the site refuses a text style naming a variable it doesn't hold; then the\n * text styles; then the Site text rows, which may follow them. Undo takes\n * them back in the opposite order, which the site accepts at each step: it\n * refuses to remove a text style while a row still follows it. Answers what\n * was stored: everything, the variables only, or nothing beyond what\n * {@link storeVariables} has said.\n */\nasync function importInSteps(steps: {\n  /** The import's variables, with the site's own Site text kept. */\n  variables: SiteTokenSet;\n  classes: ClassListEdit;\n  /** The import whole, laid over the variables as they are then. */\n  rows: () => SiteTokenSet | undefined;\n  writers: {\n    storeNow: (tokens: SiteTokenSet) => Promise<boolean | VariablesStored>;\n    edit: EditClasses;\n    onChange: (tokens: SiteTokenSet) => void;\n  };\n  refuse: (headline: string, detail?: readonly string[]) => void;\n}): Promise<\"all\" | \"variables\" | \"nothing\"> {\n  const { writers, refuse } = steps;\n  // The text styles may name a refused variable, so after a save in part\n  // they and the Site text following them wait for the author to fix it and\n  // import again.\n  const stored = await storeVariables(\n    writers.storeNow,\n    steps.variables,\n    refuse,\n    \"Only some of the variables were saved, so the text styles and Site text weren't imported.\"\n  );\n  if (!stored) return \"nothing\";\n  const refusal = await writers\n    .edit(steps.classes)\n    .catch(() => \"The text styles couldn't be saved.\");\n  if (refusal !== undefined) {\n    refuse(\"The text styles weren't imported, so neither was Site text.\", [\n      refusal,\n    ]);\n    return \"variables\";\n  }\n  const rows = steps.rows();\n  if (rows !== undefined) writers.onChange(rows);\n  return \"all\";\n}\n\n/**\n * The variables as they are with the Site text rows the import takes laid\n * over the rows as they are then, or `undefined` where that changes\n * nothing. Only those rows: the variables were stored by the first step and\n * any other row edited since stands.\n */\nfunction withRows(\n  now: SiteTokenSet,\n  rows: SiteTokenSet[\"siteText\"]\n): SiteTokenSet | undefined {\n  if (rows === undefined) return undefined;\n  const next = { ...now.siteText, ...rows };\n  return sameJsonValue(now.siteText ?? {}, next)\n    ? undefined\n    : { ...now, siteText: next };\n}\n\n/**\n * `tokens` with the import's own Site text rows (`rows`) held back: each\n * of those roles keeps the row `site` holds, to be laid over by the last\n * step. Every other row is the one `tokens` holds, which a changed fluid\n * range has already remade.\n */\nfunction withSiteRowsOf(\n  tokens: SiteTokenSet,\n  site: SiteTokenSet,\n  rows: SiteTokenSet[\"siteText\"]\n): SiteTokenSet {\n  const { siteText: merged, ...rest } = tokens;\n  const kept: Record<string, unknown> = { ...merged };\n  for (const role of Object.keys(rows ?? {})) {\n    const own = site.siteText?.[role as keyof typeof site.siteText];\n    if (own === undefined) delete kept[role];\n    else kept[role] = own;\n  }\n  return Object.keys(kept).length === 0 ? rest : { ...rest, siteText: kept };\n}\n\n/**\n * What an import is planned against: the site's text styles where the host\n * can store the file's (it has both writers an import's steps go through), and its fonts where the host says which it has.\n */\nfunction importContext(\n  host: {\n    readonly onEditClasses?: EditClasses | undefined;\n    readonly storeTokensNow?:\n      | ((tokens: SiteTokenSet) => Promise<boolean | VariablesStored>)\n      | undefined;\n    readonly currentClasses?:\n      | (() => readonly NamedClass[] | undefined)\n      | undefined;\n    readonly breakpoints?: BreakpointSet | undefined;\n  },\n  fonts: FontChoices | undefined\n): ImportContext {\n  return {\n    ...(host.onEditClasses === undefined || host.storeTokensNow === undefined\n      ? {}\n      : { textStyles: host.currentClasses?.() ?? [] }),\n    ...(fonts?.faces === undefined\n      ? {}\n      : { faces: [...fonts.faces, ...fonts.fromCode] }),\n    ...(host.breakpoints === undefined\n      ? {}\n      : { breakpoints: host.breakpoints }),\n  };\n}\n\n/**\n * What an import's toast says it stored: \"Imported 3 variables.\", or with\n * the text styles beside them, \"Imported 3 variables and 2 text styles.\".\n */\nfunction importedWords(variables: number, textStyles: number): string {\n  const said = counted(variables, \"variable\", \"variables\");\n  return textStyles === 0\n    ? `Imported ${said}.`\n    : `Imported ${said} and ${counted(textStyles, \"text style\", \"text styles\")}.`;\n}\n\n/** \"3 to add\", or nothing for none. */\nfunction count(n: number, words: string): string {\n  return n === 0 ? \"\" : `${String(n)} ${words}`;\n}\n\nfunction NameList({\n  title,\n  names,\n}: {\n  title: string;\n  names: readonly string[];\n}): React.JSX.Element | null {\n  if (names.length === 0) return null;\n  return (\n    <section className=\"nx-vars-import__section\">\n      <h3>{title}</h3>\n      <p className=\"nx-vars-import__names\">{names.join(\", \")}</p>\n    </section>\n  );\n}\n\n/**\n * \"What wasn't exported\": each variable a file did not write as other tools\n * read it, what happened to it, and why, in plain words.\n */\nfunction NotExportedList({\n  list,\n  onClose,\n  returnTo,\n}: {\n  list: NotExported;\n  onClose: () => void;\n  returnTo: React.RefObject<HTMLButtonElement | null>;\n}): React.JSX.Element {\n  return (\n    <Dialog\n      open\n      onOpenChange={open => {\n        if (!open) onClose();\n      }}\n    >\n      <DialogContent\n        className=\"nx-design-gaps\"\n        // Opened from a toast that has gone, so focus returns to the menu\n        // the export started from.\n        onCloseAutoFocus={event => {\n          event.preventDefault();\n          returnTo.current?.focus();\n        }}\n      >\n        <DialogHeader>\n          <DialogTitle>{WORDS.notExported}</DialogTitle>\n          <DialogDescription>{list.from}</DialogDescription>\n        </DialogHeader>\n        <ul className=\"nx-design-gaps__list\">\n          {list.gaps.map(gap => (\n            <li key={gapKey(gap)} className=\"nx-design-gaps__row\">\n              <span className=\"nx-design-gaps__name\">\n                {gap.label ?? \"The whole file\"}\n              </span>\n              <span\n                className=\"nx-design-gaps__outcome\"\n                data-outcome={gap.outcome}\n              >\n                {OUTCOME_WORDS[gap.outcome]}\n              </span>\n              <span className=\"nx-design-gaps__why\">{gap.why}</span>\n            </li>\n          ))}\n        </ul>\n        <DialogFooter>\n          <Button type=\"button\" variant=\"outline\" onClick={onClose}>\n            Close\n          </Button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\n\n/** What happened to a variable, as the list says it. */\nconst OUTCOME_WORDS: Readonly<Record<ExportGap[\"outcome\"], string>> = {\n  kept: WORDS.kept,\n  \"left-out\": WORDS.leftOut,\n  \"without-data\": WORDS.withoutData,\n};\n\n/** One entry per variable and outcome, however many files named it. */\nfunction oncePerVariable(gaps: readonly ExportGap[]): ExportGap[] {\n  const seen = new Map<string, ExportGap>();\n  for (const gap of gaps) {\n    if (!seen.has(gapKey(gap))) seen.set(gapKey(gap), gap);\n  }\n  return [...seen.values()];\n}\n\nfunction gapKey(gap: ExportGap): string {\n  return `${gap.outcome}|${gap.name ?? gap.why}`;\n}\n\n/**\n * A message that stays until the author dismisses it: what an import could\n * not bring in, each value named with why. A toast that left by itself would\n * take the only list of what did not arrive with it.\n */\nfunction sayUntilDismissed(\n  tone: \"error\" | \"warning\",\n  headline: string,\n  detail: readonly string[]\n): void {\n  toast[tone](headline, {\n    ...(detail.length === 0\n      ? {}\n      : {\n          description: (\n            <ul className=\"nx-design-toast__list\">\n              {detail.map((line, at) => (\n                <li key={`${String(at)}-${line}`}>{line}</li>\n              ))}\n            </ul>\n          ),\n        }),\n    duration: Number.POSITIVE_INFINITY,\n    cancel: { label: \"Dismiss\", onClick: () => undefined },\n  });\n}\n\n/** \"1 file\", \"2 files\": a count with the word that fits it. */\nfunction counted(n: number, one: string, many: string): string {\n  return `${String(n)} ${n === 1 ? one : many}`;\n}\n\n/**\n * Hand a generated file to the browser. Revoked on a later task, because the\n * download the click starts is asynchronous and revoking now can cancel it.\n */\nfunction download(made: ExportResult): void {\n  const url = URL.createObjectURL(new Blob([made.text], { type: made.mime }));\n  const link = window.document.createElement(\"a\");\n  link.href = url;\n  link.download = made.filename;\n  link.click();\n  window.setTimeout(() => {\n    URL.revokeObjectURL(url);\n  }, 0);\n}\n","/**\n * The Variables view of the Design panel: the site's named colours, type\n * sizes, spacing and the rest, each with its light and dark value.\n *\n * A panel over {@link tokens-studio}, which holds every rule this draws: what\n * group a variable is in, what an edit produces and what the engine says\n * about it. This decides only what it looks like.\n *\n * ## Compact rows, edited beside the panel\n *\n * Each variable is one row: a swatch or a specimen, its plain name, and its\n * light and dark values. Choosing a row opens its editor in a popover beside\n * the panel, so the list stays readable at a glance and the editing has room.\n *\n * ## The header is the Design panel's\n *\n * The import-and-export menu belongs in the Design panel's own header,\n * beside its title, and stays there whichever of its tabs is open. A host\n * that draws that header holds it with {@link useVariablesHeader} and hands\n * the result in as `header`; this view then takes its mode from it and draws\n * no controls of its own. Without one, the view holds them itself: drawn into\n * `headerActions` when the host gives that element, else at the top of this\n * view.\n *\n * ## The mode shown is the canvas's\n *\n * Swatches and specimens show the values of the mode the canvas is drawn in.\n * The panel has no light and dark switch of its own: the host that draws the\n * canvas offers the preview (the editor's, in its top bar) and hands the mode\n * in, so the panel and the canvas never show different modes.\n *\n * ## Edits are lifted, not saved here\n *\n * Every control reports a NEW set to the host and stores nothing. Saving\n * belongs to whoever owns the site style.\n *\n * @module tokens-panel\n */\nimport {\n  tokenIdentity,\n  type NamedClass,\n  type SiteToken,\n  type SiteTokenSet,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\n\nimport { useCanvasTokenModeAt } from \"../../canvas/prefers-dark\";\nimport { HOW_TEXT_WORKS_DOCS_HREF } from \"../../shell/docs-links\";\n\nimport { ColourCleanUp, type CleanUpColours } from \"./colour-cleanup\";\nimport {\n  ColourGroupHead,\n  ColourGroupHostContext,\n  NewGroupButton,\n  useColourGroupDrop,\n  useColourGroupHost,\n} from \"./colour-group-ui\";\nimport { colourGroups } from \"./colour-groups\";\nimport { ColoursTabEnd, useColoursOfView } from \"./colours-of-view\";\nimport {\n  GroupToggle,\n  OwnSearch,\n  ViewBody,\n  markOf,\n  useListedGroups,\n  useViewSearch,\n} from \"./design-group-toggle\";\nimport { FluidRangeFields } from \"./fluid-popover\";\nimport { ShowMore, withOpenRow } from \"./panel-actions\";\nimport { SiteTextSection } from \"./site-text-panel\";\nimport { useOpenVariable, type OnAddTo } from \"./tokens-panel-open-variable\";\nimport {\n  fluidRangeOf,\n  setFluidRange,\n  searchVariableGroups,\n  type VariableEntry,\n  type VariableGroup,\n} from \"./tokens-studio\";\nimport { ADDS, AddRows, EmptyGroup, type OnAdd } from \"./variable-adds\";\nimport { VariableRow } from \"./variable-row\";\nimport { useReachTogether } from \"./variable-together-reads\";\nimport type { VariableReach, VariablesAccess } from \"./variable-usage\";\nimport {\n  useVariableUsage,\n  type VariableUsageHere,\n} from \"./variable-usage-view\";\nimport { VariablePreview } from \"./variable-value-controls\";\nimport { useVariablesTransfer } from \"./variables-transfer\";\n\n/** A save's note to the author, and the way to read the variables again. */\nexport interface TokensPanelNotice {\n  readonly text: string;\n  readonly onReload: () => void;\n}\n\nexport interface TokensPanelProps {\n  /**\n   * The site's variables, or `undefined` while the host has not read them.\n   * A real third state: a site may legitimately have none of its own.\n   */\n  tokens: SiteTokenSet | undefined;\n  /** An edit. The host owns the site style and decides when to persist. */\n  onChange: (tokens: SiteTokenSet) => void;\n  /**\n   * Draws a variable's value on the canvas while it is typed or picked,\n   * without storing it: the whole set with the value in it, or `null` once\n   * the edit ends, said before the edit's one `onChange`. Absent, a value is\n   * drawn once it is handed to `onChange`.\n   */\n  onPreview?: (tokens: SiteTokenSet | null) => void;\n  /**\n   * The author is still at work here: typing in a field before it commits.\n   * For a host that waits for a pause before persisting, so a save is not\n   * made between one field's edit and the next.\n   */\n  onActivity?: () => void;\n  /**\n   * The author is done for now: a variable's editor closed, or this panel\n   * went away. A host waiting for a pause persists what it holds at once.\n   */\n  onSettle?: () => void;\n  /**\n   * The set the host holds RIGHT NOW, asked at the moment it is needed.\n   * Answer it from a ref the host writes as it dispatches: an import reads\n   * files asynchronously and must merge into the newest set, not into one this\n   * panel rendered with.\n   */\n  currentTokens: () => SiteTokenSet | undefined;\n  /**\n   * The variables something else supplies (the site's code and the engine's\n   * defaults), which the stored ones layer over. These can be reset and not\n   * removed: absence from the stored tier means \"no override\".\n   */\n  supplied?: SiteTokenSet;\n  /** What the last save said, when it failed. */\n  issue?: string;\n  /**\n   * What the last save has to tell the author although it was stored: that\n   * it met someone else's change to the same variables. Drawn beside\n   * `issue` as a status rather than an alert, since nothing failed, with a\n   * Reload that reads the variables again and drops the host's own copy.\n   * The host clears it on the next edit and on Reload.\n   */\n  notice?: TokensPanelNotice;\n  /**\n   * Which mode's values the swatches and specimens show, for a view that\n   * holds its header itself.\n   *\n   * - `true`: Dark, whatever the device prefers.\n   * - `false`: Light, whatever the device prefers.\n   * - omitted: the mode the canvas draws, followed live: the page's own\n   *   theme marker where it states one, else the device's scheme.\n   */\n  prefersDark?: boolean;\n  /** Why there are no variables to show: a read in flight, or one that failed. */\n  absence?: \"pending\" | \"failed\";\n  /**\n   * Shown, never changed. Fields stay selectable (`readOnly`, not disabled)\n   * and every control that would change something is left out.\n   */\n  readOnly?: boolean;\n  /** The Design panel's header element, where the header controls are drawn. */\n  headerActions?: HTMLElement | null;\n  /**\n   * The header a host draws for the whole Design panel, from\n   * {@link useVariablesHeader}. Given, the view previews its mode and leaves\n   * the controls, and what an import or export reports, to the host.\n   */\n  header?: VariablesHeader;\n  /**\n   * How widely each variable is used, read through the host: a count at the\n   * end of each row, and Remove refusing in place while a variable is used.\n   * Absent: no counts, and Remove confirms as it always has.\n   *\n   * @experimental Settles with the Variables tab's usage.\n   */\n  usage?: VariablesAccess;\n  /**\n   * The site's shared styles, so a shared style using a variable says what\n   * it sets with it (\"sets text colour\"). Absent: it says it uses it.\n   *\n   * @experimental Settles with the Variables tab's usage.\n   */\n  classes?: readonly NamedClass[];\n  /**\n   * The variable groups this view lists, in this order: one Design tab's.\n   * Absent: every group.\n   */\n  groups?: readonly VariableGroup[];\n  /**\n   * A search the host keeps across several views, as the Design panel keeps\n   * one across its tabs. Given, this view lists what it matches and draws no\n   * search box of its own.\n   */\n  search?: string;\n  /** The host's search field, where focus goes once a variable is removed. */\n  searchRef?: React.RefObject<HTMLInputElement | null>;\n  /** Which groups are folded, and the way to fold one. Absent: none fold. */\n  folds?: GroupFolds;\n  /**\n   * The variables the open page and its components use, by identity, for\n   * the Colours tab's \"Used on this page\"; read by the host from the\n   * editor's document, so it follows unsaved edits. Absent: none.\n   */\n  usedOnPage?: ReadonlySet<string>;\n  /**\n   * Remove the colours the site made that nothing uses, each judged on its\n   * own: \"Clean up unused…\" under the Colours tab's filter. Absent: not\n   * offered.\n   *\n   * @experimental Settles with the Colours tab's clean-up.\n   */\n  onCleanUp?: CleanUpColours;\n}\n\n/**\n * Which of the Design panel's groups the author folded, by group id, and\n * the way to fold or open one. The host keeps it, so a group stays folded\n * for that author across reloads.\n */\nexport interface GroupFolds {\n  readonly folded: ReadonlySet<string>;\n  readonly onFold: (group: string, folded: boolean) => void;\n}\n\n/** The Design panel's header controls, and the mode its views show. */\nexport interface VariablesHeader {\n  /** Which mode's values the swatches and specimens show. */\n  readonly mode: TokenMode;\n  /** The import-and-export menu. */\n  readonly controls: React.JSX.Element;\n  /** What an import or an export reports, and the import's preview. */\n  readonly overlays: React.JSX.Element;\n}\n\n/**\n * The header controls and their state, for a host that keeps them while the\n * Design panel's tabs change under them: the mode its views show, and the\n * import-and-export menu with what it reports.\n *\n * The mode is the host's `mode` where it hands one in: the mode it draws its\n * canvas in, so the swatches show what the canvas shows. Without one,\n * `prefersDark` as {@link TokensPanelProps.prefersDark} reads it, else the\n * mode the canvas draws by itself.\n */\nexport function useVariablesHeader({\n  prefersDark,\n  mode: hosted,\n  ...transferring\n}: Parameters<typeof useVariablesTransfer>[0] & {\n  prefersDark?: boolean;\n  mode?: TokenMode;\n}): VariablesHeader {\n  /*\n   * Without a host's mode, the one the canvas actually draws: the marker on\n   * the page it shows, which a site's own page may state, else the device's\n   * scheme. The bare device setting would name the wrong mode on a page that\n   * states its own.\n   */\n  const drawn = useCanvasTokenModeAt(null);\n  const mode: TokenMode = hosted ?? statedMode(prefersDark) ?? drawn;\n  // The writers, and what an export and import carry beyond the variables.\n  const transfer = useVariablesTransfer(transferring);\n  return {\n    mode,\n    controls: <div className=\"nx-vars__controls\">{transfer.menu}</div>,\n    overlays: transfer.overlays,\n  };\n}\n\n/** How many rows of one group mount before the author asks for more. */\nconst PAGE_SIZE = 50;\n\nexport function TokensPanel(props: TokensPanelProps): React.JSX.Element {\n  const { header } = props;\n  // The editors draw what is typed through the host's preview.\n  return (\n    <VariablePreview.Provider value={props.onPreview}>\n      {header === undefined ? (\n        <OwnHeader {...props} />\n      ) : (\n        <VariablesView {...props} header={header} placed={false} />\n      )}\n    </VariablePreview.Provider>\n  );\n}\n\n/** The view holding its header itself, where no host draws one. */\nfunction OwnHeader(props: TokensPanelProps): React.JSX.Element {\n  const header = useVariablesHeader({\n    onChange: props.onChange,\n    currentTokens: props.currentTokens,\n    readOnly: props.readOnly ?? false,\n    ...(props.prefersDark === undefined\n      ? {}\n      : { prefersDark: props.prefersDark }),\n  });\n  return <VariablesView {...props} header={header} placed />;\n}\n\nfunction VariablesView({\n  tokens,\n  onChange,\n  onActivity,\n  onSettle,\n  currentTokens,\n  supplied,\n  issue,\n  absence = \"pending\",\n  readOnly = false,\n  headerActions,\n  header,\n  placed,\n  ...hosted\n}: TokensPanelProps & {\n  header: VariablesHeader;\n  /** Whether this view draws the header's controls and reports itself. */\n  placed: boolean;\n}): React.JSX.Element {\n  const { mode } = header;\n  const { query, needle, searching, setQuery, own } = useViewSearch(\n    hosted.search\n  );\n  const {\n    root,\n    openKey,\n    fresh,\n    toggle,\n    add,\n    duplicate,\n    forget,\n    commitFrom,\n    focus,\n  } = useOpenVariable({ tokens, onChange, currentTokens, onSettle });\n  const ownSearch = React.useRef<HTMLInputElement>(null);\n  // Where focus goes once a variable is removed: the host's search where it\n  // keeps one, else the view's own.\n  const search = hosted.searchRef ?? ownSearch;\n\n  const groups = useListedGroups(tokens, mode, hosted.groups);\n  // A row just added stays shown while its editor is open, though the\n  // search would hide it: added where the author is, it is not lost.\n  const { shown: matched, held } = searched(groups, needle, fresh);\n  const usage = useUsageOfRows(hosted, groups, issue);\n  // The Colours tab's usage filter, over what the search matched, without\n  // the built-in colours the site hides.\n  const colourFilter = useColoursOfView({\n    shown: matched,\n    groups,\n    tokens,\n    usage,\n    builtIn: identity => suppliedFor(supplied, identity) !== undefined,\n    usedOnPage: hosted.usedOnPage,\n    openKey,\n  });\n  const { shown, hidden, marksBuiltIn } = colourFilter;\n\n  if (tokens === undefined) {\n    return <Unread absence={absence} />;\n  }\n\n  return (\n    // Typing anywhere in the panel, the editors beside the rows included\n    // (React carries their events here through the portal), is activity.\n    <div\n      className=\"nx-vars\"\n      ref={root}\n      data-read-only={markOf(readOnly)}\n      onInput={onActivity}\n    >\n      <PlacedControls placed={placed} slot={headerActions} header={header} />\n      <OwnSearch ref={ownSearch} shown={own} query={query} onQuery={setQuery} />\n      <ViewBody\n        adds={\n          <HiddenGroupAdds\n            groups={groups}\n            searching={searching}\n            readOnly={readOnly}\n            folds={hosted.folds}\n            onAdd={add}\n          />\n        }\n        notes={\n          <PanelNotes\n            readOnly={readOnly}\n            issue={issue}\n            notice={hosted.notice}\n          />\n        }\n        overlays={placedOverlays(placed, header)}\n      >\n        <TypeTabHelp groups={hosted.groups} />\n        <TypeTabSiteText\n          groups={hosted.groups}\n          tokens={tokens}\n          onChange={onChange}\n          readOnly={readOnly}\n          mode={mode}\n          supplied={supplied?.siteText}\n          // The text styles a row may follow (\"Heading 1 uses Display\").\n          classes={hosted.classes}\n        />\n        <TypeTabRange\n          groups={hosted.groups}\n          tokens={tokens}\n          onChange={onChange}\n          readOnly={readOnly}\n        />\n        {colourFilter.control}\n        <ColourCleanUp\n          groups={groups}\n          tokens={tokens}\n          usage={usage}\n          usedOnPage={hosted.usedOnPage}\n          builtIn={identity => suppliedFor(supplied, identity) !== undefined}\n          readOnly={readOnly}\n          onCleanUp={hosted.onCleanUp}\n        />\n        <VariableGroups\n          shown={shown}\n          searching={searching}\n          folds={hosted.folds}\n          onAdd={add}\n          rows={rowsHostOf({\n            tokens,\n            mode,\n            readOnly,\n            openKey,\n            supplied,\n            toggle,\n            commitFrom,\n            duplicate,\n            usage,\n            held,\n            fresh,\n            forget,\n            search,\n            focus,\n            hidden,\n            marksBuiltIn,\n          })}\n        />\n        <ColoursTabEnd\n          groups={groups}\n          tokens={tokens}\n          readOnly={readOnly}\n          onChange={commitFrom(BUILT_IN_COLOURS_KEY)}\n        />\n      </ViewBody>\n    </div>\n  );\n}\n\n/**\n * \"How text works\", first where the view lists the type scale: the docs page\n * on how its parts fit together, in a new tab so the panel stays as it was.\n * Drawn as \"Manage fonts…\" above it is, a target at least 24px tall.\n */\nfunction TypeTabHelp({\n  groups,\n}: {\n  groups: readonly VariableGroup[] | undefined;\n}): React.JSX.Element | null {\n  if (groups !== undefined && !groups.includes(\"type\")) return null;\n  return (\n    <a\n      className=\"nx-vars__link nx-fonts-manage\"\n      href={HOW_TEXT_WORKS_DOCS_HREF}\n      target=\"_blank\"\n      rel=\"noreferrer\"\n    >\n      How text works\n    </a>\n  );\n}\n\n/**\n * The site's text, first where the view lists the type scale: what every\n * page's headings, body text, links, buttons and captions look like.\n */\nfunction TypeTabSiteText({\n  groups,\n  ...section\n}: React.ComponentProps<typeof SiteTextSection> & {\n  groups: readonly VariableGroup[] | undefined;\n}): React.JSX.Element | null {\n  if (groups !== undefined && !groups.includes(\"type\")) return null;\n  return <SiteTextSection {...section} />;\n}\n\n/**\n * The site's fluid range, where the view lists the type scale: the Type\n * tab, or a view of every group. Changing it remakes every size made with\n * \"Fluid…\", in the same edit, so it saves and undoes as one.\n */\nfunction TypeTabRange({\n  groups,\n  tokens,\n  onChange,\n  readOnly,\n}: {\n  groups: readonly VariableGroup[] | undefined;\n  tokens: SiteTokenSet;\n  onChange: (tokens: SiteTokenSet) => void;\n  readOnly: boolean;\n}): React.JSX.Element | null {\n  if (groups !== undefined && !groups.includes(\"type\")) return null;\n  return (\n    <FluidRangeFields\n      range={fluidRangeOf(tokens)}\n      onRange={range => onChange(setFluidRange(tokens, range))}\n      readOnly={readOnly}\n    />\n  );\n}\n\n/** What an import or export reported, drawn by the view placed to draw it. */\nfunction placedOverlays(\n  placed: boolean,\n  header: VariablesHeader\n): React.JSX.Element | undefined {\n  return placed ? header.overlays : undefined;\n}\n\n/** The header's controls, drawn by the view that is placed to draw them. */\nfunction PlacedControls({\n  placed,\n  slot,\n  header,\n}: {\n  placed: boolean;\n  slot: HTMLElement | null | undefined;\n  header: VariablesHeader;\n}): React.JSX.Element | null {\n  return placed ? (\n    <HeaderControls slot={slot}>{header.controls}</HeaderControls>\n  ) : null;\n}\n\n/**\n * What the view's rows are drawn from: the view's state, with a variable\n * removed putting focus back on the search, the place a removed row's\n * focus has to go.\n */\nfunction rowsHostOf({\n  supplied,\n  forget,\n  search,\n  ...rows\n}: Omit<RowsHost, \"suppliedOf\" | \"onRemoved\"> & {\n  supplied: SiteTokenSet | undefined;\n  forget: (key: string) => void;\n  search: React.RefObject<HTMLInputElement | null>;\n}): RowsHost {\n  return {\n    ...rows,\n    suppliedOf: identity => suppliedFor(supplied, identity),\n    onRemoved: key => {\n      forget(key);\n      // After the removed row's editor has closed: closing hands focus back\n      // to its trigger, which went with the row, and would leave it nowhere.\n      window.setTimeout(() => search.current?.focus(), 0);\n    },\n  };\n}\n\n/** What every row of the view is drawn from, and what its editor reports to. */\ninterface RowsHost {\n  readonly tokens: SiteTokenSet;\n  readonly mode: TokenMode;\n  readonly readOnly: boolean;\n  /** The row whose editor is open. */\n  readonly openKey: string | null;\n  readonly suppliedOf: (identity: string) => SiteToken | undefined;\n  readonly toggle: (key: string, open: boolean) => void;\n  readonly commitFrom: (key: string) => (next: SiteTokenSet) => void;\n  /** Usage, where the host reads it. */\n  readonly usage: VariableUsageHere | undefined;\n  /** The variable whose row this is was removed. */\n  readonly onRemoved: (key: string) => void;\n  /** Adds a copy of a row's variable right below it, and opens it. */\n  readonly duplicate: (entry: VariableEntry) => void;\n  /** The new row a search would hide, shown marked \"New\" meanwhile. */\n  readonly held: string | null;\n  /** The row just added or copied, never saved, while its editor is open. */\n  readonly fresh: string | null;\n  /** Focuses a row once it is drawn, wherever it is drawn now. */\n  readonly focus: (key: string) => void;\n  /** The built-in colours the site hides, left out with any group they empty. */\n  readonly hidden: ReadonlySet<string>;\n  /** Whether a built-in colour's row says so: while the site hides the rest. */\n  readonly marksBuiltIn: boolean;\n}\n\n/** The groups a search leaves, or that none match. */\nfunction VariableGroups({\n  shown,\n  searching,\n  folds,\n  onAdd,\n  rows,\n}: {\n  shown: readonly {\n    readonly group: VariableGroup;\n    readonly heading: string;\n    readonly entries: readonly VariableEntry[];\n  }[];\n  searching: boolean;\n  folds: GroupFolds | undefined;\n  onAdd: OnAddTo;\n  rows: RowsHost;\n}): React.JSX.Element {\n  const colours = useColourGroupHost(\n    rows.tokens,\n    rows.readOnly,\n    rows.commitFrom(COLOUR_GROUPS_KEY)\n  );\n  if (shown.length === 0) {\n    return <p className=\"nx-vars__note\">No variables match this search.</p>;\n  }\n  return (\n    <ColourGroupHostContext.Provider\n      value={{\n        ...colours,\n        onMoved: (row, next) => movedInto(row, next, folds, rows.focus),\n      }}\n    >\n      {shown\n        .flatMap(group =>\n          sectionsOf(\n            group,\n            rows.tokens,\n            searching,\n            colours.pending,\n            rows.hidden\n          )\n        )\n        .map(section => (\n          <React.Fragment key={section.key}>\n            <Group\n              group={section.group}\n              heading={section.heading}\n              entries={section.entries}\n              searching={searching}\n              folds={folds}\n              readOnly={rows.readOnly}\n              openKey={rows.openKey}\n              onAdd={onAdd}\n              named={section.named}\n            >\n              {(entry: VariableEntry) => (\n                <VariableRow\n                  key={entry.row.key}\n                  entry={entry}\n                  tokens={rows.tokens}\n                  mode={rows.mode}\n                  suppliedOf={rows.suppliedOf}\n                  readOnly={rows.readOnly}\n                  open={rows.openKey === entry.row.key}\n                  onOpenChange={open => rows.toggle(entry.row.key, open)}\n                  onChange={rows.commitFrom(entry.row.key)}\n                  onDuplicate={() => rows.duplicate(entry)}\n                  fresh={\n                    rows.fresh === entry.row.key\n                      ? { marked: rows.held === entry.row.key }\n                      : undefined\n                  }\n                  usage={rows.usage}\n                  reach={rowReach(entry, rows.usage)}\n                  builtIn={\n                    rows.marksBuiltIn &&\n                    rows.suppliedOf(entry.row.identity) !== undefined\n                  }\n                  onRemoved={() => rows.onRemoved(entry.row.key)}\n                />\n              )}\n            </Group>\n          </React.Fragment>\n        ))}\n    </ColourGroupHostContext.Provider>\n  );\n}\n\n/**\n * After a colour row moved: moved into another group it is drawn there anew,\n * so that group is opened and the row keeps the focus.\n */\nfunction movedInto(\n  row: { readonly key: string; readonly identity: string },\n  next: SiteTokenSet,\n  folds: GroupFolds | undefined,\n  focus: (key: string) => void\n): void {\n  const into = colourGroups(next).find(group =>\n    group.identities.includes(row.identity)\n  );\n  if (into !== undefined) openFold(folds, colourGroupFoldKey(into.name));\n  focus(row.key);\n}\n\n/** What the Colours tab's group changes commit under: no row's editor. */\nconst COLOUR_GROUPS_KEY = \"colour-groups\";\n\n/** What the built-in colours setting commits under: no row's editor. */\nconst BUILT_IN_COLOURS_KEY = \"built-in-colours\";\n\n/** One section of the list: a group, or one named group of colours. */\ninterface ListSection {\n  readonly key: string;\n  readonly group: VariableGroup;\n  readonly heading: string;\n  readonly entries: readonly VariableEntry[];\n  readonly named?: { readonly name: string; readonly last: boolean };\n}\n\n/**\n * The sections a group is listed in: the Colours group as its named groups,\n * in the site's order, each holding its own colours; any other group whole.\n * A search lists only the named groups it matches in.\n */\nfunction sectionsOf(\n  group: {\n    readonly group: VariableGroup;\n    readonly heading: string;\n    readonly entries: readonly VariableEntry[];\n  },\n  tokens: SiteTokenSet,\n  searching: boolean,\n  /** Groups made with \"+ New group\" that hold no colour yet. */\n  pending: readonly string[] = [],\n  /** The built-in colours the site hides: a group of only these is left out. */\n  hidden: ReadonlySet<string> = new Set()\n): ListSection[] {\n  const whole: ListSection = { ...group, key: group.group };\n  if (group.group !== \"colours\" || group.entries.length === 0) return [whole];\n  const byIdentity = new Map(\n    group.entries.map(entry => [entry.row.identity, entry])\n  );\n  const named = colourGroups(tokens)\n    .map(colourGroup => ({\n      name: colourGroup.name,\n      identities: colourGroup.identities,\n      entries: colourGroup.identities.flatMap(identity => {\n        const entry = byIdentity.get(identity);\n        return entry === undefined ? [] : [entry];\n      }),\n    }))\n    .filter(colourGroup => !searching || colourGroup.entries.length > 0)\n    .filter(\n      colourGroup =>\n        colourGroup.identities.length === 0 ||\n        !colourGroup.identities.every(identity => hidden.has(identity))\n    )\n    .concat(\n      searching\n        ? []\n        : pending.map(name => ({ name, identities: [], entries: [] }))\n    );\n  return named.map((colourGroup, at) => ({\n    key: colourGroupFoldKey(colourGroup.name),\n    group: group.group,\n    heading: colourGroup.name,\n    entries: colourGroup.entries,\n    named: { name: colourGroup.name, last: at === named.length - 1 },\n  }));\n}\n\n/** What a named group with no colour in it says. */\nconst NEW_GROUP_EMPTY = \"Drag a colour here, or use Move to group…\";\n\n/** A named group's heading with its name field and ⋯; any other as it is. */\nfunction ColourGroupHeadIf({\n  name,\n  children,\n}: {\n  name: string | undefined;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  if (name === undefined) return <>{children}</>;\n  return <ColourGroupHead name={name}>{children}</ColourGroupHead>;\n}\n\n/** What a named group of colours keeps its fold under. */\nfunction colourGroupFoldKey(name: string): string {\n  return `colour-group:${name}`;\n}\n\n/**\n * How widely every variable listed is used, read once for all the groups:\n * each row's variable and, for a type size, its line height, which has no\n * row of its own and is removed from here or nowhere; and what the rows and\n * their editors are handed of it. Nothing without the host's access.\n *\n * A save refused (`issue` coming to say why) is read as a sign the counts\n * are behind: a removal the server refused because the variable is in use,\n * which these counts called unused. Every listed variable is read again,\n * since the panel cannot tell which ones the refused save dropped, so the\n * next Remove says why it waits rather than confirming again.\n */\nfunction useUsageOfRows(\n  {\n    usage: access,\n    classes,\n  }: {\n    readonly usage?: VariablesAccess | undefined;\n    readonly classes?: readonly NamedClass[] | undefined;\n  },\n  groups: readonly { readonly entries: readonly VariableEntry[] }[],\n  issue: string | undefined\n): VariableUsageHere | undefined {\n  const identities = React.useMemo(\n    () => groups.flatMap(group => group.entries.flatMap(rowIdentities)),\n    [groups]\n  );\n  const reads = useVariableUsage(access, identities);\n  const { values, reread, readAgain } = reads;\n  // Each row's variables, counted together where it stands for two.\n  const rows = React.useMemo(\n    () => groups.flatMap(group => group.entries.map(rowIdentities)),\n    [groups]\n  );\n  const reachTogether = useReachTogether(access, rows, values);\n  // The identities as of the latest render, read when a refusal arrives\n  // rather than closed over, so the effect follows the issue alone.\n  const listed = React.useRef(identities);\n  listed.current = identities;\n  React.useEffect(() => {\n    // A fresh list each time: the same list again would be no new state,\n    // and a second refusal would read nothing.\n    if (issue !== undefined) reread([...listed.current]);\n  }, [issue, reread]);\n  return React.useMemo(\n    () =>\n      access === undefined\n        ? undefined\n        : {\n            reachOf: id => values.get(id),\n            reachTogether,\n            readAgain,\n            access,\n            classes,\n          },\n    [access, values, reachTogether, readAgain, classes]\n  );\n}\n\n/** The variables a row stands for: its own, and a type size's line height. */\nfunction rowIdentities(entry: VariableEntry): string[] {\n  return entry.lineHeight === undefined\n    ? [entry.row.identity]\n    : [entry.row.identity, entry.lineHeight.identity];\n}\n\n/** A row's count: every variable it stands for, together. */\nfunction rowReach(\n  entry: VariableEntry,\n  usage: VariableUsageHere | undefined\n): VariableReach | undefined {\n  if (usage === undefined) return undefined;\n  return usage.reachTogether(rowIdentities(entry));\n}\n\n/** What shows while the variables are being read, or after a read failed. */\nfunction Unread({\n  absence,\n}: {\n  absence: \"pending\" | \"failed\";\n}): React.JSX.Element {\n  const failed = absence === \"failed\";\n  return (\n    <div className=\"nx-vars\">\n      <p\n        className={failed ? \"nx-vars__alert\" : \"nx-vars__note\"}\n        role={failed ? \"alert\" : \"status\"}\n      >\n        {failed\n          ? \"This site\\u2019s variables could not be read, so none can be shown or changed. Reload to try again.\"\n          : \"Reading this site\\u2019s variables\\u2026\"}\n      </p>\n    </div>\n  );\n}\n\n/** The header controls, in the Design panel's header when it gives one. */\nfunction HeaderControls({\n  slot,\n  children,\n}: {\n  slot: HTMLElement | null | undefined;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  if (slot) return <>{createPortal(children, slot)}</>;\n  return <div className=\"nx-vars__head\">{children}</div>;\n}\n\n/** The read-only line, a save that failed, and a save that met another. */\nfunction PanelNotes({\n  readOnly,\n  issue,\n  notice,\n}: {\n  readOnly: boolean;\n  issue: string | undefined;\n  notice: TokensPanelNotice | undefined;\n}): React.JSX.Element {\n  return (\n    <>\n      {readOnly ? (\n        <p className=\"nx-vars__note\">\n          You can view the site&rsquo;s variables but not change them.\n        </p>\n      ) : null}\n      {issue === undefined ? null : (\n        <p className=\"nx-vars__alert\" role=\"alert\">\n          {issue}\n        </p>\n      )}\n      {notice === undefined ? null : (\n        // A status, not an alert: the save was stored, and this says what\n        // it met on the way.\n        <div className=\"nx-vars__notice\" role=\"status\">\n          <p className=\"nx-vars__notice-text\">{notice.text}</p>\n          <Button\n            className=\"nx-vars__notice-reload\"\n            onClick={notice.onReload}\n            size=\"sm\"\n            type=\"button\"\n            variant=\"outline\"\n          >\n            Reload\n          </Button>\n        </div>\n      )}\n    </>\n  );\n}\n\n/**\n * The adds of the groups hidden while they hold nothing, as a worded line at\n * the end of the view: hidden, their own \"+\" would go with them, and the\n * first variable of such a group could not be made.\n */\nfunction HiddenGroupAdds({\n  groups,\n  searching,\n  readOnly,\n  folds,\n  onAdd,\n}: {\n  groups: readonly { group: VariableGroup; entries: readonly unknown[] }[];\n  searching: boolean;\n  readOnly: boolean;\n  folds: GroupFolds | undefined;\n  onAdd: OnAdd;\n}): React.JSX.Element | null {\n  const hidden = groups.filter(\n    group => SHOWN_WHEN_FILLED.has(group.group) && group.entries.length === 0\n  );\n  if (readOnly || searching || hidden.length === 0) return null;\n  return (\n    <div className=\"nx-vars__hidden-adds\">\n      {hidden.map(group => (\n        <AddRows\n          key={group.group}\n          group={group.group}\n          onAdd={(what, from) => {\n            openFold(folds, group.group);\n            onAdd(what, from);\n          }}\n        />\n      ))}\n    </div>\n  );\n}\n\n/**\n * Opens a group the author folded, for a variable about to be added to it,\n * so its row and editor are drawn: the stored fold, which a search only\n * sets aside and would bring back once the add clears it.\n */\nfunction openFold(folds: GroupFolds | undefined, group: string): void {\n  if (folds?.folded.has(group) === true) folds.onFold(group, false);\n}\n\n/** The groups that list only what they hold, hidden while they hold none. */\nconst SHOWN_WHEN_FILLED: ReadonlySet<VariableGroup> = new Set<VariableGroup>([\n  \"fonts\",\n  \"content\",\n  \"other\",\n]);\n\n/**\n * The groups narrowed to a search, through the one search rule; with no\n * search, \"Fonts and weights\" and \"Other values\" only when they have rows.\n * The row `kept` is listed at the end of its group whatever the search, so\n * a variable just added stays in view while its editor is open; `held` is\n * that row when the search alone would have hidden it, so it is marked\n * \"New\". One search decides both, so the row kept and the row marked never\n * disagree.\n */\nfunction searched<\n  G extends { group: VariableGroup; entries: readonly VariableEntry[] },\n>(\n  groups: readonly G[],\n  needle: string,\n  kept: string | null\n): { shown: G[]; held: string | null } {\n  if (needle === \"\") {\n    return {\n      shown: groups.filter(\n        group => !SHOWN_WHEN_FILLED.has(group.group) || group.entries.length > 0\n      ),\n      held: null,\n    };\n  }\n  const found = searchVariableGroups(groups, needle);\n  if (kept === null) return { shown: found, held: null };\n  let held: string | null = null;\n  const shown = groups.flatMap(group => {\n    const hit = found.find(candidate => candidate.group === group.group);\n    const keep = group.entries.find(entry => entry.row.key === kept);\n    if (keep === undefined || hit?.entries.includes(keep) === true) {\n      return hit === undefined ? [] : [hit];\n    }\n    held = kept;\n    return [{ ...group, entries: [...(hit?.entries ?? []), keep] }];\n  });\n  return { shown, held };\n}\n\n/**\n * The mode a host asked the view to show, or `null` to follow the canvas:\n * `false` is an explicit choice of light, not an absence.\n */\nfunction statedMode(prefersDark: boolean | undefined): TokenMode | null {\n  if (prefersDark === undefined) return null;\n  return prefersDark ? \"dark\" : \"light\";\n}\n\n/** One group: its heading, its \"+\", and its rows, a page at a time. */\nfunction Group({\n  group,\n  heading,\n  entries,\n  searching,\n  folds,\n  readOnly,\n  openKey,\n  onAdd,\n  named,\n  children,\n}: {\n  group: VariableGroup;\n  heading: string;\n  /**\n   * A named group of colours within the Colours group: its name, which keys\n   * its fold, and whether it ends the list and so holds the add row.\n   */\n  named?: { readonly name: string; readonly last: boolean } | undefined;\n  entries: readonly VariableEntry[];\n  searching: boolean;\n  /** Present: the heading folds the group, and shows how many it holds. */\n  folds: GroupFolds | undefined;\n  readOnly: boolean;\n  /** The row whose editor is open, which is drawn even past the page. */\n  openKey: string | null;\n  onAdd: OnAddTo;\n  children: (entry: VariableEntry) => React.ReactNode;\n}): React.JSX.Element {\n  const id = React.useId();\n  // A search opens every group it matches in and folds none; the folds come\n  // back as they were once it is cleared.\n  const { foldKey, folded } = foldOf(group, named, folds, searching);\n  return (\n    <section\n      className=\"nx-vars__group\"\n      aria-labelledby={id}\n      // Which group this is, for a host bringing one into view.\n      data-group={group}\n      data-colour-group={named?.name}\n      data-folded={folded ? \"\" : undefined}\n    >\n      <GroupHead\n        id={id}\n        name={named?.name}\n        foldKey={foldKey}\n        heading={heading}\n        count={entries.length}\n        folds={folds}\n        folded={folded}\n        searching={searching}\n      />\n      {folded ? null : (\n        <GroupRows\n          entries={entries}\n          empty={named === undefined ? ADDS[group].empty : NEW_GROUP_EMPTY}\n          searching={searching}\n          openKey={openKey}\n        >\n          {children}\n        </GroupRows>\n      )}\n      {readOnly || folded ? null : (\n        <GroupEnd\n          group={group}\n          named={named}\n          onAdd={(what, from) => {\n            openFold(folds, foldKey);\n            onAdd(what, from, named?.name);\n          }}\n        />\n      )}\n    </section>\n  );\n}\n\n/**\n * What a group's fold is kept under, and whether it is folded: a search\n * opens every group it matches in and folds none, and the folds come back\n * as they were once it is cleared.\n */\nfunction foldOf(\n  group: VariableGroup,\n  named: { readonly name: string } | undefined,\n  folds: GroupFolds | undefined,\n  searching: boolean\n): { foldKey: string; folded: boolean } {\n  const foldKey = named === undefined ? group : colourGroupFoldKey(named.name);\n  return {\n    foldKey,\n    folded: folds !== undefined && !searching && folds.folded.has(foldKey),\n  };\n}\n\n/**\n * A group's heading: its name, folding where the group folds; a named group\n * of colours with its name field, its ⋯ and a drop for a dragged colour.\n */\nfunction GroupHead({\n  id,\n  name,\n  foldKey,\n  heading,\n  count,\n  folds,\n  folded,\n  searching,\n}: {\n  id: string;\n  /** A named group of colours' name. */\n  name: string | undefined;\n  foldKey: string;\n  heading: string;\n  count: number;\n  folds: GroupFolds | undefined;\n  folded: boolean;\n  searching: boolean;\n}): React.JSX.Element {\n  // A colour dropped on a named group's heading goes to its end.\n  const dropOnHead = useColourGroupDrop(name ?? \"\");\n  return (\n    <div\n      className=\"nx-vars__group-head\"\n      {...(name === undefined ? {} : dropOnHead)}\n    >\n      <ColourGroupHeadIf name={name}>\n        <h3 className=\"nx-vars__group-name\" id={id}>\n          <GroupHeading\n            group={foldKey}\n            heading={heading}\n            count={count}\n            folds={folds}\n            folded={folded}\n            searching={searching}\n          />\n        </h3>\n      </ColourGroupHeadIf>\n    </div>\n  );\n}\n\n/**\n * What ends an open group's list, so a new row is added where it is: its\n * add row, and under the last named group of colours, \"+ New group\". A named\n * group before the last ends with neither.\n */\nfunction GroupEnd({\n  group,\n  named,\n  onAdd,\n}: {\n  group: VariableGroup;\n  named: { readonly name: string; readonly last: boolean } | undefined;\n  onAdd: OnAdd;\n}): React.JSX.Element | null {\n  if (named?.last === false) return null;\n  return (\n    <>\n      <AddRows group={group} onAdd={onAdd} />\n      {named === undefined ? null : <NewGroupButton />}\n    </>\n  );\n}\n\n/** A group's name, or, where the group folds, the button that folds it. */\nfunction GroupHeading({\n  group,\n  heading,\n  count,\n  folds,\n  folded,\n  searching,\n}: {\n  /** What the group's fold is kept under. */\n  group: string;\n  heading: string;\n  count: number;\n  folds: GroupFolds | undefined;\n  folded: boolean;\n  searching: boolean;\n}): React.JSX.Element {\n  if (folds === undefined) return <>{heading}</>;\n  return (\n    <GroupToggle\n      heading={heading}\n      count={count}\n      open={!folded}\n      onToggle={searching ? undefined : () => folds.onFold(group, !folded)}\n    />\n  );\n}\n\n/** An open group's rows, a page at a time, or its one empty line. */\nfunction GroupRows({\n  entries,\n  empty,\n  searching,\n  openKey,\n  children,\n}: {\n  entries: readonly VariableEntry[];\n  /** What an empty group says. */\n  empty: string;\n  searching: boolean;\n  openKey: string | null;\n  children: (entry: VariableEntry) => React.ReactNode;\n}): React.JSX.Element {\n  const [pages, setPages] = React.useState(1);\n  // A variable is added at the end of its group, so in a group longer than a\n  // page its row would not mount and the editor opened for it would have\n  // nothing to open beside.\n  const shown = withOpenRow(\n    entries,\n    pages * PAGE_SIZE,\n    entry => entry.row.key === openKey\n  );\n  return (\n    <>\n      {entries.length === 0 && !searching ? (\n        <EmptyGroup text={empty} />\n      ) : (\n        <ul className=\"nx-vars__list\">{shown.map(children)}</ul>\n      )}\n      <ShowMore\n        hidden={entries.length - shown.length}\n        pageSize={PAGE_SIZE}\n        onMore={() => setPages(count => count + 1)}\n      />\n    </>\n  );\n}\n\n/** The supplied version of a variable, matched the way the merge does. */\nfunction suppliedFor(\n  supplied: SiteTokenSet | undefined,\n  identity: string\n): SiteToken | undefined {\n  return (supplied?.tokens ?? []).find(\n    token => tokenIdentity(token) === identity\n  );\n}\n","/**\n * What the Styles tab lists, and how many of its styles a search matches:\n * its block looks and its shared styles, each found by its name, class name,\n * property or value.\n *\n * One listing for both: the tab builds its rows with {@link stylesTabSource}\n * and narrows them with {@link foundSharedStyles} and {@link foundLooks}, and\n * {@link stylesTabMatches} counts through the same three, so the count the\n * Design panel shows beside the tab's name and the rows under it are one\n * answer.\n *\n * @module styles-tab-matches\n */\nimport type { NamedClass, StyleCompileContext } from \"@nextlyhq/blocks-engine\";\n\nimport {\n  searchSharedStyles,\n  sharedStyleRows,\n  sharedStyleSearchText,\n  sharedStylesOnly,\n  type SharedStyleRow,\n} from \"../../styles/shared-style-library\";\n\nimport {\n  blockLookGroups,\n  type BlockLookGroup,\n  type BlockLookRow,\n} from \"./block-look-rows\";\n\n/** The Styles tab's rows before any search: shared styles, and looks by type. */\nexport interface StylesTabSource {\n  readonly rows: SharedStyleRow[];\n  readonly groups: BlockLookGroup[];\n}\n\n/** Every row the Styles tab can list, from the site's library. */\nexport function stylesTabSource(\n  library: readonly NamedClass[],\n  supplied: ReadonlySet<string>\n): StylesTabSource {\n  return {\n    rows: sharedStyleRows(sharedStylesOnly(library), supplied),\n    groups: blockLookGroups(library, supplied),\n  };\n}\n\n/** The shared styles a search finds; every one with no search. */\nexport function foundSharedStyles(\n  rows: readonly SharedStyleRow[],\n  query: string,\n  textOf: (row: SharedStyleRow) => string\n): SharedStyleRow[] {\n  return searchSharedStyles(rows, query, textOf);\n}\n\n/**\n * The looks a search finds, by block type; a type with none left is not\n * listed. Every type, whole, with no search.\n */\nexport function foundLooks(\n  groups: readonly BlockLookGroup[],\n  query: string,\n  textOf: (row: BlockLookRow) => string\n): BlockLookGroup[] {\n  if (query.trim() === \"\") return [...groups];\n  return groups\n    .map(group => ({\n      ...group,\n      rows: searchSharedStyles(group.rows, query, textOf),\n    }))\n    .filter(group => group.rows.length > 0);\n}\n\n/** How many block looks and shared styles the search matches; 0 with none. */\nexport function stylesTabMatches(\n  library: readonly NamedClass[] | undefined,\n  suppliedClassIds: readonly string[] | undefined,\n  query: string,\n  context: StyleCompileContext | undefined\n): number {\n  if (library === undefined || query.trim() === \"\") return 0;\n  const { rows, groups } = stylesTabSource(\n    library,\n    new Set(suppliedClassIds ?? [])\n  );\n  const textOf = (row: SharedStyleRow) => sharedStyleSearchText(row, context);\n  const looks = foundLooks(groups, query, textOf);\n  return (\n    foundSharedStyles(rows, query, textOf).length +\n    looks.reduce((sum, group) => sum + group.rows.length, 0)\n  );\n}\n","/**\n * The host's writes for the Styles tab's block styles, and the words the\n * Block styles section says them in.\n *\n * Each write answers with the refusal in words, or nothing once stored; the\n * two that make a style answer with its id, so the section can open it in the\n * style editor.\n *\n * Every write but a removal is one whole class list, composed against the\n * list the host's queue holds when it runs, so it builds on every class\n * write queued before it. A removal goes through the host's removal, which\n * refuses a style a page still uses and says where.\n *\n * @module block-style-actions\n * @experimental Settles with the Styles tab's Block styles.\n */\n\nimport type { NamedClass } from \"@nextlyhq/blocks-engine\";\n\nimport { EDITOR_WORDS } from \"../editor-words\";\nimport { blockLabel } from \"../panels/add/inserter\";\n\nimport {\n  duplicateBlockStylePlan,\n  newBlockStylePlan,\n  renameBlockStylePlan,\n  withDefaultBlockStyle,\n  withHiddenBlockStyle,\n  type BlockStylePlan,\n} from \"./block-style-plans\";\n\n/** A write that makes a block style: the new style's id, or why it wasn't made. */\nexport type BlockStyleMade =\n  | { readonly ok: true; readonly id: string }\n  | { readonly ok: false; readonly reason: string };\n\n/** What the Block styles section asks of its host. */\nexport interface BlockStyleActions {\n  /** Make a block style for a type, named by the author, from the ★ style's values. */\n  readonly create: (blockType: string, name: string) => Promise<BlockStyleMade>;\n  /** Copy a block style, built-in or the site's own, as the site's own. */\n  readonly duplicate: (id: string) => Promise<BlockStyleMade>;\n  /** Rename a block style the site made: its name only, never its id or class name. */\n  readonly rename: (id: string, name: string) => Promise<string | undefined>;\n  /** Remove a block style the site made, refused while a page uses it. */\n  readonly remove: (id: string) => Promise<string | undefined>;\n  /** Hide a built-in block style from the block panel, or show it again. */\n  readonly setHidden: (\n    id: string,\n    hidden: boolean\n  ) => Promise<string | undefined>;\n  /**\n   * Make a style the ★ of its type, the look its blocks have until another is\n   * picked; `null` gives ★ back to the block's own style.\n   */\n  readonly setDefault: (\n    blockType: string,\n    id: string | null\n  ) => Promise<string | undefined>;\n}\n\n/** The Block styles section's words, as decided. */\nexport const BLOCK_STYLE_WORDS = {\n  heading: EDITOR_WORDS.blockStyles as \"Block styles\",\n  line: \"Saved looks for one kind of block. ★ is the look a block has until you pick another.\",\n  sharedLine: \"Your own styles for any block.\",\n  setDefault: \"Set as default ★\",\n  defaultChip: \"★ Default\",\n  hidden: \"Hidden\",\n  edit: \"Edit\",\n  rename: \"Rename\",\n  duplicate: \"Duplicate\",\n  hide: \"Hide\",\n  show: \"Show\",\n  remove: \"Remove\",\n} as const;\n\n/** \"+ New button style\": the add row that ends a block type's styles. */\nexport function newStyleWords(blockTitle: string): string {\n  return `+ New ${blockTitle.toLowerCase()} style`;\n}\n\n/**\n * One action's class list: the whole list after it, composed from the list\n * the host's queue holds, or why it can't be stored.\n */\nexport type ClassListEdit = (\n  existing: readonly NamedClass[]\n) => { readonly classes: readonly NamedClass[] } | { readonly reason: string };\n\n/**\n * The host's whole-list class write: the list `compose` makes stored as one\n * history step, answering the refusal in words, or nothing once stored.\n */\nexport type EditClasses = (\n  compose: ClassListEdit\n) => Promise<string | undefined>;\n\n/** The host's removal of unused styles, answering the refusal in words. */\ntype RemoveClasses = (ids: readonly string[]) => Promise<string | undefined>;\n\n/** A plan as the host's writer takes it, keeping the id the plan made. */\nfunction composing(\n  plan: (existing: readonly NamedClass[]) => BlockStylePlan,\n  made: { id?: string }\n): ClassListEdit {\n  return existing => {\n    const planned = plan(existing);\n    if (!planned.ok) return { reason: planned.reason };\n    made.id = planned.id;\n    return { classes: planned.classes };\n  };\n}\n\n/** A write that makes a style, answering the style it made. */\nasync function making(\n  edit: EditClasses,\n  plan: (existing: readonly NamedClass[]) => BlockStylePlan\n): Promise<BlockStyleMade> {\n  const made: { id?: string } = {};\n  const refused = await edit(composing(plan, made));\n  if (refused !== undefined) return { ok: false, reason: refused };\n  return made.id === undefined\n    ? { ok: false, reason: \"This block style could not be saved.\" }\n    : { ok: true, id: made.id };\n}\n\n/** The title of the block type a stored style belongs to. */\nfunction titleOf(existing: readonly NamedClass[], id: string): string {\n  return blockLabel(existing.find(entry => entry.id === id)?.blockType ?? \"\");\n}\n\n/**\n * The Block styles section's writes over the host's one whole-list class\n * writer and its removal. Without a removal, removing is refused in words.\n */\nexport function blockStyleActionsOf(\n  edit: EditClasses,\n  remove: RemoveClasses | undefined\n): BlockStyleActions {\n  return {\n    create: (blockType, name) =>\n      making(edit, existing =>\n        newBlockStylePlan(existing, blockType, name, blockLabel(blockType))\n      ),\n    duplicate: id =>\n      making(edit, existing =>\n        duplicateBlockStylePlan(existing, id, titleOf(existing, id))\n      ),\n    rename: (id, name) =>\n      edit(\n        composing(\n          existing =>\n            renameBlockStylePlan(existing, id, name, titleOf(existing, id)),\n          {}\n        )\n      ),\n    remove: async id =>\n      remove === undefined\n        ? \"Block styles can't be removed here.\"\n        : remove([id]),\n    setHidden: (id, hidden) =>\n      edit(existing => ({\n        classes: withHiddenBlockStyle(existing, id, hidden),\n      })),\n    setDefault: (blockType, id) =>\n      edit(existing => ({\n        classes: withDefaultBlockStyle(existing, blockType, id),\n      })),\n  };\n}\n","/**\n * A block style row's ⋯ menu and its name field: the actions the style\n * offers, and the field a rename or a new style is named in.\n *\n * Which actions a row offers follows what the style is. The block's own\n * style can be edited and made the default again; a built-in style (one a\n * block or a plugin supplies in code) can be edited, duplicated, made the\n * default and hidden, never renamed or removed; a style the site made can be\n * edited, made the default, renamed, duplicated and removed.\n *\n * @module block-style-row-menu\n * @experimental Settles with the Styles tab's Block styles.\n */\n\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n  Input,\n} from \"@nextlyhq/ui\";\nimport { Ellipsis } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { commitOnEnter } from \"../../inspector/commit-on-enter\";\nimport { BLOCK_STYLE_WORDS } from \"../../styles/block-style-actions\";\n\n/** What a row's menu offers, from what the style is. */\nexport interface BlockStyleOffers {\n  readonly edit: boolean;\n  readonly setDefault: boolean;\n  readonly rename: boolean;\n  readonly duplicate: boolean;\n  /** \"Hide\" or \"Show\", or nothing for a style that can't be hidden. */\n  readonly hide: \"hide\" | \"show\" | undefined;\n  readonly remove: boolean;\n}\n\n/** One block style as its menu reads it. */\nexport interface BlockStyleKind {\n  /** The block's own style, the default while no style carries ★. */\n  readonly own: boolean;\n  /** Supplied in code by a block or a plugin. */\n  readonly builtIn: boolean;\n  readonly starred: boolean;\n  readonly hidden: boolean;\n}\n\n/** Nothing offered: a read-only role, or a host with no writes. */\nconst NO_OFFERS: BlockStyleOffers = {\n  edit: false,\n  setDefault: false,\n  rename: false,\n  duplicate: false,\n  hide: undefined,\n  remove: false,\n};\n\n/** The actions a style offers; a read-only role is offered none. */\nexport function blockStyleOffers(\n  style: BlockStyleKind,\n  readOnly: boolean\n): BlockStyleOffers {\n  if (readOnly) return NO_OFFERS;\n  const siteMade = !style.own && !style.builtIn;\n  const builtInWorn = style.builtIn && !style.own;\n  return {\n    edit: true,\n    setDefault: !style.starred,\n    rename: siteMade,\n    duplicate: !style.own,\n    hide: builtInWorn ? (style.hidden ? \"show\" : \"hide\") : undefined,\n    remove: siteMade,\n  };\n}\n\n/** Whether a style's menu has anything to offer. */\nexport function offersAny(offers: BlockStyleOffers): boolean {\n  return Object.values(offers).some(\n    offer => offer !== false && offer !== undefined\n  );\n}\n\n/** What the menu does when an item is chosen. */\nexport interface BlockStyleMenuActions {\n  readonly onEdit: () => void;\n  readonly onSetDefault: () => void;\n  readonly onRename: () => void;\n  readonly onDuplicate: () => void;\n  readonly onHidden: (hidden: boolean) => void;\n  readonly onRemove: () => void;\n}\n\n/**\n * The row's ⋯ button and its menu. The menu key and Shift+F10 on the row\n * open it too, through `open`, and closing it then hands focus back to the\n * row (`returnTo`) rather than the ⋯. An item that hands focus elsewhere\n * (the name field, the style editor) says so, so closing the menu takes\n * focus nowhere.\n */\nexport function BlockStyleMenu({\n  name,\n  offers,\n  actions,\n  open,\n  onOpenChange,\n  returnTo,\n}: {\n  readonly name: string;\n  readonly offers: BlockStyleOffers;\n  readonly actions: BlockStyleMenuActions;\n  readonly open: boolean;\n  readonly onOpenChange: (open: boolean) => void;\n  /**\n   * Where focus goes as the menu closes, while set: the row it was opened\n   * from. Cleared as it is used, so a later pointer open returns to the ⋯.\n   */\n  readonly returnTo?: React.RefObject<HTMLElement | null>;\n}): React.JSX.Element {\n  return (\n    <RowMenuFrame\n      name={name}\n      open={open}\n      onOpenChange={onOpenChange}\n      {...(returnTo === undefined ? {} : { returnTo })}\n    >\n      {handOff => (\n        <>\n          {offers.edit ? (\n            <DropdownMenuItem onSelect={handOff(actions.onEdit)}>\n              {BLOCK_STYLE_WORDS.edit}\n            </DropdownMenuItem>\n          ) : null}\n          {offers.setDefault ? (\n            <DropdownMenuItem onSelect={actions.onSetDefault}>\n              {BLOCK_STYLE_WORDS.setDefault}\n            </DropdownMenuItem>\n          ) : null}\n          {offers.rename ? (\n            <DropdownMenuItem onSelect={handOff(actions.onRename)}>\n              {BLOCK_STYLE_WORDS.rename}\n            </DropdownMenuItem>\n          ) : null}\n          {offers.duplicate ? (\n            <DropdownMenuItem onSelect={handOff(actions.onDuplicate)}>\n              {BLOCK_STYLE_WORDS.duplicate}\n            </DropdownMenuItem>\n          ) : null}\n          {offers.hide === undefined ? null : (\n            <DropdownMenuItem\n              onSelect={() => actions.onHidden(offers.hide === \"hide\")}\n            >\n              {offers.hide === \"hide\"\n                ? BLOCK_STYLE_WORDS.hide\n                : BLOCK_STYLE_WORDS.show}\n            </DropdownMenuItem>\n          )}\n          {offers.remove ? (\n            <>\n              <DropdownMenuSeparator />\n              <DropdownMenuItem onSelect={actions.onRemove}>\n                {BLOCK_STYLE_WORDS.remove}\n              </DropdownMenuItem>\n            </>\n          ) : null}\n        </>\n      )}\n    </RowMenuFrame>\n  );\n}\n\n/**\n * A row's ⋯ button and its menu, whose items the caller draws: shared by\n * the Block styles and the Text styles rows. The menu key and Shift+F10 on\n * a row open it too, through `open`, and closing it then hands focus back\n * to the row (`returnTo`) rather than the ⋯. An item that hands focus\n * elsewhere runs through `handOff`, so closing the menu takes focus nowhere.\n */\nexport function RowMenuFrame({\n  name,\n  open,\n  onOpenChange,\n  returnTo,\n  children,\n}: {\n  readonly name: string;\n  readonly open: boolean;\n  readonly onOpenChange: (open: boolean) => void;\n  readonly returnTo?: React.RefObject<HTMLElement | null>;\n  readonly children: (\n    handOff: (then: () => void) => () => void\n  ) => React.ReactNode;\n}): React.JSX.Element {\n  const handingOff = React.useRef(false);\n  const handOff = (then: () => void) => () => {\n    handingOff.current = true;\n    then();\n  };\n  return (\n    // Not modal: a modal menu marks the panel around it aria-hidden while\n    // its rows stay focusable.\n    <DropdownMenu modal={false} open={open} onOpenChange={onOpenChange}>\n      <DropdownMenuTrigger asChild>\n        <button\n          type=\"button\"\n          className=\"nx-vars__icon-button nx-vars__more\"\n          aria-label={`More actions for ${name}`}\n        >\n          <Ellipsis aria-hidden=\"true\" size={14} />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align=\"end\"\n        collisionPadding={8}\n        className=\"nx-vars__menu\"\n        onCloseAutoFocus={event => {\n          if (handingOff.current) {\n            handingOff.current = false;\n            event.preventDefault();\n            return;\n          }\n          if (returnTo === undefined) return;\n          const back = returnTo.current;\n          if (back === null) return;\n          returnTo.current = null;\n          event.preventDefault();\n          back.focus();\n        }}\n      >\n        {children(handOff)}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/**\n * A block style's name being typed: a new style's, or a rename's. Enter\n * keeps it; Escape puts it down. The refusal, when the write was refused, is\n * said under it and the field stays open.\n */\nexport function BlockStyleNameField({\n  label,\n  initial,\n  onCommit,\n  onCancel,\n}: {\n  /** The field's accessible name: \"New button style name\", \"Rename Ghost\". */\n  readonly label: string;\n  readonly initial: string;\n  /** Store the name: the refusal in words, or nothing once stored. */\n  readonly onCommit: (name: string) => Promise<string | undefined>;\n  readonly onCancel: () => void;\n}): React.JSX.Element {\n  const [value, setValue] = React.useState(initial);\n  const [refusal, setRefusal] = React.useState<string | null>(null);\n  const [busy, setBusy] = React.useState(false);\n  const issueId = React.useId();\n  const commit = async (): Promise<void> => {\n    if (busy) return;\n    setBusy(true);\n    try {\n      setRefusal((await onCommit(value)) ?? null);\n    } finally {\n      setBusy(false);\n    }\n  };\n  return (\n    <div className=\"nx-block-styles__name-field\">\n      <Input\n        autoFocus\n        className=\"nx-vars__rename-field\"\n        aria-label={label}\n        aria-describedby={refusal === null ? undefined : issueId}\n        aria-invalid={refusal === null ? undefined : true}\n        value={value}\n        readOnly={busy}\n        onFocus={event => event.currentTarget.select()}\n        onChange={event => {\n          setValue(event.target.value);\n          setRefusal(null);\n        }}\n        onKeyDown={event => {\n          if (commitOnEnter(event, () => void commit())) return;\n          if (event.key !== \"Escape\") return;\n          // The innermost thing Escape closes: the field, never the canvas\n          // selection or the panel around it.\n          event.preventDefault();\n          event.stopPropagation();\n          onCancel();\n        }}\n      />\n      {refusal === null ? null : (\n        <p className=\"nx-vars-editor__issue\" id={issueId} role=\"alert\">\n          {refusal}\n        </p>\n      )}\n    </div>\n  );\n}\n","/**\n * The Styles tab's Block styles section: every block type's block styles,\n * the block's own style first, each drawn as a small block of its type. A\n * type's styles fold under its name and end with \"+ New <block> style\".\n * Choosing a row edits that style in the style editor, with no block\n * selected; its ⋯ menu holds the style's other actions.\n *\n * Keyboard: Enter or Space on a row edits it, F2 renames a style the site\n * made, and the menu key or Shift+F10 opens its ⋯ menu. Escape in a name\n * field puts it down and hands focus back to the row it came from.\n *\n * @module block-looks-group\n * @experimental Settles with the Styles tab's Block styles.\n */\n\nimport type {\n  NamedClass,\n  SiteTokenSet,\n  TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { LookSpecimen } from \"../../inspector/style-inspector/look-tiles-view\";\nimport {\n  BLOCK_STYLE_WORDS,\n  newStyleWords,\n  type BlockStyleActions,\n  type BlockStyleMade,\n} from \"../../styles/block-style-actions\";\nimport {\n  sharedStyleReachSentence,\n  type BlocksOnThisPage,\n  type SharedStyleReach,\n} from \"../../styles/shared-style-library\";\nimport { blockLabel } from \"../add/inserter\";\n\nimport {\n  ownLookDescription,\n  sameLook,\n  siteBaseOf,\n  type BlockLookGroup,\n  type BlockLookRow,\n  type LookKey,\n} from \"./block-look-rows\";\nimport {\n  blockStyleOffers,\n  BlockStyleMenu,\n  BlockStyleNameField,\n  offersAny,\n  type BlockStyleMenuActions,\n  type BlockStyleOffers,\n} from \"./block-style-row-menu\";\nimport { GroupToggle } from \"./design-group-toggle\";\nimport type { GroupFolds } from \"./tokens-panel\";\n\nexport interface BlockLooksGroupProps {\n  readonly groups: readonly BlockLookGroup[];\n  readonly library: readonly NamedClass[];\n  readonly tokens: SiteTokenSet | undefined;\n  readonly mode: TokenMode;\n  /** The style being edited in the style editor, whose row shows as chosen. */\n  readonly editing: LookKey | null | undefined;\n  /** Edit a style in the style editor. Absent: the rows are shown, not chosen. */\n  readonly onEdit?: (look: LookKey) => void;\n  /** The host's writes. Absent, or read-only: the rows offer no action. */\n  readonly actions?: BlockStyleActions;\n  readonly readOnly?: boolean;\n  /** Which types the author folded, kept by the host. Absent: none fold. */\n  readonly folds?: GroupFolds;\n  /** Whether a search is narrowing the rows: every type is open then. */\n  readonly searching?: boolean;\n  /** A worn style's reach, as the tab's usage read has it, or `undefined`. */\n  readonly reachOf: (row: BlockLookRow) => SharedStyleReach | undefined;\n  /**\n   * The open page's blocks wearing a worn style, as the shared styles count\n   * theirs: the page's unsaved blocks are not in the site's index yet.\n   */\n  readonly blocksOf: (row: BlockLookRow) => BlocksOnThisPage | undefined;\n  /** A reach drawn as the shared styles' counts are. */\n  readonly chip: (reach: SharedStyleReach) => React.ReactNode;\n}\n\n/**\n * A block type's group in the author's folds, and the name a reveal finds it\n * by (`data-group`), so a host sending the author to one type's styles opens\n * the group this section draws.\n *\n * @experimental Settles with the Design panel's Block styles.\n */\nexport function blockStyleFoldId(blockType: string): string {\n  return `block-styles:${blockType}`;\n}\n\n/** Whether the section may write: a host's actions, and a role that may change Design. */\nfunction writableOf(props: BlockLooksGroupProps): boolean {\n  return props.readOnly !== true && props.actions !== undefined;\n}\n\nexport function BlockLooksGroup(\n  props: BlockLooksGroupProps\n): React.JSX.Element | null {\n  const headingId = React.useId();\n  const lineId = React.useId();\n  if (props.groups.length === 0) return null;\n  return (\n    <section\n      className=\"nx-vars__group nx-block-styles\"\n      aria-labelledby={headingId}\n      aria-describedby={lineId}\n    >\n      <div className=\"nx-block-styles__head\">\n        <h3 id={headingId} className=\"nx-vars__group-name\">\n          {BLOCK_STYLE_WORDS.heading}\n        </h3>\n        <p id={lineId} className=\"nx-block-styles__line\">\n          {BLOCK_STYLE_WORDS.line}\n        </p>\n      </div>\n      {props.groups.map(group => (\n        <TypeGroup key={group.blockType} group={group} panel={props} />\n      ))}\n    </section>\n  );\n}\n\n/** Whether a type's group is folded: never while a search narrows the rows. */\nfunction foldedOf(panel: BlockLooksGroupProps, id: string): boolean {\n  return panel.searching !== true && panel.folds?.folded.has(id) === true;\n}\n\n/** One block type's styles under its folding heading, then its add row. */\nfunction TypeGroup({\n  group,\n  panel,\n}: {\n  readonly group: BlockLookGroup;\n  readonly panel: BlockLooksGroupProps;\n}): React.JSX.Element {\n  const title = blockLabel(group.blockType);\n  const base = siteBaseOf(panel.library, group.blockType);\n  const id = blockStyleFoldId(group.blockType);\n  const folded = foldedOf(panel, id);\n  const folds = panel.searching === true ? undefined : panel.folds;\n  return (\n    <div\n      className=\"nx-block-styles__type\"\n      data-group={id}\n      data-block-type={group.blockType}\n    >\n      <h4 className=\"nx-block-styles__type-head\">\n        <GroupToggle\n          heading={title}\n          count={group.rows.length}\n          open={!folded}\n          onToggle={\n            folds === undefined ? undefined : () => folds.onFold(id, !folded)\n          }\n        />\n      </h4>\n      {folded ? null : (\n        <>\n          <ul className=\"nx-block-styles__rows\" aria-label={`${title} styles`}>\n            {group.rows.map(row => (\n              <li key={row.id}>\n                <StyleRow\n                  row={row}\n                  title={title}\n                  panel={panel}\n                  specimen={\n                    <LookSpecimen\n                      blockType={group.blockType}\n                      // The own style's specimen is the site's base itself;\n                      // every other style is drawn over it.\n                      base={base}\n                      styles={row.own ? undefined : row.styles}\n                      tokens={panel.tokens}\n                      mode={panel.mode}\n                    />\n                  }\n                />\n              </li>\n            ))}\n          </ul>\n          {writableOf(panel) ? (\n            <NewStyleRow\n              blockType={group.blockType}\n              title={title}\n              panel={panel}\n            />\n          ) : null}\n        </>\n      )}\n    </div>\n  );\n}\n\n/** Focus a button once the field that took its place is gone. */\nfunction focusLater(target: React.RefObject<HTMLElement | null>): void {\n  requestAnimationFrame(() => target.current?.focus());\n}\n\n/** \"+ New <block> style\", then the field its name is typed in. */\nfunction NewStyleRow({\n  blockType,\n  title,\n  panel,\n}: {\n  readonly blockType: string;\n  readonly title: string;\n  readonly panel: BlockLooksGroupProps;\n}): React.JSX.Element {\n  const [naming, setNaming] = React.useState(false);\n  const button = React.useRef<HTMLButtonElement>(null);\n  const words = newStyleWords(title);\n  if (naming) {\n    return (\n      <BlockStyleNameField\n        label={`${words.slice(2)} name`}\n        initial=\"\"\n        onCommit={async name => {\n          const made = await panel.actions?.create(blockType, name);\n          if (made === undefined) return undefined;\n          if (!made.ok) return made.reason;\n          setNaming(false);\n          // Opened in the style editor, as the new style's first edit.\n          panel.onEdit?.({ id: made.id, blockType });\n          return undefined;\n        }}\n        onCancel={() => {\n          setNaming(false);\n          focusLater(button);\n        }}\n      />\n    );\n  }\n  return (\n    <button\n      ref={button}\n      type=\"button\"\n      className=\"nx-block-styles__add\"\n      onClick={() => setNaming(true)}\n    >\n      {words}\n    </button>\n  );\n}\n\n/** A row's chips: ★ Default and Hidden, then how widely it is used. */\nfunction Chips({\n  row,\n  reach,\n  chip,\n}: {\n  readonly row: BlockLookRow;\n  readonly reach: SharedStyleReach | undefined;\n  readonly chip: (reach: SharedStyleReach) => React.ReactNode;\n}): React.JSX.Element {\n  // Hidden from assistive technology: the row's name says each in words.\n  return (\n    <span className=\"nx-block-styles__chips\" aria-hidden=\"true\">\n      {row.starred ? (\n        <span className=\"nx-vars__chip nx-block-styles__star\">\n          {BLOCK_STYLE_WORDS.defaultChip}\n        </span>\n      ) : null}\n      {row.hidden ? (\n        <span className=\"nx-vars__chip\">{BLOCK_STYLE_WORDS.hidden}</span>\n      ) : null}\n      {reach === undefined ? null : chip(reach)}\n    </span>\n  );\n}\n\n/** What a row is called: its name, what it is, and its reach in words. */\nfunction rowName(row: BlockLookRow, sentence: string): string {\n  return [\n    row.name,\n    row.starred ? \"default\" : \"\",\n    row.hidden ? \"hidden\" : \"\",\n    row.inCode && !row.own ? \"built-in\" : \"\",\n    sentence,\n  ]\n    .filter(part => part !== \"\")\n    .join(\", \");\n}\n\n/** A write's refusal in words, or nothing once stored. */\ntype Write = () => Promise<string | undefined>;\n\n/** A write that makes a style, opening the style it made in the style editor. */\nfunction opening(\n  make: () => Promise<BlockStyleMade>,\n  open: (id: string) => void\n): Write {\n  return async () => {\n    const made = await make();\n    if (!made.ok) return made.reason;\n    open(made.id);\n    return undefined;\n  };\n}\n\n/**\n * Why a style can't be removed for what the open page holds, or `undefined`:\n * a block on it wears the style, unsaved and so in no document the removal\n * reads, or the page has more blocks than could be read to tell.\n */\nfunction pageUseRefusal(\n  row: BlockLookRow,\n  blocks: BlocksOnThisPage | undefined\n): string | undefined {\n  if (blocks === undefined || !blocks.complete) {\n    return `${row.name} can't be removed: this page has more blocks than could be read to check it isn't used.`;\n  }\n  if (blocks.count === 0) return undefined;\n  const them = blocks.count === 1 ? \"1 block\" : `${blocks.count} blocks`;\n  return `${row.name} is used on ${them} on this page. Take it off them first.`;\n}\n\n/** The menu's actions for one row, through the host's writes. */\nfunction menuActionsOf(\n  row: BlockLookRow,\n  panel: BlockLooksGroupProps,\n  run: (write: Write | undefined) => void,\n  onRename: () => void\n): BlockStyleMenuActions {\n  const actions = panel.actions;\n  const edit = (id: string) => panel.onEdit?.({ id, blockType: row.blockType });\n  return {\n    onEdit: () => edit(row.id),\n    onSetDefault: () =>\n      run(\n        actions &&\n          (() => actions.setDefault(row.blockType, row.own ? null : row.id))\n      ),\n    onRename,\n    onDuplicate: () =>\n      run(actions && opening(() => actions.duplicate(row.id), edit)),\n    onHidden: hidden =>\n      run(actions && (() => actions.setHidden(row.id, hidden))),\n    onRemove: () =>\n      run(\n        actions &&\n          (async () =>\n            pageUseRefusal(row, panel.blocksOf(row)) ?? actions.remove(row.id))\n      ),\n  };\n}\n\n/** Whether a key on a row opens its ⋯ menu: the menu key, or Shift+F10. */\nfunction opensMenu(event: React.KeyboardEvent): boolean {\n  return event.key === \"ContextMenu\" || (event.key === \"F10\" && event.shiftKey);\n}\n\n/** The row's keys: F2 renames where a rename is offered; the menu key opens ⋯. */\nfunction rowKeys(\n  offers: BlockStyleOffers,\n  onRename: () => void,\n  onMenu: () => void\n): (event: React.KeyboardEvent) => void {\n  return event => {\n    if (event.key === \"F2\" && offers.rename) {\n      event.preventDefault();\n      onRename();\n    } else if (opensMenu(event) && offersAny(offers)) {\n      event.preventDefault();\n      onMenu();\n    }\n  };\n}\n\nfunction StyleRow({\n  row,\n  title,\n  panel,\n  specimen,\n}: {\n  readonly row: BlockLookRow;\n  readonly title: string;\n  readonly panel: BlockLooksGroupProps;\n  readonly specimen: React.ReactNode;\n}): React.JSX.Element {\n  const [menuOpen, setMenuOpen] = React.useState(false);\n  // Set while the menu was opened from the row by its keys, so closing it\n  // returns there; a ref, since the close reads it after the last render.\n  const returnTo = React.useRef<HTMLElement | null>(null);\n  const [renaming, setRenaming] = React.useState(false);\n  const [refusal, setRefusal] = React.useState<string | null>(null);\n  const rowRef = React.useRef<HTMLButtonElement>(null);\n  const reach = row.own ? undefined : panel.reachOf(row);\n  const sentence = sharedStyleReachSentence(\n    row.own ? undefined : panel.blocksOf(row),\n    reach\n  );\n  const offers = blockStyleOffers(\n    {\n      own: row.own,\n      builtIn: row.inCode,\n      starred: row.starred,\n      hidden: row.hidden,\n    },\n    !writableOf(panel)\n  );\n  const run = (write: Write | undefined): void => {\n    if (write === undefined) return;\n    void write().then(refused => setRefusal(refused ?? null));\n  };\n  const startRename = () => {\n    setRefusal(null);\n    setRenaming(true);\n  };\n  // Drawn only while the section may still write: a role that loses the\n  // right with the field open is shown the row again.\n  if (renaming && writableOf(panel)) {\n    return (\n      <BlockStyleNameField\n        label={`Rename ${row.name}`}\n        initial={row.name}\n        onCommit={async name => {\n          if (!writableOf(panel)) return undefined;\n          const refused = await panel.actions?.rename(row.id, name);\n          if (refused === undefined) {\n            setRenaming(false);\n            focusLater(rowRef);\n          }\n          return refused;\n        }}\n        onCancel={() => {\n          setRenaming(false);\n          focusLater(rowRef);\n        }}\n      />\n    );\n  }\n  return (\n    <div\n      className=\"nx-vars__line nx-block-styles__item\"\n      data-hidden={row.hidden ? \"\" : undefined}\n    >\n      <button\n        ref={rowRef}\n        type=\"button\"\n        className=\"nx-vars__row nx-block-styles__row\"\n        aria-pressed={\n          panel.onEdit === undefined ? undefined : sameLook(row, panel.editing)\n        }\n        aria-description={row.own ? ownLookDescription(title) : undefined}\n        title={sentence === \"\" ? undefined : sentence}\n        data-block-look={row.id}\n        onClick={() => panel.onEdit?.({ id: row.id, blockType: row.blockType })}\n        onKeyDown={rowKeys(offers, startRename, () => {\n          returnTo.current = rowRef.current;\n          setMenuOpen(true);\n        })}\n      >\n        <span className=\"nx-block-looks__specimen\">{specimen}</span>\n        <span className=\"nx-vars__name\" title={row.name} aria-hidden=\"true\">\n          {row.name}\n        </span>\n        <Chips row={row} reach={reach} chip={panel.chip} />\n        {/* The row's name, in one element: its name, what it is and its\n            reach. Text rather than an aria-label, which would have to hold\n            every drawn word, the specimen's and the chips' included. */}\n        <span className=\"nx-sr-only\">{rowName(row, sentence)}</span>\n      </button>\n      {offersAny(offers) ? (\n        <BlockStyleMenu\n          name={row.name}\n          offers={offers}\n          actions={menuActionsOf(row, panel, run, startRename)}\n          open={menuOpen}\n          onOpenChange={setMenuOpen}\n          returnTo={returnTo}\n        />\n      ) : null}\n      {refusal === null ? null : (\n        <p\n          className=\"nx-vars-editor__issue nx-block-styles__issue\"\n          role=\"alert\"\n        >\n          {refusal}\n        </p>\n      )}\n    </div>\n  );\n}\n","/**\n * One row of the Shared styles tab: its tile and the paint it is drawn from,\n * its accessible name, the row with its popover editor, the dark-mode tip,\n * its content and its reach chip.\n *\n * @module shared-style-row\n */\n\nimport type { SiteTokenSet } from \"@nextlyhq/blocks-engine\";\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n  TooltipProvider,\n} from \"@nextlyhq/ui\";\nimport { Lock, Moon } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { usePrefersDark } from \"../../canvas/prefers-dark\";\nimport { ChromeTooltip } from \"../../chrome-tooltip\";\nimport {\n  sharedStyleTile,\n  SHARED_STYLE_DARK_UNREADABLE,\n  sharedStylePreview,\n  sharedStyleReachChip,\n  sharedStyleReachSentence,\n  type SharedStyleReach,\n  type SharedStyleRow,\n  type SharedStyleTile,\n} from \"../../styles/shared-style-library\";\nimport { activeTokenMode } from \"../../styles/style-colour\";\n\nimport type { TokenMode } from \"./font-library\";\nimport { SharedStyleDetails } from \"./shared-style-details\";\n\n/** What each row's tile is drawn from: the site's variables, in the canvas's mode. */\nexport interface TilePaint {\n  readonly tokens: SiteTokenSet | undefined;\n  readonly mode: TokenMode;\n}\n\n/** The site's variables and the mode the canvas shows, for every row's tile. */\nexport function usePaint(tokens: SiteTokenSet | undefined): TilePaint {\n  return { tokens, mode: activeTokenMode(usePrefersDark()) };\n}\n\n/** A row's accessible name: its name, class name, marks and reach in words. */\nfunction rowLabel(\n  row: SharedStyleRow,\n  name: string,\n  sentence: string,\n  tile: SharedStyleTile\n): string {\n  return [\n    name,\n    row.className,\n    ...(row.locked ? [\"locked\"] : []),\n    ...(row.inCode ? [\"set in your site’s code\"] : []),\n    ...(tile.darkUnreadable ? [SHARED_STYLE_DARK_UNREADABLE] : []),\n    ...(sentence === \"\" ? [] : [sentence]),\n  ].join(\", \");\n}\n\n/** What a row's details are handed beside the row and its name. */\ntype RowDetails = Omit<\n  React.ComponentProps<typeof SharedStyleDetails>,\n  \"row\" | \"name\" | \"sentence\"\n>;\n\n/** One shared style: a row that opens its details beside the panel. */\nexport function StyleRow({\n  row,\n  name,\n  details,\n  paint,\n  open,\n  onOpenChange,\n}: {\n  row: SharedStyleRow;\n  name: string;\n  details: RowDetails;\n  /** What the row's preview tile is drawn from. */\n  paint: TilePaint;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n}): React.JSX.Element {\n  const sentence = sharedStyleReachSentence(details.blocks, details.reach);\n  const tile = sharedStyleTile(\n    paint.tokens,\n    paint.mode,\n    sharedStylePreview(row.styles, details.styleContext)\n  );\n  // A name that can't be changed is not focused, and so not selected, on\n  // open: selected text reads as editable. The details take focus instead.\n  const fixed = details.readOnly || row.locked || row.inCode;\n  const content = React.useRef<HTMLDivElement>(null);\n  return (\n    <li>\n      <Popover open={open} onOpenChange={onOpenChange} modal>\n        <DarkModeTip shown={tile.darkUnreadable}>\n          <PopoverTrigger asChild>\n            <button\n              type=\"button\"\n              className=\"nx-vars__row nx-shared-styles__row\"\n              title={sentence === \"\" ? undefined : sentence}\n              data-shared-style={row.id}\n            >\n              <RowContent\n                row={row}\n                name={name}\n                reach={details.reach}\n                tile={tile}\n              />\n              {/* The row's whole name, in one element: the name and class it\n                  shows first, then its marks and reach. Text rather than an\n                  aria-label, which must hold every drawn word, the tile's\n                  \"Aa\" included; one element, so no browser puts a space\n                  before its commas. */}\n              <span className=\"nx-sr-only\">\n                {rowLabel(row, name, sentence, tile)}\n              </span>\n            </button>\n          </PopoverTrigger>\n        </DarkModeTip>\n        <PopoverContent\n          side=\"right\"\n          align=\"start\"\n          sideOffset={12}\n          className=\"nx-vars-editor nx-shared-styles__editor\"\n          aria-label={name}\n          ref={content}\n          onOpenAutoFocus={\n            fixed\n              ? event => {\n                  event.preventDefault();\n                  content.current?.focus();\n                }\n              : undefined\n          }\n        >\n          <SharedStyleDetails\n            {...details}\n            row={row}\n            name={name}\n            sentence={sentence}\n          />\n        </PopoverContent>\n      </Popover>\n    </li>\n  );\n}\n\n/**\n * The row's \"Hard to read in dark mode\" tooltip, shown when the row is\n * hovered or focused, so keyboard and touch users meet it too; the row's\n * accessible name says it as well. Nothing is added inside the row button,\n * which is already the one control.\n */\nfunction DarkModeTip({\n  shown,\n  children,\n}: {\n  shown: boolean;\n  children: React.ReactElement;\n}): React.JSX.Element {\n  if (!shown) return children;\n  return (\n    <TooltipProvider delayDuration={300}>\n      {/* The editor's own tooltip, which closes as the pointer moves onto the\n          canvas; to the right of the row, as before. */}\n      <ChromeTooltip side=\"right\" content={SHARED_STYLE_DARK_UNREADABLE}>\n        {children}\n      </ChromeTooltip>\n    </TooltipProvider>\n  );\n}\n\n/** A row's preview, name and class name, lock, and count. */\nfunction RowContent({\n  row,\n  name,\n  reach,\n  tile,\n}: {\n  row: SharedStyleRow;\n  name: string;\n  reach: SharedStyleReach | undefined;\n  tile: SharedStyleTile;\n}): React.JSX.Element {\n  return (\n    <>\n      {/* The page under the preview, so its colours read as on the site; the\n          light page, marked, where the style is hard to read on the dark. */}\n      <span\n        className=\"nx-shared-styles__tile\"\n        aria-hidden=\"true\"\n        style={tile.page}\n        data-dark-unreadable={tile.darkUnreadable ? \"\" : undefined}\n      >\n        {/* Outlined: its outline is inline, chosen against its own\n            background; the class marks it. */}\n        <span\n          className={\n            tile.outlined\n              ? \"nx-vars__specimen nx-shared-styles__lead nx-shared-styles__lead--outlined\"\n              : \"nx-vars__specimen nx-shared-styles__lead\"\n          }\n          style={tile.specimen}\n        >\n          Aa\n        </span>\n        {tile.darkUnreadable ? (\n          <Moon className=\"nx-shared-styles__dark-flag\" size={8} />\n        ) : null}\n      </span>\n      {/* Drawn only: the row's screen-reader name starts with them. */}\n      <span className=\"nx-shared-styles__names\" aria-hidden=\"true\">\n        <span className=\"nx-vars__name\" title={name}>\n          {name}\n        </span>\n        <span className=\"nx-shared-styles__class\">{row.className}</span>\n      </span>\n      {row.locked ? (\n        <Lock className=\"nx-shared-styles__lock\" aria-hidden=\"true\" size={12} />\n      ) : null}\n      {row.inCode ? (\n        <span className=\"nx-vars__chip\" aria-hidden=\"true\">\n          In code\n        </span>\n      ) : null}\n      {reach === undefined ? null : <ReachChip reach={reach} />}\n    </>\n  );\n}\n\n/** A row's count, muted while it is a zero not counted yet. */\nexport function ReachChip({\n  reach,\n}: {\n  reach: SharedStyleReach;\n}): React.JSX.Element {\n  const chip = sharedStyleReachChip(reach);\n  return (\n    <span\n      className={\n        chip.uncounted\n          ? \"nx-vars__chip nx-shared-styles__count--uncounted\"\n          : \"nx-vars__chip\"\n      }\n      aria-hidden=\"true\"\n      // Each kind in words on hover, which \"5 places\" totals; the row's\n      // name says the same to a screen reader.\n      title={sharedStyleReachSentence(undefined, reach) || undefined}\n    >\n      {chip.words}\n    </span>\n  );\n}\n","/**\n * The Shared styles tab's list and what is said around it: the filter bar,\n * the note above the list, the notes while pages are counted, the styles\n * withheld from removal, the list of rows, and the rows not yet read.\n *\n * @module shared-styles-list\n */\n\nimport { Button } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport {\n  inSharedStyleFilter,\n  sharedStyleFilterEmpty,\n  SHARED_STYLE_FILTERS,\n  SHARED_STYLE_COUNTING_NOTE,\n  SHARED_STYLE_UNCOUNTABLE_NOTE,\n  SHARED_STYLE_UNUSED_UNCERTAIN,\n  SHARED_STYLES_WORD,\n  type SharedStyleFilter,\n  type SharedStyleRow,\n} from \"../../styles/shared-style-library\";\n\nimport type { Issue } from \"./shared-styles-usage\";\nimport {\n  BackgroundJobsLink,\n  CountedByJobs,\n  countNowWords,\n  type CountNow,\n} from \"./usage-reads\";\n\n/**\n * All · Used · Unused · Locked, each with how many styles it holds. Used and\n * Unused are counted only once every count is exact: while some pages are\n * still being counted, or some usage is still being read, a number there\n * would be a guess.\n */\nexport function FilterBar({\n  rows,\n  filter,\n  onFilter,\n  usageOf,\n  exact,\n}: {\n  rows: readonly SharedStyleRow[];\n  filter: SharedStyleFilter;\n  onFilter: (filter: SharedStyleFilter) => void;\n  usageOf: (row: SharedStyleRow) => \"used\" | \"unused\" | undefined;\n  exact: boolean;\n}): React.JSX.Element {\n  const countOf = (candidate: SharedStyleFilter): number | undefined => {\n    if ((candidate === \"used\" || candidate === \"unused\") && !exact) {\n      return undefined;\n    }\n    return rows.filter(row => inSharedStyleFilter(row, candidate, usageOf(row)))\n      .length;\n  };\n  return (\n    <div className=\"nx-shared-styles__filters\" role=\"group\" aria-label=\"Show\">\n      <div className=\"nx-vars__seg\">\n        {SHARED_STYLE_FILTERS.map(({ filter: candidate, word }) => {\n          const count = countOf(candidate);\n          return (\n            <button\n              key={candidate}\n              type=\"button\"\n              className=\"nx-shared-styles__filter\"\n              aria-pressed={filter === candidate}\n              aria-label={\n                count === undefined ? word : `${word} ${String(count)}`\n              }\n              onClick={() => onFilter(candidate)}\n            >\n              {word}\n              {count === undefined ? null : (\n                <span\n                  className=\"nx-shared-styles__filter-count\"\n                  aria-hidden=\"true\"\n                >\n                  {count}\n                </span>\n              )}\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\n/** A rename refused for this style, shown in its details. */\nexport function issueOf(issue: Issue | null, id: string): string | null {\n  return issue?.id === id ? issue.reason : null;\n}\n\n/** A refused rename whose details are closed, shown above the list instead. */\nexport function issueBesideList(\n  issue: Issue | null,\n  openId: string | null\n): string | null {\n  return issue === null || issue.id === openId ? null : issue.reason;\n}\n\n/**\n * The one note while counts are floors, at the top of the list, and while\n * pages are still being counted, what counts them, with Count now. Carries\n * the id Remove unused points at when it says why that waits.\n */\nexport function TopNote({\n  note,\n  says,\n  jobs,\n  counter,\n}: {\n  note: string | undefined;\n  /** Whether it says why Remove unused waits. */\n  says: boolean;\n  jobs: boolean;\n  counter: CountNow | undefined;\n}): React.JSX.Element | null {\n  if (note === undefined) return null;\n  return (\n    <div className=\"nx-shared-styles__counting\">\n      <p\n        className=\"nx-vars__note\"\n        id={says ? \"nx-shared-styles-withheld\" : undefined}\n      >\n        {note}\n      </p>\n      {jobs ? <CountedBy counter={counter} /> : null}\n    </div>\n  );\n}\n\n/**\n * Who counts the pages, beside a note that some are not counted yet. The\n * counts are filled in by one of the site's background jobs, which nothing\n * runs on a site with no scheduler, so there the counts never finish; this\n * says so, and links to how the jobs are run, rather than promising a wait.\n */\nfunction CountedBy({\n  counter,\n}: {\n  /** Counting the pages now, when this author may and the host can. */\n  counter: CountNow | undefined;\n}): React.JSX.Element {\n  if (counter === undefined) return <CountedByJobs />;\n  // One line under the note: the count, what it found, and how the jobs\n  // that would have counted run. A button, since it does work; the docs are\n  // a link, since they go somewhere.\n  return (\n    <div className=\"nx-shared-styles__count-row\">\n      {/* None once a count said another cannot get further. */}\n      {counter.final ? null : (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          className=\"nx-shared-styles__count-now\"\n          disabled={counter.busy}\n          onClick={counter.run}\n        >\n          {countNowWords(counter)}\n        </Button>\n      )}\n      {/* What the last count found, said as it changes. */}\n      <span className=\"nx-vars__note\" role=\"status\">\n        {counter.said ?? \"\"}\n      </span>\n      <BackgroundJobsLink />\n    </div>\n  );\n}\n\n/** The read-only line, a usage read that failed, and a refused rename. */\nexport function PanelNotes({\n  readOnly,\n  usageFailed,\n  issue,\n}: {\n  readOnly: boolean;\n  usageFailed: boolean;\n  issue: string | null;\n}): React.JSX.Element {\n  return (\n    <>\n      {readOnly ? (\n        <p className=\"nx-vars__note\">\n          {`You can view the site’s ${SHARED_STYLES_WORD} but not change them.`}\n        </p>\n      ) : null}\n      {usageFailed ? (\n        <p className=\"nx-vars__alert\" role=\"alert\">\n          {`Where these ${SHARED_STYLES_WORD} are used could not be read.`}\n        </p>\n      ) : null}\n      {issue === null ? null : (\n        <p className=\"nx-vars__alert\" role=\"alert\">\n          {issue}\n        </p>\n      )}\n    </>\n  );\n}\n\n/**\n * Why the tab's counts are floors: the site is still being counted (or may\n * be), or it cannot be counted in full, so they stay floors. Undefined while\n * every page is counted, whatever one style's own count says.\n */\nexport type FloorReason = \"counting\" | \"permanent\" | undefined;\n\nexport function floorReason(\n  whole: boolean | undefined,\n  counting: \"yes\" | \"unknown\" | \"no\"\n): FloorReason {\n  if (whole !== false) return undefined;\n  return counting === \"no\" ? \"permanent\" : \"counting\";\n}\n\n/**\n * Which notes the tab says about floors. While counts are floors, ONE note\n * says why, at the top of the list, where the counts first read as\n * minimums. It covers the minimums, the rows Unused holds back and Remove\n * unused waiting, so neither the head nor the list says it again. Rows held back while every page is counted (one\n * style's count cut short) get their own line in the list: nothing is\n * waiting, and the proven rows are listed.\n */\nexport function countingNotes(\n  withheld: boolean,\n  reason: FloorReason\n): {\n  withheld: boolean;\n  /** Whether the top note says why Remove unused waits. */\n  one: boolean;\n  /** The top note's words, while counts are floors. */\n  top: string | undefined;\n  /** Whether that note says pages are not counted yet, so who counts them. */\n  jobs: boolean;\n} {\n  return {\n    withheld,\n    one: reason !== undefined,\n    top:\n      reason === \"counting\"\n        ? SHARED_STYLE_COUNTING_NOTE\n        : reason === \"permanent\"\n          ? SHARED_STYLE_UNCOUNTABLE_NOTE\n          : undefined,\n    jobs: reason === \"counting\",\n  };\n}\n\n/**\n * Whether Unused is holding back a row the search found: one whose zero is\n * not counted in full yet, so it is neither used nor certainly unused.\n */\nexport function unusedWithheld(\n  filter: SharedStyleFilter,\n  found: readonly SharedStyleRow[],\n  usageOf: (row: SharedStyleRow) => \"used\" | \"unused\" | undefined\n): boolean {\n  return filter === \"unused\" && found.some(row => usageOf(row) === undefined);\n}\n\n/**\n * Unused while it holds rows back: the rows proven unused, and, when the top\n * note does not already say why (every page counted, but one style's count\n * cut short), a line that says so.\n */\nfunction WithheldList({\n  covered,\n  listed,\n  children,\n}: {\n  covered: boolean;\n  listed: boolean;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  return (\n    <>\n      {covered ? null : (\n        <p className=\"nx-vars__empty\">{SHARED_STYLE_UNUSED_UNCERTAIN}</p>\n      )}\n      {listed ? <ul className=\"nx-vars__list\">{children}</ul> : null}\n    </>\n  );\n}\n\n/** The rows, or what to say when there are none or none match. */\nexport function StyleList({\n  rows,\n  found,\n  filter,\n  query,\n  withheld,\n  covered,\n  children,\n}: {\n  rows: readonly SharedStyleRow[];\n  /** The rows the search and the filter leave. */\n  found: readonly SharedStyleRow[];\n  filter: SharedStyleFilter;\n  query: string;\n  /**\n   * Unused is holding back rows whose zero is not counted in full yet. The\n   * rows proven unused are still listed, each judged on its own.\n   */\n  withheld: boolean;\n  /** Whether the top note already says why rows are held back. */\n  covered: boolean;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  // Whenever Unused holds a row back it says so, beside the rows it lists.\n  if (withheld && rows.length > 0) {\n    return (\n      <WithheldList covered={covered} listed={found.length > 0}>\n        {children}\n      </WithheldList>\n    );\n  }\n  if (rows.length === 0) {\n    return (\n      <p className=\"nx-vars__empty\">\n        {`No ${SHARED_STYLES_WORD} yet. Select a block and choose Save as shared style…`}\n      </p>\n    );\n  }\n  if (found.length === 0) {\n    return (\n      <p className=\"nx-vars__empty\">\n        {filter === \"all\"\n          ? `No ${SHARED_STYLES_WORD} match “${query}”.`\n          : sharedStyleFilterEmpty(filter, query)}\n      </p>\n    );\n  }\n  return <ul className=\"nx-vars__list\">{children}</ul>;\n}\n\n/** What shows while the library is being read, or after a read failed. */\nexport function Unread({\n  absence,\n}: {\n  absence: \"pending\" | \"failed\";\n}): React.JSX.Element {\n  const failed = absence === \"failed\";\n  return (\n    <div className=\"nx-vars nx-shared-styles\">\n      <div className=\"nx-vars__body\">\n        <p\n          className={failed ? \"nx-vars__alert\" : \"nx-vars__note\"}\n          role={failed ? \"alert\" : \"status\"}\n        >\n          {failed\n            ? `This site’s ${SHARED_STYLES_WORD} could not be read, so none can be shown or changed. Reload to try again.`\n            : `Reading this site’s ${SHARED_STYLES_WORD}…`}\n        </p>\n      </div>\n    </div>\n  );\n}\n","/**\n * What the Shared styles tab is handed and answers in: the host's access to\n * the library, a rename's answer, the page's blocks by class, the look editor\n * the tab mounts, the tab's props, and how many rows mount at a time.\n * `shared-styles-panel.tsx` still exports each of these names.\n *\n * @module shared-styles-types\n */\n\nimport type {\n  NamedClass,\n  SiteTokenSet,\n  StyleCompileContext,\n} from \"@nextlyhq/blocks-engine\";\n\nimport type { EditClasses } from \"../../styles/block-style-actions\";\nimport type {\n  SharedStyleRefusal,\n  SharedStylesCount,\n  SharedStylesUsage,\n  SharedStyleUsesPage,\n} from \"../../styles/shared-style-library\";\n\nimport type { LookKey } from \"./block-look-rows\";\nimport type { GroupFolds } from \"./tokens-panel\";\n\n/** What the host answers a rename with. */\nexport type ClassRenameOutcome =\n  | { readonly ok: true }\n  | { readonly ok: false; readonly reason: string };\n\n/** The host's reads and writes through the site's shared-style routes. */\nexport interface SharedStylesAccess {\n  /** How widely each of these styles is used: at most fifty ids per read. */\n  readonly usage: (\n    ids: readonly string[],\n    signal: AbortSignal\n  ) => Promise<SharedStylesUsage>;\n  /** One page, from 1, of the documents a style is used on. */\n  readonly uses: (\n    id: string,\n    page: number,\n    signal: AbortSignal\n  ) => Promise<SharedStyleUsesPage>;\n  /** Lock or unlock a style. Resolves to the refusal, or nothing. */\n  readonly lock: (id: string, locked: boolean) => Promise<string | undefined>;\n  /** Remove unused styles, at most fifty. Resolves to the refusal, or nothing. */\n  readonly remove: (ids: readonly string[]) => Promise<string | undefined>;\n  /**\n   * `remove`, answering a refusal with its words and whether it said a style\n   * is still used. Optional: a host without it keeps working through\n   * `remove`, and the tab then takes no refusal as saying a style is used.\n   *\n   * @experimental Settles with the Shared styles tab.\n   */\n  readonly removeWithReason?: (\n    ids: readonly string[]\n  ) => Promise<SharedStyleRefusal | undefined>;\n  /**\n   * Count the site's pages now, for a bounded time, rather than waiting for\n   * the site's background jobs. Optional: without it the tab only says the\n   * jobs count them.\n   *\n   * @experimental Settles with the Shared styles tab.\n   */\n  readonly count?: () => Promise<SharedStylesCount>;\n}\n\n/** The blocks on the open page carrying each style, by id. */\nexport interface PageClassBlocks {\n  readonly counts: ReadonlyMap<string, number>;\n  /** False when the page has more blocks than could be read. */\n  readonly complete: boolean;\n}\n\nexport interface SharedStylesPanelProps {\n  /** The site's class library, or `undefined` while it is being read. */\n  library: readonly NamedClass[] | undefined;\n  /** Why the library is absent, when it is. */\n  absence?: \"pending\" | \"failed\";\n  /** The styles the site's code supplies: shown, never changed here. */\n  suppliedClassIds?: readonly string[];\n  /** The context the page compiles with, so summaries match the page. */\n  styleContext?: StyleCompileContext;\n  /**\n   * The site's variables, so each row's preview is drawn on the site's page\n   * colours. Absent: a neutral tile.\n   */\n  tokens?: SiteTokenSet;\n  /** The blocks on the open page carrying each style. */\n  pageBlocks: PageClassBlocks;\n  /** Shown, never changed: no rename and no removal. A lock is its own right. */\n  readOnly?: boolean;\n  /** The usage routes and the lock and remove writes. Absent: none read. */\n  access?: SharedStylesAccess;\n  /** Rename a style: the name typed, and the class name derived from it. */\n  onRename?: (\n    classId: string,\n    name: { label: string; slug: string }\n  ) => Promise<ClassRenameOutcome>;\n  /**\n   * The live rename attempt for a style, as the host counts it, read right\n   * after `onRename` is called, so a late answer to an earlier rename is not\n   * shown as the current one.\n   */\n  currentRenameAttempt?: (classId: string) => number;\n  /** The name each style is being renamed to while its write is open. */\n  pendingNames?: Readonly<Record<string, string>>;\n  /**\n   * Choosing a look to edit in the inspector, with no block selected. Absent:\n   * the Block looks group is listed, not chosen.\n   *\n   * @experimental\n   */\n  looks?: PanelLookEditing;\n  /**\n   * The host's whole-list class write, through which the Block styles\n   * section makes, copies, renames and hides block styles and moves ★; a\n   * removal goes through `access`. Absent, or read-only: the section offers\n   * none of them.\n   *\n   * @experimental Settles with the Styles tab's Block styles.\n   */\n  onEditClasses?: EditClasses;\n  /**\n   * Which block types' styles the author folded, kept by the host as the\n   * other Design groups' are. Absent: every type is open.\n   *\n   * @experimental Settles with the Styles tab's Block styles.\n   */\n  folds?: GroupFolds;\n  /**\n   * The style whose details are open as the tab mounts, as when the Variables\n   * tab sends the author to a style that uses a variable. Read once.\n   *\n   * @experimental Settles with the Variables tab's usage.\n   */\n  initialOpenId?: string;\n}\n\n/** How the Block looks group's rows choose the look the inspector edits. */\nexport interface PanelLookEditing {\n  /** Edit a look in the inspector. */\n  readonly onEdit: (look: LookKey) => void;\n  /** The look the inspector is editing, whose row shows as chosen. */\n  readonly editing: LookKey | null;\n}\n\n/** How many rows mount before the author asks for more. */\nexport const PAGE_SIZE = 50;\n","/**\n * Removing the shared styles nothing uses: the head that offers it, how the\n * unused ones are found a page at a time, and the confirmation that removes\n * them.\n *\n * @module shared-styles-remove-unused\n */\n\nimport {\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { EDITOR_WORDS } from \"../../editor-words\";\nimport {\n  isUnused,\n  SHARED_STYLE_NOT_WHOLE_REMOVAL,\n  SHARED_STYLE_RENAME_PENDING,\n  SHARED_STYLE_UNCOUNTABLE_REMOVAL,\n  SHARED_STYLE_UNCOUNTED_USES,\n  SHARED_STYLES_WORD,\n  type BlocksOnThisPage,\n  type SharedStyleRow,\n} from \"../../styles/shared-style-library\";\n\nimport { KeepOrRemove, Refusal, useRefusableWrite } from \"./panel-actions\";\nimport { HoldReason, removeSharedStylesThrough } from \"./shared-style-details\";\nimport type { FloorReason } from \"./shared-styles-list\";\nimport type { SharedStylesAccess } from \"./shared-styles-types\";\nimport { PAGE_SIZE } from \"./shared-styles-types\";\n\n/**\n * Why \"Remove unused…\" waits, or `undefined` when it need not: while some\n * pages are still being counted, said first since it lasts longer, or while\n * a rename is stored, since a removal writes the whole list of styles too.\n */\nfunction removeUnusedWait(\n  reason: FloorReason,\n  held: boolean\n): string | undefined {\n  if (reason === \"counting\") return SHARED_STYLE_NOT_WHOLE_REMOVAL;\n  if (reason === \"permanent\") return SHARED_STYLE_UNCOUNTABLE_REMOVAL;\n  return held ? SHARED_STYLE_RENAME_PENDING : undefined;\n}\n\n/** What \"Remove unused…\" found: still reading, a refusal, or the list. */\ntype UnusedRead =\n  | { readonly kind: \"reading\" }\n  | { readonly kind: \"refused\"; readonly reason: string }\n  | { readonly kind: \"found\"; readonly rows: readonly SharedStyleRow[] };\n\n/**\n * The group's heading, with \"Remove unused…\": it reads the usage of every\n * style that could be removed, lists the unused ones by name, and removes\n * them only once the author confirms. Withheld while some pages are still\n * being counted, saying so in the route's words.\n */\nexport function RemoveUnusedHead({\n  rows,\n  offered,\n  access,\n  reason,\n  held,\n  saidInNote,\n  blocksOf,\n  onRemoved,\n}: {\n  rows: readonly SharedStyleRow[];\n  /** False for a role that may not change the site's design. */\n  offered: boolean;\n  access: SharedStylesAccess | undefined;\n  /** Why the counts are floors, which decides why removal waits. */\n  reason: FloorReason;\n  /** A rename is being stored, so a removal, which writes the whole list, waits. */\n  held: boolean;\n  /**\n   * The tab's one counting note already says why it waits, under the same\n   * id, so its own line is not drawn a second time.\n   */\n  saidInNote: boolean;\n  blocksOf: (id: string) => BlocksOnThisPage;\n  onRemoved: () => void;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  // A locked style refuses removal, and one in code cannot be removed here.\n  const candidates = rows.filter(row => !row.locked && !row.inCode);\n  const shown = offered && access !== undefined && candidates.length > 0;\n  const wait = removeUnusedWait(reason, held);\n  return (\n    <Popover open={open} onOpenChange={setOpen} modal>\n      <PopoverAnchor asChild>\n        <div className=\"nx-vars__group-head\">\n          <h3 className=\"nx-vars__group-name\" id=\"nx-shared-styles-all\">\n            {EDITOR_WORDS.sharedStyles}\n          </h3>\n          {shown ? (\n            <PopoverTrigger asChild>\n              <button\n                type=\"button\"\n                className=\"nx-vars__link nx-shared-styles__remove-unused\"\n                disabled={wait !== undefined}\n                aria-describedby={\n                  wait === undefined ? undefined : \"nx-shared-styles-withheld\"\n                }\n              >\n                Remove unused&hellip;\n              </button>\n            </PopoverTrigger>\n          ) : null}\n        </div>\n      </PopoverAnchor>\n      {shown && wait !== undefined && !saidInNote ? (\n        <p className=\"nx-shared-styles__meta\" id=\"nx-shared-styles-withheld\">\n          {wait}\n        </p>\n      ) : null}\n      {shown && access !== undefined ? (\n        <PopoverContent\n          side=\"right\"\n          align=\"start\"\n          sideOffset={12}\n          className=\"nx-vars-editor nx-shared-styles__editor\"\n          aria-label={`Remove unused ${SHARED_STYLES_WORD}`}\n        >\n          <RemoveUnused\n            candidates={candidates}\n            access={access}\n            held={held}\n            blocksOf={blocksOf}\n            onDone={() => {\n              setOpen(false);\n              onRemoved();\n            }}\n            onKeep={() => setOpen(false)}\n          />\n        </PopoverContent>\n      ) : null}\n    </Popover>\n  );\n}\n\n/**\n * The styles nothing uses, from the usage of every candidate read fifty at a\n * time; a refusal in the route's words while some pages are still being\n * counted.\n */\nasync function findUnused(\n  access: SharedStylesAccess,\n  candidates: readonly SharedStyleRow[],\n  blocksOf: (id: string) => BlocksOnThisPage,\n  signal: AbortSignal\n): Promise<UnusedRead> {\n  const unused: SharedStyleRow[] = [];\n  for (let at = 0; at < candidates.length; at += PAGE_SIZE) {\n    const batch = candidates.slice(at, at + PAGE_SIZE);\n    const answer = await access.usage(\n      batch.map(row => row.id),\n      signal\n    );\n    if (!answer.whole) {\n      return { kind: \"refused\", reason: SHARED_STYLE_NOT_WHOLE_REMOVAL };\n    }\n    unused.push(\n      ...batch.filter(row => {\n        const reach = answer.styles.get(row.id);\n        return reach !== undefined && isUnused(blocksOf(row.id), reach);\n      })\n    );\n  }\n  return { kind: \"found\", rows: unused };\n}\n\n/** \"1 unused shared style\", \"3 unused shared styles\". */\nfunction unusedCount(count: number): string {\n  return `${count} unused ${count === 1 ? \"shared style\" : SHARED_STYLES_WORD}`;\n}\n\n/** The unused styles, listed, and their removal once confirmed. */\nfunction RemoveUnused({\n  candidates,\n  access,\n  held,\n  blocksOf,\n  onDone,\n  onKeep,\n}: {\n  candidates: readonly SharedStyleRow[];\n  access: SharedStylesAccess;\n  held: boolean;\n  blocksOf: (id: string) => BlocksOnThisPage;\n  onDone: () => void;\n  onKeep: () => void;\n}): React.JSX.Element {\n  const [read, setRead] = React.useState<UnusedRead>({ kind: \"reading\" });\n  // Read once per opening, from what stands when the author asks.\n  const [asked] = React.useState(() => ({ candidates, blocksOf }));\n  React.useEffect(() => {\n    const controller = new AbortController();\n    findUnused(access, asked.candidates, asked.blocksOf, controller.signal)\n      .then(found => {\n        if (!controller.signal.aborted) setRead(found);\n      })\n      .catch(() => {\n        if (controller.signal.aborted) return;\n        setRead({\n          kind: \"refused\",\n          reason: `Where these ${SHARED_STYLES_WORD} are used could not be read.`,\n        });\n      });\n    return () => controller.abort();\n  }, [access, asked]);\n\n  if (read.kind !== \"found\") {\n    return (\n      <div className=\"nx-vars-editor__body\">\n        {read.kind === \"refused\" ? (\n          <Refusal refusal={read.reason} />\n        ) : (\n          <p className=\"nx-shared-styles__meta\" role=\"status\">\n            {`Finding unused ${SHARED_STYLES_WORD}…`}\n          </p>\n        )}\n      </div>\n    );\n  }\n  if (read.rows.length === 0) {\n    return (\n      <div className=\"nx-vars-editor__body\">\n        <p className=\"nx-shared-styles__meta\" role=\"status\">\n          Every shared style here is in use.\n        </p>\n      </div>\n    );\n  }\n  return (\n    <ConfirmUnused\n      rows={read.rows}\n      access={access}\n      held={held}\n      onDone={onDone}\n      onKeep={onKeep}\n    />\n  );\n}\n\n/** \"50 were removed before the rest were refused.\" */\nfunction removedBefore(count: number): string {\n  return `${count} ${count === 1 ? \"was\" : \"were\"} removed before the rest were refused.`;\n}\n\n/**\n * The confirmation listing the unused styles, removed fifty at a time.\n *\n * Each batch the route stores is gone for good, so it leaves the list as it\n * lands: when a later batch is refused, the list holds only what is left, a\n * retry sends only that, and the dialog says how many went first.\n */\nfunction ConfirmUnused({\n  rows,\n  access,\n  held,\n  onDone,\n  onKeep,\n}: {\n  rows: readonly SharedStyleRow[];\n  access: SharedStylesAccess;\n  held: boolean;\n  onDone: () => void;\n  onKeep: () => void;\n}): React.JSX.Element {\n  const { busy, refusal, run } = useRefusableWrite();\n  const [left, setLeft] = React.useState(rows);\n  const [removed, setRemoved] = React.useState(0);\n  const count = left.length;\n  const remove = async (): Promise<void> => {\n    let rest = left;\n    while (rest.length > 0) {\n      const batch = rest.slice(0, PAGE_SIZE);\n      const write = async () =>\n        (\n          await removeSharedStylesThrough(\n            access,\n            batch.map(row => row.id)\n          )\n        )?.reason;\n      if (!(await run(write))) return;\n      rest = rest.slice(PAGE_SIZE);\n      setLeft(rest);\n      setRemoved(gone => gone + batch.length);\n    }\n    onDone();\n  };\n  return (\n    <div\n      className=\"nx-vars-editor__body nx-vars-editor__confirm\"\n      role=\"group\"\n      aria-label={`Remove ${unusedCount(count)}`}\n    >\n      <p>{`Remove ${unusedCount(count)}? No page uses them in the editor.`}</p>\n      <p className=\"nx-shared-styles__meta\">{SHARED_STYLE_UNCOUNTED_USES}</p>\n      {/* Stacked, so a long name and its class both read in full. */}\n      <ul className=\"nx-shared-styles__uses nx-shared-styles__uses--stacked\">\n        {left.map(row => (\n          <li key={row.id}>\n            <span className=\"nx-shared-styles__use-title\">{row.name}</span>\n            <span className=\"nx-shared-styles__class\">{row.className}</span>\n          </li>\n        ))}\n      </ul>\n      {refusal !== null && removed > 0 ? (\n        <p className=\"nx-shared-styles__meta\">{removedBefore(removed)}</p>\n      ) : null}\n      <Refusal refusal={refusal} />\n      <KeepOrRemove\n        busy={busy}\n        onKeep={onKeep}\n        onRemove={() => void remove()}\n        removeLabel={`Remove ${count}`}\n        removeHeld={held}\n        removeDescribedBy=\"nx-shared-styles-confirm-held\"\n      />\n      <HoldReason held={held} id=\"nx-shared-styles-confirm-held\" />\n    </div>\n  );\n}\n","/**\n * How widely the Shared styles tab's rows are used, and renaming a row: the\n * usage read for the rows on screen, the rename write with its pending names,\n * and the refusal shown where the author will see it.\n *\n * @module shared-styles-usage\n */\n\nimport type { NamedClass } from \"@nextlyhq/blocks-engine\";\nimport * as React from \"react\";\n\nimport { useSurvivingReport } from \"../../shell/builder-notices\";\nimport {\n  renameSharedStyle,\n  type SharedStyleReach,\n  type SharedStyleRow,\n  type SharedStylesUsage,\n} from \"../../styles/shared-style-library\";\n\nimport type {\n  SharedStylesAccess,\n  SharedStylesPanelProps,\n} from \"./shared-styles-types\";\nimport {\n  useUsageReads,\n  type CountNow,\n  type UsageRead,\n  type UsageSource,\n} from \"./usage-reads\";\n\n/** The words for a refusal that came with none. */\nconst UNEXPLAINED_REFUSAL = \"This shared style could not be renamed.\";\n\n/**\n * The name a style is heading for while its rename is open, read as an own\n * entry: a style id is stored data, and `__proto__` must not read the\n * record's prototype.\n */\nexport function pendingName(\n  pendingNames: Readonly<Record<string, string>>,\n  id: string\n): string | undefined {\n  return Object.hasOwn(pendingNames, id) ? pendingNames[id] : undefined;\n}\n\n/** A refusal shown where the author will see it: in its popover or the panel. */\nexport interface Issue {\n  readonly id: string;\n  readonly reason: string;\n}\n\n/** Usage read for the rows on screen, kept as it arrives. */\nexport interface UsageState {\n  readonly styles: ReadonlyMap<string, SharedStyleReach>;\n  /**\n   * Whether every style's usage was read while every page had been counted.\n   * Undefined until a read has answered.\n   */\n  readonly whole: boolean | undefined;\n  /** Whether floors among them may still become whole. */\n  readonly counting: \"yes\" | \"unknown\" | \"no\";\n  readonly mayLock: boolean;\n  /** Whether this author may ask for the pages to be counted now. */\n  readonly mayCount: boolean;\n  readonly failed: boolean;\n  /** Ask about these styles again, as after a removal the server refused. */\n  readonly reread: (ids: readonly string[]) => void;\n  /**\n   * Counting the pages now, when this author may and the host can; its\n   * answer reads the rows on screen again.\n   */\n  readonly counter: CountNow | undefined;\n}\n\n/** A shared-style usage read, in the shape the usage reads take. */\ntype SharedStylesRead = UsageRead<SharedStyleReach> & SharedStylesUsage;\n\n/** The tab's access as a usage source: each read's styles are its values. */\nfunction sharedStylesSource(\n  access: SharedStylesAccess\n): UsageSource<SharedStyleReach, SharedStylesRead> {\n  return {\n    usage: async (ids, signal) => {\n      const read = await access.usage(ids, signal);\n      return { ...read, values: read.styles };\n    },\n    ...(access.count === undefined ? {} : { count: access.count }),\n  };\n}\n\n/**\n * How widely the rows on screen are used, through the usage reads every\n * Design tab shares, with whether this author may lock from the latest read.\n */\nexport function useUsage(\n  access: SharedStylesAccess | undefined,\n  ids: readonly string[]\n): UsageState {\n  const source = React.useMemo(\n    () => (access === undefined ? undefined : sharedStylesSource(access)),\n    [access]\n  );\n  const reads = useUsageReads(source, ids);\n  return {\n    styles: reads.values,\n    whole: reads.whole,\n    counting: reads.counting,\n    // Absent until a read answers: no lock is offered before one.\n    mayLock: reads.latest?.mayLock ?? false,\n    mayCount: reads.mayCount,\n    failed: reads.failed,\n    reread: reads.reread,\n    counter: reads.counter,\n  };\n}\n\n/**\n * The rename a row's Name field commits: checked here, written by the host,\n * and a refusal shown where the author is, or raised as a notice once this\n * panel is gone.\n */\nexport function useRename({\n  library,\n  onRename,\n  currentRenameAttempt,\n  pendingNames,\n  setIssue,\n}: {\n  library: readonly NamedClass[] | undefined;\n  onRename: SharedStylesPanelProps[\"onRename\"];\n  currentRenameAttempt: SharedStylesPanelProps[\"currentRenameAttempt\"];\n  pendingNames: Readonly<Record<string, string>>;\n  setIssue: (issue: Issue | null) => void;\n}): (row: SharedStyleRow, value: string) => void {\n  const survive = useSurvivingReport();\n  return (row, value) => {\n    if (onRename === undefined || library === undefined) return;\n    // Compared with the name the style is heading for, so typing back the\n    // old name while a rename is open is a rename of its own.\n    if (value.trim() === (pendingName(pendingNames, row.id) ?? row.name)) {\n      setIssue(null);\n      return;\n    }\n    const report = (reason: string): void =>\n      survive(reason, () => {\n        setIssue({ id: row.id, reason });\n        return true;\n      });\n    const verdict = renameSharedStyle(value, row.id, library);\n    if (!verdict.ok) {\n      report(verdict.reason);\n      return;\n    }\n    setIssue(null);\n    const answer = onRename(row.id, {\n      label: verdict.label,\n      slug: verdict.slug,\n    });\n    const mine = currentRenameAttempt?.(row.id);\n    const current = (): boolean =>\n      mine === undefined || currentRenameAttempt?.(row.id) === mine;\n    answer.then(\n      outcome => {\n        if (!current() || outcome.ok) return;\n        report(\n          outcome.reason.trim() === \"\" ? UNEXPLAINED_REFUSAL : outcome.reason\n        );\n      },\n      () => {\n        if (current()) report(UNEXPLAINED_REFUSAL);\n      }\n    );\n  };\n}\n","/**\n * The Shared styles tab of the Design panel: every shared style the site\n * renders, found by name, property or value, with how widely each is used,\n * and each row's details beside the panel ({@link shared-style-details}).\n *\n * Drawn in the Variables and Fonts tabs' language: a search, a small-caps\n * group, compact rows, and a 240px popover editor per row.\n *\n * ## Two sections\n *\n * \"Block styles\" first, the saved looks for one kind of block by block type\n * ({@link block-looks-group}), then \"Shared styles\", the author's own styles\n * for any block, each with a line that says which is which.\n *\n * ## Shared styles are made from a block\n *\n * There is no \"+\" among the shared styles. One is made from a block's own\n * look, with \"Save as shared style…\" on the block, so the empty list says\n * that. A block style is made with its type's \"+ New <block> style\".\n *\n * ## Counts are read a page of rows at a time\n *\n * How widely a style is used comes from the site's usage index, asked for the\n * rows on screen (at most fifty per read), never for the whole library. While\n * some pages are still being counted every number is a floor, said \"at least\",\n * and nothing can be removed.\n *\n * ## Edits are lifted\n *\n * Renaming, locking and removing are the host's writes; this panel reports an\n * intent and shows the answer.\n *\n * ## Where the parts live\n *\n * This module is the tab itself and the entry for the rest: its shapes are in\n * `shared-styles-types.ts`, the usage reads and the rename in\n * `shared-styles-usage.ts`, one row in `shared-style-row.tsx`, the list and\n * the notes around it in `shared-styles-list.tsx`, and removing unused styles\n * in `shared-styles-remove-unused.tsx`. Every name it exported, it still\n * exports.\n *\n * @module shared-styles-panel\n */\nimport type {\n  NamedClass,\n  SiteTokenSet,\n  StyleCompileContext,\n} from \"@nextlyhq/blocks-engine\";\nimport { Input } from \"@nextlyhq/ui\";\nimport { Search } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport {\n  BLOCK_STYLE_WORDS,\n  blockStyleActionsOf,\n  type BlockStyleActions,\n} from \"../../styles/block-style-actions\";\nimport {\n  inSharedStyleFilter,\n  sharedStyleUse,\n  sharedStyleSearchText,\n  SHARED_STYLES_WORD,\n  type BlocksOnThisPage,\n  type SharedStyleFilter,\n  type SharedStyleReach,\n  type SharedStyleRow,\n} from \"../../styles/shared-style-library\";\n\nimport { lookKeyOf, type BlockLookGroup } from \"./block-look-rows\";\nimport { BlockLooksGroup } from \"./block-looks-group\";\nimport { ShowMore, withOpenRow } from \"./panel-actions\";\nimport {\n  ReachChip,\n  StyleRow,\n  type TilePaint,\n  usePaint,\n} from \"./shared-style-row\";\nimport {\n  countingNotes,\n  floorReason,\n  FilterBar,\n  issueBesideList,\n  issueOf,\n  PanelNotes,\n  StyleList,\n  TopNote,\n  Unread,\n  unusedWithheld,\n} from \"./shared-styles-list\";\nimport { RemoveUnusedHead } from \"./shared-styles-remove-unused\";\nimport type {\n  PageClassBlocks,\n  PanelLookEditing,\n  SharedStylesAccess,\n  SharedStylesPanelProps,\n} from \"./shared-styles-types\";\nimport { PAGE_SIZE } from \"./shared-styles-types\";\nimport {\n  type Issue,\n  pendingName,\n  type UsageState,\n  useRename,\n  useUsage,\n} from \"./shared-styles-usage\";\nimport {\n  foundLooks,\n  foundSharedStyles,\n  stylesTabSource,\n} from \"./styles-tab-matches\";\nimport type { GroupFolds } from \"./tokens-panel\";\nimport { idsKey, idsOf } from \"./usage-reads\";\n\n// The tab's shapes, its usage reads and rename, its row, its list and the\n// removal of unused styles live in modules of their own beside it; every name\n// this module exported still is.\nexport type {\n  ClassRenameOutcome,\n  PageClassBlocks,\n  SharedStylesAccess,\n  SharedStylesPanelProps,\n} from \"./shared-styles-types\";\n// Part of this module's exported names; no importer in the package reads it.\n// fallow-ignore-next-line unused-type\nexport type { PanelLookEditing } from \"./shared-styles-types\";\n\n/*\n * The recount timing lives with the reads it times; said here too, where the\n * tab's hosts and tests have always found it.\n */\nexport { USAGE_RECOUNT_IDLE_MAX, USAGE_RECOUNT_MS } from \"./usage-reads\";\n\n/** A search a host keeps across several views, and the way to change it. */\nexport interface HostSearch {\n  readonly query: string;\n  readonly onQuery: (query: string) => void;\n  /** The host's search box, where focus goes once a style is removed. */\n  readonly searchRef?: React.RefObject<HTMLInputElement | null>;\n}\n\n/**\n * The search a host keeps across several views, as the Design panel keeps\n * one across its tabs. Provided, the tab lists what it matches and draws no\n * search box of its own.\n */\nexport const SharedStylesHostSearch: React.Context<HostSearch | undefined> =\n  React.createContext<HostSearch | undefined>(undefined);\n\n/**\n * What the tab searches for: the host's search where it keeps one, changed\n * through the host, else the tab's own. With it, the box focus goes back to\n * once a style is removed: the host's, since the tab then draws none.\n */\nfunction usePanelSearch(): {\n  query: string;\n  setQuery: (query: string) => void;\n  box: React.RefObject<HTMLInputElement | null>;\n} {\n  const host = React.useContext(SharedStylesHostSearch);\n  const [own, setOwn] = React.useState(\"\");\n  const ownBox = React.useRef<HTMLInputElement>(null);\n  return host === undefined\n    ? { query: own, setQuery: setOwn, box: ownBox }\n    : {\n        query: host.query,\n        setQuery: host.onQuery,\n        box: host.searchRef ?? ownBox,\n      };\n}\n\n/** The filter bar, drawn only while there are styles to filter. */\nfunction FiltersWhenListed(\n  props: React.ComponentProps<typeof FilterBar>\n): React.JSX.Element | null {\n  return props.rows.length > 0 ? <FilterBar {...props} /> : null;\n}\n\n/** No pending names, as one value rather than a fresh record each render. */\nconst NO_NAMES: Readonly<Record<string, string>> = Object.freeze({});\n\n/**\n * The rows the library gives, from the listing the Design panel counts with,\n * kept while the library and the code's ids are.\n */\nfunction useRows(\n  library: readonly NamedClass[] | undefined,\n  suppliedClassIds: readonly string[] | undefined\n): { rows: SharedStyleRow[]; groups: BlockLookGroup[]; lookIds: string[] } {\n  // Keyed by the ids rather than the array, which a host may build afresh on\n  // every render: the search text compiles every style, once per library,\n  // not once per render.\n  const suppliedKey = idsKey(suppliedClassIds ?? []);\n  return React.useMemo(() => {\n    if (library === undefined) return { rows: [], groups: [], lookIds: [] };\n    const { rows, groups } = stylesTabSource(\n      library,\n      new Set(idsOf(suppliedKey))\n    );\n    // The worn looks, whose counts are read with the styles' in one read, so\n    // the tab's counting and failure notes speak for both.\n    return { rows, groups, lookIds: wornLookIds(groups) };\n  }, [library, suppliedKey]);\n}\n\n/**\n * The rows, those the search finds by name, property or value, and what\n * their tiles are drawn from. Each row's search text compiles its style, so\n * it is kept per library and context rather than made again on every render.\n */\nfunction useListedRows({\n  library,\n  suppliedClassIds,\n  styleContext,\n  tokens,\n  query,\n}: {\n  library: readonly NamedClass[] | undefined;\n  suppliedClassIds: readonly string[] | undefined;\n  styleContext: StyleCompileContext | undefined;\n  tokens: SiteTokenSet | undefined;\n  query: string;\n}): {\n  rows: SharedStyleRow[];\n  lookIds: string[];\n  found: SharedStyleRow[];\n  paint: TilePaint;\n} {\n  const paint = usePaint(tokens);\n  const { rows, lookIds } = useRows(library, suppliedClassIds);\n  const texts = React.useMemo(\n    () =>\n      new Map(\n        rows.map(row => [row.id, sharedStyleSearchText(row, styleContext)])\n      ),\n    [rows, styleContext]\n  );\n  const found = foundSharedStyles(rows, query, row => texts.get(row.id) ?? \"\");\n  return { rows, lookIds, found, paint };\n}\n\n/**\n * The site's looks by block type, narrowed by the search to the looks whose\n * name holds it; a type with none left is not listed.\n */\nfunction useLookGroups(\n  library: readonly NamedClass[] | undefined,\n  suppliedClassIds: readonly string[] | undefined,\n  query: string,\n  styleContext: StyleCompileContext | undefined\n): BlockLookGroup[] {\n  const { groups } = useRows(library, suppliedClassIds);\n  // Each look's search text, as each shared style's is: its name and every\n  // property and value it declares, so a search the box promises finds both.\n  // Keyed by look, its type with its id, since two types' own looks may\n  // share an id and each is found by its own text.\n  const texts = React.useMemo(\n    () =>\n      new Map(\n        groups.flatMap(group =>\n          group.rows.map(row => [\n            lookKeyOf(row),\n            sharedStyleSearchText(row, styleContext),\n          ])\n        )\n      ),\n    [groups, styleContext]\n  );\n  return foundLooks(groups, query, row => texts.get(lookKeyOf(row)) ?? \"\");\n}\n\n/**\n * The Block styles section above the shared styles: the site's looks by\n * block type, found by the same search, with the worn looks' counts read as\n * the shared styles' are. An own look has no count of its own.\n */\nfunction PanelLooks({\n  library,\n  suppliedClassIds,\n  query,\n  paint,\n  editing,\n  styleContext,\n  reaches,\n  blocksOf,\n  actions,\n  readOnly,\n  folds,\n}: {\n  library: readonly NamedClass[];\n  suppliedClassIds: readonly string[] | undefined;\n  query: string;\n  styleContext: StyleCompileContext | undefined;\n  paint: TilePaint;\n  editing: PanelLookEditing | undefined;\n  /** Each worn look's reach, from the tab's one usage read. */\n  reaches: ReadonlyMap<string, SharedStyleReach>;\n  /** The open page's blocks carrying a class, as the shared styles read them. */\n  blocksOf: (id: string) => BlocksOnThisPage;\n  actions: BlockStyleActions | undefined;\n  readOnly: boolean;\n  folds: GroupFolds | undefined;\n}): React.JSX.Element | null {\n  const groups = useLookGroups(library, suppliedClassIds, query, styleContext);\n  return (\n    <BlockLooksGroup\n      groups={groups}\n      library={library}\n      tokens={paint.tokens}\n      mode={paint.mode}\n      editing={editing?.editing}\n      onEdit={editing?.onEdit}\n      {...(actions === undefined ? {} : { actions })}\n      readOnly={readOnly}\n      {...(folds === undefined ? {} : { folds })}\n      searching={query.trim() !== \"\"}\n      reachOf={row => reaches.get(row.id)}\n      blocksOf={row => blocksOf(row.id)}\n      chip={reach => <ReachChip reach={reach} />}\n    />\n  );\n}\n\n/**\n * The Block styles section's writes, over the host's whole-list class write\n * and the shared styles' removal, which refuses a style a page still uses.\n */\nfunction useBlockStyleActions(\n  edit: SharedStylesPanelProps[\"onEditClasses\"],\n  access: SharedStylesAccess | undefined\n): BlockStyleActions | undefined {\n  const remove = access?.remove;\n  return React.useMemo(\n    () => (edit === undefined ? undefined : blockStyleActionsOf(edit, remove)),\n    [edit, remove]\n  );\n}\n\n/** Whether a style may be renamed here: the tab is writable and a rename has a host. */\nfunction mayRename(\n  readOnly: boolean,\n  onRename: SharedStylesPanelProps[\"onRename\"]\n): boolean {\n  return !readOnly && onRename !== undefined;\n}\n\n/** The worn looks among the groups, whose counts are read. */\nfunction wornLookIds(groups: readonly BlockLookGroup[]): string[] {\n  return groups.flatMap(group =>\n    group.rows.filter(row => !row.own).map(row => row.id)\n  );\n}\n\nexport function SharedStylesPanel({\n  library,\n  absence = \"pending\",\n  suppliedClassIds,\n  styleContext,\n  tokens,\n  pageBlocks,\n  readOnly = false,\n  access,\n  onRename,\n  currentRenameAttempt,\n  pendingNames = NO_NAMES,\n  looks,\n  initialOpenId,\n  // The Block styles section's own props, handed to it whole.\n  ...section\n}: SharedStylesPanelProps): React.JSX.Element {\n  const { query, setQuery, box: search } = usePanelSearch();\n  const [filter, setFilter] = React.useState<SharedStyleFilter>(\"all\");\n  const [pages, setPages] = React.useState(1);\n  const [issue, setIssue] = React.useState<Issue | null>(null);\n  const [openId, setOpenId] = React.useState<string | null>(\n    openFirst(initialOpenId)\n  );\n  const { rows, lookIds, found, paint } = useListedRows({\n    library,\n    suppliedClassIds,\n    styleContext,\n    tokens,\n    query,\n  });\n  // Every style's usage is read, so each filter can be counted: the rows the\n  // search puts first, then the rest, fifty to a read.\n  const usage = useUsage(access, usageOrder(rows, found, pages, lookIds));\n  const { counter } = usage;\n  const exact = countsExact(usage, pageBlocks, rows);\n\n  const usageOf = (row: SharedStyleRow) =>\n    sharedStyleUse(pageBlocksOf(pageBlocks, row.id), usage.styles.get(row.id));\n  const reason = floorReason(usage.whole, usage.counting);\n  const notes = countingNotes(unusedWithheld(filter, found, usageOf), reason);\n  const filtered = found.filter(row =>\n    inSharedStyleFilter(row, filter, usageOf(row))\n  );\n  const shown = shownWithOpen(filtered, pages, openId);\n  const rename = useRename({\n    library,\n    onRename,\n    currentRenameAttempt,\n    pendingNames,\n    setIssue,\n  });\n  const blockStyles = useBlockStyleActions(section.onEditClasses, access);\n  if (library === undefined) return <Unread absence={absence} />;\n\n  const blocksOf = (id: string): BlocksOnThisPage =>\n    pageBlocksOf(pageBlocks, id);\n  const writable = mayRename(readOnly, onRename);\n  // Any rename still being stored. A rename writes the whole list of styles,\n  // and so do Lock, Remove and Remove unused, so each waits for every\n  // pending rename, not only its own row's: whichever landed second would put\n  // the other's list back.\n  const held = Object.keys(pendingNames).length > 0;\n\n  return (\n    <div className=\"nx-vars nx-shared-styles\" {...readOnlyMark(readOnly)}>\n      <SearchBox\n        ref={search}\n        query={query}\n        onQuery={next => {\n          setQuery(next);\n          setPages(1);\n        }}\n      />\n      <FiltersWhenListed\n        rows={rows}\n        filter={filter}\n        onFilter={next => {\n          setFilter(next);\n          setPages(1);\n        }}\n        usageOf={usageOf}\n        exact={exact}\n      />\n      <div className=\"nx-vars__body\">\n        <PanelNotes\n          readOnly={readOnly}\n          usageFailed={usage.failed}\n          issue={issueBesideList(issue, openId)}\n        />\n        <PanelLooks\n          library={library}\n          suppliedClassIds={suppliedClassIds}\n          query={query}\n          paint={paint}\n          editing={looks}\n          styleContext={styleContext}\n          reaches={usage.styles}\n          blocksOf={blocksOf}\n          actions={blockStyles}\n          readOnly={readOnly}\n          folds={section.folds}\n        />\n        <section\n          className=\"nx-vars__group\"\n          aria-labelledby=\"nx-shared-styles-all\"\n          aria-describedby=\"nx-shared-styles-line\"\n        >\n          <RemoveUnusedHead\n            rows={rows}\n            offered={removalOffered(readOnly, access)}\n            access={access}\n            reason={reason}\n            held={held}\n            saidInNote={notes.one}\n            blocksOf={blocksOf}\n            onRemoved={() => search.current?.focus()}\n          />\n          <p className=\"nx-shared-styles__line\" id=\"nx-shared-styles-line\">\n            {BLOCK_STYLE_WORDS.sharedLine}\n          </p>\n          <TopNote\n            note={notes.top}\n            says={notes.one}\n            jobs={notes.jobs}\n            counter={counter}\n          />\n          <StyleList\n            rows={rows}\n            found={filtered}\n            filter={filter}\n            query={query.trim()}\n            withheld={notes.withheld}\n            covered={notes.top !== undefined}\n          >\n            {shown.map(row => (\n              <StyleRow\n                key={row.id}\n                row={row}\n                name={shownName(pendingNames, row)}\n                details={{\n                  styleContext,\n                  blocks: blocksOf(row.id),\n                  reach: usage.styles.get(row.id),\n                  whole: usage.whole,\n                  mayLock: usage.mayLock,\n                  readOnly: !writable,\n                  access,\n                  held,\n                  issue: issueOf(issue, row.id),\n                  onRename: value => rename(row, value),\n                  onRemoved: () => {\n                    setOpenId(null);\n                    search.current?.focus();\n                  },\n                  // A refusal says why, not whether it is used: a lock or a\n                  // count no longer whole refuses too. The read again decides.\n                  onRefused: () => usage.reread([row.id]),\n                }}\n                paint={paint}\n                open={openId === row.id}\n                onOpenChange={openedOrClosed(setOpenId, row.id)}\n              />\n            ))}\n          </StyleList>\n          <ShowMore\n            hidden={filtered.length - shown.length}\n            pageSize={PAGE_SIZE}\n            onMore={() => setPages(count => count + 1)}\n          />\n        </section>\n      </div>\n    </div>\n  );\n}\n\n/** A row's name: the one it is being renamed to while that is stored. */\nfunction shownName(\n  pendingNames: Readonly<Record<string, string>>,\n  row: SharedStyleRow\n): string {\n  return pendingName(pendingNames, row.id) ?? row.name;\n}\n\n/** A row's details opened or closed: its id while open, none once closed. */\nfunction openedOrClosed(\n  setOpenId: (id: string | null) => void,\n  id: string\n): (open: boolean) => void {\n  return open => setOpenId(open ? id : null);\n}\n\n/** Whether removing styles is offered: a writable tab with the routes. */\nfunction removalOffered(\n  readOnly: boolean,\n  access: SharedStylesAccess | undefined\n): boolean {\n  return !readOnly && access !== undefined;\n}\n\n/** The style whose details open first: the one another tab asked for, or none. */\nfunction openFirst(initialOpenId: string | undefined): string | null {\n  return initialOpenId ?? null;\n}\n\n/**\n * The rows the pages show, with the open style's row: a style opened from\n * another tab can lie past the pages, and its row is drawn all the same, so\n * its details have a row to open beside.\n */\nfunction shownWithOpen(\n  rows: readonly SharedStyleRow[],\n  pages: number,\n  openId: string | null\n): readonly SharedStyleRow[] {\n  return withOpenRow(rows, pages * PAGE_SIZE, row => row.id === openId);\n}\n\n/** The tab's read-only mark, for the styles that draw a read-only tab. */\nfunction readOnlyMark(readOnly: boolean): { \"data-read-only\"?: \"\" } {\n  return readOnly ? { \"data-read-only\": \"\" } : {};\n}\n\n/** The search over every style, by name, property or value. */\nfunction SearchBox({\n  ref,\n  query,\n  onQuery,\n}: {\n  ref: React.Ref<HTMLInputElement>;\n  query: string;\n  onQuery: (query: string) => void;\n}): React.JSX.Element | null {\n  // Not drawn where a host keeps the search.\n  if (React.useContext(SharedStylesHostSearch) !== undefined) return null;\n  return (\n    <div className=\"nx-vars__search\">\n      <Search aria-hidden=\"true\" size={16} />\n      <Input\n        ref={ref}\n        type=\"search\"\n        aria-label={`Search ${SHARED_STYLES_WORD}`}\n        placeholder=\"Search by name, property or value\"\n        value={query}\n        onChange={event => onQuery(event.target.value)}\n      />\n    </div>\n  );\n}\n\n/**\n * Whether Used and Unused can be counted: every page counted, the open page\n * read in full, and every style's reach complete.\n */\nfunction countsExact(\n  usage: UsageState,\n  pageBlocks: PageClassBlocks,\n  rows: readonly SharedStyleRow[]\n): boolean {\n  return (\n    usage.whole === true &&\n    pageBlocks.complete &&\n    rows.every(row => usage.styles.get(row.id)?.complete === true)\n  );\n}\n\n/** The blocks on the open page that carry one style. */\nfunction pageBlocksOf(\n  pageBlocks: PageClassBlocks,\n  id: string\n): BlocksOnThisPage {\n  return {\n    count: pageBlocks.counts.get(id) ?? 0,\n    complete: pageBlocks.complete,\n  };\n}\n\n/**\n * The order usage is read in: the rows the search lists on screen first, so\n * their counts arrive first, then every other style, so each filter can be\n * counted.\n */\nfunction usageOrder(\n  rows: readonly SharedStyleRow[],\n  found: readonly SharedStyleRow[],\n  pages: number,\n  lookIds: readonly string[] = []\n): string[] {\n  const first = found.slice(0, pages * PAGE_SIZE).map(row => row.id);\n  const listed = new Set(first);\n  // The worn looks after the styles: few, and listed above the styles.\n  return [\n    ...first,\n    ...rows.map(row => row.id).filter(id => !listed.has(id)),\n    ...lookIds,\n  ];\n}\n","/**\n * What Design's \"Body font\" and \"Headings font\" read and write.\n *\n * Each is a font variable and the Site text rows pointing at it: Body is\n * `font.body` and the Body row, Headings is `font.heading` and the six\n * heading rows. Picking a font writes the variable's value and points the\n * rows' font at the variable, in one new token set, so the pick saves,\n * merges and undoes as one edit, and a host's own CSS can read the font\n * through the variable's custom property. Until a row points at a font the\n * rows write none: Body is then the site's own font, and headings take the\n * body text's.\n *\n * @module site-font-roles-model\n */\nimport {\n  compileStyleValues,\n  customPropertiesReferenced,\n  DEFAULT_SITE_TEXT,\n  isTokenRef,\n  readFamilyList,\n  resolveSiteText,\n  resolveSiteTokens,\n  resolveTokenPrefix,\n  siteTextStyles,\n  tokenCustomProperty,\n  tokenIdentity,\n  tokenRef,\n  type FontFaceDef,\n  type NamedClass,\n  type SiteTextEntry,\n  type SiteTextMap,\n  type SiteTextRole,\n  type SiteTokenSet,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { declarationsText } from \"../../inspector/code-hints\";\n\nimport { drawsBold, roleStack, siteFamilies } from \"./font-library\";\n\n/** The two site-wide fonts. */\nexport type FontRole = \"body\" | \"heading\";\n\n/** The variable each role's font is held in, by identity. */\nconst FONT_ROLE_TOKEN: Readonly<Record<FontRole, string>> = {\n  body: \"font.body\",\n  heading: \"font.heading\",\n};\n\n/** The heading rows, which the Headings font points together. */\nconst HEADING_ROWS: readonly SiteTextRole[] = [\n  \"h1\",\n  \"h2\",\n  \"h3\",\n  \"h4\",\n  \"h5\",\n  \"h6\",\n];\n\n/** The Site text rows a role's font is written on. */\nexport function fontRoleRows(role: FontRole): readonly SiteTextRole[] {\n  return role === \"body\" ? [\"body\"] : HEADING_ROWS;\n}\n\n/**\n * What a role is set to:\n *\n * - `unset`: no row holds a font, so Body is the site's own font and\n *   headings take the body text's;\n * - `set`: every row draws one font, the variable's value where the rows\n *   point at a variable, else the value they hold;\n * - `mixed`: the heading rows hold different fonts (set through the API).\n */\nexport type FontRoleSetting =\n  | { readonly kind: \"unset\" }\n  | { readonly kind: \"set\"; readonly stack: string }\n  | { readonly kind: \"mixed\" };\n\n/** The colour mode a variable's value is read in. */\ntype FontMode = \"light\" | \"dark\";\n\n/**\n * A variable's value in a mode, a built-in's included. A variable with no\n * dark value draws its light one in dark mode too.\n */\nfunction variableValue(\n  tokens: SiteTokenSet,\n  identity: string,\n  mode: FontMode\n): string | undefined {\n  const values = resolveSiteTokens(tokens).tokens.find(\n    token => tokenIdentity(token) === identity\n  )?.values;\n  return mode === \"dark\" ? (values?.dark ?? values?.light) : values?.light;\n}\n\n/** The site variable a custom property is, by identity, or none. */\nfunction siteVariableNamed(\n  tokens: SiteTokenSet,\n  property: string\n): string | undefined {\n  const { prefix } = resolveTokenPrefix(tokens.prefix);\n  const read = resolveSiteTokens(tokens).tokens.find(\n    token => tokenCustomProperty(tokenIdentity(token), prefix) === property\n  );\n  return read === undefined ? undefined : tokenIdentity(read);\n}\n\n/**\n * The fallback a family that is one whole `var()` gives, as written, read as\n * a family list is: `Lora` from `var(--unset, Lora)`. None where the family\n * is more than one call, or the fallback is empty or not a family list.\n */\nfunction varFallback(raw: string): string | undefined {\n  const call = /^var\\(([\\s\\S]*)\\)$/i.exec(raw);\n  if (call === null) return undefined;\n  // The call's custom property, then its fallback, split as a stack is.\n  const [, ...fallback] = readFamilyList(call[1] ?? \"\").parts;\n  const text = fallback.map(each => each.part.raw).join(\", \");\n  const { kind } = readFamilyList(text);\n  return kind === \"families\" || kind === \"dynamic\" ? text : undefined;\n}\n\n/**\n * What a stack's first family reads when it is a `var()`: the site variable\n * it names, or, where it names none, the stack drawn with its fallback in its\n * place, as `var(--unset, Lora), serif` draws `Lora, serif`. Nothing for a\n * first family that is no `var()`, or one naming no site variable and giving\n * no fallback, which a browser drops the whole value for.\n */\nfunction firstVarRead(\n  tokens: SiteTokenSet,\n  stack: string\n): { readonly identity: string } | { readonly stack: string } | undefined {\n  const [first, ...rest] = readFamilyList(stack).parts;\n  if (first?.kind !== \"dynamic\") return undefined;\n  const [property] = customPropertiesReferenced(first.part.raw) ?? [];\n  if (property === undefined) return undefined;\n  const identity = siteVariableNamed(tokens, property);\n  if (identity !== undefined) return { identity };\n  const fallback = varFallback(first.part.raw);\n  if (fallback === undefined) return undefined;\n  return { stack: [fallback, ...rest.map(each => each.part.raw)].join(\", \") };\n}\n\n/**\n * A row's font as the browser takes its first step: the site variable it\n * reads, a `$token` or a first family that is a `var()` of one, as\n * `var(--site-font-display), serif` reads `font.display`; else the stack it\n * draws as written. A leading `var()` naming no site variable is read as its\n * fallback, each in turn; a `var()` later in the stack is only a fallback.\n */\nfunction firstStep(\n  tokens: SiteTokenSet,\n  value: StyleValue\n): { readonly identity: string } | { readonly stack: string } | undefined {\n  if (isTokenRef(value)) return { identity: value.$token };\n  if (typeof value !== \"string\") return undefined;\n  let stack = value;\n  // Each fallback lies inside the first family before it, so the first\n  // family shrinks at every step and the reading ends.\n  for (\n    let read = firstVarRead(tokens, stack);\n    read !== undefined;\n    read = firstVarRead(tokens, stack)\n  ) {\n    if (\"identity\" in read) return read;\n    stack = read.stack;\n  }\n  return { stack };\n}\n\n/** The site variable a row's font reads, by identity ({@link firstStep}). */\nfunction variableRead(\n  tokens: SiteTokenSet,\n  value: StyleValue\n): string | undefined {\n  const step = firstStep(tokens, value);\n  return step !== undefined && \"identity\" in step ? step.identity : undefined;\n}\n\n/**\n * Whether a font value reads a role's variable, directly or through the\n * variables it reads in turn ({@link firstStep}): such a font changes when\n * the role's font is chosen. A loop reads no role.\n */\nexport function fontReadsRole(\n  tokens: SiteTokenSet,\n  value: StyleValue,\n  role: FontRole\n): boolean {\n  const seen = new Set<string>();\n  let step = firstStep(tokens, value);\n  while (step !== undefined && \"identity\" in step) {\n    if (step.identity === FONT_ROLE_TOKEN[role]) return true;\n    if (seen.has(step.identity)) return false;\n    seen.add(step.identity);\n    const next = variableValue(tokens, step.identity, \"light\");\n    if (next === undefined) return false;\n    step = firstStep(tokens, next);\n  }\n  return false;\n}\n\n/**\n * The font a row's value draws in a mode, as a stack. A variable it reads is\n * followed, and so is one that variable reads through `var()` in turn, past\n * fallbacks as {@link firstStep} reads them. A loop of variables draws no\n * font, as a browser draws none.\n */\nfunction drawnStack(\n  tokens: SiteTokenSet,\n  value: StyleValue,\n  mode: FontMode\n): string | undefined {\n  const seen = new Set<string>();\n  let step = firstStep(tokens, value);\n  while (step !== undefined && \"identity\" in step) {\n    if (seen.has(step.identity)) return undefined;\n    seen.add(step.identity);\n    const next = variableValue(tokens, step.identity, mode);\n    if (next === undefined) return undefined;\n    step = firstStep(tokens, next);\n  }\n  return step?.stack;\n}\n\n/**\n * The fonts a site variable draws, in light and dark mode, as stacks: what\n * it holds, or what a variable it reads through `var()` holds.\n */\nexport function variableStacks(\n  tokens: SiteTokenSet,\n  identity: string\n): readonly string[] {\n  return ([\"light\", \"dark\"] as const).flatMap(mode => {\n    const stack = drawnStack(tokens, tokenRef(identity), mode);\n    return stack === undefined ? [] : [stack];\n  });\n}\n\n/**\n * What a role is set to, read from the rows it is written on, in light mode\n * as the picker shows it.\n */\nexport function fontRoleSetting(\n  tokens: SiteTokenSet,\n  role: FontRole\n): FontRoleSetting {\n  const rows = resolveSiteText(tokens.siteText);\n  const fonts = fontRoleRows(role).map(row => rows[row]?.fontFamily);\n  if (fonts.every(font => font === undefined)) {\n    return { kind: \"unset\" };\n  }\n  // Compared by the font each row draws, so a row holding the font as written\n  // and one pointing at a variable of that font read as one setting.\n  const stacks = fonts.map(font =>\n    font === undefined ? undefined : drawnStack(tokens, font, \"light\")\n  );\n  const [stack] = stacks;\n  return stack !== undefined && stacks.every(each => each === stack)\n    ? { kind: \"set\", stack }\n    : { kind: \"mixed\" };\n}\n\n/**\n * The fonts a row draws, as the engine writes it: a row following a text\n * style draws the style's, at every state and size, and its own otherwise.\n */\nfunction rowFonts(\n  row: SiteTextRole,\n  entry: SiteTextEntry | undefined,\n  classes: readonly NamedClass[] | undefined\n): StyleValue[] {\n  const styles = siteTextStyles(row, entry, classes) ?? {};\n  return Object.values(styles).flatMap(sizes =>\n    Object.values(sizes ?? {}).flatMap(values =>\n      values?.fontFamily === undefined ? [] : [values.fontFamily]\n    )\n  );\n}\n\n/** Every font a role's rows draw, each row on its own, as the engine reads it. */\nfunction roleFonts(\n  tokens: SiteTokenSet,\n  role: FontRole,\n  classes: readonly NamedClass[] | undefined\n): StyleValue[] {\n  const rows = resolveSiteText(tokens.siteText);\n  return fontRoleRows(role).flatMap(row => rowFonts(row, rows[row], classes));\n}\n\n/**\n * Every font a role's rows draw, each row on its own and in both modes, as\n * stacks: what removing a font takes from the role, whether its rows agree\n * or not. A row with no font of its own adds none, and a row following a\n * text style adds the style's.\n *\n * @param classes - the site's classes, where its text styles are\n */\nexport function fontRoleStacks(\n  tokens: SiteTokenSet,\n  role: FontRole,\n  classes?: readonly NamedClass[]\n): readonly string[] {\n  const stacks = new Set<string>();\n  for (const font of roleFonts(tokens, role, classes)) {\n    for (const mode of [\"light\", \"dark\"] as const) {\n      const stack = drawnStack(tokens, font, mode);\n      if (stack !== undefined) stacks.add(stack);\n    }\n  }\n  return [...stacks];\n}\n\n/**\n * The variables a role's rows point at, by identity, a followed text\n * style's included.\n *\n * @param classes - the site's classes, where its text styles are\n */\nexport function fontRoleVariables(\n  tokens: SiteTokenSet,\n  role: FontRole,\n  classes?: readonly NamedClass[]\n): readonly string[] {\n  const identities = roleFonts(tokens, role, classes).flatMap(font => {\n    const identity = variableRead(tokens, font);\n    return identity === undefined ? [] : [identity];\n  });\n  return [...new Set(identities)];\n}\n\n/** Two rows holding the same values, whatever order they hold them in. */\nfunction sameRow(a: SiteTextEntry, b: SiteTextEntry | undefined): boolean {\n  const left = Object.entries(a);\n  const right = Object.entries(b ?? {});\n  return (\n    left.length === right.length &&\n    left.every(\n      ([key, value]) =>\n        JSON.stringify(value) ===\n        JSON.stringify((b as Record<string, unknown> | undefined)?.[key])\n    )\n  );\n}\n\n/** The set with a role's variable holding a font. */\nfunction withRoleVariable(\n  tokens: SiteTokenSet,\n  identity: string,\n  stack: string\n): SiteTokenSet {\n  const at = tokens.tokens.findIndex(\n    token => tokenIdentity(token) === identity\n  );\n  if (at === -1) {\n    return {\n      ...tokens,\n      tokens: [\n        ...tokens.tokens,\n        { name: identity, kind: \"fontFamily\", values: { light: stack } },\n      ],\n    };\n  }\n  return {\n    ...tokens,\n    // The light value alone: a font picked for the role is the font in\n    // either mode.\n    tokens: tokens.tokens.map((token, index) =>\n      index === at ? { ...token, values: { light: stack } } : token\n    ),\n  };\n}\n\n/**\n * The set with a role set to a font, or, given `undefined`, with its rows'\n * font taken away: Body back to the site's own font, Headings back to the\n * body text's. One set, the variable and the rows together.\n *\n * A row left holding just its built-in values is left out again, so it\n * reads as the built-in row it is, unless the site's code supplies that row,\n * whose font would otherwise come back.\n *\n * @param supplied - the rows the site's code supplies\n */\nexport function withFontRole(\n  tokens: SiteTokenSet,\n  role: FontRole,\n  stack: string | undefined,\n  supplied?: SiteTextMap\n): SiteTokenSet {\n  const identity = FONT_ROLE_TOKEN[role];\n  const rows = resolveSiteText(tokens.siteText);\n  const stated: Partial<Record<SiteTextRole, SiteTextEntry>> = {\n    ...tokens.siteText,\n  };\n  for (const row of fontRoleRows(role)) {\n    const { fontFamily: _font, ...rest } = rows[row] ?? {};\n    const next: SiteTextEntry =\n      stack === undefined ? rest : { ...rest, fontFamily: tokenRef(identity) };\n    const builtIn =\n      stack === undefined &&\n      sameRow(next, DEFAULT_SITE_TEXT[row] ?? {}) &&\n      (supplied === undefined || !Object.hasOwn(supplied, row));\n    if (builtIn) delete stated[row];\n    else stated[row] = next;\n  }\n  const withRows: SiteTokenSet = { ...tokens, siteText: stated };\n  return stack === undefined\n    ? withRows\n    : withRoleVariable(withRows, identity, stack);\n}\n\n/** One of the site's variables, as a token set stores it. */\ntype StoredToken = SiteTokenSet[\"tokens\"][number];\n\n/**\n * A role as a set holds it, to put back later exactly: its variable as\n * stored, both modes included, and each of its rows as stated.\n */\nexport interface RoleSnapshot {\n  readonly role: FontRole;\n  /** The role's variable as stored; `undefined` where the set holds none. */\n  readonly variable: StoredToken | undefined;\n  /** Each of the role's rows as stated; a row the set states not, absent. */\n  readonly rows: Readonly<Partial<Record<SiteTextRole, SiteTextEntry>>>;\n}\n\n/** The role as `tokens` holds it, for {@link withRoleSnapshot}. */\nexport function roleSnapshot(\n  tokens: SiteTokenSet,\n  role: FontRole\n): RoleSnapshot {\n  const identity = FONT_ROLE_TOKEN[role];\n  const rows: Partial<Record<SiteTextRole, SiteTextEntry>> = {};\n  for (const row of fontRoleRows(role)) {\n    const stated = tokens.siteText?.[row];\n    if (stated !== undefined) rows[row] = stated;\n  }\n  return {\n    role,\n    variable: tokens.tokens.find(token => tokenIdentity(token) === identity),\n    rows,\n  };\n}\n\n/**\n * A role's row put back as a snapshot stated it, onto the row as it is now:\n * only its font, so another change to the row since is kept. A row the\n * snapshot did not state, left with its built-in values, is left out again,\n * unless the site's code supplies it.\n */\nfunction restoredRow(\n  row: SiteTextRole,\n  was: SiteTextEntry | undefined,\n  now: SiteTextEntry | undefined,\n  supplied: SiteTextMap | undefined\n): SiteTextEntry | undefined {\n  const base = now ?? was;\n  if (was !== undefined && Object.hasOwn(was, \"fontFamily\")) {\n    return { ...base, fontFamily: was.fontFamily };\n  }\n  if (base === undefined) return undefined;\n  const { fontFamily: _font, ...rest } = base;\n  const builtIn =\n    was === undefined &&\n    sameRow(rest, DEFAULT_SITE_TEXT[row] ?? {}) &&\n    (supplied === undefined || !Object.hasOwn(supplied, row));\n  return builtIn ? undefined : rest;\n}\n\n/**\n * The set with a role put back as a snapshot held it, onto the set as it is\n * now: the role's variable exactly as it was (or taken away where there was\n * none) and its rows' fonts, leaving every other variable and row, the other\n * role's included, as they are.\n *\n * @param supplied - the rows the site's code supplies\n */\nexport function withRoleSnapshot(\n  tokens: SiteTokenSet,\n  snapshot: RoleSnapshot,\n  supplied?: SiteTextMap\n): SiteTokenSet {\n  const identity = FONT_ROLE_TOKEN[snapshot.role];\n  const stated: Partial<Record<SiteTextRole, SiteTextEntry>> = {\n    ...tokens.siteText,\n  };\n  for (const row of fontRoleRows(snapshot.role)) {\n    const next = restoredRow(row, snapshot.rows[row], stated[row], supplied);\n    if (next === undefined) delete stated[row];\n    else stated[row] = next;\n  }\n  const others = tokens.tokens.filter(\n    token => tokenIdentity(token) !== identity\n  );\n  const at = tokens.tokens.findIndex(\n    token => tokenIdentity(token) === identity\n  );\n  const { variable } = snapshot;\n  let variables: StoredToken[] = others;\n  if (variable !== undefined) {\n    variables =\n      at === -1\n        ? [...tokens.tokens, variable]\n        : tokens.tokens.map((token, index) =>\n            index === at ? variable : token\n          );\n  }\n  return { ...tokens, tokens: variables, siteText: stated };\n}\n\n/** The element a role's font is written on, as a developer names it. */\nconst ROLE_SELECTOR: Readonly<Record<FontRole, string>> = {\n  body: \".nx-pb-page\",\n  heading: \"h1, h2, h3, h4, h5, h6\",\n};\n\n/** A font as the compiler writes it: a variable's `var()`, else as given. */\nfunction writtenFont(value: StyleValue, prefix: string): string {\n  const { declarations } = compileStyleValues(\n    { fontFamily: value },\n    \"\",\n    prefix\n  );\n  return declarationsText(declarations);\n}\n\n/**\n * The variable a row's font reads and its value, as a declaration, or\n * nothing for a font the row holds as written.\n */\nfunction variableDeclared(\n  tokens: SiteTokenSet,\n  value: StyleValue,\n  prefix: string\n): string {\n  if (!isTokenRef(value)) return \"\";\n  const property = tokenCustomProperty(value.$token, prefix);\n  return `${property}: ${variableValue(tokens, value.$token, \"light\") ?? \"\"}; `;\n}\n\n/**\n * The CSS a role writes, for its hover text, read from the rows themselves:\n * the variable a row points at with its value, and the rule the row writes,\n * or \"Nothing\" while it is unset. Heading rows holding different fonts are\n * said one by one.\n */\nexport function fontRoleWrites(tokens: SiteTokenSet, role: FontRole): string {\n  const { prefix } = resolveTokenPrefix(tokens.prefix);\n  const rows = resolveSiteText(tokens.siteText);\n  const held = fontRoleRows(role).flatMap(row => {\n    const font = rows[row]?.fontFamily;\n    return font === undefined ? [] : [[row, font] as const];\n  });\n  const [first] = held;\n  if (first === undefined) return \"Nothing\";\n  // One rule for every row only where each row holds the font the same way.\n  const uniform =\n    held.length === fontRoleRows(role).length &&\n    held.every(([, font]) => JSON.stringify(font) === JSON.stringify(first[1]));\n  if (uniform) {\n    return `${variableDeclared(tokens, first[1], prefix)}${ROLE_SELECTOR[role]} { ${writtenFont(first[1], prefix)} }`;\n  }\n  return held\n    .map(\n      ([row, font]) =>\n        `${variableDeclared(tokens, font, prefix)}${row} { ${writtenFont(font, prefix)} }`\n    )\n    .join(\" \");\n}\n\n/** One family the site loads, as a role's picker offers it. */\nexport interface RoleFamily {\n  /** The family as first written. */\n  readonly family: string;\n  /** What picking it stores: the family and the generic of its kind. */\n  readonly stack: string;\n  readonly faces: readonly FontFaceDef[];\n}\n\n/** The families the site loads, each with the stack a role stores for it. */\nexport function roleFamilies(\n  faces: readonly FontFaceDef[],\n  fromCode: readonly FontFaceDef[]\n): RoleFamily[] {\n  return siteFamilies(faces, fromCode).map(family => ({\n    family: family.family,\n    stack: roleStack(family.family, family.category),\n    faces: family.faces,\n  }));\n}\n\n/** The first family a stack names, lower-cased as CSS matches it. */\nexport function firstFamily(stack: string): string | undefined {\n  const reading = readFamilyList(stack);\n  if (reading.kind !== \"families\" && reading.kind !== \"dynamic\") {\n    return undefined;\n  }\n  return reading.parts[0]?.part.name.toLowerCase();\n}\n\n/** The cut a heading is missing, and how to add it where it can be. */\nexport interface MissingBold {\n  /** The family, as first written. */\n  readonly family: string;\n  /**\n   * What to ask the catalogue for, for a family the site got from it; absent\n   * for an uploaded one, which only a new file can give a bold.\n   */\n  readonly add?: {\n    readonly id: string;\n    readonly weights: readonly number[];\n    readonly styles: readonly (\"normal\" | \"italic\")[];\n    readonly subsets: readonly string[];\n  };\n}\n\n/** The catalogue request that adds a family's bold, where it came from one. */\nfunction boldRequest(faces: readonly FontFaceDef[]): MissingBold[\"add\"] {\n  const id = faces.find(face => face.source?.kind === \"google\")?.source?.id;\n  if (id === undefined) return undefined;\n  const subsets = [\n    ...new Set(\n      faces.flatMap(face =>\n        face.source?.subset === undefined ? [] : [face.source.subset]\n      )\n    ),\n  ];\n  return {\n    id,\n    weights: [700],\n    styles: [\"normal\"],\n    subsets: subsets.length === 0 ? [\"latin\"] : subsets,\n  };\n}\n\n/**\n * The family headings are drawn in with no face at 600 or heavier, so a\n * browser thickens a lighter one for every bold heading; `undefined` when\n * they have a bold, or are not drawn in one of the site's families.\n *\n * Headings drawn in the Body font (\"Same as body\") are judged by it.\n */\nexport function missingBold(\n  tokens: SiteTokenSet,\n  families: readonly RoleFamily[]\n): MissingBold | undefined {\n  const heading = fontRoleSetting(tokens, \"heading\");\n  const drawn =\n    heading.kind === \"unset\" ? fontRoleSetting(tokens, \"body\") : heading;\n  if (drawn.kind !== \"set\") return undefined;\n  const key = firstFamily(drawn.stack);\n  const family = families.find(each => each.family.toLowerCase() === key);\n  if (family === undefined || drawsBold(family.faces)) return undefined;\n  const add = boldRequest(family.faces);\n  return { family: family.family, ...(add === undefined ? {} : { add }) };\n}\n","\"use client\";\n\n/**\n * The top of Design → Type: \"Body font\" and \"Headings font\", the fonts every\n * page's text and headings are set in, on the canvas and the live site.\n *\n * Each is a row naming its font, drawn in it, that opens a list of what the\n * site can draw: the site's own fonts, the system's, and \"Your site's own\n * font\" (for Headings, \"Same as body\"), which writes nothing. A pick is one\n * new token set handed to the host, as a variable edit is, so it saves,\n * merges and undoes the same way (`site-font-roles-model`). What a row writes\n * is said on hover and, while \"Show CSS names\" is on, under the row.\n *\n * Under them, when headings are drawn in one of the site's fonts that has no\n * bold, a line says so, with \"Add Bold\" for a font from the catalogue.\n *\n * @module site-font-roles\n */\nimport type {\n  FontFaceDef,\n  SiteTextMap,\n  SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\nimport { Button, Popover, PopoverContent, PopoverTrigger } from \"@nextlyhq/ui\";\nimport { ChevronDown } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { ChoiceList } from \"../../choice-list\";\nimport { FONT_ROLE_WORDS, noBoldWords } from \"../../editor-words\";\nimport { CssHint, CssNamesLine } from \"../../inspector/css-hint\";\n\nimport type { CatalogueAddRequest } from \"./font-catalogue-view\";\nimport { Refusal, useRefusableWrite } from \"./panel-actions\";\nimport {\n  firstFamily,\n  fontRoleSetting,\n  fontRoleWrites,\n  missingBold,\n  roleFamilies,\n  withFontRole,\n  type FontRole,\n  type MissingBold,\n  type RoleFamily,\n} from \"./site-font-roles-model\";\n\nexport interface SiteFontRolesProps {\n  readonly tokens: SiteTokenSet;\n  readonly onChange: (tokens: SiteTokenSet) => void;\n  readonly readOnly: boolean;\n  /** The Site text rows the site's code supplies. */\n  readonly supplied?: SiteTextMap | undefined;\n  /** The faces the page loads, or `undefined` while they are being read. */\n  readonly faces: readonly FontFaceDef[] | undefined;\n  /** The faces the site's code supplies. */\n  readonly fromCode: readonly FontFaceDef[];\n  /** Open the site's fonts, where fonts are added. Absent, no link shows. */\n  readonly onManageFonts?: (() => void) | undefined;\n  /**\n   * Add cuts of a catalogue family to the site, resolving to a message when\n   * refused. Absent, \"Add Bold\" is not offered.\n   */\n  readonly onAddCut?:\n    | ((request: CatalogueAddRequest) => Promise<string | undefined>)\n    | undefined;\n}\n\n/** One entry of a role's list. */\ninterface RoleChoice {\n  readonly key: string;\n  readonly group: \"start\" | \"site\" | \"system\";\n  readonly label: string;\n  /** What picking it stores, or `undefined` for the entry writing nothing. */\n  readonly stack: string | undefined;\n}\n\n/** The system's own fonts, each with the fallback of its kind. */\nconst SYSTEM_STACKS: ReadonlyArray<readonly [string, string]> = [\n  [\"System UI\", \"system-ui, sans-serif\"],\n  [\"Sans serif\", \"sans-serif\"],\n  [\"Serif\", \"serif\"],\n  [\"Monospace\", \"monospace\"],\n  [\"System serif\", \"ui-serif, serif\"],\n  [\"System monospace\", \"ui-monospace, monospace\"],\n  [\"System rounded\", \"ui-rounded, sans-serif\"],\n];\n\nconst GROUPS: ReadonlyArray<{ group: RoleChoice[\"group\"]; heading: string }> = [\n  { group: \"start\", heading: \"\" },\n  { group: \"site\", heading: \"On this site\" },\n  { group: \"system\", heading: \"System\" },\n];\n\n/** What a role says while it writes nothing. */\nfunction unsetWords(role: FontRole): string {\n  return role === \"body\" ? FONT_ROLE_WORDS.ownFont : FONT_ROLE_WORDS.sameAsBody;\n}\n\n/** Every entry a role's list offers, in the order it lists them. */\nfunction choicesFor(\n  role: FontRole,\n  families: readonly RoleFamily[]\n): RoleChoice[] {\n  return [\n    { key: \"start\", group: \"start\", label: unsetWords(role), stack: undefined },\n    ...families.map(\n      (family): RoleChoice => ({\n        key: `site:${family.family.toLowerCase()}`,\n        group: \"site\",\n        label: family.family,\n        stack: family.stack,\n      })\n    ),\n    ...SYSTEM_STACKS.map(\n      ([label, stack]): RoleChoice => ({\n        key: `system:${stack}`,\n        group: \"system\",\n        label,\n        stack,\n      })\n    ),\n  ];\n}\n\n/** A stack as two equal stacks compare: no spacing, no case. */\nfunction normalised(stack: string): string {\n  return stack\n    .replace(/\\s*,\\s*/g, \",\")\n    .trim()\n    .toLowerCase();\n}\n\n/**\n * The entry a stack is: the one storing it, else the one naming the same\n * first family, since the first family in a stack is the author's choice.\n */\nfunction choiceOf(\n  stack: string,\n  choices: readonly RoleChoice[]\n): RoleChoice | undefined {\n  const exact = choices.find(\n    choice =>\n      choice.stack !== undefined &&\n      normalised(choice.stack) === normalised(stack)\n  );\n  if (exact !== undefined) return exact;\n  const first = firstFamily(stack);\n  return choices.find(\n    choice => choice.stack !== undefined && firstFamily(choice.stack) === first\n  );\n}\n\n/** What a role's row shows: its entry, and its words. */\ninterface RoleShown {\n  readonly current: RoleChoice | undefined;\n  readonly words: string;\n  /** The stack the row's specimen is drawn in, when one can be drawn. */\n  readonly drawn: string | undefined;\n}\n\n/** A role as its row shows it. */\nfunction shownOf(\n  tokens: SiteTokenSet,\n  role: FontRole,\n  choices: readonly RoleChoice[]\n): RoleShown {\n  const setting = fontRoleSetting(tokens, role);\n  if (setting.kind === \"unset\") {\n    return { current: choices[0], words: unsetWords(role), drawn: undefined };\n  }\n  if (setting.kind === \"mixed\") {\n    return { current: undefined, words: \"Set per heading\", drawn: undefined };\n  }\n  const current = choiceOf(setting.stack, choices);\n  return {\n    current,\n    words: current?.label ?? `${setting.stack} · not on this site`,\n    drawn: /var\\s*\\(/i.test(setting.stack) ? undefined : setting.stack,\n  };\n}\n\n/** The two rows, and the missing-Bold line under them. */\nexport function SiteFontRoles({\n  tokens,\n  onChange,\n  readOnly,\n  supplied,\n  faces,\n  fromCode,\n  onManageFonts,\n  onAddCut,\n}: SiteFontRolesProps): React.JSX.Element {\n  const families = React.useMemo(\n    () => roleFamilies(faces ?? [], fromCode),\n    [faces, fromCode]\n  );\n  const missing = missingBold(tokens, families);\n  const pick = (role: FontRole, stack: string | undefined): void =>\n    onChange(withFontRole(tokens, role, stack, supplied));\n  return (\n    <section className=\"nx-font-roles\" aria-label=\"Body and headings fonts\">\n      {([\"body\", \"heading\"] as const).map(role => (\n        <FontRoleRow\n          key={role}\n          role={role}\n          tokens={tokens}\n          choices={choicesFor(role, families)}\n          readOnly={readOnly}\n          onPick={stack => pick(role, stack)}\n          onManageFonts={onManageFonts}\n        />\n      ))}\n      {missing === undefined ? null : (\n        <MissingBoldLine\n          missing={missing}\n          onAddCut={readOnly ? undefined : onAddCut}\n        />\n      )}\n    </section>\n  );\n}\n\n/** One role's row and its list. */\nfunction FontRoleRow({\n  role,\n  tokens,\n  choices,\n  readOnly,\n  onPick,\n  onManageFonts,\n}: {\n  role: FontRole;\n  tokens: SiteTokenSet;\n  choices: readonly RoleChoice[];\n  readOnly: boolean;\n  onPick: (stack: string | undefined) => void;\n  onManageFonts: (() => void) | undefined;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const namesId = React.useId();\n  const label = FONT_ROLE_WORDS[role];\n  const shown = shownOf(tokens, role, choices);\n  const face = (\n    <>\n      <span\n        className=\"nx-font-roles__specimen\"\n        aria-hidden=\"true\"\n        style={\n          shown.drawn === undefined ? undefined : { fontFamily: shown.drawn }\n        }\n      >\n        Aa\n      </span>\n      <span className=\"nx-font-roles__text\" aria-hidden=\"true\">\n        <span className=\"nx-font-roles__name\">{label}</span>\n        <span className=\"nx-font-roles__value\" title={shown.words}>\n          {shown.words}\n        </span>\n      </span>\n      {/* The row's name, in one element: the role, then the font it shows.\n          Text rather than an aria-label, which would have to hold every drawn\n          word, the \"Aa\" included; one element, so no browser puts a space\n          before its comma. */}\n      <span className=\"nx-sr-only\">{`${label}, ${shown.words}`}</span>\n    </>\n  );\n  if (readOnly) {\n    return (\n      <div className=\"nx-font-roles__row\" data-font-role={role}>\n        {face}\n      </div>\n    );\n  }\n  return (\n    <div className=\"nx-font-roles__item\">\n      <Popover open={open} onOpenChange={setOpen} modal={false}>\n        <CssHint writes={fontRoleWrites(tokens, role)}>\n          <PopoverTrigger asChild>\n            <button\n              type=\"button\"\n              className=\"nx-font-roles__row\"\n              data-font-role={role}\n              aria-haspopup=\"listbox\"\n              aria-expanded={open}\n            >\n              {face}\n              <ChevronDown aria-hidden=\"true\" size={14} />\n            </button>\n          </PopoverTrigger>\n        </CssHint>\n        <CssNamesLine id={namesId} names={[\"font-family\"]} />\n        <PopoverContent\n          align=\"start\"\n          sideOffset={4}\n          collisionPadding={8}\n          className=\"nx-font-pick__popover nx-font-roles__popover\"\n          onOpenAutoFocus={event => event.preventDefault()}\n        >\n          <div className=\"nx-font-pick__body\">\n            <ChoiceList\n              choices={choices}\n              currentKey={shown.current?.key}\n              onPick={choice => {\n                setOpen(false);\n                onPick(choice.stack);\n              }}\n              label={label}\n              searchLabel=\"Search fonts\"\n              noMatch=\"No fonts match this search.\"\n              groups={GROUPS}\n              // Each font is drawn in itself.\n              choiceStyle={choice =>\n                choice.stack === undefined\n                  ? undefined\n                  : { fontFamily: choice.stack }\n              }\n            />\n            {onManageFonts === undefined ? null : (\n              <div className=\"nx-font-pick__footer\">\n                <button\n                  type=\"button\"\n                  className=\"nx-vars__link\"\n                  onClick={() => {\n                    setOpen(false);\n                    onManageFonts();\n                  }}\n                >\n                  Manage fonts…\n                </button>\n              </div>\n            )}\n          </div>\n        </PopoverContent>\n      </Popover>\n    </div>\n  );\n}\n\n/** \"<font> has no Bold…\", with \"Add Bold\" where the catalogue can add it. */\nfunction MissingBoldLine({\n  missing,\n  onAddCut,\n}: {\n  missing: MissingBold;\n  onAddCut:\n    | ((request: CatalogueAddRequest) => Promise<string | undefined>)\n    | undefined;\n}): React.JSX.Element {\n  const { busy, refusal, run } = useRefusableWrite();\n  const { add } = missing;\n  return (\n    <div className=\"nx-font-roles__note\" role=\"status\">\n      <p className=\"nx-font-roles__note-text\">{noBoldWords(missing.family)}</p>\n      {add === undefined || onAddCut === undefined ? null : (\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          className=\"nx-font-roles__add\"\n          disabled={busy}\n          onClick={() => void run(() => onAddCut(add))}\n        >\n          {FONT_ROLE_WORDS.addBold}\n        </Button>\n      )}\n      <Refusal refusal={refusal} />\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * The bottom bar: where the selected block sits on the page, one click to each\n * container holding it, and a hint at the keys that work from there.\n *\n * The canvas answers \"what does this look like\" and the layers panel answers\n * \"what is the whole page\". Neither answers the question an author has while\n * editing one block — what am I inside — and that question is why selecting a\n * parent is otherwise a hunt: the outer container of a full-width section has\n * almost no pixels that are not covered by its own children, so clicking it on\n * the canvas is a game of finding a margin.\n *\n * **Reads the same tree the layers panel does.** `pathTo` is the one\n * implementation of \"which blocks contain this one\", so the trail and the\n * panel's highlight cannot name different ancestors — and the labels match the\n * palette's, because they come from the same rule.\n *\n * **A list of buttons, not a `<nav>`.** The WAI-ARIA breadcrumb pattern\n * describes navigation between pages; this moves a selection inside one\n * document and navigates nowhere. Announcing it as site navigation would send\n * a screen-reader user looking for links that do not exist, so it is a labelled\n * list whose items are buttons.\n *\n * @module breadcrumb\n */\n\nimport { detectApplePlatform } from \"@nextlyhq/ui\";\nimport { ChevronRight } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { firstInlineProp } from \"../canvas/inline-target\";\nimport type { EditorState } from \"../editor-state\";\nimport { EDITOR_WORDS } from \"../editor-words\";\nimport { pathTo, type ComponentTitleOf } from \"../panels/layers/layers\";\n\nimport { keyHint } from \"./key-hint\";\n\nexport interface SelectionBreadcrumbProps {\n  /** The editor whose selection this describes and changes. */\n  editor: EditorState;\n  /**\n   * The keys the host has bound, so the hint offers only what works:\n   * `editText` when Enter begins editing a block's text on the canvas,\n   * `goUp` when Escape selects the block holding the selection, and\n   * `commandPalette` when the command palette opens with the modifier and K.\n   */\n  hints?: {\n    readonly editText?: boolean;\n    readonly goUp?: boolean;\n    readonly commandPalette?: boolean;\n  };\n  /**\n   * A component's title by id, so a selected placement reads as what the\n   * author placed. The library holds the titles, and the host read it.\n   */\n  componentTitle?: ComponentTitleOf;\n  /**\n   * What the trail's first crumb, the document's root, is called. The page\n   * by default; a host editing a field below the top level of its document\n   * names where that field sits (`Sections · Hero banner · Body`), so the\n   * bar says which of several such fields this is.\n   */\n  rootLabel?: string;\n}\n\n/** One crumb: a block, or the page itself at the trail's root. */\ninterface Crumb {\n  readonly key: string;\n  readonly label: string;\n  readonly select: () => void;\n}\n\nexport function SelectionBreadcrumb({\n  editor,\n  hints = {},\n  componentTitle,\n  rootLabel = EDITOR_WORDS.page,\n}: SelectionBreadcrumbProps): React.JSX.Element {\n  /*\n   * The page first, always, then the selected block's ancestors.\n   *\n   * With nothing selected, or a selection the document no longer holds (an\n   * undo can remove the selected node), the trail is the page alone, marked\n   * as the current position: the bar always says where the author is.\n   */\n  const path = pathTo(editor.document, editor.selectedId, componentTitle);\n  // Keys in two namespaces: a block's id is any unique string, \"page\"\n  // among them, so the root crumb cannot share their key space.\n  const crumbs: Crumb[] = [\n    {\n      key: \"root:page\",\n      label: rootLabel,\n      select: () => editor.select(null),\n    },\n    ...path.map(node => ({\n      key: `block:${node.id}`,\n      label: node.label,\n      select: () => editor.select(node.id),\n    })),\n  ];\n  const selected = path.length > 0 ? editor.selectedId : null;\n\n  /*\n   * Which keyboard is in front of the author, resolved AFTER mounting, as\n   * the Layers legend does: a server render has no `navigator` and would\n   * spell the palette's key differently from the browser's first render.\n   * Until it is known, the hint names no platform key.\n   */\n  const [apple, setApple] = React.useState<boolean | null>(null);\n  React.useEffect(() => {\n    setApple(detectApplePlatform());\n  }, []);\n  const hint = hintFor(editor, selected, hints, apple);\n\n  return (\n    <div className=\"nx-bottom-bar\">\n      {/* Named for what it always shows, the page down to the selection,\n          rather than for a selection there may not be. */}\n      <ol className=\"nx-breadcrumb\" aria-label=\"Current location\">\n        {crumbs.map((crumb, index) => (\n          <li className=\"nx-breadcrumb__item\" key={crumb.key}>\n            {index > 0 ? (\n              <ChevronRight\n                className=\"nx-breadcrumb__separator\"\n                size={12}\n                aria-hidden=\"true\"\n              />\n            ) : null}\n            <button\n              type=\"button\"\n              className=\"nx-breadcrumb__crumb\"\n              // The last crumb IS the selection, so it is rendered as the\n              // current position rather than as a way to reach it. Left\n              // clickable and marked current: pressing it is harmless, and\n              // disabling it would take the trail's end out of the tab order\n              // for no gain.\n              aria-current={index === crumbs.length - 1 ? \"true\" : undefined}\n              onClick={crumb.select}\n            >\n              {crumb.label}\n            </button>\n          </li>\n        ))}\n      </ol>\n      {hint === \"\" ? null : <p className=\"nx-bottom-bar__hint\">{hint}</p>}\n    </div>\n  );\n}\n\n/**\n * The bar's hint, from the keys that work right now: Enter where the host\n * edits text and the selected block has some, Escape where the host binds it\n * to go up, and the command palette where the host has one and the platform\n * is known. Empty when nothing applies.\n */\nfunction hintFor(\n  editor: EditorState,\n  selected: string | null,\n  hints: NonNullable<SelectionBreadcrumbProps[\"hints\"]>,\n  apple: boolean | null\n): string {\n  const parts: string[] = [];\n  if (selected === null) {\n    parts.push(\"Click a block to select it\");\n  } else {\n    if (\n      hints.editText === true &&\n      firstInlineProp(editor.document, selected) !== null\n    ) {\n      parts.push(\"Enter to edit text\");\n    }\n    if (hints.goUp === true) parts.push(\"Esc to go up\");\n  }\n  const palette =\n    hints.commandPalette === true && apple !== null\n      ? keyHint(\"mod+k\", apple)\n      : null;\n  if (palette !== null) parts.push(`${palette} for anything`);\n  return parts.join(\" · \");\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","\"use client\";\n\n/**\n * The page's data against its limit: in the top bar once it matters, and in\n * Page settings always.\n *\n * A published page loads every piece of data its blocks show (a list's\n * entries, an image, a link to an entry) under one limit per visit. The top\n * bar stays quiet on a page far from it: the meter appears only from 80% of\n * the limit, amber, saying \"Page data: 430 of 500 · what's this?\", and red\n * once the limit is spent or passed (\"· over the limit\"). A count that could\n * not be made shows too, since a hidden failure could hide a page over its\n * limit. Page settings draws the same meter as a line at every level, so the\n * count can always be found.\n *\n * Each is one button; \"what's this?\" is drawn as a link inside it, not a\n * second control. Pressed, it opens a panel saying what the page loads and,\n * over the limit, naming each block that comes up empty on the live site,\n * each one a way to select that block.\n *\n * @module read-budget-meter\n * @experimental Settles with the canvas's read count.\n */\n\nimport { DEFAULT_MAX_QUERIES } from \"@nextlyhq/blocks-react\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@nextlyhq/ui\";\nimport {\n  CircleAlert,\n  CircleCheck,\n  FileText,\n  Image,\n  Info,\n  Link,\n  List,\n  LoaderCircle,\n  Repeat,\n  Component as ComponentMark,\n  TriangleAlert,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { CanvasRegion } from \"../canvas/canvas-regions\";\nimport type { EditorState } from \"../editor-state\";\nimport { blockNameOf, type ComponentTitleOf } from \"../panels/layers/layers\";\nimport { BUILDER_TOKENS_CLASS } from \"../shell-state\";\n\nimport {\n  COUNT_FAILED_NAME,\n  pageDataCount,\n  READ_KIND_WORDS,\n  READ_KINDS,\n  readBudgetName,\n  readBudgetStanding,\n  readCount,\n  shownInTopBar,\n  unreadBlocks,\n  readShare,\n  warningAt,\n  type PageReadReport,\n  type ReadBudgetStanding,\n  type ReadKind,\n} from \"./read-budget\";\nimport { regionHolding } from \"./unread-places\";\n\nexport interface ReadBudgetMeterProps {\n  /** The latest draw's count, or `undefined` while the canvas is counting. */\n  report: PageReadReport | undefined;\n  /** The editor whose page this counts, for block names and selection. */\n  editor: Pick<EditorState, \"document\" | \"select\">;\n  /** A component's title by id, so a placement is named as Layers names it. */\n  componentTitle?: ComponentTitleOf;\n  /**\n   * The Layout regions the page is drawn inside, as the canvas draws them, so\n   * an unread block of a header or footer is named with the Layout it comes\n   * from, and offers the way to edit that Layout.\n   */\n  regions?: readonly CanvasRegion[];\n  /**\n   * Given when the latest count could not be made: the meter says so, in\n   * place of a count, and pressing it counts again.\n   */\n  failed?: { readonly retry: () => void } | undefined;\n  /**\n   * Where it is drawn: the top bar (the default), which shows it only from\n   * 80% of the limit or when the count failed, or Page settings, which shows\n   * the count at every level, counting included.\n   */\n  place?: \"bar\" | \"settings\";\n}\n\n/** The mark each standing wears in the panel's verdict. */\nconst STANDING_MARK: Record<\n  ReadBudgetStanding,\n  React.ComponentType<{ className?: string; \"aria-hidden\"?: boolean }>\n> = {\n  counting: LoaderCircle,\n  within: CircleCheck,\n  near: TriangleAlert,\n  over: CircleAlert,\n};\n\n/** The mark of each kind of read, in the panel's rows and its unread list. */\nconst KIND_MARK: Record<\n  ReadKind,\n  React.ComponentType<{ className?: string; \"aria-hidden\"?: boolean }>\n> = {\n  entries: List,\n  related: Repeat,\n  image: Image,\n  link: Link,\n  page: FileText,\n  component: ComponentMark,\n};\n\n/** No Layout: a page drawn inside none. */\nconst NO_REGIONS: readonly CanvasRegion[] = [];\n\n/** The panel's one-line verdict, beside its title. */\nconst STANDING_WORDS: Record<ReadBudgetStanding, string> = {\n  counting: \"Counting\",\n  within: \"Within the limit\",\n  near: \"Near the limit\",\n  over: \"Over the limit\",\n};\n\nexport function ReadBudgetMeter({\n  report,\n  editor,\n  componentTitle,\n  regions,\n  failed,\n  place = \"bar\",\n}: ReadBudgetMeterProps): React.JSX.Element | null {\n  const [open, setOpen] = React.useState(false);\n  const standing = readBudgetStanding(report);\n  const shown = place === \"settings\" || shownInTopBar(standing);\n  // Closed on failing, or on leaving the bar, so neither a retry, a late\n  // answer nor the page nearing its limit again opens the panel by itself:\n  // it was opened on a count that has since been replaced. Set while\n  // rendering, so no frame draws the panel open over what replaced it.\n  if ((failed !== undefined || !shown) && open) setOpen(false);\n  if (failed !== undefined) {\n    return <ReadCountFailed retry={failed.retry} place={place} />;\n  }\n  if (!shown) return null;\n  const name = readBudgetName(report);\n\n  return (\n    <Popover open={open} onOpenChange={setOpen} modal={false}>\n      <PopoverTrigger asChild>\n        <button\n          type=\"button\"\n          className=\"nx-read-meter\"\n          data-place={place}\n          data-standing={standing}\n          aria-label={name}\n          // The same words as a tooltip, for the shorter form a crowded bar\n          // draws.\n          title={name}\n          // Busy while counting, so a reader is not told a stale number.\n          aria-busy={standing === \"counting\" ? true : undefined}\n        >\n          <MeterWords report={report} standing={standing} />\n        </button>\n      </PopoverTrigger>\n      <PopoverContent\n        align={place === \"bar\" ? \"start\" : \"end\"}\n        sideOffset={6}\n        // Drawn in a portal, outside the shell, so it carries the editor's\n        // token scope itself, as the component banner does.\n        className={`nx-read-panel ${BUILDER_TOKENS_CLASS}`}\n        aria-label=\"Page data\"\n      >\n        <ReadPanel\n          report={report}\n          standing={standing}\n          editor={editor}\n          componentTitle={componentTitle}\n          regions={regions ?? NO_REGIONS}\n          onPicked={() => setOpen(false)}\n        />\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/**\n * The meter when the count could not be made, in its place, saying so:\n * pressing it counts again. Not a panel's trigger, since there is nothing to\n * say past this.\n */\nfunction ReadCountFailed({\n  retry,\n  place,\n}: {\n  readonly retry: () => void;\n  readonly place: \"bar\" | \"settings\";\n}): React.JSX.Element {\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-read-meter\"\n      data-place={place}\n      data-standing=\"failed\"\n      aria-label={COUNT_FAILED_NAME}\n      // The same words as a tooltip.\n      title={COUNT_FAILED_NAME}\n      onClick={retry}\n    >\n      <span className=\"nx-read-meter__label\">\n        Page data: couldn&apos;t count\n      </span>\n      <span className=\"nx-read-meter__standing\">\n        {\" · \"}\n        <span className=\"nx-read-meter__link\">Retry</span>\n      </span>\n    </button>\n  );\n}\n\n/**\n * The meter's words: the count, then near the limit a \"what's this?\" drawn\n * as a link (which a crowded bar drops first), over it \"over the limit\",\n * and within it, in Page settings, a quiet mark that it explains itself.\n */\nfunction MeterWords({\n  report,\n  standing,\n}: {\n  report: PageReadReport | undefined;\n  standing: ReadBudgetStanding;\n}): React.JSX.Element {\n  if (report === undefined) {\n    return <span className=\"nx-read-meter__label\">Page data: counting…</span>;\n  }\n  const count = (\n    <span className=\"nx-read-meter__label\">{pageDataCount(report)}</span>\n  );\n  if (standing === \"over\") {\n    return (\n      <>\n        {count}\n        <span className=\"nx-read-meter__standing\"> · over the limit</span>\n      </>\n    );\n  }\n  if (standing === \"near\") {\n    return (\n      <>\n        {count}\n        {/* Steps aside where the top bar is crowded (`top-bar-room`). */}\n        <span className=\"nx-read-meter__more\" data-topbar-word=\"\">\n          {\" · \"}\n          <span className=\"nx-read-meter__link\">what&apos;s this?</span>\n        </span>\n      </>\n    );\n  }\n  return (\n    <>\n      {count}\n      <Info className=\"nx-read-meter__info\" aria-hidden={true} />\n    </>\n  );\n}\n\nfunction MeterMark({\n  standing,\n}: {\n  standing: ReadBudgetStanding;\n}): React.JSX.Element {\n  const Mark = STANDING_MARK[standing];\n  return <Mark className=\"nx-read-meter__mark\" aria-hidden={true} />;\n}\n\n/**\n * What the panel says, in plain words: what the page loads and its limit, the\n * bar, what it went on, and over the limit, the blocks that come up empty.\n */\nfunction ReadPanel({\n  report,\n  standing,\n  editor,\n  componentTitle,\n  regions,\n  onPicked,\n}: {\n  report: PageReadReport | undefined;\n  standing: ReadBudgetStanding;\n  editor: ReadBudgetMeterProps[\"editor\"];\n  componentTitle: ComponentTitleOf | undefined;\n  regions: readonly CanvasRegion[];\n  onPicked: () => void;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-read-panel__body\" data-standing={standing}>\n      <div className=\"nx-read-panel__head\">\n        <p className=\"nx-read-panel__title\">Page data</p>\n        <p className=\"nx-read-panel__verdict\">\n          <MeterMark standing={standing} />\n          {STANDING_WORDS[standing]}\n        </p>\n      </div>\n      {report === undefined ? (\n        <p className=\"nx-read-panel__note\">\n          The page is still being drawn. Its data is counted once every block\n          has loaded.\n        </p>\n      ) : (\n        <>\n          <ReadFigure report={report} standing={standing} />\n          <p className=\"nx-read-panel__note\">\n            Each time someone opens this page, it loads the data its blocks\n            show: a list&apos;s entries, an image, a link to an entry. Each one\n            counts once.{\" \"}\n            {Number.isFinite(report.cap)\n              ? `A page can load up to ${readCount(report.cap)}.`\n              : \"This site sets no limit.\"}\n          </p>\n          <ReadBar report={report} />\n          <ReadKinds report={report} />\n          <StandingNote\n            report={report}\n            standing={standing}\n            editor={editor}\n            componentTitle={componentTitle}\n            regions={regions}\n            onPicked={onPicked}\n          />\n          {/* How the site's front end reads media lives in its code, which\n              the admin cannot read: the count takes the media library's\n              way, and says so. */}\n          <p className=\"nx-read-panel__foot\">\n            Images are counted as the media library loads them. A developer can\n            change the limit in the site&apos;s code.\n          </p>\n        </>\n      )}\n    </div>\n  );\n}\n\n/**\n * What the standing means for the live site: near the limit, a warning;\n * over it, the blocks that come up empty, or with none yet, that the next\n * one would.\n */\nfunction StandingNote({\n  report,\n  standing,\n  ...unread\n}: {\n  report: PageReadReport;\n  standing: ReadBudgetStanding;\n  editor: ReadBudgetMeterProps[\"editor\"];\n  componentTitle: ComponentTitleOf | undefined;\n  regions: readonly CanvasRegion[];\n  onPicked: () => void;\n}): React.JSX.Element | null {\n  if (standing === \"near\") {\n    return (\n      <p className=\"nx-read-panel__note\">\n        This page is close to its limit. Past {readCount(report.cap)}, blocks\n        that need more data come up empty on the live site.\n      </p>\n    );\n  }\n  if (standing !== \"over\") return null;\n  if (unreadBlocks(report).length === 0) {\n    return (\n      <p className=\"nx-read-panel__note\">\n        This page uses its whole limit. One more list, image or link would come\n        up empty on the live site.\n      </p>\n    );\n  }\n  return <UnreadBlocks report={report} {...unread} />;\n}\n\n/** \"1 block comes up empty\", \"3 blocks come up empty\". */\nfunction emptyBlocks(count: number): string {\n  return count === 1\n    ? \"1 block comes up empty\"\n    : `${String(count)} blocks come up empty`;\n}\n\n/**\n * The panel's headline count. Over the limit it says how many blocks come up\n * empty too, never \"500 of 500\" alone, which reads as a page that fits:\n * what it would need is not known, since a read refused never asks for what\n * it would have led to.\n */\nfunction ReadFigure({\n  report,\n  standing,\n}: {\n  report: PageReadReport;\n  standing: ReadBudgetStanding;\n}): React.JSX.Element {\n  const blocks = unreadBlocks(report).length;\n  return (\n    <p className=\"nx-read-panel__figure\">\n      <span className=\"nx-read-panel__used\">{readCount(report.used)}</span>\n      {Number.isFinite(report.cap)\n        ? ` of ${readCount(report.cap)}`\n        : \" (no limit)\"}\n      {standing === \"over\" && blocks > 0 ? ` · ${emptyBlocks(blocks)}` : \"\"}\n    </p>\n  );\n}\n\n/** The limit as a bar, with the point the editor warns from marked. */\nfunction ReadBar({ report }: { report: PageReadReport }): React.JSX.Element {\n  const limited = Number.isFinite(report.cap) && report.cap > 0;\n  return (\n    <div className=\"nx-read-panel__bar\">\n      <div className=\"nx-read-panel__track\" aria-hidden=\"true\">\n        <span\n          className=\"nx-read-panel__fill\"\n          style={{ inlineSize: `${String(readShare(report) * 100)}%` }}\n        />\n        {limited ? <span className=\"nx-read-panel__tick\" /> : null}\n      </div>\n      {limited ? (\n        <p className=\"nx-read-panel__scale\">\n          <span>Warning from {readCount(warningAt(report.cap))}</span>\n          <span>\n            Limit {readCount(report.cap)}\n            {report.cap === DEFAULT_MAX_QUERIES ? \" (the default)\" : \"\"}\n          </span>\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\n/** What the page loads: one row per kind it loads any of. */\nfunction ReadKinds({ report }: { report: PageReadReport }): React.JSX.Element {\n  const rows = READ_KINDS.filter(kind => (report.byKind[kind] ?? 0) > 0);\n  if (rows.length === 0) {\n    return <p className=\"nx-read-panel__note\">This page loads no data yet.</p>;\n  }\n  return (\n    <dl className=\"nx-read-panel__kinds\">\n      {rows.map(kind => {\n        const Mark = KIND_MARK[kind];\n        return (\n          <div className=\"nx-read-panel__kind\" key={kind}>\n            <dt>\n              <Mark className=\"nx-read-panel__kind-mark\" aria-hidden={true} />\n              {READ_KIND_WORDS[kind].label}\n            </dt>\n            <dd>{readCount(report.byKind[kind] ?? 0)}</dd>\n          </div>\n        );\n      })}\n    </dl>\n  );\n}\n\n/** The blocks that come up empty on the live site, each a way to select it. */\nfunction UnreadBlocks({\n  report,\n  editor,\n  componentTitle,\n  regions,\n  onPicked,\n}: {\n  report: PageReadReport;\n  editor: ReadBudgetMeterProps[\"editor\"];\n  componentTitle: ComponentTitleOf | undefined;\n  regions: readonly CanvasRegion[];\n  onPicked: () => void;\n}): React.JSX.Element {\n  const headingId = React.useId();\n  const rows = unreadBlocks(report);\n  const blocks = rows.length;\n  return (\n    <section className=\"nx-read-panel__unread\" aria-labelledby={headingId}>\n      <p className=\"nx-read-panel__unread-title\" id={headingId}>\n        {emptyBlocks(blocks)}\n      </p>\n      <p className=\"nx-read-panel__note\">\n        This page needs more than {readCount(report.cap)}. On the live site,\n        these blocks show without their data:\n      </p>\n      <ul className=\"nx-read-panel__list\">\n        {rows.map(({ nodeId, what }) => (\n          <li key={nodeId}>\n            <UnreadRow\n              nodeId={nodeId}\n              what={what}\n              editor={editor}\n              componentTitle={componentTitle}\n              regions={regions}\n              onPicked={onPicked}\n            />\n          </li>\n        ))}\n      </ul>\n    </section>\n  );\n}\n\n/**\n * One unread block: a page's selects it; a Layout region's is named with\n * the Layout it comes from and offers that Layout's editor, since the page's\n * editor cannot select it; one neither holds (an undo since the draw) is\n * named by what it missed alone.\n */\nfunction UnreadRow({\n  nodeId,\n  what,\n  editor,\n  componentTitle,\n  regions,\n  onPicked,\n}: {\n  nodeId: string;\n  what: readonly ReadKind[];\n  editor: ReadBudgetMeterProps[\"editor\"];\n  componentTitle: ComponentTitleOf | undefined;\n  regions: readonly CanvasRegion[];\n  onPicked: () => void;\n}): React.JSX.Element {\n  const Mark = KIND_MARK[what[0] ?? \"page\"];\n  const missed = what.map(kind => READ_KIND_WORDS[kind].unread).join(\" · \");\n  const name = blockNameOf(editor.document, nodeId, componentTitle);\n  const held =\n    name === undefined\n      ? regionHolding(\n          regions,\n          nodeId,\n          region => region.document,\n          componentTitle\n        )\n      : undefined;\n  if (held !== undefined) {\n    const { region } = held;\n    return (\n      <div className=\"nx-read-panel__block\" data-source=\"layout\">\n        <Mark className=\"nx-read-panel__kind-mark\" aria-hidden={true} />\n        <span className=\"nx-read-panel__block-name\">{held.name}</span>\n        <span className=\"nx-read-panel__block-what\">\n          {region.label} · {missed}\n        </span>\n        {region.edit === undefined ? null : (\n          <a\n            className=\"nx-read-panel__block-edit\"\n            href={region.edit.href}\n            target=\"_blank\"\n            rel=\"noopener noreferrer\"\n            aria-label={region.edit.name}\n          >\n            {region.edit.text}\n          </a>\n        )}\n      </div>\n    );\n  }\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-read-panel__block\"\n      disabled={name === undefined}\n      onClick={() => {\n        editor.select(nodeId);\n        onPicked();\n      }}\n    >\n      <Mark className=\"nx-read-panel__kind-mark\" aria-hidden={true} />\n      <span className=\"nx-read-panel__block-name\">\n        {name ?? \"A removed block\"}\n      </span>\n      <span className=\"nx-read-panel__block-what\">{missed}</span>\n    </button>\n  );\n}\n","\"use client\";\n\n/**\n * \"Save as shared style…\": name the block's look, see the class name it will\n * have and what moves, and save.\n *\n * Opened by the block verb, which every surface runs (the block card's menu,\n * the toolbar's More, the context menu, the bar), so the form is one dialog\n * the host raises rather than a popover tied to one of them.\n *\n * The save is two writes: the new style into the site style, then the block\n * (its styles cleared, the style put on it). The style goes first and the\n * block waits for it, since a page may not reference a style the site does\n * not define; a refused style leaves the block untouched.\n *\n * @module shared-style-save-dialog\n */\n\nimport {\n  findNode,\n  namedClassName,\n  type NamedClass,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n  Input,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport type { EditorState } from \"../../editor-state\";\nimport { lockViewOf } from \"../../inspector/inspector\";\nimport { sharedStyleSlug } from \"../../styles/shared-style-library\";\nimport {\n  newSharedStyleName,\n  planSaveAsSharedStyle,\n  saveAsSharedStyleOps,\n  sharedStyleMoveSummary,\n  sharedStyleMoveWhat,\n  type SharedStyleOffer,\n} from \"../../styles/shared-style-target\";\n\nimport { Refusal } from \"./panel-actions\";\n\n/** @experimental Settles with the shared-styles editor. */\nexport interface SaveSharedStyleDialogProps {\n  readonly editor: EditorState;\n  /** The block whose look is saved. */\n  readonly nodeId: string;\n  readonly offer: SharedStyleOffer;\n  /** Store the new style; resolves to the refusal in words, or nothing. */\n  readonly onAdd: (entry: NamedClass) => Promise<string | undefined>;\n  /** Told once the style is stored and on the block, with its name. */\n  readonly onSaved?: (name: string) => void;\n  readonly onClose: () => void;\n}\n\n/**\n * How long a saved style is waited for in the library the canvas draws from\n * before the block is moved onto it anyway: it is stored, and the canvas\n * draws it on its next read.\n */\nexport const SAVE_AS_DRAWN_WAIT_MS = 10_000;\n\n/**\n * Store the new style, then move the block onto it: the refusal in words, or\n * `undefined` once both are done. The block keeps its own look until the\n * style is in the library the canvas draws from, since the library is read\n * again only after the save: moved sooner, the block is drawn for a moment\n * with neither. The block's half is built from the block as it stands then,\n * so a value it gained meanwhile is kept, where the plan's ops would drop it.\n */\nasync function storeAndApply(\n  entry: NamedClass,\n  onAdd: (entry: NamedClass) => Promise<string | undefined>,\n  drawn: (id: string) => Promise<void>,\n  live: () => EditorState,\n  nodeId: string\n): Promise<string | undefined> {\n  const refused = await onAdd(entry);\n  if (refused !== undefined) return refused;\n  await drawn(entry.id);\n  const now = live();\n  const block = findNode(now.document.nodes, nodeId);\n  const ops = block === undefined ? null : saveAsSharedStyleOps(block, entry);\n  if (ops === null || now.applyAll(ops) === null) {\n    return `${entry.label ?? entry.slug} was saved, but this block could not be changed to use it.`;\n  }\n  return undefined;\n}\n\n/**\n * A wait for a style to be in `library`, the library the canvas draws from as\n * the host hands it, answered as each new library arrives, and at most\n * {@link SAVE_AS_DRAWN_WAIT_MS}.\n */\nfunction useDrawnIn(\n  library: readonly NamedClass[] | undefined\n): (id: string) => Promise<void> {\n  const latest = React.useRef(library);\n  latest.current = library;\n  const waiting = React.useRef(new Set<() => void>());\n  React.useEffect(() => {\n    for (const check of [...waiting.current]) check();\n  }, [library]);\n  return React.useCallback(\n    (id: string) =>\n      new Promise<void>(resolve => {\n        const done = (): void => {\n          clearTimeout(timer);\n          waiting.current.delete(check);\n          resolve();\n        };\n        const check = (): void => {\n          if (latest.current?.some(entry => entry.id === id) === true) done();\n        };\n        const timer = setTimeout(done, SAVE_AS_DRAWN_WAIT_MS);\n        waiting.current.add(check);\n        check();\n      }),\n    []\n  );\n}\n\n/** The dialog that saves a block's look as a new shared style. */\nexport function SaveSharedStyleDialog({\n  editor,\n  nodeId,\n  offer,\n  onAdd,\n  onSaved,\n  onClose,\n}: SaveSharedStyleDialogProps): React.JSX.Element {\n  const [name, setName] = React.useState(\"\");\n  const [problem, setProblem] = React.useState<string | undefined>(undefined);\n  const [saving, setSaving] = React.useState(false);\n  // The editor as it stands when the style has been stored, for the page\n  // edit that follows it.\n  const live = React.useRef(editor);\n  live.current = editor;\n  const drawn = useDrawnIn(offer.library);\n  const nameId = React.useId();\n  const hintId = `${nameId}-hint`;\n  const node = findNode(editor.document.nodes, nodeId);\n  const slug = sharedStyleSlug(name);\n  // Said while typing, once there is a class name to collide.\n  const nameIssue =\n    slug === \"\" || offer.library === undefined\n      ? undefined\n      : (() => {\n          const checked = newSharedStyleName(name, offer.library);\n          return checked.ok ? undefined : checked.reason;\n        })();\n  const shown = problem ?? nameIssue;\n\n  const save = async (): Promise<void> => {\n    if (saving) return;\n    const plan = planSaveAsSharedStyle(\n      editor.document,\n      nodeId,\n      name,\n      offer,\n      lockViewOf(editor)\n    );\n    if (!plan.ok) {\n      setProblem(plan.reason);\n      return;\n    }\n    setSaving(true);\n    try {\n      const refused = await storeAndApply(\n        plan.entry,\n        onAdd,\n        drawn,\n        () => live.current,\n        nodeId\n      );\n      if (refused !== undefined) {\n        setProblem(refused);\n        return;\n      }\n      onSaved?.(plan.entry.label ?? plan.entry.slug);\n      onClose();\n    } finally {\n      setSaving(false);\n    }\n  };\n\n  return (\n    <Dialog\n      open\n      onOpenChange={next => {\n        if (!next && !saving) onClose();\n      }}\n    >\n      <DialogContent className=\"max-w-sm\" data-save-shared-style=\"\">\n        <form\n          className=\"nx-vars-editor__body\"\n          onSubmit={event => {\n            event.preventDefault();\n            void save();\n          }}\n        >\n          <DialogHeader>\n            <DialogTitle>Save as shared style</DialogTitle>\n            <DialogDescription>\n              {/*\n               * While the name cannot be used (it is another style's), the\n               * summary must not read as a merge into that style.\n               */}\n              {nameIssue === undefined\n                ? `${sharedStyleMoveSummary(node?.styles, name)} Other blocks can then wear it, and a change to it reaches them all.`\n                : `Choose another name to move ${sharedStyleMoveWhat(node?.styles)}.`}\n            </DialogDescription>\n          </DialogHeader>\n          <div className=\"nx-vars-editor__field\">\n            <label className=\"nx-vars-editor__label\" htmlFor={nameId}>\n              Name\n            </label>\n            <Input\n              id={nameId}\n              value={name}\n              placeholder=\"Card\"\n              autoFocus\n              aria-describedby={hintId}\n              aria-invalid={shown !== undefined}\n              onChange={event => {\n                setName(event.target.value);\n                setProblem(undefined);\n              }}\n            />\n            {/* The class the page will carry, as the Shared styles tab shows it. */}\n            <p\n              className=\"nx-vars-editor__code nx-shared-style-save__class\"\n              aria-live=\"polite\"\n            >\n              {slug === \"\" ? \" \" : `.${namedClassName(slug)}`}\n            </p>\n            <p className=\"nx-shared-style-save__hint\" id={hintId}>\n              Name it for what it is, like Card or Primary button.\n            </p>\n          </div>\n          {/* In the field-error style the other Design editors use. */}\n          <Refusal refusal={shown ?? null} />\n          <DialogFooter>\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              disabled={saving}\n              onClick={onClose}\n            >\n              Cancel\n            </Button>\n            <Button\n              type=\"submit\"\n              disabled={saving || slug === \"\" || nameIssue !== undefined}\n            >\n              Save shared style\n            </Button>\n          </DialogFooter>\n        </form>\n      </DialogContent>\n    </Dialog>\n  );\n}\n","/**\n * The parts of a text style as Design's Type → \"Text styles\" editor reads\n * and writes them: its size for each device (Desktop, then the site's own\n * devices), its case in the author's words, its letter spacing with a unit\n * (`em` unless another is typed), and its font as the Body font, the\n * Headings font or a family the site loads.\n *\n * Pure, so the rules are testable without a DOM.\n *\n * @module text-style-parts\n */\nimport {\n  BASE_BREAKPOINT,\n  isTokenRef,\n  type BreakpointId,\n  type BreakpointSet,\n  type NodeStyles,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { deviceOptions } from \"../../shell/breakpoint-switcher\";\n\n/** One device a text style's size is set for. */\nexport interface TextStyleDevice {\n  readonly id: BreakpointId;\n  /** \"Desktop\", \"Tablet\", \"Mobile\": the site's own words for it. */\n  readonly label: string;\n}\n\n/**\n * The devices a size is set for, as the top bar offers them: Desktop, then\n * each device the site defines, widest first.\n */\nexport function textStyleDevices(\n  breakpoints: BreakpointSet | undefined\n): TextStyleDevice[] {\n  return deviceOptions(breakpoints).map(option => ({\n    id: option.id,\n    label: option.label,\n  }));\n}\n\n/** A part's value at one device in the normal state, or `undefined`. */\nexport function partAt(\n  styles: NodeStyles,\n  breakpoint: BreakpointId,\n  property: string\n): StyleValue | undefined {\n  const values: unknown = styles.base?.[breakpoint];\n  if (typeof values !== \"object\" || values === null) return undefined;\n  return Object.hasOwn(values, property)\n    ? (values as Record<string, StyleValue>)[property]\n    : undefined;\n}\n\n/** The text style's cases: what each stores, and what it is called. */\nexport const TEXT_STYLE_CASES: ReadonlyArray<readonly [string, string]> = [\n  [\"none\", \"As typed\"],\n  [\"uppercase\", \"UPPERCASE\"],\n  [\"lowercase\", \"lowercase\"],\n  [\"capitalize\", \"Capitalised\"],\n];\n\n/** The units a letter spacing is offered in, its default first. */\nexport const LETTER_SPACING_UNITS: readonly string[] = [\"em\", \"px\"];\n\n/** A number as typed, with an optional sign and unit. */\nconst SPACING_RE = /^([+-]?)(\\d*\\.?\\d+)\\s*(em|px|rem)?$/i;\n\n/**\n * The letter spacing a typed amount writes: a bare number takes `unit`, a\n * number typed with a unit keeps it; `null` clears it, and `undefined` is\n * not a spacing at all.\n */\nexport function letterSpacingValue(\n  typed: string,\n  unit: string\n): string | null | undefined {\n  const text = typed.trim();\n  if (text === \"\") return null;\n  const match = SPACING_RE.exec(text);\n  if (match === null) return undefined;\n  const [, sign = \"\", amount = \"\", typedUnit] = match;\n  return `${sign === \"-\" ? \"-\" : \"\"}${amount}${(typedUnit ?? unit).toLowerCase()}`;\n}\n\n/** A stored letter spacing as its number and unit, `em` when it holds none. */\nexport function letterSpacingParts(value: StyleValue | undefined): {\n  amount: string;\n  unit: string;\n} {\n  if (typeof value !== \"string\" && typeof value !== \"number\") {\n    return { amount: \"\", unit: LETTER_SPACING_UNITS[0] ?? \"em\" };\n  }\n  const match = SPACING_RE.exec(String(value).trim());\n  if (match === null) return { amount: String(value), unit: \"em\" };\n  const [, sign = \"\", amount = \"\", unit = \"em\"] = match;\n  return {\n    amount: `${sign === \"-\" ? \"-\" : \"\"}${amount}`,\n    unit: unit.toLowerCase(),\n  };\n}\n\n/** The Body and Headings fonts' variables, which a text style's font may follow. */\nconst FONT_ROLE_TOKENS = {\n  body: \"font.body\",\n  heading: \"font.heading\",\n} as const;\n\n/**\n * Which font a text style uses: `body` or `heading` for a font role, the\n * stack it names for a family, or `\"\"` for none.\n */\nexport function fontChoiceOf(value: StyleValue | undefined): string {\n  if (isTokenRef(value)) {\n    if (value.$token === FONT_ROLE_TOKENS.body) return \"body\";\n    if (value.$token === FONT_ROLE_TOKENS.heading) return \"heading\";\n    return value.$token;\n  }\n  return typeof value === \"string\" ? value : \"\";\n}\n\n/** The value a font choice stores: a font role's variable, or the stack. */\nexport function fontValueOf(choice: string): StyleValue {\n  if (choice === \"body\") return { $token: FONT_ROLE_TOKENS.body };\n  if (choice === \"heading\") return { $token: FONT_ROLE_TOKENS.heading };\n  return choice;\n}\n\n/** The address a part is written at: the normal state, at one device. */\nexport function partAddress(\n  breakpoint: BreakpointId,\n  property: string\n): { state: \"base\"; breakpoint: BreakpointId; property: string; path: [] } {\n  return { state: \"base\", breakpoint, property, path: [] };\n}\n\n/** The widest device, where every part but the size is set. */\nexport const TEXT_STYLE_BASE: BreakpointId = BASE_BREAKPOINT;\n","\"use client\";\n\n/**\n * A text style's parts, in the popup its row in Type → \"Text styles\" opens:\n * its font (the Body font, the Headings font or a family the site loads),\n * its size for each device (a type size, a typed size or a fluid one), its\n * line height, weight, letter spacing (with its unit, `em` unless another is\n * typed) and case. Every part but the font and the case can follow a\n * variable, picked from the variables that fit it, or hold a plain value.\n *\n * Each change is one address-level change to the style's styles, handed to\n * the host, which stores it and keeps it as one step of undo; the fields\n * show it at once, before the store reads back.\n *\n * @module text-style-editor\n */\nimport {\n  isTokenRef,\n  tokenRef,\n  fluidValue,\n  type FluidRangeWidths,\n  type FluidSizes,\n  type NodeStyles,\n  type SiteTokenSet,\n  type StyleLeaf,\n  type StyleValue,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { propertyVariableLeaf } from \"../../inspector/style-inspector/style-value-fields\";\nimport {\n  sharedStyleChange,\n  type SharedStyleChange,\n} from \"../../styles/shared-style-target\";\nimport {\n  fontWeightOptions,\n  lineHeightFromText,\n} from \"../../styles/style-folded\";\n\nimport { FluidButton } from \"./fluid-popover\";\nimport { FontChoicesContext } from \"./font-family-field\";\nimport { roleFamilies } from \"./site-font-roles-model\";\nimport {\n  fontChoiceOf,\n  fontValueOf,\n  LETTER_SPACING_UNITS,\n  letterSpacingParts,\n  letterSpacingValue,\n  partAddress,\n  partAt,\n  TEXT_STYLE_BASE,\n  TEXT_STYLE_CASES,\n  type TextStyleDevice,\n} from \"./text-style-parts\";\nimport { fluidRangeOf, setFluidRange } from \"./tokens-studio\";\nimport { VariableChip, VariableChoice } from \"./variable-choice\";\nimport {\n  CommitInput,\n  LineHeightInput,\n  SizeInput,\n} from \"./variable-value-controls\";\n\n/** What the editor is handed. */\nexport interface TextStyleEditorProps {\n  /** The style's name, for the fields' names. */\n  readonly name: string;\n  /** Its styles as the edits on their way leave them. */\n  readonly styles: NodeStyles;\n  readonly tokens: SiteTokenSet | undefined;\n  readonly devices: readonly TextStyleDevice[];\n  /** Why its parts can't be changed (a lock, a role), or `undefined`. */\n  readonly heldBy: string | undefined;\n  /** Store one change to its styles: the refusal in words, or nothing. */\n  readonly write: (change: SharedStyleChange) => Promise<string | undefined>;\n  /** Change the site's variables, for the fluid range \"Fluid…\" sets. */\n  readonly onTokens?: ((tokens: SiteTokenSet) => void) | undefined;\n  /** The two sizes each device's size was made fluid from, where it was. */\n  readonly fluidSizes?: Readonly<Record<string, FluidSizes>> | undefined;\n  /**\n   * Store a size made fluid with the two sizes it was made from, as one\n   * change, so a change of the site's fluid range can make it again: the\n   * refusal in words, or nothing. Absent, only the size is written.\n   */\n  readonly onFluid?:\n    | ((\n        device: string,\n        sizes: FluidSizes,\n        value: string\n      ) => Promise<string | undefined>)\n    | undefined;\n}\n\n/**\n * The leaf each part's variables are offered for, from the one reading the\n * style panel uses: line height and weight are unions, so each takes the\n * folded leaf over its forms, not none.\n */\nconst LEAVES = {\n  fontSize: propertyVariableLeaf(\"fontSize\"),\n  lineHeight: propertyVariableLeaf(\"lineHeight\"),\n  fontWeight: propertyVariableLeaf(\"fontWeight\"),\n  letterSpacing: propertyVariableLeaf(\"letterSpacing\"),\n} as const;\n\n/** A plain value as a field shows it. */\nfunction plain(value: StyleValue | undefined): string {\n  return typeof value === \"string\" || typeof value === \"number\"\n    ? String(value)\n    : \"\";\n}\n\n/** The text style's parts. */\nexport function TextStyleEditor(\n  props: TextStyleEditorProps\n): React.JSX.Element {\n  const [refusal, setRefusal] = React.useState<string | null>(null);\n  const readOnly = props.heldBy !== undefined;\n  /** Store a value at one device, or clear it with `null`. */\n  const set = (\n    breakpoint: string,\n    property: string,\n    value: StyleValue | null\n  ): void => {\n    if (readOnly) return;\n    void props\n      .write(sharedStyleChange(partAddress(breakpoint, property), value))\n      .then(answer => setRefusal(answer ?? null));\n  };\n  const at = (property: string): StyleValue | undefined =>\n    partAt(props.styles, TEXT_STYLE_BASE, property);\n  return (\n    <div\n      className=\"nx-vars-editor__body nx-text-styles__editor\"\n      spellCheck={false}\n    >\n      <p className=\"nx-vars-editor__label nx-site-text__title\">{props.name}</p>\n      {props.heldBy === undefined ? null : (\n        <p className=\"nx-inspector__note\">{props.heldBy}</p>\n      )}\n      <FontPart\n        value={at(\"fontFamily\")}\n        readOnly={readOnly}\n        onValue={value => set(TEXT_STYLE_BASE, \"fontFamily\", value)}\n      />\n      <fieldset className=\"nx-text-styles__sizes\">\n        <legend className=\"nx-vars-editor__label\">Size</legend>\n        {props.devices.map(device => (\n          <SizePart\n            key={device.id}\n            device={device}\n            value={partAt(props.styles, device.id, \"fontSize\")}\n            tokens={props.tokens}\n            readOnly={readOnly}\n            onValue={value => set(device.id, \"fontSize\", value)}\n            onClear={() => set(device.id, \"fontSize\", null)}\n            onTokens={props.onTokens}\n            made={props.fluidSizes?.[device.id]}\n            onFluid={\n              props.onFluid === undefined || readOnly\n                ? undefined\n                : (sizes, value) =>\n                    void props\n                      .onFluid?.(device.id, sizes, value)\n                      .then(answer => setRefusal(answer ?? null))\n            }\n          />\n        ))}\n      </fieldset>\n      <VariablePart\n        label=\"Line height\"\n        leaf={LEAVES.lineHeight}\n        value={at(\"lineHeight\")}\n        tokens={props.tokens}\n        readOnly={readOnly}\n        onValue={value => set(TEXT_STYLE_BASE, \"lineHeight\", value)}\n        onClear={() => set(TEXT_STYLE_BASE, \"lineHeight\", null)}\n      >\n        <LineHeightInput\n          label=\"Line height\"\n          value={plain(at(\"lineHeight\"))}\n          readOnly={readOnly}\n          onCommit={text => {\n            const typed = lineHeightFromText(text);\n            if (typeof typed === \"string\" || typeof typed === \"number\") {\n              set(TEXT_STYLE_BASE, \"lineHeight\", typed);\n            }\n          }}\n        />\n      </VariablePart>\n      <VariablePart\n        label=\"Weight\"\n        leaf={LEAVES.fontWeight}\n        value={at(\"fontWeight\")}\n        tokens={props.tokens}\n        readOnly={readOnly}\n        onValue={value => set(TEXT_STYLE_BASE, \"fontWeight\", value)}\n        onClear={() => set(TEXT_STYLE_BASE, \"fontWeight\", null)}\n      >\n        <WeightPart\n          value={at(\"fontWeight\")}\n          readOnly={readOnly}\n          onValue={value => set(TEXT_STYLE_BASE, \"fontWeight\", value)}\n        />\n      </VariablePart>\n      <VariablePart\n        label=\"Letter spacing\"\n        leaf={LEAVES.letterSpacing}\n        value={at(\"letterSpacing\")}\n        tokens={props.tokens}\n        readOnly={readOnly}\n        onValue={value => set(TEXT_STYLE_BASE, \"letterSpacing\", value)}\n        onClear={() => set(TEXT_STYLE_BASE, \"letterSpacing\", null)}\n      >\n        <SpacingPart\n          value={at(\"letterSpacing\")}\n          readOnly={readOnly}\n          onValue={value => set(TEXT_STYLE_BASE, \"letterSpacing\", value)}\n          onRefused={setRefusal}\n        />\n      </VariablePart>\n      <CasePart\n        value={at(\"textTransform\")}\n        readOnly={readOnly}\n        onValue={value => set(TEXT_STYLE_BASE, \"textTransform\", value)}\n      />\n      {refusal === null ? null : (\n        <p className=\"nx-vars-editor__issue\" role=\"alert\">\n          {refusal}\n        </p>\n      )}\n    </div>\n  );\n}\n\n/**\n * One part that may follow a variable: the variable's chip, with Unlink,\n * while it follows one, else the plain field with the list of variables\n * that fit beside it.\n */\nfunction VariablePart({\n  label,\n  leaf,\n  value,\n  tokens,\n  readOnly,\n  onValue,\n  onClear,\n  children,\n}: {\n  label: string;\n  leaf: StyleLeaf | undefined;\n  value: StyleValue | undefined;\n  tokens: SiteTokenSet | undefined;\n  readOnly: boolean;\n  onValue: (value: StyleValue) => void;\n  /**\n   * Take the part's value away, so the style writes none for it: an emptied\n   * field writes nothing, so this is the way back. Absent: not offered.\n   */\n  onClear?: (() => void) | undefined;\n  children: React.ReactNode;\n}): React.JSX.Element {\n  const labelId = React.useId();\n  const held = isTokenRef(value) ? value.$token : undefined;\n  // A scaled reference's multiplier (\"half of Display\"), kept when another\n  // variable is picked and when the part is unlinked, so the value written is\n  // the one the page draws rather than the variable's own.\n  const times = isTokenRef(value) ? value.times : undefined;\n  return (\n    <div className=\"nx-vars-editor__field nx-text-styles__part\">\n      <span className=\"nx-vars-editor__label\" id={labelId}>\n        {label}\n      </span>\n      <div className=\"nx-text-styles__value\">\n        {held !== undefined && leaf !== undefined ? (\n          <VariableChip\n            leaf={leaf}\n            tokens={tokens}\n            identity={held}\n            times={times}\n            label={label}\n            labelledBy={labelId}\n            onPick={identity => onValue(tokenRef(identity, times))}\n            onUnlink={onValue}\n          />\n        ) : (\n          children\n        )}\n        {readOnly || leaf === undefined || held !== undefined ? null : (\n          <VariableChoice\n            leaf={leaf}\n            tokens={tokens}\n            current={held}\n            label={label}\n            onPick={identity => onValue(tokenRef(identity))}\n          />\n        )}\n      </div>\n      {readOnly || onClear === undefined || value === undefined ? null : (\n        <ResetPart label={`Reset ${label}`} onClear={onClear} />\n      )}\n    </div>\n  );\n}\n\n/** \"Reset\" beside a part holding a value, which takes it away. */\nfunction ResetPart({\n  label,\n  onClear,\n}: {\n  label: string;\n  onClear: () => void;\n}): React.JSX.Element {\n  return (\n    <button\n      type=\"button\"\n      className=\"nx-style-inspector__breakpoint-action\"\n      aria-label={label}\n      onClick={onClear}\n    >\n      Reset\n    </button>\n  );\n}\n\n/** The font: the Body font, the Headings font, or a family the site loads. */\nfunction FontPart({\n  value,\n  readOnly,\n  onValue,\n}: {\n  value: StyleValue | undefined;\n  readOnly: boolean;\n  onValue: (value: StyleValue) => void;\n}): React.JSX.Element {\n  const fonts = React.useContext(FontChoicesContext);\n  const id = React.useId();\n  const current = fontChoiceOf(value);\n  const families = roleFamilies(fonts?.faces ?? [], fonts?.fromCode ?? []);\n  const options: (readonly [string, string])[] = [\n    [\"body\", \"Body font\"],\n    [\"heading\", \"Headings font\"],\n    ...families.map(family => [family.stack, family.family] as const),\n  ];\n  // A stored font the list doesn't hold is shown as it is.\n  if (current !== \"\" && !options.some(([key]) => key === current)) {\n    options.push([current, current]);\n  }\n  // A style that sets no font says so, rather than showing Body font as\n  // chosen: it keeps the font of what it is laid on, and Body font has to be\n  // a choice the author can make.\n  if (current === \"\") options.unshift([UNSET_PART, \"Not set\"]);\n  return (\n    <div className=\"nx-vars-editor__field nx-text-styles__part\">\n      <label className=\"nx-vars-editor__label\" htmlFor={id}>\n        Font\n      </label>\n      <PartSelect\n        id={id}\n        label=\"Font\"\n        value={current === \"\" ? UNSET_PART : current}\n        options={options}\n        disabled={readOnly}\n        onChange={choice => {\n          if (choice !== UNSET_PART) onValue(fontValueOf(choice));\n        }}\n      />\n    </div>\n  );\n}\n\n/**\n * The stored sizes, only while they still make the size: one typed since is\n * the author's, and \"Fluid…\" starts from it as it reads.\n */\nfunction sizesStillMaking(\n  made: FluidSizes | undefined,\n  range: FluidRangeWidths | undefined,\n  size: string\n): FluidSizes | undefined {\n  if (made === undefined || range === undefined) return undefined;\n  return fluidValue(made, range) === size ? made : undefined;\n}\n\n/** One device's size: a type size, a typed size, or a fluid one. */\nfunction SizePart({\n  device,\n  value,\n  tokens,\n  readOnly,\n  onValue,\n  onClear,\n  onTokens,\n  made,\n  onFluid,\n}: {\n  device: TextStyleDevice;\n  value: StyleValue | undefined;\n  tokens: SiteTokenSet | undefined;\n  readOnly: boolean;\n  onValue: (value: StyleValue) => void;\n  /** Take the device's own size away, so it follows Desktop's again. */\n  onClear: () => void;\n  onTokens: ((tokens: SiteTokenSet) => void) | undefined;\n  /** The two sizes the size was made fluid from, where it was. */\n  made: FluidSizes | undefined;\n  /** Store a size made fluid with its two sizes; absent, the size alone. */\n  onFluid: ((sizes: FluidSizes, value: string) => void) | undefined;\n}): React.JSX.Element {\n  const range = tokens === undefined ? undefined : fluidRangeOf(tokens);\n  const size = plain(value);\n  const sizes = sizesStillMaking(made, range, size);\n  // A device other than Desktop holding a size of its own can give it up:\n  // an emptied field writes nothing, so this is the way back.\n  const own = !readOnly && device.id !== TEXT_STYLE_BASE && value !== undefined;\n  return (\n    <>\n      <VariablePart\n        label={device.label}\n        leaf={LEAVES.fontSize}\n        value={value}\n        tokens={tokens}\n        readOnly={readOnly}\n        onValue={onValue}\n      >\n        <SizeInput\n          label={`Size on ${device.label}`}\n          value={size}\n          readOnly={readOnly}\n          onCommit={onValue}\n          css={`\n            font-size: ${size};\n          `}\n        />\n        {readOnly || range === undefined || tokens === undefined ? null : (\n          <FluidButton\n            hook={{\n              sizes,\n              value: size,\n              range,\n              onFluid: next => {\n                const fluid = fluidValue(next, range);\n                if (onFluid === undefined) onValue(fluid);\n                else onFluid(next, fluid);\n              },\n              onRange: next => onTokens?.(setFluidRange(tokens, next)),\n            }}\n          />\n        )}\n      </VariablePart>\n      {own ? (\n        <ResetPart\n          label={`Reset the size on ${device.label}`}\n          onClear={onClear}\n        />\n      ) : null}\n    </>\n  );\n}\n\n/** The select key of a part the style leaves unset, apart from every value. */\nconst UNSET_PART = \"unset\";\nconst UNSET_WEIGHT = UNSET_PART;\n\n/** The weight, by name: \"Semibold 600\". */\nfunction WeightPart({\n  value,\n  readOnly,\n  onValue,\n}: {\n  value: StyleValue | undefined;\n  readOnly: boolean;\n  onValue: (value: StyleValue) => void;\n}): React.JSX.Element {\n  const options = fontWeightOptions(value);\n  // A style that sets no weight says so, rather than showing Regular 400 as\n  // chosen: a heading following it keeps its own bold, and Regular has to be\n  // a choice the author can make, not one the list thinks already made.\n  const current =\n    value === undefined\n      ? UNSET_WEIGHT\n      : (options.find(option => option.value === value)?.key ?? UNSET_WEIGHT);\n  return (\n    <PartSelect\n      label=\"Weight\"\n      value={current}\n      options={[\n        ...(current === UNSET_WEIGHT\n          ? [[UNSET_WEIGHT, \"Not set\"] as const]\n          : []),\n        ...options.map(option => [option.key, option.label] as const),\n      ]}\n      disabled={readOnly}\n      onChange={key => {\n        const picked = options.find(option => option.key === key);\n        if (picked !== undefined) onValue(picked.value);\n      }}\n    />\n  );\n}\n\n/** Letter spacing: a number, in `em` unless another unit is typed or chosen. */\nfunction SpacingPart({\n  value,\n  readOnly,\n  onValue,\n  onRefused,\n}: {\n  value: StyleValue | undefined;\n  readOnly: boolean;\n  onValue: (value: StyleValue | null) => void;\n  onRefused: (words: string) => void;\n}): React.JSX.Element {\n  const { amount, unit } = letterSpacingParts(value);\n  const commit = (typed: string, inUnit: string): void => {\n    const next = letterSpacingValue(typed, inUnit);\n    if (next === undefined) {\n      onRefused(\"Type the letter spacing as a number, such as 0.08.\");\n      return;\n    }\n    onValue(next);\n  };\n  return (\n    <span className=\"nx-text-styles__spacing\">\n      <CommitInput\n        label=\"Letter spacing\"\n        value={amount}\n        readOnly={readOnly}\n        onCommit={typed => commit(typed, unit)}\n      />\n      <PartSelect\n        label=\"Letter spacing unit\"\n        value={unit}\n        options={LETTER_SPACING_UNITS.map(each => [each, each] as const)}\n        disabled={readOnly || amount === \"\"}\n        onChange={next => commit(amount, next)}\n      />\n    </span>\n  );\n}\n\n/** The case: As typed, UPPERCASE, lowercase or Capitalised. */\nfunction CasePart({\n  value,\n  readOnly,\n  onValue,\n}: {\n  value: StyleValue | undefined;\n  readOnly: boolean;\n  onValue: (value: StyleValue) => void;\n}): React.JSX.Element {\n  const name = React.useId();\n  // A style that sets no case checks none: \"As typed\" writes `none`, which\n  // overrides a case the block gets from elsewhere, so it must be choosable.\n  const current = typeof value === \"string\" ? value : undefined;\n  return (\n    <fieldset className=\"nx-site-text__sizes nx-text-styles__case\">\n      <legend className=\"nx-vars-editor__label\">Case</legend>\n      {TEXT_STYLE_CASES.map(([stored, words]) => (\n        <label key={stored} className=\"nx-site-text__option\">\n          <input\n            type=\"radio\"\n            name={name}\n            value={stored}\n            checked={current === stored}\n            disabled={readOnly}\n            onChange={() => onValue(stored)}\n          />\n          <span>{words}</span>\n        </label>\n      ))}\n    </fieldset>\n  );\n}\n\n/**\n * A short list a part is chosen from: the admin's select, whose list is\n * drawn above the popup it is opened in.\n */\nfunction PartSelect<V extends string>({\n  id,\n  label,\n  value,\n  options,\n  onChange,\n  disabled = false,\n}: {\n  id?: string;\n  /** What the control is, said before its value: \"Weight\". */\n  label: string;\n  value: V;\n  options: ReadonlyArray<readonly [V, string]>;\n  onChange: (value: V) => void;\n  disabled?: boolean;\n}): React.JSX.Element {\n  const shown = options.find(([option]) => option === value)?.[1] ?? value;\n  return (\n    <Select\n      value={value}\n      disabled={disabled}\n      onValueChange={next => {\n        const picked = options.find(([option]) => option === next);\n        if (picked !== undefined && picked[0] !== value) onChange(picked[0]);\n      }}\n    >\n      <SelectTrigger\n        id={id}\n        className=\"nx-text-styles__select\"\n        aria-label={`${label}, ${shown}`}\n      >\n        <SelectValue>{shown}</SelectValue>\n      </SelectTrigger>\n      <SelectContent>\n        {options.map(([option, words]) => (\n          <SelectItem key={option} value={option}>\n            {words}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n","/**\n * What Design's Type → \"Text styles\" writes: a new text style, a copy of\n * one, a rename, and a size made fluid. Each is the site's whole class list after the action,\n * so the host stores it through the one writer every class write joins (and\n * so it undoes as one step), or why it can't be.\n *\n * A rename keeps the text style's id and class name, so every block and\n * Site text row following it keeps doing so; only the name changes.\n *\n * @module text-style-plans\n */\nimport {\n  BASE_BREAKPOINT,\n  fluidValue,\n  isTextStyle,\n  MAX_NAMED_CLASS_NAME_LENGTH,\n  newId,\n  tokenLabelIssue,\n  type FluidRangeWidths,\n  type FluidSizes,\n  type NamedClass,\n  type NodeStyles,\n} from \"@nextlyhq/blocks-engine\";\n\nimport {\n  firstCopyName,\n  nextOrderIndex,\n  unusedSlug,\n  type BlockStylePlan,\n} from \"../../styles/block-style-plans\";\nimport {\n  sharedStyleName,\n  sharedStyleSlug,\n} from \"../../styles/shared-style-library\";\n\n/** A text style action's answer: the classes to store and the style it made, or why not. */\nexport type TextStylePlanResult = BlockStylePlan;\n\n/** What a text style no longer on the site is told. */\nconst GONE = \"This text style is no longer on the site.\";\n\n/** A text style by id, or `undefined` for none, or a class of another kind. */\nfunction textStyleOf(\n  library: readonly NamedClass[],\n  id: string\n): NamedClass | undefined {\n  return library.find(entry => entry.id === id && isTextStyle(entry));\n}\n\n/** Whether another text style has this name, in any case. */\nfunction nameHeld(\n  library: readonly NamedClass[],\n  label: string,\n  except: string | undefined\n): boolean {\n  return library.some(\n    entry =>\n      entry.id !== except &&\n      isTextStyle(entry) &&\n      sharedStyleName(entry).toLowerCase() === label.toLowerCase()\n  );\n}\n\n/** Why a name can't be a text style's, or `undefined`. */\nfunction nameRefusal(\n  library: readonly NamedClass[],\n  label: string,\n  except: string | undefined\n): string | undefined {\n  if (label === \"\") return \"A text style needs a name.\";\n  const issue = tokenLabelIssue(label);\n  if (issue !== undefined) return issue.replace(\"A label\", \"A name\");\n  if (sharedStyleSlug(label) === \"\") {\n    return \"Use at least one letter or digit in the name.\";\n  }\n  if (nameHeld(library, label, except)) {\n    return `There is already a text style named “${label}”. Choose another name.`;\n  }\n  return undefined;\n}\n\n/** A text style the site made, last in the library, with the styles given. */\nfunction madeTextStyle(\n  library: readonly NamedClass[],\n  label: string,\n  styles: NamedClass[\"styles\"],\n  mintId: () => string\n): NamedClass {\n  const slug = sharedStyleSlug(label)\n    .slice(0, MAX_NAMED_CLASS_NAME_LENGTH)\n    .replace(/-+$/, \"\");\n  return {\n    id: mintId(),\n    slug: unusedSlug(library, slug),\n    label,\n    orderIndex: nextOrderIndex(library),\n    role: \"text\",\n    // A copy, so an edit to the new style never edits the one it came from.\n    styles: structuredClone(styles),\n  };\n}\n\n/**\n * A new text style, named by the author, on the site's Body font: a start\n * every other part is then set over.\n */\nexport function newTextStylePlan(\n  library: readonly NamedClass[],\n  name: string,\n  mintId: () => string = newId\n): TextStylePlanResult {\n  const label = name.trim();\n  const refusal = nameRefusal(library, label, undefined);\n  if (refusal !== undefined) return { ok: false, reason: refusal };\n  const entry = madeTextStyle(\n    library,\n    label,\n    { base: { [BASE_BREAKPOINT]: { fontFamily: { $token: \"font.body\" } } } },\n    mintId\n  );\n  return { ok: true, classes: [...library, entry], id: entry.id };\n}\n\n/** The first \"<name> copy\", \"<name> copy 2\"… no text style is named. */\nfunction copyName(\n  library: readonly NamedClass[],\n  name: string\n): string | undefined {\n  return firstCopyName(\n    name,\n    candidate => nameRefusal(library, candidate, undefined) === undefined\n  );\n}\n\n/**\n * A copy of a text style: its parts and the sizes a fluid size was made\n * from (each only while it still makes its size across `range`), under the\n * next free \"copy\" name, and unlocked, since a lock is the original's.\n */\nexport function duplicateTextStylePlan(\n  library: readonly NamedClass[],\n  id: string,\n  mintId: () => string = newId,\n  /** The site's fluid range now, or `undefined` where it is not known. */\n  range?: FluidRangeWidths\n): TextStylePlanResult {\n  const source = textStyleOf(library, id);\n  if (source === undefined) return { ok: false, reason: GONE };\n  const label = copyName(library, sharedStyleName(source));\n  if (label === undefined) {\n    return {\n      ok: false,\n      reason: `There are as many copies of “${sharedStyleName(source)}” as a name can count. Rename one first.`,\n    };\n  }\n  const made = madeTextStyle(library, label, source.styles, mintId);\n  // The sizes its fluid sizes were made from go with them, so the copy's\n  // follow a change of the site's fluid range as the original's do.\n  const fluidSizes = fluidSizesStillMaking(source, range);\n  const entry = fluidSizes === undefined ? made : { ...made, fluidSizes };\n  return { ok: true, classes: [...library, entry], id: entry.id };\n}\n\n/**\n * A text style's fluid sizes for each device whose size they still make\n * across `range`, or `undefined` for none. A size typed since, or made across\n * another range, is the author's: sizes copied beside it would be taken for\n * the ones it was made from, and the copy's size made again from them.\n * Nothing is copied where the range is not known.\n */\nfunction fluidSizesStillMaking(\n  source: NamedClass,\n  range: FluidRangeWidths | undefined\n): NamedClass[\"fluidSizes\"] {\n  const sizes = source.fluidSizes;\n  if (sizes === undefined || range === undefined) return undefined;\n  const atRest = source.styles.base ?? {};\n  const kept = Object.entries(sizes).filter(\n    ([device, made]) => atRest[device]?.fontSize === fluidValue(made, range)\n  );\n  return kept.length === 0 ? undefined : Object.fromEntries(kept);\n}\n\n/**\n * A text style an action may change, or why not: it is gone, or locked, said\n * with the action's own words after \"<name> is locked\".\n */\nfunction unlockedTextStyle(\n  library: readonly NamedClass[],\n  id: string,\n  whenLocked: string\n): { readonly source: NamedClass } | { readonly reason: string } {\n  const source = textStyleOf(library, id);\n  if (source === undefined) return { reason: GONE };\n  return source.locked === true\n    ? { reason: `${sharedStyleName(source)} is locked${whenLocked}` }\n    : { source };\n}\n\n/**\n * A text style renamed: its name only. Its id and class name stay, so every\n * block and row following it keeps resolving.\n */\nexport function renameTextStylePlan(\n  library: readonly NamedClass[],\n  id: string,\n  name: string\n): TextStylePlanResult {\n  // A lock holds a style's name as well as its parts.\n  const found = unlockedTextStyle(library, id, \", so it can't be renamed.\");\n  if (\"reason\" in found) return { ok: false, reason: found.reason };\n  const { source } = found;\n  const label = name.trim();\n  const refused = nameRefusal(library, label, id);\n  if (refused !== undefined) return { ok: false, reason: refused };\n  return {\n    ok: true,\n    classes: library.map(entry =>\n      entry === source ? { ...entry, label } : entry\n    ),\n    id,\n  };\n}\n\n/**\n * A text style's size on one device made fluid: the value \"Fluid…\" made, and\n * the two sizes it was made from kept beside the styles, so a change of the\n * site's fluid range makes the size again. One edit, so the two are stored\n * and undone together, and never apart.\n */\nexport function fluidTextStyleSizePlan(\n  library: readonly NamedClass[],\n  id: string,\n  device: string,\n  sizes: FluidSizes,\n  value: string\n): TextStylePlanResult {\n  const found = unlockedTextStyle(library, id, \". Unlock it to change it.\");\n  if (\"reason\" in found) return { ok: false, reason: found.reason };\n  const { source } = found;\n  const atRest = source.styles.base ?? {};\n  const styles: NodeStyles = {\n    ...source.styles,\n    base: { ...atRest, [device]: { ...atRest[device], fontSize: value } },\n  };\n  const fluidSizes = {\n    ...source.fluidSizes,\n    [device]: { small: sizes.small, large: sizes.large },\n  };\n  return {\n    ok: true,\n    classes: library.map(entry =>\n      entry === source ? { ...entry, styles, fluidSizes } : entry\n    ),\n    id,\n  };\n}\n","\"use client\";\n\n/**\n * Design → Type → \"Text styles\": the site's text styles, each row previewing\n * sample text in its look beside its size and line height, and \"+ Add text\n * style\". A row opens its parts in a popup beside the panel\n * (`text-style-editor`); its ⋯ menu renames, duplicates, locks and removes.\n *\n * Making, copying and renaming write the site's whole class list through the\n * host's one class writer, and a part's change writes one address of the\n * style's styles, so each saves and undoes as a block style does. Lock and\n * Remove go through the shared styles' routes, which refuse to remove a text\n * style a block or a Site text row uses, saying where.\n *\n * Keyboard: Enter or Space on a row opens its parts, F2 renames it, and the\n * menu key or Shift+F10 opens its ⋯ menu. Escape in a name field puts it\n * down and hands focus back to the row it came from.\n *\n * @module text-styles-section\n */\nimport {\n  newId,\n  textStylesOf,\n  type BreakpointSet,\n  type NamedClass,\n  type SiteTokenSet,\n  type TokenMode,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@nextlyhq/ui\";\nimport { Lock } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { EDITOR_WORDS } from \"../../editor-words\";\nimport {\n  useQueuedStyles,\n  type SharedStylesHost,\n} from \"../../inspector/style-inspector/style-target\";\nimport type { EditClasses } from \"../../styles/block-style-actions\";\nimport {\n  heldByThisPage,\n  sharedStyleRows,\n  USED_ON_THIS_PAGE_REMOVAL,\n  type SharedStyleRow,\n} from \"../../styles/shared-style-library\";\n\nimport { BlockStyleNameField, RowMenuFrame } from \"./block-style-row-menu\";\nimport { removeSharedStylesThrough } from \"./shared-style-details\";\nimport type {\n  PageClassBlocks,\n  SharedStylesAccess,\n} from \"./shared-styles-types\";\nimport { PopupRow } from \"./site-text-panel\";\nimport { textStyleOptions, type TextStyleOption } from \"./text-style-choice\";\nimport { TextStyleEditor } from \"./text-style-editor\";\nimport { textStyleDevices } from \"./text-style-parts\";\nimport {\n  duplicateTextStylePlan,\n  fluidTextStyleSizePlan,\n  newTextStylePlan,\n  renameTextStylePlan,\n  type TextStylePlanResult,\n} from \"./text-style-plans\";\nimport { fluidRangeOf } from \"./tokens-studio\";\nimport { CloseVariableEditor } from \"./variable-value-controls\";\n\n/** What the section is handed. */\nexport interface TextStylesSectionProps {\n  /** The site's class library, or `undefined` while it is being read. */\n  readonly library: readonly NamedClass[] | undefined;\n  readonly tokens: SiteTokenSet | undefined;\n  /** The mode the previews are drawn in. */\n  readonly mode: TokenMode;\n  /** The site's devices, which a size is set for. */\n  readonly breakpoints?: BreakpointSet | undefined;\n  /** Shown, never changed: a role that may not change the site's design. */\n  readonly readOnly: boolean;\n  /** The host's whole-list class write: make, copy, rename. */\n  readonly onEditClasses?: EditClasses | undefined;\n  /** The host's write of one style's styles, for a part's change. */\n  readonly host?: SharedStylesHost | undefined;\n  /** The shared styles' routes: lock and remove. */\n  readonly access?: SharedStylesAccess | undefined;\n  /**\n   * The blocks on the open page wearing each style. A removal is refused while\n   * one does, since the route reads only saved documents. Absent: read as worn.\n   */\n  readonly pageBlocks?: PageClassBlocks | undefined;\n  /** Change the site's variables, for the fluid range a fluid size sets. */\n  readonly onTokens?: ((tokens: SiteTokenSet) => void) | undefined;\n}\n\n/** The sample every row previews its look with, as Site text's rows do. */\nconst SAMPLE = \"The quick survey\";\n\n/** What a write the host can't make is told. */\nconst NO_WRITE = \"Text styles can't be changed here.\";\n\n/** The section, for the Type tab. */\nexport function TextStylesSection(\n  props: TextStylesSectionProps\n): React.JSX.Element | null {\n  const headingId = React.useId();\n  const { library } = props;\n  if (library === undefined) return null;\n  const options = textStyleOptions(library, props.tokens, props.mode);\n  // The rows' locks and styles, read as the Shared styles tab reads them.\n  const rows = new Map(\n    sharedStyleRows(textStylesOf(library), new Set()).map(row => [row.id, row])\n  );\n  const writable = !props.readOnly && props.onEditClasses !== undefined;\n  return (\n    <section\n      className=\"nx-vars__group nx-text-styles\"\n      aria-labelledby={headingId}\n    >\n      <div className=\"nx-vars__group-head\">\n        <h3 className=\"nx-vars__group-name\" id={headingId}>\n          {EDITOR_WORDS.textStyles}\n        </h3>\n      </div>\n      <ul className=\"nx-vars__list\">\n        {options.map(option => {\n          const row = rows.get(option.id);\n          return row === undefined ? null : (\n            <TextStyleRow\n              key={option.id}\n              option={option}\n              row={row}\n              panel={props}\n              writable={writable}\n            />\n          );\n        })}\n      </ul>\n      {options.length === 0 ? (\n        <p className=\"nx-inspector__note\">\n          No text styles yet. A text style is a whole look for text, which any\n          block can use from its Style tab.\n        </p>\n      ) : null}\n      {writable ? <AddRow panel={props} /> : null}\n    </section>\n  );\n}\n\n/** Run a whole-list plan through the host's writer: the refusal, or the id made. */\nasync function runPlan(\n  edit: EditClasses | undefined,\n  plan: (existing: readonly NamedClass[]) => TextStylePlanResult\n): Promise<{ refused: string } | { id: string }> {\n  if (edit === undefined) return { refused: NO_WRITE };\n  let made: string | undefined;\n  const refused = await edit(existing => {\n    const planned = plan(existing);\n    if (!planned.ok) return { reason: planned.reason };\n    made = planned.id;\n    return { classes: planned.classes };\n  });\n  if (refused !== undefined) return { refused };\n  return made === undefined ? { refused: NO_WRITE } : { id: made };\n}\n\n/** Focus a button once the field that took its place is gone. */\nfunction focusLater(target: React.RefObject<HTMLElement | null>): void {\n  requestAnimationFrame(() => target.current?.focus());\n}\n\n/** \"+ Add text style\", then the field its name is typed in. */\nfunction AddRow({\n  panel,\n}: {\n  panel: TextStylesSectionProps;\n}): React.JSX.Element {\n  const [naming, setNaming] = React.useState(false);\n  const button = React.useRef<HTMLButtonElement>(null);\n  if (naming) {\n    return (\n      <BlockStyleNameField\n        label=\"New text style name\"\n        initial=\"\"\n        onCommit={async name => {\n          const answer = await runPlan(panel.onEditClasses, existing =>\n            newTextStylePlan(existing, name)\n          );\n          if (\"refused\" in answer) return answer.refused;\n          setNaming(false);\n          focusLater(button);\n          return undefined;\n        }}\n        onCancel={() => {\n          setNaming(false);\n          focusLater(button);\n        }}\n      />\n    );\n  }\n  return (\n    <button\n      ref={button}\n      type=\"button\"\n      className=\"nx-block-styles__add\"\n      onClick={() => setNaming(true)}\n    >\n      + Add text style\n    </button>\n  );\n}\n\n/** Whether a key on a row opens its ⋯ menu: the menu key, or Shift+F10. */\nfunction opensMenu(event: React.KeyboardEvent): boolean {\n  return event.key === \"ContextMenu\" || (event.key === \"F10\" && event.shiftKey);\n}\n\n/** One row: its button, its ⋯ menu, its popup, and what was refused. */\nfunction TextStyleRow({\n  option,\n  row,\n  panel,\n  writable,\n}: {\n  option: TextStyleOption;\n  row: SharedStyleRow;\n  panel: TextStylesSectionProps;\n  writable: boolean;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const [menu, setMenu] = React.useState(false);\n  const [renaming, setRenaming] = React.useState(false);\n  const [refusal, setRefusal] = React.useState<string | null>(null);\n  const button = React.useRef<HTMLButtonElement>(null);\n  const returnTo = React.useRef<HTMLElement | null>(null);\n  const issueId = React.useId();\n  const renamable = writable && !row.locked;\n  if (renaming) {\n    return (\n      <li className=\"nx-vars__item\">\n        <BlockStyleNameField\n          label={`Rename ${option.name}`}\n          initial={option.name}\n          onCommit={async name => {\n            const answer = await runPlan(panel.onEditClasses, existing =>\n              renameTextStylePlan(existing, row.id, name)\n            );\n            if (\"refused\" in answer) return answer.refused;\n            setRenaming(false);\n            focusLater(button);\n            return undefined;\n          }}\n          onCancel={() => {\n            setRenaming(false);\n            focusLater(button);\n          }}\n        />\n      </li>\n    );\n  }\n  const actions = rowActions({ row, panel, setRefusal });\n  const named = `${EDITOR_WORDS.textStyles}: ${option.name}${option.pair === \"\" ? \"\" : `, ${option.pair}`}${row.locked ? \", locked\" : \"\"}`;\n  return (\n    <PopupRow\n      open={open}\n      onOpen={setOpen}\n      after={\n        refusal === null ? null : (\n          <p className=\"nx-vars-editor__issue\" id={issueId} role=\"alert\">\n            {refusal}\n          </p>\n        )\n      }\n    >\n      <div className=\"nx-vars__line\">\n        <PopoverTrigger asChild>\n          <button\n            ref={button}\n            type=\"button\"\n            className=\"nx-vars__row nx-site-text__row\"\n            data-text-style={row.id}\n            aria-label={named}\n            aria-describedby={refusal === null ? undefined : issueId}\n            onKeyDown={event => {\n              if (event.key === \"F2\" && renamable) {\n                event.preventDefault();\n                setRenaming(true);\n              } else if (opensMenu(event) && writable) {\n                event.preventDefault();\n                returnTo.current = button.current;\n                setMenu(true);\n              }\n            }}\n          >\n            <span className=\"nx-vars__name\" title={option.name}>\n              {option.name}\n            </span>\n            <span\n              className=\"nx-site-text__preview\"\n              aria-hidden=\"true\"\n              style={option.preview}\n            >\n              {SAMPLE}\n            </span>\n            <span className=\"nx-vars__chip\" title={option.pair}>\n              {row.locked ? <Lock aria-hidden=\"true\" size={11} /> : null}\n              {option.pair}\n            </span>\n          </button>\n        </PopoverTrigger>\n        {writable ? (\n          <RowMenu\n            name={option.name}\n            locked={row.locked}\n            open={menu}\n            onOpenChange={setMenu}\n            returnTo={returnTo}\n            onRename={() => setRenaming(true)}\n            {...actions}\n          />\n        ) : null}\n      </div>\n      <PopoverContent\n        side=\"right\"\n        align=\"start\"\n        sideOffset={12}\n        collisionPadding={8}\n        className=\"nx-vars-editor nx-site-text__editor\"\n        aria-label={`${panel.readOnly ? \"\" : \"Edit \"}${option.name}`}\n      >\n        <CloseVariableEditor.Provider value={() => setOpen(false)}>\n          <RowEditor row={row} name={option.name} panel={panel} />\n        </CloseVariableEditor.Provider>\n      </PopoverContent>\n    </PopupRow>\n  );\n}\n\n/** A row's popup: its parts, edited through the host's queued writes. */\nfunction RowEditor({\n  row,\n  name,\n  panel,\n}: {\n  row: SharedStyleRow;\n  name: string;\n  panel: TextStylesSectionProps;\n}): React.JSX.Element {\n  const queued = useQueuedStyles(row, panel.host);\n  const heldBy =\n    panel.readOnly || panel.host === undefined || !panel.host.mayChange\n      ? \"You can't change this site's design.\"\n      : row.locked\n        ? `${name} is locked. Unlock it to change it.`\n        : undefined;\n  return (\n    <TextStyleEditor\n      name={name}\n      styles={queued?.style.styles ?? row.styles}\n      tokens={panel.tokens}\n      devices={textStyleDevices(panel.breakpoints)}\n      heldBy={heldBy}\n      write={change =>\n        queued === undefined ? Promise.resolve(NO_WRITE) : queued.write(change)\n      }\n      onTokens={panel.onTokens}\n      fluidSizes={panel.library?.find(entry => entry.id === row.id)?.fluidSizes}\n      onFluid={(device, sizes, value) =>\n        runPlan(panel.onEditClasses, existing =>\n          fluidTextStyleSizePlan(existing, row.id, device, sizes, value)\n        ).then(answer => (\"refused\" in answer ? answer.refused : undefined))\n      }\n    />\n  );\n}\n\n/** A row's menu actions, each saying a refusal under the row. */\nfunction rowActions({\n  row,\n  panel,\n  setRefusal,\n}: {\n  row: SharedStyleRow;\n  panel: TextStylesSectionProps;\n  setRefusal: (words: string | null) => void;\n}): {\n  onDuplicate: () => void;\n  onLock: () => void;\n  onRemove: () => void;\n} {\n  const said = (words: string | undefined): void => setRefusal(words ?? null);\n  return {\n    onDuplicate: () =>\n      void runPlan(panel.onEditClasses, existing =>\n        duplicateTextStylePlan(\n          existing,\n          row.id,\n          newId,\n          panel.tokens === undefined ? undefined : fluidRangeOf(panel.tokens)\n        )\n      ).then(answer => said(\"refused\" in answer ? answer.refused : undefined)),\n    onLock: () => {\n      const lock = panel.access?.lock;\n      if (lock === undefined) {\n        said(NO_WRITE);\n        return;\n      }\n      void lock(row.id, !row.locked).then(said);\n    },\n    onRemove: () => {\n      const access = panel.access;\n      if (access === undefined) {\n        said(NO_WRITE);\n        return;\n      }\n      // The open page first: a block wearing it there may not be saved yet,\n      // which no saved count holds.\n      const here = panel.pageBlocks;\n      if (\n        heldByThisPage(\n          here === undefined\n            ? undefined\n            : {\n                count: here.counts.get(row.id) ?? 0,\n                complete: here.complete,\n              }\n        )\n      ) {\n        said(USED_ON_THIS_PAGE_REMOVAL);\n        return;\n      }\n      // The route refuses a text style a block or a Site text row uses, and\n      // its words say where.\n      void removeSharedStylesThrough(access, [row.id]).then(refused =>\n        said(refused?.reason)\n      );\n    },\n  };\n}\n\n/** The row's ⋯ button and its menu. */\nfunction RowMenu({\n  name,\n  locked,\n  open,\n  onOpenChange,\n  returnTo,\n  onRename,\n  onDuplicate,\n  onLock,\n  onRemove,\n}: {\n  name: string;\n  locked: boolean;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /** The row, while the menu key opened the menu, to hand focus back to. */\n  returnTo: React.RefObject<HTMLElement | null>;\n  onRename: () => void;\n  onDuplicate: () => void;\n  onLock: () => void;\n  onRemove: () => void;\n}): React.JSX.Element {\n  return (\n    <RowMenuFrame\n      name={name}\n      open={open}\n      onOpenChange={onOpenChange}\n      returnTo={returnTo}\n    >\n      {handOff => (\n        <>\n          {locked ? null : (\n            // The name field takes focus.\n            <DropdownMenuItem onSelect={handOff(onRename)}>\n              Rename\n            </DropdownMenuItem>\n          )}\n          <DropdownMenuItem onSelect={onDuplicate}>Duplicate</DropdownMenuItem>\n          <DropdownMenuItem onSelect={onLock}>\n            {locked ? \"Unlock\" : \"Lock\"}\n          </DropdownMenuItem>\n          {locked ? null : (\n            <>\n              <DropdownMenuSeparator />\n              <DropdownMenuItem onSelect={onRemove}>Remove</DropdownMenuItem>\n            </>\n          )}\n        </>\n      )}\n    </RowMenuFrame>\n  );\n}\n","/**\n * A select drawn as the admin's menu: a button naming the current choice, and\n * a menu of radio items. Used where Fonts offers one of a short list (a\n * weight, a category), so no native select is ever drawn.\n *\n * @module font-choice-menu\n */\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuTrigger,\n} from \"@nextlyhq/ui\";\nimport { ChevronDown } from \"lucide-react\";\nimport type * as React from \"react\";\n\nexport interface ChoiceMenuProps<V extends string> {\n  /** What the control is, said before its value: \"Weight\", \"Category\". */\n  readonly label: string;\n  readonly value: V;\n  readonly options: ReadonlyArray<readonly [V, string]>;\n  readonly onChange: (value: V) => void;\n  readonly disabled?: boolean;\n  readonly id?: string;\n}\n\nexport function ChoiceMenu<V extends string>({\n  label,\n  value,\n  options,\n  onChange,\n  disabled = false,\n  id,\n}: ChoiceMenuProps<V>): React.JSX.Element {\n  const shown = options.find(([option]) => option === value)?.[1] ?? value;\n  return (\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild disabled={disabled}>\n        <button\n          type=\"button\"\n          id={id}\n          className=\"nx-fonts__choice\"\n          aria-label={`${label}, ${shown}`}\n        >\n          <span className=\"nx-fonts__choice-value\">{shown}</span>\n          <ChevronDown aria-hidden=\"true\" size={14} />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent align=\"start\" className=\"nx-vars__menu\">\n        <DropdownMenuRadioGroup\n          value={value}\n          onValueChange={next => {\n            const picked = options.find(([option]) => option === next);\n            if (picked !== undefined) onChange(picked[0]);\n          }}\n        >\n          {options.map(([option, words]) => (\n            <DropdownMenuRadioItem key={option} value={option}>\n              {words}\n            </DropdownMenuRadioItem>\n          ))}\n        </DropdownMenuRadioGroup>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n","/**\n * Previews of catalogue families while an author browses Google Fonts.\n *\n * A preview is loaded into the EDITOR's own document only, never into the\n * canvas frame or the site's stylesheet, so nothing a visitor loads changes.\n * It loads from the address the host built (the catalogue's file host), only\n * once its row is on screen, and under the name `nx-preview-<id>`, which no\n * site family can have, so a preview never stands in for a font the site\n * actually stores.\n *\n * A preview that fails leaves its row in the admin's font, without a word: a\n * missing preview changes nothing an author can act on.\n *\n * @module font-preview\n */\nimport * as React from \"react\";\n\n/** The family a preview is loaded under. */\nexport function previewFamily(id: string): string {\n  return `nx-preview-${id}`;\n}\n\n/** Each preview once per page, whichever rows ask for it. */\nconst loaded = new Map<string, Promise<boolean>>();\n\n/** Load one preview into a document's fonts; answers whether it loaded. */\nfunction loadPreview(id: string, url: string, doc: Document): Promise<boolean> {\n  const key = `${id}|${url}`;\n  const known = loaded.get(key);\n  if (known !== undefined) return known;\n  const face = new FontFace(previewFamily(id), `url(\"${url}\")`);\n  doc.fonts.add(face);\n  const done = face.load().then(\n    () => true,\n    () => false\n  );\n  loaded.set(key, done);\n  return done;\n}\n\n/**\n * Whether a row's preview has loaded. Starts loading the first time the row\n * is on screen, and never while `url` is null: the author has not yet\n * agreed to their browser loading previews from the catalogue's file host.\n */\nexport function usePreview(\n  target: Element | null,\n  id: string,\n  url: string | null,\n  doc: Document = document\n): boolean {\n  const [ready, setReady] = React.useState(false);\n  React.useEffect(() => {\n    if (\n      url === null ||\n      target === null ||\n      typeof IntersectionObserver === \"undefined\"\n    ) {\n      return;\n    }\n    let live = true;\n    const observer = new IntersectionObserver(entries => {\n      if (!entries.some(entry => entry.isIntersecting)) return;\n      observer.disconnect();\n      void loadPreview(id, url, doc).then(done => {\n        if (live) setReady(done);\n      });\n    });\n    observer.observe(target);\n    return () => {\n      live = false;\n      observer.disconnect();\n    };\n  }, [target, id, url, doc]);\n  return ready;\n}\n","/**\n * The Google Fonts catalogue, shown in the Fonts tab in place of the site's\n * fonts: search it, filter it by category, preview each family in itself, and\n * add one to the site.\n *\n * Adding never downloads anything in the editor. It names a family, its\n * weights, styles and scripts to the host, whose server downloads the files\n * into the site's media; visitors' browsers then load fonts only from the\n * site. Previews are the one thing the editor's browser fetches, from the\n * catalogue's file host, while an author browses ({@link font-preview}).\n *\n * @module font-catalogue-view\n */\nimport {\n  Button,\n  Checkbox,\n  Input,\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n  Spinner,\n  toast,\n} from \"@nextlyhq/ui\";\nimport { ArrowLeft, Search } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { EDITOR_WORDS } from \"../../editor-words\";\nimport type { PreferenceStore } from \"../../shell-state\";\n\nimport { ChoiceMenu } from \"./font-choice-menu\";\nimport {\n  licenceName,\n  SPECIMEN,\n  weightName,\n  type SiteFamily,\n} from \"./font-library\";\nimport { previewFamily, usePreview } from \"./font-preview\";\n\n/** One family in the catalogue, as the host hands it over. */\nexport interface CatalogueFamilyView {\n  readonly id: string;\n  readonly family: string;\n  readonly category: string;\n  readonly weights: readonly number[];\n  readonly styles: readonly (\"normal\" | \"italic\")[];\n  readonly subsets: readonly string[];\n  readonly defSubset: string;\n  readonly variable: boolean;\n  readonly licence: string;\n  /**\n   * How much the family is used, which \"Popular\" orders by: higher is more.\n   * Absent when the host could not say, and the list is then ordered by name.\n   */\n  readonly popularity?: number;\n}\n\n/** What the Fonts tab asks the catalogue to add: names, never addresses. */\nexport interface CatalogueAddRequest {\n  readonly id: string;\n  readonly weights: readonly number[] | \"variable\";\n  readonly styles: readonly (\"normal\" | \"italic\")[];\n  readonly subsets: readonly string[];\n}\n\n/** The host's catalogue: where it reads, previews from and adds through. */\nexport interface FontCatalogue {\n  /** The catalogue's families, read through the host's server. */\n  readonly load: (\n    signal: AbortSignal\n  ) => Promise<{ readonly families: readonly CatalogueFamilyView[] }>;\n  /** Where one preview file loads from, in the editor only. */\n  readonly previewUrl: (\n    family: CatalogueFamilyView,\n    weight: number | \"variable\",\n    style: \"normal\" | \"italic\"\n  ) => string;\n  /** Add a family to the site. Resolves to a message when refused. */\n  readonly add: (request: CatalogueAddRequest) => Promise<string | undefined>;\n  /**\n   * Where the author's choice to show previews is kept, so they are asked\n   * once. Absent, nothing is kept and the author is asked on every visit.\n   */\n  readonly previewConsent?: PreferenceStore;\n}\n\n/** What the consent store holds once the author has asked for previews. */\nconst PREVIEWS_SHOWN = \"shown\";\n\n/**\n * Whether previews may load, and the way to allow them. The kept choice is\n * read again whenever the store changes, since it can arrive late (the\n * author's identity is read after the catalogue may open), and a press made\n * before it arrived is kept in it once it does.\n */\nfunction usePreviewConsent(\n  store: PreferenceStore | undefined\n): readonly [boolean, () => void] {\n  const kept = React.useMemo(() => store?.read() === PREVIEWS_SHOWN, [store]);\n  const [pressed, setPressed] = React.useState(false);\n  React.useEffect(() => {\n    if (pressed && !kept) store?.write(PREVIEWS_SHOWN);\n  }, [pressed, kept, store]);\n  const allow = React.useCallback(() => setPressed(true), []);\n  return [kept || pressed, allow];\n}\n\n/** The list before the catalogue has answered, kept so its order is too. */\nconst NO_FAMILIES: readonly CatalogueFamilyView[] = Object.freeze([]);\n\n/** How many families mount before the author asks for more. */\nconst PAGE_SIZE = 30;\n\nconst CATEGORIES = [\n  [\"all\", \"All categories\"],\n  [\"sans-serif\", \"Sans serif\"],\n  [\"serif\", \"Serif\"],\n  [\"display\", \"Display\"],\n  [\"handwriting\", \"Handwriting\"],\n  [\"monospace\", \"Monospace\"],\n] as const;\n\ntype Category = (typeof CATEGORIES)[number][0];\n\n// \"Popular first\" rather than \"Popular\", which beside the category filter\n// could read as a filter for popular families only.\nconst SORTS = [\n  [\"popular\", \"Popular first\"],\n  [\"name\", \"A–Z\"],\n] as const;\n\ntype Sort = (typeof SORTS)[number][0];\n\n/** Names in the order a reader expects, whatever their case or accents. */\nconst BY_NAME = new Intl.Collator(undefined, { sensitivity: \"base\" });\n\n/**\n * The families in the order chosen: the most used first, then by name among\n * equals; or by name alone. The catalogue arrives in its own order, which is\n * not promised to be either.\n */\nfunction ordered(\n  families: readonly CatalogueFamilyView[],\n  sort: Sort\n): CatalogueFamilyView[] {\n  return [...families].sort(\n    (a, b) =>\n      (sort === \"popular\" ? (b.popularity ?? 0) - (a.popularity ?? 0) : 0) ||\n      BY_NAME.compare(a.family, b.family)\n  );\n}\n\n/** Whether the host said how much any family is used, so \"Popular\" can mean something. */\nfunction knowsPopularity(families: readonly CatalogueFamilyView[]): boolean {\n  return families.some(family => family.popularity !== undefined);\n}\n\n/** A category in words. */\nfunction categoryName(category: string): string {\n  return CATEGORIES.find(([value]) => value === category)?.[1] ?? category;\n}\n\n/** Scripts in the words a reader of them would use. */\nconst SUBSET_NAMES: Readonly<Record<string, string>> = {\n  latin: \"Latin\",\n  \"latin-ext\": \"Latin Extended\",\n  cyrillic: \"Cyrillic\",\n  \"cyrillic-ext\": \"Cyrillic Extended\",\n  greek: \"Greek\",\n  \"greek-ext\": \"Greek Extended\",\n  vietnamese: \"Vietnamese\",\n};\n\n/** A script in words: known ones by name, others from their own spelling. */\nfunction subsetName(subset: string): string {\n  const known = SUBSET_NAMES[subset];\n  if (known !== undefined) return known;\n  const words = subset.replaceAll(\"-\", \" \");\n  return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n/** How many styles a family offers: one per weight and style. */\nfunction styleCount(family: CatalogueFamilyView): number {\n  return family.weights.length * family.styles.length;\n}\n\n/** `Sans serif · 18 styles · Variable`. */\nfunction metaLine(family: CatalogueFamilyView): string {\n  const count = styleCount(family);\n  return [\n    categoryName(family.category),\n    `${String(count)} ${count === 1 ? \"style\" : \"styles\"}`,\n    ...(family.variable ? [\"Variable\"] : []),\n  ].join(\" · \");\n}\n\ntype Load =\n  | { status: \"loading\" }\n  | { status: \"failed\" }\n  | { status: \"ready\"; families: readonly CatalogueFamilyView[] };\n\n/** The catalogue, read once per opening, and read again on \"Try again\". */\nfunction useCatalogue(catalogue: FontCatalogue): {\n  load: Load;\n  retry: () => void;\n} {\n  const [attempt, setAttempt] = React.useState(0);\n  const [load, setLoad] = React.useState<Load>({ status: \"loading\" });\n  React.useEffect(() => {\n    const controller = new AbortController();\n    setLoad({ status: \"loading\" });\n    catalogue.load(controller.signal).then(\n      read => {\n        if (!controller.signal.aborted) {\n          setLoad({ status: \"ready\", families: read.families });\n        }\n      },\n      () => {\n        if (!controller.signal.aborted) setLoad({ status: \"failed\" });\n      }\n    );\n    return () => controller.abort();\n  }, [catalogue, attempt]);\n  return { load, retry: () => setAttempt(count => count + 1) };\n}\n\nexport function FontCatalogueView({\n  catalogue,\n  onBack,\n  initialQuery = \"\",\n  onSite,\n  onAdded,\n}: {\n  catalogue: FontCatalogue;\n  /** Back to the site's fonts. */\n  onBack: () => void;\n  /** The search to open on, such as one the site's fonts found nothing for. */\n  initialQuery?: string;\n  /** The families already on the site. */\n  onSite: readonly SiteFamily[];\n  /**\n   * Told the family and its category once one finishes adding, so the\n   * screen can ask how to use it.\n   */\n  onAdded?: (family: string, category: string) => void;\n}): React.JSX.Element {\n  const { load, retry } = useCatalogue(catalogue);\n  const [previews, allowPreviews] = usePreviewConsent(catalogue.previewConsent);\n  const [query, setQuery] = React.useState(initialQuery);\n  const [category, setCategory] = React.useState<Category>(\"all\");\n  const [sort, setSort] = React.useState<Sort>(\"popular\");\n  const [sample, setSample] = React.useState(\"\");\n  const [pages, setPages] = React.useState(1);\n  const search = React.useRef<HTMLInputElement>(null);\n\n  // The view opens on its search box, so typing starts the search.\n  React.useEffect(() => {\n    search.current?.focus();\n  }, []);\n\n  const needle = query.trim().toLowerCase();\n  const families = load.status === \"ready\" ? load.families : NO_FAMILIES;\n  // Without figures \"Popular\" would be a promise the list cannot keep, so the\n  // choice is not offered and the list reads by name.\n  const sortable = knowsPopularity(families);\n  const sorted = React.useMemo(\n    () => ordered(families, sortable ? sort : \"name\"),\n    [families, sortable, sort]\n  );\n  const matching =\n    load.status === \"ready\"\n      ? sorted.filter(\n          family =>\n            (category === \"all\" || family.category === category) &&\n            family.family.toLowerCase().includes(needle)\n        )\n      : [];\n  const shown = matching.slice(0, pages * PAGE_SIZE);\n  const hidden = matching.length - shown.length;\n\n  return (\n    <div className=\"nx-vars nx-fonts nx-fonts-catalogue\">\n      <div className=\"nx-fonts-catalogue__head\">\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"sm\"\n          className=\"nx-fonts-catalogue__back\"\n          aria-label={`Back to this site’s ${EDITOR_WORDS.fonts.toLowerCase()}`}\n          onClick={onBack}\n        >\n          <ArrowLeft aria-hidden=\"true\" size={14} />\n          {EDITOR_WORDS.fonts}\n        </Button>\n        <h3 className=\"nx-fonts-catalogue__title\">Google Fonts</h3>\n      </div>\n      <div className=\"nx-vars__search\">\n        <Search aria-hidden=\"true\" size={16} />\n        <Input\n          ref={search}\n          type=\"search\"\n          aria-label=\"Search Google Fonts\"\n          placeholder=\"Search Google Fonts\"\n          value={query}\n          onChange={event => {\n            setQuery(event.target.value);\n            setPages(1);\n          }}\n          onKeyDown={event => {\n            if (event.key === \"Escape\") {\n              event.preventDefault();\n              onBack();\n            }\n          }}\n        />\n      </div>\n      <div className=\"nx-fonts-catalogue__filters\">\n        <div className=\"nx-fonts-catalogue__choices\">\n          <ChoiceMenu\n            label=\"Category\"\n            value={category}\n            options={CATEGORIES}\n            onChange={next => {\n              setCategory(next);\n              setPages(1);\n            }}\n          />\n          {sortable ? (\n            <ChoiceMenu\n              label=\"Sort\"\n              value={sort}\n              options={SORTS}\n              onChange={next => {\n                setSort(next);\n                setPages(1);\n              }}\n            />\n          ) : null}\n        </div>\n        <Input\n          type=\"text\"\n          aria-label=\"Preview text\"\n          placeholder=\"Type to preview\"\n          value={sample}\n          onChange={event => setSample(event.target.value)}\n        />\n      </div>\n      <div className=\"nx-vars__body\">\n        <PreviewConsent previews={previews} onAllow={allowPreviews} />\n        {load.status === \"loading\" ? <Loading /> : null}\n        {load.status === \"failed\" ? (\n          <div className=\"nx-fonts-catalogue__failed\">\n            <p className=\"nx-vars__alert\" role=\"alert\">\n              Google Fonts could not be reached. The fonts already on this site\n              still work.\n            </p>\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              size=\"sm\"\n              className=\"nx-vars-editor__button\"\n              onClick={retry}\n            >\n              Try again\n            </Button>\n          </div>\n        ) : null}\n        {load.status === \"ready\" && matching.length === 0 ? (\n          <p className=\"nx-vars__empty\">No Google Fonts match this search.</p>\n        ) : null}\n        {shown.length > 0 ? (\n          <ul className=\"nx-vars__list\">\n            {shown.map(family => (\n              <CatalogueRow\n                key={family.id}\n                family={family}\n                catalogue={catalogue}\n                sample={sample}\n                previews={previews}\n                site={onSite.find(\n                  each => each.key === family.family.toLowerCase()\n                )}\n                onAdded={onAdded}\n              />\n            ))}\n          </ul>\n        ) : null}\n        <ShowMore\n          count={Math.min(hidden, PAGE_SIZE)}\n          onMore={() => setPages(count => count + 1)}\n        />\n      </div>\n    </div>\n  );\n}\n\n/**\n * Above the catalogue: that fonts added are copied to the site, and, until\n * the author agrees, where previews would load from, with \"Show previews\".\n * Until then each family is named in the builder's own font.\n */\nfunction PreviewConsent({\n  previews,\n  onAllow,\n}: {\n  previews: boolean;\n  onAllow: () => void;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-fonts-catalogue__consent\">\n      <p className=\"nx-vars__note\">\n        Fonts you add are copied to your site. Visitors never contact Google.\n      </p>\n      {previews ? null : (\n        <div className=\"nx-fonts-catalogue__previews\">\n          <p className=\"nx-vars__note\">\n            To show previews, your browser loads them from Fontsource, a free\n            copy of Google Fonts.\n          </p>\n          <Button\n            type=\"button\"\n            variant=\"outline\"\n            size=\"sm\"\n            className=\"nx-vars-editor__button\"\n            onClick={onAllow}\n          >\n            Show previews\n          </Button>\n        </div>\n      )}\n    </div>\n  );\n}\n\n/** The next page of families, named by how many it adds; nothing at the end. */\nfunction ShowMore({\n  count,\n  onMore,\n}: {\n  count: number;\n  onMore: () => void;\n}): React.JSX.Element | null {\n  if (count <= 0) return null;\n  return (\n    <button className=\"nx-vars__link\" type=\"button\" onClick={onMore}>\n      {`Show ${String(count)} more`}\n    </button>\n  );\n}\n\n/** Six placeholder rows, still, and a status for a screen reader. */\nfunction Loading(): React.JSX.Element {\n  return (\n    <>\n      <p className=\"nx-vars__note\" role=\"status\">\n        Loading Google Fonts&hellip;\n      </p>\n      <ul className=\"nx-vars__list\" aria-hidden=\"true\">\n        {Array.from({ length: 6 }, (_, index) => (\n          <li className=\"nx-fonts__skeleton\" key={index}>\n            <span />\n            <span />\n          </li>\n        ))}\n      </ul>\n    </>\n  );\n}\n\n/** The preview's family when it has loaded; the admin's font until then. */\nfunction previewStyle(\n  family: CatalogueFamilyView,\n  loaded: boolean\n): React.CSSProperties | undefined {\n  return loaded ? { fontFamily: `\"${previewFamily(family.id)}\"` } : undefined;\n}\n\n/** The weight a family's preview file is drawn from. */\nfunction previewWeight(family: CatalogueFamilyView): number | \"variable\" {\n  if (family.variable) return \"variable\";\n  return family.weights.includes(400) ? 400 : (family.weights[0] ?? 400);\n}\n\n/** One family: a two-line row that opens its add editor beside the panel. */\nfunction CatalogueRow({\n  family,\n  catalogue,\n  sample,\n  previews,\n  site,\n  onAdded,\n}: {\n  family: CatalogueFamilyView;\n  catalogue: FontCatalogue;\n  sample: string;\n  /** Whether the author has agreed to previews loading. */\n  previews: boolean;\n  site: SiteFamily | undefined;\n  onAdded: ((family: string, category: string) => void) | undefined;\n}): React.JSX.Element {\n  const [open, setOpen] = React.useState(false);\n  const [element, setElement] = React.useState<HTMLButtonElement | null>(null);\n  const loaded = usePreview(\n    element,\n    family.id,\n    previews\n      ? catalogue.previewUrl(\n          family,\n          previewWeight(family),\n          startingStyle(family)\n        )\n      : null\n  );\n  const meta = metaLine(family);\n  return (\n    <li>\n      <Popover open={open} onOpenChange={setOpen} modal>\n        <PopoverTrigger asChild>\n          <button\n            ref={setElement}\n            type=\"button\"\n            className=\"nx-vars__row nx-fonts-catalogue__row\"\n            data-catalogue-family={family.id}\n          >\n            {/* The row's name, in one element: the family, what the meta\n                line says, and whether the site has it. Text rather than an\n                aria-label, which must hold every drawn word, the preview\n                sentence included; what is drawn is for the eye. */}\n            <span className=\"nx-sr-only\">\n              {`${family.family}, ${meta}${site === undefined ? \"\" : \", added\"}`}\n            </span>\n            <span className=\"nx-fonts-catalogue__text\" aria-hidden=\"true\">\n              {/* The name whole on hover: cut when long, or drawn over by\n                  the preview text. */}\n              <span\n                className=\"nx-fonts-catalogue__preview\"\n                style={previewStyle(family, loaded)}\n                title={family.family}\n              >\n                {sample.trim() === \"\" ? family.family : sample}\n              </span>\n              <span className=\"nx-fonts-catalogue__meta\">{meta}</span>\n            </span>\n            {site === undefined ? null : (\n              <span\n                className=\"nx-vars__chip nx-fonts__added\"\n                aria-hidden=\"true\"\n              >\n                Added\n              </span>\n            )}\n          </button>\n        </PopoverTrigger>\n        <PopoverContent\n          side=\"right\"\n          align=\"start\"\n          sideOffset={12}\n          className=\"nx-vars-editor nx-fonts-add\"\n          aria-label={`Add ${family.family}`}\n        >\n          <AddEditor\n            family={family}\n            catalogue={catalogue}\n            sample={sample}\n            loaded={loaded}\n            site={site}\n            onAdded={() => {\n              setOpen(false);\n              element?.focus();\n              onAdded?.(family.family, family.category);\n            }}\n          />\n        </PopoverContent>\n      </Popover>\n    </li>\n  );\n}\n\n/** The style a family starts from: its regular, or its italic when that's all it has. */\nfunction startingStyle(family: CatalogueFamilyView): \"normal\" | \"italic\" {\n  return family.styles.includes(\"normal\") ? \"normal\" : \"italic\";\n}\n\n/** The weights to start with: Regular and Bold where offered, else the first. */\nfunction startingWeights(family: CatalogueFamilyView): Set<number> {\n  const both = family.weights.filter(\n    weight => weight === 400 || weight === 700\n  );\n  const first = family.weights[0];\n  return new Set(both.length > 0 ? both : first === undefined ? [] : [first]);\n}\n\n/**\n * The styles the site already has of a family, as `weight|style|script`: the\n * same cut in another script is another file, and still addable. A face that\n * names no script matches none, as the server's comparison of ranges does.\n */\nfunction presentStyles(\n  family: CatalogueFamilyView,\n  site: SiteFamily | undefined\n): Set<string> {\n  const present = new Set<string>();\n  for (const face of site?.faces ?? []) {\n    const style = face.style === \"italic\" ? \"italic\" : \"normal\";\n    // The weight as stored, so a static 400 is never taken for the variable\n    // file's whole range; the planner compares faces the same way.\n    const weight = (face.weight ?? \"400\").trim().replace(/\\s+/g, \" \");\n    // A face that names no script (an upload, the site's code) covers no\n    // catalogue script: the server adds the catalogue's file beside it.\n    const subset = face.source?.subset ?? \"\";\n    present.add(`${weight}|${style}|${subset}`);\n  }\n  return present;\n}\n\n/** A cut as a stored face declares its weight: a variable file its range. */\nfunction declaredWeight(\n  family: CatalogueFamilyView,\n  cut: number | \"variable\"\n): string {\n  if (cut !== \"variable\") return String(cut);\n  const low = Math.min(...family.weights);\n  const high = Math.max(...family.weights);\n  return low === high ? String(low) : `${String(low)} ${String(high)}`;\n}\n\n/** What the add button says, and whether it can be pressed. */\nfunction addLabel(\n  name: string,\n  chosen: number,\n  fresh: number,\n  hasSome: boolean\n): { label: string; ready: boolean } {\n  const styles = (count: number): string =>\n    `${String(count)} ${count === 1 ? \"style\" : \"styles\"}`;\n  if (hasSome) {\n    return fresh === 0\n      ? { label: \"Already on this site\", ready: false }\n      : {\n          label: `Add ${String(fresh)} more ${fresh === 1 ? \"style\" : \"styles\"}`,\n          ready: true,\n        };\n  }\n  return chosen === 0\n    ? { label: `Add ${name}`, ready: false }\n    : { label: `Add ${name} \\u00b7 ${styles(chosen)}`, ready: true };\n}\n\n/**\n * What an add asks for, from the editor's choices and the faces the site\n * has: the styles, the scripts, the weights (held ones included), whether a\n * cut is already on the site in every chosen script, and the button.\n */\nfunction addSelection(\n  family: CatalogueFamilyView,\n  present: ReadonlySet<string>,\n  choices: {\n    weights: ReadonlySet<number>;\n    italics: boolean;\n    subsets: ReadonlySet<string>;\n  }\n): {\n  base: \"normal\" | \"italic\";\n  offersBoth: boolean;\n  styles: Array<\"normal\" | \"italic\">;\n  chosenSubsets: string[];\n  held: (cut: number | \"variable\", style: string) => boolean;\n  cuts: Array<number | \"variable\">;\n  label: string;\n  ready: boolean;\n} {\n  // A family that comes only in italic starts from its italic; italics are a\n  // choice only where it has both.\n  const base = startingStyle(family);\n  const offersBoth = base === \"normal\" && family.styles.includes(\"italic\");\n  const styles: Array<\"normal\" | \"italic\"> =\n    choices.italics && offersBoth ? [base, \"italic\"] : [base];\n  const chosenSubsets = family.subsets.filter(subset =>\n    choices.subsets.has(subset)\n  );\n  /** Whether the site has a cut in every script chosen. */\n  const held = (cut: number | \"variable\", style: string): boolean =>\n    chosenSubsets.length > 0 &&\n    chosenSubsets.every(subset =>\n      present.has(`${declaredWeight(family, cut)}|${style}|${subset}`)\n    );\n  const cuts: Array<number | \"variable\"> = family.variable\n    ? [\"variable\"]\n    : family.weights.filter(\n        weight => choices.weights.has(weight) || held(weight, base)\n      );\n  const combos = cuts.flatMap(cut => styles.map(style => ({ cut, style })));\n  // A style counts as new when any chosen script of it is missing.\n  const fresh = combos.filter(combo => !held(combo.cut, combo.style)).length;\n  const { label, ready } = addLabel(\n    family.family,\n    combos.length,\n    fresh,\n    present.size > 0\n  );\n  return { base, offersBoth, styles, chosenSubsets, held, cuts, label, ready };\n}\n\n/** The editor that adds one family: weights, italics, scripts, licence. */\nfunction AddEditor({\n  family,\n  catalogue,\n  sample,\n  loaded,\n  site,\n  onAdded,\n}: {\n  family: CatalogueFamilyView;\n  catalogue: FontCatalogue;\n  sample: string;\n  loaded: boolean;\n  site: SiteFamily | undefined;\n  onAdded: () => void;\n}): React.JSX.Element {\n  const ids = React.useId();\n  const present = presentStyles(family, site);\n  const [weights, setWeights] = React.useState(() => startingWeights(family));\n  const [italics, setItalics] = React.useState(false);\n  const [subsets, setSubsets] = React.useState(\n    () => new Set([family.defSubset])\n  );\n  const [busy, setBusy] = React.useState(false);\n  const [issue, setIssue] = React.useState<string | null>(null);\n\n  const { base, offersBoth, styles, chosenSubsets, held, cuts, label, ready } =\n    addSelection(family, present, { weights, italics, subsets });\n\n  const toggle = <T,>(set: Set<T>, value: T): Set<T> => {\n    const next = new Set(set);\n    if (next.has(value)) next.delete(value);\n    else next.add(value);\n    return next;\n  };\n\n  const submit = async (): Promise<void> => {\n    if (!ready || busy || subsets.size === 0) return;\n    setBusy(true);\n    setIssue(null);\n    try {\n      const refusal = await catalogue.add({\n        id: family.id,\n        weights: family.variable\n          ? \"variable\"\n          : cuts.filter((cut): cut is number => cut !== \"variable\"),\n        styles,\n        subsets: chosenSubsets,\n      });\n      if (refusal !== undefined) {\n        setIssue(refusal);\n        return;\n      }\n      toast.success(`${family.family} is now on this site.`);\n      onAdded();\n    } finally {\n      setBusy(false);\n    }\n  };\n\n  const drawn = previewStyle(family, loaded);\n  const low = Math.min(...family.weights);\n  const high = Math.max(...family.weights);\n\n  return (\n    <div className=\"nx-vars-editor__body\">\n      <div className=\"nx-fonts__heading\">\n        <span className=\"nx-fonts__title nx-fonts__title--large\" style={drawn}>\n          {family.family}\n        </span>\n        <span className=\"nx-fonts__sample\" style={drawn}>\n          {sample.trim() === \"\" ? SPECIMEN : sample}\n        </span>\n      </div>\n\n      {family.variable ? (\n        <p className=\"nx-fonts__hint\">\n          {`Every weight from ${String(low)} to ${String(high)}, in one file.`}\n        </p>\n      ) : (\n        <fieldset className=\"nx-fonts__fieldset\">\n          <legend className=\"nx-vars-editor__label\">Weights</legend>\n          <div className=\"nx-fonts__weights\">\n            {family.weights.map(weight => {\n              const have = held(weight, base);\n              const id = `${ids}-w${String(weight)}`;\n              return (\n                <div className=\"nx-fonts__check\" key={weight}>\n                  <Checkbox\n                    id={id}\n                    checked={have || weights.has(weight)}\n                    disabled={busy || have}\n                    onCheckedChange={() =>\n                      setWeights(current => toggle(current, weight))\n                    }\n                  />\n                  <label\n                    htmlFor={id}\n                    style={\n                      loaded ? { ...drawn, fontWeight: weight } : undefined\n                    }\n                  >\n                    {weightName(weight)}\n                  </label>\n                </div>\n              );\n            })}\n          </div>\n          <span className=\"nx-fonts__hint\">Fewer styles load faster.</span>\n        </fieldset>\n      )}\n\n      {offersBoth ? (\n        <div className=\"nx-fonts__check\">\n          <Checkbox\n            id={`${ids}-italic`}\n            checked={italics}\n            disabled={busy}\n            onCheckedChange={checked => setItalics(checked === true)}\n          />\n          <label htmlFor={`${ids}-italic`}>Include italics</label>\n        </div>\n      ) : null}\n\n      {family.subsets.length > 1 ? (\n        <fieldset className=\"nx-fonts__fieldset\">\n          <legend className=\"nx-vars-editor__label\">Languages</legend>\n          {family.subsets.map(subset => {\n            const id = `${ids}-s-${subset}`;\n            return (\n              <div className=\"nx-fonts__check\" key={subset}>\n                <Checkbox\n                  id={id}\n                  checked={subsets.has(subset)}\n                  disabled={busy}\n                  onCheckedChange={() =>\n                    setSubsets(current => toggle(current, subset))\n                  }\n                />\n                <label htmlFor={id}>{subsetName(subset)}</label>\n              </div>\n            );\n          })}\n        </fieldset>\n      ) : null}\n\n      <p className=\"nx-fonts__meta\">{licenceName(family.licence)}</p>\n\n      {issue === null ? null : (\n        <p className=\"nx-vars-editor__issue\" role=\"alert\">\n          {issue}\n        </p>\n      )}\n      <p className=\"nx-fonts__live\" role=\"status\" aria-live=\"polite\">\n        {busy ? `Downloading ${family.family} to your site…` : \"\"}\n      </p>\n\n      <div className=\"nx-vars-editor__actions\">\n        <Button\n          type=\"button\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button nx-fonts__add-button\"\n          disabled={busy || !ready || subsets.size === 0}\n          onClick={() => void submit()}\n        >\n          {busy ? (\n            <>\n              <Spinner aria-hidden=\"true\" size=\"sm\" />\n              {`Adding ${family.family}…`}\n            </>\n          ) : (\n            label\n          )}\n        </Button>\n      </div>\n    </div>\n  );\n}\n","/**\n * Upload a font file: the editor beside the Fonts tab that adds one face from\n * a file on the author's computer.\n *\n * The weight and style are asked for rather than read from the file, because\n * getting them wrong is silent: a face declaring 400 for a bold file loads and\n * matches nothing the author meant.\n *\n * NOT a `<form>`, and that is deliberate. The panel is rendered inside the\n * entry editor, whose fields sit in one, and HTML forbids a form inside a\n * form; a submit raised in here would bubble to the entry's handler and save\n * the page. Enter in a text field still uploads, by handling the keystroke\n * here, and a composing (IME) keystroke is left alone.\n *\n * @module font-upload-editor\n */\nimport { Button, Checkbox, Input } from \"@nextlyhq/ui\";\nimport type * as React from \"react\";\nimport { useId, useRef, useState } from \"react\";\n\nimport { ChoiceMenu } from \"./font-choice-menu\";\nimport { weightName } from \"./font-library\";\n\n/** A font file and the descriptors an author states for it. */\nexport interface FontFaceUpload {\n  file: File;\n  family: string;\n  /** `400`, `700`, or a variable range such as `100 900`. */\n  weight: string;\n  /** `normal` or `italic`. */\n  style: string;\n}\n\ntype WeightChoice =\n  | \"100\"\n  | \"200\"\n  | \"300\"\n  | \"400\"\n  | \"500\"\n  | \"600\"\n  | \"700\"\n  | \"800\"\n  | \"900\"\n  | \"variable\";\n\nconst WEIGHTS: ReadonlyArray<readonly [WeightChoice, string]> = [\n  ...(\n    [\"100\", \"200\", \"300\", \"400\", \"500\", \"600\", \"700\", \"800\", \"900\"] as const\n  ).map(weight => [weight, weightName(Number(weight))] as const),\n  [\"variable\", \"Variable (a range)\"],\n];\n\n/** What an author is told about a weight or range that cannot be stored. */\nconst WEIGHT_PROBLEM =\n  \"Choose a weight, or a range with the lighter weight first.\";\n\n/**\n * The family a filename suggests, as a starting point the author can correct:\n * `Inter-BoldItalic.woff2` is `Inter`.\n */\nfunction familyFromFilename(name: string): string {\n  const stem = name.replace(/\\.[^.]+$/, \"\");\n  return (stem.split(/[-_]/)[0] ?? stem).trim();\n}\n\n/** A weight from 1 to 1000 written as plain digits, or nothing. */\nfunction weightNumber(value: string): number | undefined {\n  if (!/^\\d{1,4}$/.test(value.trim())) return undefined;\n  const number = Number(value);\n  return number >= 1 && number <= 1000 ? number : undefined;\n}\n\n/** The weight descriptor the choice stands for, or nothing when unusable. */\nfunction weightOf(\n  choice: WeightChoice,\n  from: string,\n  to: string\n): string | undefined {\n  if (choice !== \"variable\") return choice;\n  const low = weightNumber(from);\n  const high = weightNumber(to);\n  if (low === undefined || high === undefined || low > high) return undefined;\n  return low === high ? String(low) : `${String(low)} ${String(high)}`;\n}\n\n/** The upload's state, its checks and its submit, apart from how it looks. */\nfunction useUploadForm(\n  onAddFace: (request: FontFaceUpload) => Promise<string | undefined>\n) {\n  const [file, setFile] = useState<File | null>(null);\n  const [family, setFamily] = useState(\"\");\n  /*\n   * Whether the family came from the author or from a filename. Emptiness\n   * cannot answer it: a guess is replaced by a better guess when the file\n   * changes, and what an author typed is theirs.\n   */\n  const [familyAuthored, setFamilyAuthored] = useState(false);\n  const [weight, setWeight] = useState<WeightChoice>(\"400\");\n  const [from, setFrom] = useState(\"100\");\n  const [to, setTo] = useState(\"900\");\n  const [style, setStyle] = useState<\"normal\" | \"italic\">(\"normal\");\n  const [rights, setRights] = useState(false);\n  const [error, setError] = useState<string | null>(null);\n  const [busy, setBusy] = useState(false);\n  /*\n   * The picker element itself. A file input is uncontrolled, and a browser\n   * raises `change` only when the selection changes, so it is cleared by hand\n   * after an upload: choosing the same file again is how a family gets its\n   * italic.\n   */\n  const picker = useRef<HTMLInputElement | null>(null);\n\n  const chooseFile = (chosen: File | null): void => {\n    setFile(chosen);\n    setError(null);\n    if (chosen !== null && !familyAuthored) {\n      setFamily(familyFromFilename(chosen.name));\n    }\n  };\n\n  const typeFamily = (value: string): void => {\n    setFamily(value);\n    setFamilyAuthored(true);\n  };\n\n  const ready = file !== null && family.trim() !== \"\" && rights && !busy;\n\n  /** Everything back to a fresh start; the cut too, or a kept `700 Italic`\n   *  would be applied to the next file by default, and the rights. */\n  const clear = (): void => {\n    setFile(null);\n    if (picker.current !== null) picker.current.value = \"\";\n    setFamily(\"\");\n    setFamilyAuthored(false);\n    setWeight(\"400\");\n    // The range too: the next variable file's bounds are its own.\n    setFrom(\"100\");\n    setTo(\"900\");\n    setStyle(\"normal\");\n    // The rights are the next file's to confirm, not carried from this one.\n    setRights(false);\n  };\n\n  const submit = async (): Promise<void> => {\n    if (!ready) return;\n    const descriptor = weightOf(weight, from, to);\n    if (descriptor === undefined) {\n      setError(WEIGHT_PROBLEM);\n      return;\n    }\n    setBusy(true);\n    setError(null);\n    try {\n      const refusal = await onAddFace({\n        file,\n        family: family.trim(),\n        weight: descriptor,\n        style,\n      });\n      // A refusal leaves everything where the author left it.\n      if (refusal === undefined) clear();\n      else setError(refusal);\n    } finally {\n      setBusy(false);\n    }\n  };\n\n  /** Enter uploads; a composing keystroke belongs to the IME. */\n  const uploadOnEnter = (event: React.KeyboardEvent): void => {\n    if (event.key !== \"Enter\") return;\n    const native = event.nativeEvent;\n    if (native.isComposing || native.keyCode === 229) return;\n    event.preventDefault();\n    void submit();\n  };\n\n  return {\n    file,\n    family,\n    weight,\n    from,\n    to,\n    style,\n    rights,\n    error,\n    busy,\n    ready,\n    picker,\n    chooseFile,\n    typeFamily,\n    setWeight,\n    setFrom,\n    setTo,\n    setStyle,\n    setRights,\n    submit,\n    uploadOnEnter,\n  };\n}\n\ntype UploadForm = ReturnType<typeof useUploadForm>;\n\nexport function FontUploadEditor({\n  onAddFace,\n  acceptFiles,\n}: {\n  onAddFace: (request: FontFaceUpload) => Promise<string | undefined>;\n  acceptFiles?: string;\n}): React.JSX.Element {\n  const ids = useId();\n  const form = useUploadForm(onAddFace);\n  return (\n    <div className=\"nx-vars-editor__body nx-fonts-upload\">\n      <h3 className=\"nx-fonts__editor-title\">Upload a font file</h3>\n      <FileField ids={ids} form={form} acceptFiles={acceptFiles} />\n      <div className=\"nx-vars-editor__field\">\n        <label className=\"nx-vars-editor__label\" htmlFor={`${ids}-family`}>\n          Family\n        </label>\n        <Input\n          id={`${ids}-family`}\n          value={form.family}\n          placeholder=\"Inter\"\n          disabled={form.busy}\n          onChange={event => form.typeFamily(event.target.value)}\n          onKeyDown={form.uploadOnEnter}\n        />\n      </div>\n      <WeightField ids={ids} form={form} />\n      <StyleField ids={ids} form={form} />\n      <div className=\"nx-fonts__check\">\n        <Checkbox\n          id={`${ids}-rights`}\n          checked={form.rights}\n          disabled={form.busy}\n          onCheckedChange={checked => form.setRights(checked === true)}\n        />\n        <label htmlFor={`${ids}-rights`}>\n          I have the right to use this font on the web\n        </label>\n      </div>\n      {form.error === null ? null : (\n        <p className=\"nx-vars-editor__issue\" role=\"alert\">\n          {form.error}\n        </p>\n      )}\n      <div className=\"nx-vars-editor__actions\">\n        {/* `type=\"button\"`: inside the entry's form a button defaults to submit. */}\n        <Button\n          type=\"button\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button\"\n          disabled={!form.ready}\n          onClick={() => void form.submit()}\n        >\n          {form.busy ? \"Uploading\\u2026\" : \"Upload\"}\n        </Button>\n      </div>\n    </div>\n  );\n}\n\n/** The file: the admin's button opens the hidden native picker. */\nfunction FileField({\n  ids,\n  form,\n  acceptFiles,\n}: {\n  ids: string;\n  form: UploadForm;\n  acceptFiles: string | undefined;\n}): React.JSX.Element {\n  const { file } = form;\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\">File</span>\n      <div className=\"nx-fonts-upload__file\">\n        <input\n          ref={form.picker}\n          className=\"nx-fonts-upload__input\"\n          type=\"file\"\n          accept={acceptFiles}\n          aria-label=\"Font file\"\n          // Out of the accessibility tree: \"Choose file\" is the control.\n          aria-hidden=\"true\"\n          tabIndex={-1}\n          onChange={event => form.chooseFile(event.target.files?.[0] ?? null)}\n        />\n        <Button\n          type=\"button\"\n          variant=\"outline\"\n          size=\"sm\"\n          className=\"nx-vars-editor__button\"\n          aria-describedby={`${ids}-file-name`}\n          disabled={form.busy}\n          onClick={() => form.picker.current?.click()}\n        >\n          Choose file\n        </Button>\n        <span className=\"nx-fonts-upload__name\" id={`${ids}-file-name`}>\n          {file === null\n            ? \"No file chosen\"\n            : `${file.name} \\u00b7 ${String(Math.round(file.size / 1024))} KB`}\n        </span>\n      </div>\n      <span className=\"nx-fonts__hint\">.woff2 or .woff</span>\n    </div>\n  );\n}\n\n/** The weight: one of the nine, or a range for a variable file. */\nfunction WeightField({\n  ids,\n  form,\n}: {\n  ids: string;\n  form: UploadForm;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\" aria-hidden=\"true\">\n        Weight\n      </span>\n      <ChoiceMenu\n        label=\"Weight\"\n        value={form.weight}\n        options={WEIGHTS}\n        onChange={form.setWeight}\n        disabled={form.busy}\n      />\n      {form.weight === \"variable\" ? (\n        <div className=\"nx-fonts-upload__range\">\n          <label className=\"nx-fonts__hint\" htmlFor={`${ids}-from`}>\n            From\n          </label>\n          <Input\n            id={`${ids}-from`}\n            inputMode=\"numeric\"\n            value={form.from}\n            disabled={form.busy}\n            onChange={event => form.setFrom(event.target.value)}\n            onKeyDown={form.uploadOnEnter}\n          />\n          <label className=\"nx-fonts__hint\" htmlFor={`${ids}-to`}>\n            To\n          </label>\n          <Input\n            id={`${ids}-to`}\n            inputMode=\"numeric\"\n            value={form.to}\n            disabled={form.busy}\n            onChange={event => form.setTo(event.target.value)}\n            onKeyDown={form.uploadOnEnter}\n          />\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\n/** The style: Normal or Italic, as a segmented pair. */\nfunction StyleField({\n  ids,\n  form,\n}: {\n  ids: string;\n  form: UploadForm;\n}): React.JSX.Element {\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\" id={`${ids}-style`}>\n        Style\n      </span>\n      <div\n        className=\"nx-vars__seg\"\n        role=\"group\"\n        aria-labelledby={`${ids}-style`}\n      >\n        {([\"normal\", \"italic\"] as const).map(candidate => (\n          <button\n            key={candidate}\n            type=\"button\"\n            aria-pressed={form.style === candidate}\n            disabled={form.busy}\n            onClick={() => form.setStyle(candidate)}\n          >\n            {candidate === \"normal\" ? \"Normal\" : \"Italic\"}\n          </button>\n        ))}\n      </div>\n    </div>\n  );\n}\n","/**\n * Where one of the site's fonts is used, as the Fonts screen says it, and\n * what the screen says when removing or using one.\n *\n * A font is used by the site's Body or Headings font, read from each row\n * they are written on in either mode (`fontRoleStacks`), and by the font\n * variables whose first family it is, in either mode: blocks, text styles and shared styles\n * reach a font through those variables, and the variables' own usage says\n * how widely. A font a block names as plain text is not a use the site can\n * count, and never breaks a page: the text falls back.\n *\n * @module font-uses\n */\nimport {\n  readFamilyList,\n  resolveSiteTokens,\n  tokenDisplayLabel,\n  tokenIdentity,\n  type NamedClass,\n  type SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\n\nimport { FONT_ROLE_WORDS } from \"../../editor-words\";\nimport { listedWords } from \"../../styles/shared-style-library\";\n\nimport {\n  firstFamily,\n  fontReadsRole,\n  fontRoleRows,\n  fontRoleStacks,\n  fontRoleVariables,\n  variableStacks,\n  type FontRole,\n} from \"./site-font-roles-model\";\nimport { siteTextRowViews } from \"./site-text-rows\";\n\n/** A font variable whose first family is the font. */\nexport interface FontVariableUse {\n  /** The variable's identity, as usage and the Variables tab name it. */\n  readonly identity: string;\n  /** Its plain name, as Variables shows it. */\n  readonly label: string;\n  /** What its text is drawn in once the font is gone. */\n  readonly fallback: string;\n}\n\n/** Where a font is used. */\nexport interface FamilyUses {\n  /** The site-wide fonts it is: Body, Headings, both or neither. */\n  readonly roles: readonly FontRole[];\n  /** The font variables naming it first, other than the roles' own. */\n  readonly variables: readonly FontVariableUse[];\n  /**\n   * Every font variable naming it first, the roles' own included, by\n   * identity: the variables whose places say how widely it is used.\n   */\n  readonly counted: readonly string[];\n}\n\n/** The fallback of a stack once its first family is gone. */\nfunction fallbackOf(stack: string): string | undefined {\n  const reading = readFamilyList(stack);\n  if (reading.kind !== \"families\" && reading.kind !== \"dynamic\") {\n    return undefined;\n  }\n  const rest = reading.parts.slice(1).map(entry => entry.part.raw.trim());\n  return rest.length === 0 ? undefined : rest.join(\", \");\n}\n\n/** What a stack with nothing after the font falls back to, in words. */\nconst BROWSER_FONT = \"the browser’s own font\";\n\n/**\n * Where the font a family key names (lower-cased, as CSS matches it) is\n * used in a token set.\n *\n * @param key - The family, lower-cased\n * @param tokens - The site's variables and Site text, or `undefined` unread\n * @param classes - The site's classes, where the text styles rows follow are\n * @returns The roles it is, the other font variables naming it first, and\n *   every variable whose places count towards it\n */\nexport function familyUses(\n  key: string,\n  tokens: SiteTokenSet | undefined,\n  classes?: readonly NamedClass[]\n): FamilyUses {\n  if (tokens === undefined) return { roles: [], variables: [], counted: [] };\n  // Row by row and in both modes: a heading row the others disagree with,\n  // or a variable's dark value, still loses the font when it goes.\n  const roles = ([\"body\", \"heading\"] as const).filter(role =>\n    fontRoleStacks(tokens, role, classes).some(\n      stack => firstFamily(stack) === key\n    )\n  );\n  const naming = resolveSiteTokens(tokens)\n    .tokens.filter(token => token.kind === \"fontFamily\")\n    .flatMap((token): FontVariableUse[] => {\n      // In either mode, and through a variable it reads, as it is drawn.\n      const stack = variableStacks(tokens, tokenIdentity(token)).find(\n        each => firstFamily(each) === key\n      );\n      if (stack === undefined) return [];\n      return [\n        {\n          identity: tokenIdentity(token),\n          label: tokenDisplayLabel(token),\n          fallback: fallbackOf(stack) ?? BROWSER_FONT,\n        },\n      ];\n    });\n  // A role's own variable is said as the role, not a second time, and its\n  // places still count: blocks may name it too.\n  const held = new Set(\n    roles.flatMap(role => fontRoleVariables(tokens, role, classes))\n  );\n  return {\n    roles,\n    variables: naming.filter(each => !held.has(each.identity)),\n    counted: naming.map(each => each.identity),\n  };\n}\n\n/** \"body\", \"headings\" or \"body and headings\", as a sentence names roles. */\nfunction rolesWords(roles: readonly FontRole[]): string {\n  return roles\n    .map(role => (role === \"body\" ? \"body\" : \"headings\"))\n    .join(\" and \");\n}\n\n/**\n * Why a font cannot be removed while it is the Body or Headings font, and\n * what to do first; `undefined` for a font that is neither.\n *\n * @param family - The font, as first written\n * @param roles - The roles it is\n * @returns The refusal, or `undefined`\n */\nexport function roleRefusal(\n  family: string,\n  roles: readonly FontRole[]\n): string | undefined {\n  if (roles.length === 0) return undefined;\n  const which = rolesWords(roles);\n  const another =\n    roles.length === 1 ? `another ${which} font` : `other ${which} fonts`;\n  return `${family} is your ${which} font. Choose ${another} first.`;\n}\n\n/**\n * What a toast says once a font is used for the roles chosen: \"Inter is now\n * your headings font\".\n *\n * @param family - The font, as first written\n * @param roles - The roles it now is\n * @returns The sentence\n */\nexport function nowYourFontWords(\n  family: string,\n  roles: readonly FontRole[]\n): string {\n  return `${family} is now your ${rolesWords(roles)} font`;\n}\n\n/**\n * What a font chosen for some roles leaves as it is, in words: the rows\n * following a text style keep drawing that style's font, as the Type tab\n * draws them. One sentence for each text style a role's rows follow,\n * \"Heading 1 and Heading 2 follow the text style “Display”, so a headings\n * font doesn’t change them.\"; none where no row follows one.\n *\n * @param tokens - The site's variables and Site text\n * @param roles - The roles a font is, or would be, chosen for\n * @param classes - The site's classes, where the text styles rows follow are\n * @returns The sentences, role by role\n */\nexport function followedStyleWords(\n  tokens: SiteTokenSet,\n  roles: readonly FontRole[],\n  classes: readonly NamedClass[] | undefined\n): string[] {\n  // The Type tab's own reading of which rows follow which style.\n  const views = siteTextRowViews(tokens, \"light\", classes);\n  const styles = new Map((classes ?? []).map(each => [each.id, each]));\n  return roles.flatMap(role => {\n    const rows = new Set<string>(fontRoleRows(role));\n    const byStyle = new Map<string, string[]>();\n    for (const view of views) {\n      if (view.follows === undefined || !rows.has(view.role)) continue;\n      if (!keepsItsFont(tokens, styles.get(view.follows.id), role)) continue;\n      const labels = byStyle.get(view.follows.name) ?? [];\n      byStyle.set(view.follows.name, [...labels, view.label]);\n    }\n    return [...byStyle].map(([style, labels]) => {\n      const one = labels.length === 1;\n      return `${listedWords(labels)} ${one ? \"follows\" : \"follow\"} the text style “${style}”, so a ${rolesWords([role])} font doesn’t change ${one ? \"it\" : \"them\"}.`;\n    });\n  });\n}\n\n/**\n * Whether a text style keeps its own font when `role`'s font is chosen: it\n * names one, and not one that reads the role's variable. A style naming no\n * font leaves the row's font to what it inherits, so nothing is promised.\n */\nfunction keepsItsFont(\n  tokens: SiteTokenSet,\n  style: NamedClass | undefined,\n  role: FontRole\n): boolean {\n  const font = style?.styles.base?.base?.fontFamily;\n  return font !== undefined && !fontReadsRole(tokens, font, role);\n}\n\n/** The role's own name, as Design's Type tab labels it (\"Body font\"). */\nexport function roleLabel(role: FontRole): string {\n  return FONT_ROLE_WORDS[role];\n}\n","/**\n * Where one of the site's fonts is used, as the Fonts screen draws it, and\n * the two things that follow from it: what Remove says of a font in use, and\n * the question a font that finishes adding asks.\n *\n * The rules are {@link font-uses}'s; how many places a font variable reaches\n * is the Variables tab's own usage read ({@link variable-usage-view}), so the\n * screen and the Colours rows say the same \"Used in N places\".\n *\n * @module font-uses-view\n */\nimport type {\n  FontFaceDef,\n  NamedClass,\n  SiteTextMap,\n  SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\nimport { toast } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { roleStack, type SiteFamily } from \"./font-library\";\nimport {\n  familyUses,\n  followedStyleWords,\n  roleLabel,\n  roleRefusal,\n  nowYourFontWords,\n  type FamilyUses,\n} from \"./font-uses\";\nimport {\n  roleFamilies,\n  roleSnapshot,\n  withFontRole,\n  withRoleSnapshot,\n  type FontRole,\n} from \"./site-font-roles-model\";\nimport { useReachTogether } from \"./variable-together-reads\";\nimport {\n  variableRemoval,\n  variableStatus,\n  type VariableReach,\n  type VariablesAccess,\n} from \"./variable-usage\";\nimport { useVariableUsage } from \"./variable-usage-view\";\n\n/** Where one family is used, and how many places its variables reach. */\nexport interface FamilyUsesHere {\n  readonly uses: FamilyUses;\n  /** The places its variables reach together; `undefined` until all are read. */\n  readonly reach: VariableReach | undefined;\n}\n\n/** A family nothing is known to use. */\nconst UNUSED: FamilyUsesHere = {\n  uses: { roles: [], variables: [], counted: [] },\n  reach: undefined,\n};\n\n/**\n * Where each of the site's families is used, by its key: the roles and font\n * variables naming it, and their places read through `usage` once for every\n * family together. No places are read without `usage`.\n */\nexport function useFamiliesUses(\n  families: readonly SiteFamily[],\n  tokens: SiteTokenSet | undefined,\n  usage: VariablesAccess | undefined,\n  classes?: readonly NamedClass[]\n): (key: string) => FamilyUsesHere {\n  const byKey = React.useMemo(\n    () =>\n      new Map(\n        families.map(family => [\n          family.key,\n          familyUses(family.key, tokens, classes),\n        ])\n      ),\n    [families, tokens, classes]\n  );\n  const identities = React.useMemo(\n    () => [...new Set([...byKey.values()].flatMap(uses => uses.counted))],\n    [byKey]\n  );\n  const reads = useVariableUsage(usage, identities);\n  const groups = React.useMemo(\n    () => [...byKey.values()].map(uses => uses.counted),\n    [byKey]\n  );\n  // A page naming two of a font's variables is one place.\n  const together = useReachTogether(usage, groups, reads.values);\n  return (key: string): FamilyUsesHere => {\n    const uses = byKey.get(key);\n    if (uses === undefined) return UNUSED;\n    // Every variable naming it counts, a role's own included.\n    const reach =\n      uses.counted.length === 0 ? undefined : together(uses.counted);\n    return { uses, reach };\n  };\n}\n\n/** The places a font's variables reach, when any do. */\nfunction placesUsed(reach: VariableReach | undefined): string | undefined {\n  return variableRemoval(reach) === \"in-use\"\n    ? variableStatus(reach)\n    : undefined;\n}\n\n/**\n * Where a font is used, in a family's details: \"Body font\", \"Headings font\"\n * and \"Used in N places\", each a link where the host can open it. Nothing\n * while nothing is known to use it.\n */\nexport function WhereUsed({\n  here,\n  onOpenRole,\n  onOpenTokens,\n}: {\n  here: FamilyUsesHere;\n  onOpenRole: ((role: FontRole) => void) | undefined;\n  onOpenTokens: (() => void) | undefined;\n}): React.JSX.Element | null {\n  const places = placesUsed(here.reach);\n  if (here.uses.roles.length === 0 && places === undefined) return null;\n  const label = \"Where it’s used\";\n  return (\n    <div className=\"nx-vars-editor__field\">\n      <span className=\"nx-vars-editor__label\" aria-hidden=\"true\">\n        {label}\n      </span>\n      <ul className=\"nx-fonts__uses\" aria-label={label}>\n        {here.uses.roles.map(role => (\n          <li key={role}>\n            <Linked\n              words={roleLabel(role)}\n              onOpen={\n                onOpenRole === undefined ? undefined : () => onOpenRole(role)\n              }\n            />\n          </li>\n        ))}\n        {places === undefined ? null : (\n          <li>\n            <Linked words={places} onOpen={onOpenTokens} />\n          </li>\n        )}\n      </ul>\n    </div>\n  );\n}\n\n/** Words that open what they name where the host can, and are said otherwise. */\nfunction Linked({\n  words,\n  onOpen,\n}: {\n  words: string;\n  onOpen: (() => void) | undefined;\n}): React.JSX.Element {\n  if (onOpen === undefined) return <>{words}</>;\n  return (\n    <button type=\"button\" className=\"nx-vars__link\" onClick={onOpen}>\n      {words}\n    </button>\n  );\n}\n\n/**\n * Why Remove does not go ahead for the Body or Headings font, in place of\n * its confirmation, with the way to choose another where the host has one.\n */\nexport function RoleRefusal({\n  family,\n  roles,\n  onOpenRole,\n  onBack,\n}: {\n  family: string;\n  roles: readonly FontRole[];\n  onOpenRole: ((role: FontRole) => void) | undefined;\n  onBack: () => void;\n}): React.JSX.Element {\n  const [first] = roles;\n  return (\n    <div\n      className=\"nx-vars-editor__confirm\"\n      role=\"group\"\n      aria-label={`${family} can’t be removed`}\n    >\n      <p>{roleRefusal(family, roles)}</p>\n      <div className=\"nx-vars-editor__actions\">\n        <button type=\"button\" className=\"nx-vars__link\" onClick={onBack}>\n          Keep\n        </button>\n        {onOpenRole === undefined || first === undefined ? null : (\n          <button\n            type=\"button\"\n            className=\"nx-vars__link\"\n            onClick={() => onOpenRole(first)}\n          >\n            Choose another font\n          </button>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/**\n * What a removal says of the font variables that lose the font: how many\n * places use them, then each variable with what its text falls back to.\n */\nexport function FallbackList({\n  family,\n  here,\n}: {\n  family: string;\n  here: FamilyUsesHere;\n}): React.JSX.Element {\n  const places = placesUsed(here.reach);\n  const reach = places === undefined ? \"\" : ` It’s ${lowerFirst(places)}.`;\n  return (\n    <>\n      <p>\n        Remove <strong>{family}</strong>?{reach} These variables will fall back:\n      </p>\n      <ul className=\"nx-fonts__fallbacks\">\n        {here.uses.variables.map(variable => (\n          <li key={variable.identity}>\n            {`${variable.label} falls back to “${variable.fallback}”`}\n          </li>\n        ))}\n      </ul>\n      <p>The files stay in your media library.</p>\n    </>\n  );\n}\n\n/** \"Used in 4 places\" as the middle of a sentence. */\nfunction lowerFirst(words: string): string {\n  return `${words.charAt(0).toLowerCase()}${words.slice(1)}`;\n}\n\n/** A font that finished adding, waiting for the author to say how to use it. */\nexport interface Asked {\n  readonly family: string;\n  /** The catalogue's category, when it came from there. */\n  readonly category?: string;\n}\n\n/** The answers to \"Use <font> for\", in their order, with the roles each sets. */\nconst ANSWERS: readonly (readonly [string, readonly FontRole[]])[] = [\n  [\"Body\", [\"body\"]],\n  [\"Headings\", [\"heading\"]],\n  [\"Both\", [\"body\", \"heading\"]],\n];\n\n/** What the question needs from the host: the site's variables and a writer. */\nexport interface UseForHost {\n  readonly tokens: SiteTokenSet | undefined;\n  /** The site's faces, `undefined` while unread. */\n  readonly faces: readonly FontFaceDef[] | undefined;\n  readonly codeFaces: readonly FontFaceDef[];\n  /** A role that may not change the design is never asked. */\n  readonly readOnly: boolean;\n  /** Absent, or while the variables are unread, nothing is asked. */\n  readonly onTokensChange: ((tokens: SiteTokenSet) => void) | undefined;\n  /** The Site text rows the site's code supplies, which a role change keeps. */\n  readonly suppliedText: SiteTextMap | undefined;\n  /** The site's classes, where the text styles rows follow are. */\n  readonly classes?: readonly NamedClass[] | undefined;\n  /**\n   * Told once a role is chosen, so the upload editor the question sits in\n   * closes: open, it holds the toast's Undo and the canvas out of reach.\n   */\n  readonly onChosen?: () => void;\n}\n\n/** A toast's description saying what a role choice left as it is, if anything. */\nfunction keptDescription(kept: readonly string[]): { description?: string } {\n  return kept.length === 0 ? {} : { description: kept.join(\" \") };\n}\n\n/**\n * The question a font that finished adding asks, and its answers. Body,\n * Headings or Both sets the site's font at once and says so in a toast whose\n * Undo puts back the roles as they were, onto the variables as they are by\n * then; Not now asks nothing more.\n */\nexport function useUseFor(host: UseForHost): {\n  readonly asked: Asked | null;\n  /**\n   * What a role chosen now leaves as it is: the rows following a text style,\n   * which keep its font. Said beside the question.\n   */\n  readonly kept: readonly string[];\n  readonly ask: (family: string, category?: string) => void;\n  readonly answer: (roles: readonly FontRole[] | null) => void;\n  /** Stop asking about a family once it is removed: it has no faces now. */\n  readonly dismiss: (family: string) => void;\n} {\n  const [asked, setAsked] = React.useState<Asked | null>(null);\n  // The toast whose Undo builds on this screen's copy of the variables. It\n  // goes when the screen does: past that, the copy no longer follows edits\n  // made elsewhere, and an Undo would write them away.\n  const offered = React.useRef<string | number | undefined>(undefined);\n  React.useEffect(\n    () => () => {\n      if (offered.current !== undefined) toast.dismiss(offered.current);\n    },\n    []\n  );\n  // The variables as last drawn, so an Undo pressed later builds on them.\n  const latest = React.useRef(host.tokens);\n  latest.current = host.tokens;\n  const onTokensChange = host.readOnly ? undefined : host.onTokensChange;\n  const ask = (family: string, category?: string): void => {\n    if (onTokensChange === undefined || host.tokens === undefined) return;\n    setAsked(category === undefined ? { family } : { family, category });\n  };\n  const answer = (roles: readonly FontRole[] | null): void => {\n    const now = latest.current;\n    setAsked(null);\n    if (roles === null || asked === null || now === undefined) return;\n    if (onTokensChange === undefined) return;\n    const stack =\n      roleFamilies(host.faces ?? [], host.codeFaces).find(\n        each => each.family.toLowerCase() === asked.family.toLowerCase()\n      )?.stack ?? roleStack(asked.family, asked.category);\n    // Each role as it was, its variable whole and its rows' fonts, so Undo\n    // puts back exactly these and nothing changed since.\n    const before = roles.map(role => roleSnapshot(now, role));\n    const set = roles.reduce(\n      (tokens, role) => withFontRole(tokens, role, stack, host.suppliedText),\n      now\n    );\n    onTokensChange(set);\n    host.onChosen?.();\n    offered.current = toast.success(nowYourFontWords(asked.family, roles), {\n      // Said again once chosen, of the roles chosen: the question is gone.\n      ...keptDescription(followedStyleWords(now, roles, host.classes)),\n      action: {\n        label: \"Undo\",\n        onClick: () => {\n          onTokensChange(\n            before.reduce(\n              (tokens, snapshot) =>\n                withRoleSnapshot(tokens, snapshot, host.suppliedText),\n              latest.current ?? set\n            )\n          );\n        },\n      },\n    });\n  };\n  const dismiss = (family: string): void => {\n    setAsked(current =>\n      current !== null && current.family.toLowerCase() === family.toLowerCase()\n        ? null\n        : current\n    );\n  };\n  const kept = React.useMemo(\n    () =>\n      asked === null || host.tokens === undefined\n        ? []\n        : followedStyleWords(host.tokens, [\"body\", \"heading\"], host.classes),\n    [asked, host.tokens, host.classes]\n  );\n  return { asked, kept, ask, answer, dismiss };\n}\n\n/**\n * \"Use <font> for: Body / Headings / Both / Not now\", in place, while a font\n * that finished adding waits for an answer, with what a choice leaves as it\n * is; nothing otherwise.\n */\nexport function UseForQuestion({\n  asked,\n  kept = [],\n  onAnswer,\n}: {\n  asked: Asked | null;\n  /** The rows following a text style, which keep its font, in words. */\n  kept?: readonly string[];\n  onAnswer: (roles: readonly FontRole[] | null) => void;\n}): React.JSX.Element | null {\n  const id = React.useId();\n  if (asked === null) return null;\n  const { family } = asked;\n  return (\n    <div className=\"nx-fonts-use\" role=\"group\" aria-labelledby={id}>\n      <p className=\"nx-fonts-use__ask\" id={id}>\n        {`Use ${family} for:`}\n      </p>\n      <div className=\"nx-fonts-use__answers\">\n        {ANSWERS.map(([words, roles]) => (\n          <button\n            key={words}\n            type=\"button\"\n            className=\"nx-vars__link\"\n            onClick={() => onAnswer(roles)}\n          >\n            {words}\n          </button>\n        ))}\n        <button\n          type=\"button\"\n          className=\"nx-vars__link\"\n          onClick={() => onAnswer(null)}\n        >\n          Not now\n        </button>\n      </div>\n      {kept.map(words => (\n        <p key={words} className=\"nx-fonts-use__kept\">\n          {words}\n        </p>\n      ))}\n    </div>\n  );\n}\n","/**\n * The Fonts tab of the Design panel: the fonts on this site, the site's font\n * variables, and the two ways a font gets here — from the Google Fonts\n * catalogue, downloaded to the site, or uploaded as a file.\n *\n * Drawn in the Variables tab's language: a search, small-caps groups, compact\n * rows, and each row's details in a 240px editor beside the panel.\n *\n * ## Every family is drawn in itself\n *\n * A row's \"Aa\" and each style in its details are set in the face they name,\n * so a family the site has no file for shows the fallback, and an author sees\n * the substitution rather than reading about it.\n *\n * ## It authors no variables\n *\n * The Variables tab creates and edits `fontFamily` variables. This tab lists\n * them with a note when one asks first for a font the site has no file for,\n * and sends the author to Variables to change it: one editor for one question.\n *\n * @module fonts-panel\n */\nimport { cssString, tokenDisplayLabel } from \"@nextlyhq/blocks-engine\";\nimport type {\n  FontFaceDef,\n  NamedClass,\n  SiteTextMap,\n  SiteTokenSet,\n} from \"@nextlyhq/blocks-engine\";\nimport {\n  Button,\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n  Input,\n  Popover,\n  PopoverAnchor,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@nextlyhq/ui\";\nimport { ArrowLeft, Plus, Search } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { EDITOR_WORDS } from \"../../editor-words\";\n\nimport { FontCatalogueView, type FontCatalogue } from \"./font-catalogue-view\";\nimport {\n  cutName,\n  familyDescription,\n  fontTokenRows,\n  siteFamilies,\n  SPECIMEN,\n  specimenText,\n  specimenWeight,\n  tokenNotes,\n  type FontTokenRow,\n  type SiteFamily,\n} from \"./font-library\";\nimport { FontUploadEditor, type FontFaceUpload } from \"./font-upload-editor\";\nimport {\n  FallbackList,\n  RoleRefusal,\n  UseForQuestion,\n  useFamiliesUses,\n  useUseFor,\n  WhereUsed,\n  type FamilyUsesHere,\n} from \"./font-uses-view\";\nimport { KeepOrRemove, Refusal, useRefusableWrite } from \"./panel-actions\";\nimport type { FontRole } from \"./site-font-roles-model\";\nimport type { VariablesAccess } from \"./variable-usage\";\n\nexport type { FontFaceUpload } from \"./font-upload-editor\";\nexport type {\n  CatalogueAddRequest,\n  CatalogueFamilyView,\n  FontCatalogue,\n} from \"./font-catalogue-view\";\n\nexport interface FontsPanelProps {\n  /**\n   * Every face the page emits, or `undefined` while the host has not read\n   * them. A real third state: a site may legitimately have no faces.\n   */\n  faces: readonly FontFaceDef[] | undefined;\n  /** The faces the site's code supplies, which this tab cannot remove. */\n  codeFaces?: readonly FontFaceDef[];\n  /** The site's variables, whose `fontFamily` members this lists. */\n  tokens: SiteTokenSet | undefined;\n  /** Why the faces are absent, when they are. */\n  absence?: \"pending\" | \"failed\";\n  /** Shown, never changed: no add, no remove. */\n  readOnly?: boolean;\n  /** Open the Variables tab, where a font variable is changed. */\n  onOpenTokens?: () => void;\n  /**\n   * Upload a font file. Resolves to a message when the host refused and to\n   * `undefined` when it stored one. Absent hides the upload.\n   */\n  onAddFace?: (request: FontFaceUpload) => Promise<string | undefined>;\n  /** What the file picker offers, as an `accept` attribute. */\n  acceptFiles?: string;\n  /**\n   * Remove a family's stored faces. Resolves to a message when refused.\n   * The files stay in the media library.\n   */\n  onRemoveFamily?: (family: SiteFamily) => Promise<string | undefined>;\n  /** The Google Fonts catalogue, when the host offers one. */\n  catalogue?: FontCatalogue;\n  /**\n   * How widely the site's variables are used, read for the font variables\n   * naming each font, so its details say how many places use it. Absent,\n   * no places are said.\n   *\n   * @experimental Settles with the Fonts screen.\n   */\n  usage?: VariablesAccess;\n  /**\n   * Open the Body or Headings font's picker, where a font's \"Body font\" or\n   * \"Headings font\" links. Absent, those are said, not linked.\n   *\n   * @experimental Settles with the Fonts screen.\n   */\n  onOpenRole?: (role: FontRole) => void;\n  /**\n   * Write the site's variables, so a font that finishes adding can be made\n   * the Body or Headings font at once. Absent, that is not asked.\n   *\n   * @experimental Settles with the Fonts screen.\n   */\n  onTokensChange?: (tokens: SiteTokenSet) => void;\n  /**\n   * The Site text rows the site's code supplies, which setting or taking\n   * back a role keeps.\n   *\n   * @experimental Settles with the Fonts screen.\n   */\n  suppliedText?: SiteTextMap;\n  /**\n   * The site's classes, where the text styles Site text rows follow are, so\n   * a font a row takes from one counts as the role's.\n   *\n   * @experimental Settles with the Fonts screen.\n   */\n  classes?: readonly NamedClass[];\n  /**\n   * What the last save of the site's variables said, when it failed. A role\n   * chosen here is saved with them, so its failure is said here too.\n   *\n   * @experimental Settles with the Fonts screen.\n   */\n  issue?: string;\n}\n\n/** What the Fonts screen adds to the list it draws: where it opens. */\nexport interface FontsScreenProps extends FontsPanelProps {\n  /**\n   * Close the screen, back to Design, where it opens over the Design panel.\n   * Absent where it is a page of its own, which has no \"back\".\n   */\n  onClose?: () => void;\n  /**\n   * The id of the heading that names the screen, where the page around it\n   * draws one. Absent, the screen draws its own \"Fonts\" title.\n   */\n  labelledBy?: string;\n}\n\n/**\n * The one Fonts screen: the site's fonts, adding and removing them, under a\n * \"Fonts\" heading. Every way in mounts this, so the builder (over its Design\n * panel, from Design → Type or a font picker's \"Manage fonts…\") and the\n * admin's own Fonts page show the same screen and behave the same; the host\n * hands each the same writers.\n *\n * @param props - The list's inputs, and where the screen opens\n * @returns The screen\n */\nexport function FontsScreen({\n  onClose,\n  labelledBy,\n  ...panel\n}: FontsScreenProps): React.JSX.Element {\n  const ownTitle = React.useId();\n  const back = React.useRef<HTMLButtonElement>(null);\n  // Opened over Design, the keyboard follows: the screen took the panel's\n  // place, so focus left behind would be on nothing.\n  const opensOver = onClose !== undefined && labelledBy === undefined;\n  React.useEffect(() => {\n    if (opensOver) back.current?.focus();\n  }, [opensOver]);\n  return (\n    <section\n      className=\"nx-fonts-screen\"\n      aria-labelledby={labelledBy ?? ownTitle}\n      data-fonts-screen=\"\"\n    >\n      {labelledBy === undefined ? (\n        <div className=\"nx-fonts-screen__head\">\n          {onClose === undefined ? null : (\n            <button\n              ref={back}\n              type=\"button\"\n              className=\"nx-vars__icon-button nx-fonts-screen__back\"\n              aria-label={`Back to ${EDITOR_WORDS.design}`}\n              title={`Back to ${EDITOR_WORDS.design}`}\n              onClick={onClose}\n            >\n              <ArrowLeft aria-hidden=\"true\" size={16} />\n            </button>\n          )}\n          <h2 className=\"nx-fonts-screen__title\" id={ownTitle}>\n            {EDITOR_WORDS.fonts}\n          </h2>\n        </div>\n      ) : null}\n      <FontsPanel {...panel} />\n    </section>\n  );\n}\n\n/**\n * The tab's place names inside a sentence, from the editor's one catalogue of\n * them, so a rename of the tab moves its sentences with it.\n */\nfunction words(): { fonts: string; variables: string } {\n  return {\n    fonts: EDITOR_WORDS.fonts.toLowerCase(),\n    variables: EDITOR_WORDS.variables.toLowerCase(),\n  };\n}\n\n/** What the tab shows: the site's fonts, or the catalogue in their place. */\ntype View = { kind: \"list\" } | { kind: \"catalogue\"; query: string };\n\nexport function FontsPanel({\n  faces,\n  codeFaces = [],\n  tokens,\n  absence = \"pending\",\n  readOnly = false,\n  onOpenTokens,\n  onAddFace,\n  acceptFiles,\n  onRemoveFamily,\n  catalogue,\n  usage,\n  onOpenRole,\n  onTokensChange,\n  suppliedText,\n  // The rest is what a host's studio adds: its text styles and a failed save.\n  ...studio\n}: FontsPanelProps): React.JSX.Element {\n  const [view, setView] = React.useState<View>({ kind: \"list\" });\n  // The upload editor, open or not: held here so choosing a role for a font\n  // just uploaded closes it.\n  const [uploading, setUploading] = React.useState(false);\n  const addButton = React.useRef<HTMLButtonElement>(null);\n  const families = React.useMemo(\n    () => (faces === undefined ? [] : siteFamilies(faces, codeFaces)),\n    [faces, codeFaces]\n  );\n  const usesOf = useFamiliesUses(families, tokens, usage, studio.classes);\n  // Asked once a font finishes adding, from the catalogue or a file.\n  const useFor = useUseFor({\n    tokens,\n    faces,\n    codeFaces,\n    readOnly,\n    onTokensChange,\n    suppliedText,\n    classes: studio.classes,\n    onChosen: () => setUploading(false),\n  });\n  const question = (\n    <UseForQuestion\n      asked={useFor.asked}\n      kept={useFor.kept}\n      onAnswer={useFor.answer}\n    />\n  );\n\n  if (faces === undefined) return <Unread absence={absence} />;\n\n  if (view.kind === \"catalogue\" && catalogue !== undefined) {\n    return (\n      <>\n        {question}\n        <SaveIssue issue={studio.issue} />\n        <FontCatalogueView\n          catalogue={catalogue}\n          initialQuery={view.query}\n          onSite={families}\n          onAdded={useFor.ask}\n          onBack={() => backToList(setView, addButton)}\n        />\n      </>\n    );\n  }\n\n  return (\n    <FontsList\n      families={families}\n      question={question}\n      uploading={uploading}\n      setUploading={setUploading}\n      faces={faces}\n      tokens={tokens}\n      readOnly={readOnly}\n      issue={studio.issue}\n      addButton={addButton}\n      onOpenTokens={onOpenTokens}\n      onOpenRole={onOpenRole}\n      usesOf={usesOf}\n      onRemoveFamily={removalDismissing(onRemoveFamily, useFor.dismiss)}\n      onBrowse={browseOf(readOnly, catalogue, setView)}\n      upload={uploadAsking(readOnly, onAddFace, acceptFiles, useFor.ask)}\n    />\n  );\n}\n\n/**\n * The host's removal, which stops asking how to use the family once it is\n * removed: answering then would make a font with no faces the site's own.\n */\nfunction removalDismissing(\n  onRemoveFamily: FontsPanelProps[\"onRemoveFamily\"],\n  dismiss: (family: string) => void\n): FontsPanelProps[\"onRemoveFamily\"] {\n  if (onRemoveFamily === undefined) return undefined;\n  return async family => {\n    const refusal = await onRemoveFamily(family);\n    if (refusal === undefined) dismiss(family.family);\n    return refusal;\n  };\n}\n\n/** Back from the catalogue, with focus where the catalogue was opened. */\nfunction backToList(\n  setView: (view: View) => void,\n  addButton: React.RefObject<HTMLButtonElement | null>\n): void {\n  setView({ kind: \"list\" });\n  requestAnimationFrame(() => addButton.current?.focus());\n}\n\n/** The way to the catalogue, or none for a role without the grant. */\nfunction browseOf(\n  readOnly: boolean,\n  catalogue: FontCatalogue | undefined,\n  setView: (view: View) => void\n): ((query?: string) => void) | undefined {\n  if (readOnly || catalogue === undefined) return undefined;\n  return (query = \"\") => setView({ kind: \"catalogue\", query });\n}\n\n/** The list's upload, which asks how to use a font once its file is stored. */\ntype ListUpload = {\n  onAddFace: (request: FontFaceUpload) => Promise<string | undefined>;\n  acceptFiles: string | undefined;\n};\n\n/**\n * The upload the list offers, or none for a role without the grant or a host\n * without an upload: the host's own, asking how to use the font once stored.\n */\nfunction uploadAsking(\n  readOnly: boolean,\n  onAddFace: FontsPanelProps[\"onAddFace\"],\n  acceptFiles: string | undefined,\n  ask: (family: string) => void\n): ListUpload | undefined {\n  if (readOnly || onAddFace === undefined) return undefined;\n  return {\n    onAddFace: async request => {\n      const refusal = await onAddFace(request);\n      if (refusal === undefined) ask(request.family);\n      return refusal;\n    },\n    acceptFiles,\n  };\n}\n\n/** The site's fonts and font variables: the tab's list view. */\nfunction FontsList({\n  families,\n  faces,\n  tokens,\n  readOnly,\n  issue,\n  addButton,\n  onOpenTokens,\n  onOpenRole,\n  usesOf,\n  question,\n  uploading,\n  setUploading,\n  onRemoveFamily,\n  onBrowse,\n  upload,\n}: {\n  families: readonly SiteFamily[];\n  /**\n   * \"Use <font> for\", once a font finishes adding: in the upload editor\n   * while it is open, which holds the rest of the screen inert, else at the\n   * top of the list.\n   */\n  question: React.ReactNode;\n  /** Whether the upload editor is open, held by the panel. */\n  uploading: boolean;\n  setUploading: (open: boolean) => void;\n  faces: readonly FontFaceDef[];\n  tokens: SiteTokenSet | undefined;\n  readOnly: boolean;\n  issue: string | undefined;\n  addButton: React.RefObject<HTMLButtonElement | null>;\n  onOpenTokens: (() => void) | undefined;\n  onOpenRole: FontsPanelProps[\"onOpenRole\"];\n  /** Where each family is used, by its key. */\n  usesOf: (key: string) => FamilyUsesHere;\n  onRemoveFamily: FontsPanelProps[\"onRemoveFamily\"];\n  onBrowse: ((query?: string) => void) | undefined;\n  upload: ListUpload | undefined;\n}): React.JSX.Element {\n  const [query, setQuery] = React.useState(\"\");\n  const search = React.useRef<HTMLInputElement>(null);\n  const needle = query.trim().toLowerCase();\n  const shownFamilies = families.filter(family =>\n    family.family.toLowerCase().includes(needle)\n  );\n  const rows = matchingRows(tokens, faces, needle);\n  const { fonts } = words();\n  const openUpload =\n    upload === undefined ? undefined : () => setUploading(true);\n\n  return (\n    <div\n      className=\"nx-vars nx-fonts\"\n      data-read-only={readOnly ? \"\" : undefined}\n    >\n      <div className=\"nx-vars__search\">\n        <Search aria-hidden=\"true\" size={16} />\n        <Input\n          ref={search}\n          type=\"search\"\n          aria-label={`Search ${fonts}`}\n          placeholder={`Search ${fonts}`}\n          value={query}\n          onChange={event => setQuery(event.target.value)}\n        />\n      </div>\n      <div className=\"nx-vars__body\">\n        {uploading ? null : question}\n        <ListNotes readOnly={readOnly} issue={issue} />\n        <Popover open={uploading} onOpenChange={setUploading} modal>\n          <section className=\"nx-vars__group\" aria-labelledby=\"nx-fonts-site\">\n            <PopoverAnchor asChild>\n              <div className=\"nx-vars__group-head\">\n                <h3 className=\"nx-vars__group-name\" id=\"nx-fonts-site\">\n                  On this site\n                </h3>\n                <AddFontMenu\n                  trigger={addButton}\n                  onBrowse={onBrowse}\n                  onUpload={openUpload}\n                />\n              </div>\n            </PopoverAnchor>\n            <SiteFamilies\n              families={shownFamilies}\n              searching={needle !== \"\"}\n              query={query.trim()}\n              readOnly={readOnly}\n              usesOf={usesOf}\n              opens={{ onOpenRole, onOpenTokens }}\n              onRemoveFamily={onRemoveFamily}\n              onRemoved={() => search.current?.focus()}\n              onBrowse={onBrowse}\n              onUpload={openUpload}\n            />\n          </section>\n          <UploadEditor upload={upload} question={question} />\n        </Popover>\n        <FontVariables\n          rows={rows}\n          faces={faces}\n          searching={needle !== \"\"}\n          onOpenTokens={onOpenTokens}\n        />\n        <p className=\"nx-vars__note nx-fonts__privacy\">\n          Fonts are stored on your site. Visitors&rsquo; browsers never contact\n          Google.\n        </p>\n      </div>\n    </div>\n  );\n}\n\n/**\n * The upload editor beside the panel, with \"Use <font> for\" at its top once\n * a file is stored; nothing for a host without an upload.\n */\nfunction UploadEditor({\n  upload,\n  question,\n}: {\n  upload: ListUpload | undefined;\n  question: React.ReactNode;\n}): React.JSX.Element | null {\n  if (upload === undefined) return null;\n  return (\n    <PopoverContent\n      side=\"right\"\n      align=\"start\"\n      sideOffset={12}\n      className=\"nx-vars-editor\"\n      aria-label=\"Upload a font file\"\n    >\n      {question}\n      <FontUploadEditor\n        onAddFace={upload.onAddFace}\n        acceptFiles={upload.acceptFiles}\n      />\n    </PopoverContent>\n  );\n}\n\n/**\n * What a role without the grant is told above the list, and a save of the\n * site's variables that failed, as the Variables tab says it.\n */\nfunction ListNotes({\n  readOnly,\n  issue,\n}: {\n  readOnly: boolean;\n  issue: string | undefined;\n}): React.JSX.Element {\n  return (\n    <>\n      {readOnly ? (\n        <p className=\"nx-vars__note\">\n          {`You can view the site’s ${words().fonts} but not change them.`}\n        </p>\n      ) : null}\n      <SaveIssue issue={issue} />\n    </>\n  );\n}\n\n/**\n * A save of the site's variables that failed, as the Variables tab says it:\n * in the list and in the catalogue, wherever a role was chosen.\n */\nfunction SaveIssue({\n  issue,\n}: {\n  issue: string | undefined;\n}): React.JSX.Element | null {\n  if (issue === undefined) return null;\n  return (\n    <p className=\"nx-vars__alert\" role=\"alert\">\n      {issue}\n    </p>\n  );\n}\n\n/** What shows while the fonts are being read, or after a read failed. */\nfunction Unread({\n  absence,\n}: {\n  absence: \"pending\" | \"failed\";\n}): React.JSX.Element {\n  const failed = absence === \"failed\";\n  const { fonts } = words();\n  return (\n    <div className=\"nx-vars nx-fonts\">\n      <div className=\"nx-vars__body\">\n        <p\n          className={failed ? \"nx-vars__alert\" : \"nx-vars__note\"}\n          role={failed ? \"alert\" : \"status\"}\n        >\n          {failed\n            ? `This site’s ${fonts} could not be read, so none can be shown or changed. Reload to try again.`\n            : `Reading this site’s ${fonts}…`}\n        </p>\n      </div>\n    </div>\n  );\n}\n\n/**\n * The group's \"+\": a menu of the ways a font can be added, or nothing where\n * there is none.\n */\nfunction AddFontMenu({\n  trigger,\n  onBrowse,\n  onUpload,\n}: {\n  trigger: React.RefObject<HTMLButtonElement | null>;\n  /** Open the catalogue, on no search. */\n  onBrowse: ((query?: string) => void) | undefined;\n  onUpload: (() => void) | undefined;\n}): React.JSX.Element | null {\n  // Set while a choice opens something else, so the menu does not hand focus\n  // back to its button and close what was just opened.\n  const handingOff = React.useRef(false);\n  if (onBrowse === undefined && onUpload === undefined) return null;\n  const choose = (action: () => void) => () => {\n    handingOff.current = true;\n    action();\n  };\n  return (\n    <DropdownMenu modal={false}>\n      <DropdownMenuTrigger asChild>\n        <button\n          ref={trigger}\n          type=\"button\"\n          className=\"nx-vars__icon-button nx-vars__add\"\n          aria-label=\"Add a font\"\n          title=\"Add a font\"\n        >\n          <Plus aria-hidden=\"true\" size={14} />\n        </button>\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align=\"end\"\n        className=\"nx-vars__menu\"\n        onCloseAutoFocus={event => {\n          if (handingOff.current) event.preventDefault();\n          handingOff.current = false;\n        }}\n      >\n        {onBrowse === undefined ? null : (\n          <DropdownMenuItem onSelect={choose(() => onBrowse())}>\n            From Google Fonts\n          </DropdownMenuItem>\n        )}\n        {onUpload === undefined ? null : (\n          <DropdownMenuItem onSelect={choose(onUpload)}>\n            Upload a font file\n          </DropdownMenuItem>\n        )}\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\n/** The site's families as rows, or what to say when there are none. */\nfunction SiteFamilies({\n  families,\n  searching,\n  query,\n  readOnly,\n  usesOf,\n  opens,\n  onRemoveFamily,\n  onRemoved,\n  onBrowse,\n  onUpload,\n}: {\n  families: readonly SiteFamily[];\n  searching: boolean;\n  query: string;\n  readOnly: boolean;\n  usesOf: (key: string) => FamilyUsesHere;\n  opens: UsesOpeners;\n  onRemoveFamily: FontsPanelProps[\"onRemoveFamily\"];\n  onRemoved: () => void;\n  onBrowse: ((query?: string) => void) | undefined;\n  onUpload: (() => void) | undefined;\n}): React.JSX.Element {\n  const [openKey, setOpenKey] = React.useState<string | null>(null);\n  const { fonts } = words();\n  if (families.length === 0 && searching) {\n    return (\n      <p className=\"nx-vars__empty\">\n        {`No ${fonts} on this site match this search.`}\n        {onBrowse === undefined ? null : (\n          <button\n            type=\"button\"\n            className=\"nx-vars__link\"\n            onClick={() => onBrowse(query)}\n          >\n            {`Search Google Fonts for “${query}”`}\n          </button>\n        )}\n      </p>\n    );\n  }\n  if (families.length === 0) {\n    return (\n      <p className=\"nx-vars__empty\">\n        {`No ${fonts} on this site yet, so pages use the system font.`}\n        {onBrowse === undefined ? null : (\n          <button\n            type=\"button\"\n            className=\"nx-vars__link\"\n            onClick={() => onBrowse()}\n          >\n            Add from Google Fonts\n          </button>\n        )}\n        {onUpload === undefined ? null : (\n          <button type=\"button\" className=\"nx-vars__link\" onClick={onUpload}>\n            Upload a font file\n          </button>\n        )}\n      </p>\n    );\n  }\n  return (\n    <ul className=\"nx-vars__list\">\n      {families.map(family => (\n        <FamilyRow\n          key={family.key}\n          family={family}\n          open={openKey === family.key}\n          onOpenChange={open => setOpenKey(open ? family.key : null)}\n          here={usesOf(family.key)}\n          opens={opens}\n          onRemove={\n            readOnly || !family.removable || onRemoveFamily === undefined\n              ? undefined\n              : async () => {\n                  const refusal = await onRemoveFamily(family);\n                  if (refusal === undefined) {\n                    setOpenKey(null);\n                    onRemoved();\n                  }\n                  return refusal;\n                }\n          }\n        />\n      ))}\n    </ul>\n  );\n}\n\n/** A face's own descriptors, so a specimen draws in that exact face. */\nfunction faceStyle(face: FontFaceDef): React.CSSProperties {\n  const weight = specimenWeight(face.weight);\n  return {\n    // Escaped as the site sheet writes the same name, or a legal family with\n    // a quote in it would draw in the fallback.\n    fontFamily: `\"${cssString(face.family)}\"`,\n    ...(weight === undefined ? {} : { fontWeight: weight }),\n    ...(face.style === undefined ? {} : { fontStyle: face.style }),\n  };\n}\n\n/** One family: a row that opens its details beside the panel. */\nfunction FamilyRow({\n  family,\n  open,\n  onOpenChange,\n  here,\n  opens,\n  onRemove,\n}: {\n  family: SiteFamily;\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  here: FamilyUsesHere;\n  opens: UsesOpeners;\n  onRemove: (() => Promise<string | undefined>) | undefined;\n}): React.JSX.Element {\n  return (\n    <li>\n      <Popover open={open} onOpenChange={onOpenChange} modal>\n        <PopoverTrigger asChild>\n          <button\n            type=\"button\"\n            className=\"nx-vars__row\"\n            aria-label={familyDescription(family)}\n            data-font-family={family.key}\n          >\n            <span\n              className=\"nx-vars__specimen nx-fonts__lead\"\n              aria-hidden=\"true\"\n              style={{ fontFamily: `\"${cssString(family.family)}\"` }}\n            >\n              Aa\n            </span>\n            {/* Cut with an ellipsis when long, so the name is whole on hover. */}\n            <span className=\"nx-vars__name\" title={family.family}>\n              {family.family}\n            </span>\n            <span className=\"nx-vars__chip\" aria-hidden=\"true\">\n              {family.styles}\n            </span>\n          </button>\n        </PopoverTrigger>\n        <PopoverContent\n          side=\"right\"\n          align=\"start\"\n          sideOffset={12}\n          className=\"nx-vars-editor\"\n          aria-label={family.family}\n        >\n          <FamilyDetails\n            family={family}\n            here={here}\n            opens={opens}\n            onRemove={onRemove}\n          />\n        </PopoverContent>\n      </Popover>\n    </li>\n  );\n}\n\n/** Where a family came from, as its details say it. */\nfunction sourceLine(family: SiteFamily): string {\n  if (family.origin === \"code\") return \"Set in your site’s code\";\n  if (family.origin === \"upload\") return \"Uploaded\";\n  return family.licence === undefined\n    ? \"From Google Fonts\"\n    : `From Google Fonts · ${family.licence}`;\n}\n\n/** A family's details: its name and sample in itself, each style, its source. */\nfunction FamilyDetails({\n  family,\n  here,\n  opens,\n  onRemove,\n}: {\n  family: SiteFamily;\n  here: FamilyUsesHere;\n  opens: UsesOpeners;\n  onRemove: (() => Promise<string | undefined>) | undefined;\n}): React.JSX.Element {\n  const first = family.faces[0];\n  const cuts = new Map<string, FontFaceDef>();\n  for (const face of family.faces) {\n    const name = cutName(face.weight, face.style);\n    if (!cuts.has(name)) cuts.set(name, face);\n  }\n  return (\n    <div className=\"nx-vars-editor__body\">\n      <div className=\"nx-fonts__heading\">\n        <span\n          className=\"nx-fonts__title\"\n          style={first === undefined ? undefined : faceStyle(first)}\n        >\n          {family.family}\n        </span>\n        <span\n          className=\"nx-fonts__sample\"\n          style={first === undefined ? undefined : faceStyle(first)}\n        >\n          {first === undefined ? SPECIMEN : specimenText(first)}\n        </span>\n      </div>\n      <div className=\"nx-vars-editor__field\">\n        <span className=\"nx-vars-editor__label\">Styles</span>\n        <ul className=\"nx-fonts__styles\">\n          {[...cuts].map(([name, face]) => (\n            <li key={name} style={faceStyle(face)}>\n              {name}\n            </li>\n          ))}\n        </ul>\n      </div>\n      <p className=\"nx-fonts__meta\">{sourceLine(family)}</p>\n      <WhereUsed\n        here={here}\n        onOpenRole={opens.onOpenRole}\n        onOpenTokens={opens.onOpenTokens}\n      />\n      {onRemove === undefined ? null : (\n        <RemoveFamily\n          family={family.family}\n          keepsCode={family.origin === \"code\"}\n          here={here}\n          onOpenRole={opens.onOpenRole}\n          onRemove={onRemove}\n        />\n      )}\n    </div>\n  );\n}\n\n/** Where a family's details send the author: a role's picker, the variables. */\ninterface UsesOpeners {\n  readonly onOpenRole: FontsPanelProps[\"onOpenRole\"];\n  readonly onOpenTokens: (() => void) | undefined;\n}\n\n/**\n * Remove, behind a confirmation naming what happens to the text and files:\n * refused for the Body or Headings font, which must be changed first, and\n * naming each font variable that loses the font with what it falls back to.\n */\nfunction RemoveFamily({\n  family,\n  keepsCode,\n  here,\n  onOpenRole,\n  onRemove,\n}: {\n  family: string;\n  /** Whether the site's code supplies some of its styles, which stay. */\n  keepsCode: boolean;\n  here: FamilyUsesHere;\n  onOpenRole: FontsPanelProps[\"onOpenRole\"];\n  onRemove: () => Promise<string | undefined>;\n}): React.JSX.Element {\n  const [confirming, setConfirming] = React.useState(false);\n  const { busy, refusal, run } = useRefusableWrite();\n  // The styles the site's code supplies stay, so the family keeps its uses.\n  const refused = !keepsCode && here.uses.roles.length > 0;\n  return (\n    <>\n      <Refusal refusal={refusal} />\n      {confirming && refused ? (\n        <RoleRefusal\n          family={family}\n          roles={here.uses.roles}\n          onOpenRole={onOpenRole}\n          onBack={() => setConfirming(false)}\n        />\n      ) : confirming ? (\n        <div\n          className=\"nx-vars-editor__confirm\"\n          role=\"group\"\n          aria-label={`Remove ${family}`}\n        >\n          {keepsCode ? (\n            <p>\n              Remove the <strong>{family}</strong> styles you added here? Styles\n              from your site&rsquo;s code stay. The files stay in your media\n              library.\n            </p>\n          ) : here.uses.variables.length > 0 ? (\n            <FallbackList family={family} here={here} />\n          ) : (\n            <p>\n              Remove <strong>{family}</strong>? Text set in it falls back to the\n              next font in its list. The files stay in your media library.\n            </p>\n          )}\n          <KeepOrRemove\n            busy={busy}\n            onKeep={() => setConfirming(false)}\n            onRemove={() => void run(onRemove)}\n            removeLabel={`Remove ${family}`}\n          />\n        </div>\n      ) : (\n        <div className=\"nx-vars-editor__actions\">\n          <Button\n            type=\"button\"\n            variant=\"ghost\"\n            size=\"sm\"\n            className=\"nx-vars-editor__button nx-vars-editor__remove\"\n            onClick={() => setConfirming(true)}\n          >\n            Remove\n          </Button>\n        </div>\n      )}\n    </>\n  );\n}\n\n/** The font variables whose plain or code name holds the search. */\nfunction matchingRows(\n  tokens: SiteTokenSet | undefined,\n  faces: readonly FontFaceDef[],\n  needle: string\n): FontTokenRow[] {\n  return fontTokenRows(tokens, faces).filter(\n    row =>\n      labelOf(row).toLowerCase().includes(needle) ||\n      row.token.name.toLowerCase().includes(needle)\n  );\n}\n\n/** A font variable's plain name. */\nfunction labelOf(row: FontTokenRow): string {\n  // The name Variables shows for it, never the code name.\n  return tokenDisplayLabel(row.token);\n}\n\n/**\n * The site's font variables, each with a note when its first font has no\n * file; nothing while a search matches none of them.\n */\nfunction FontVariables({\n  rows,\n  faces,\n  searching,\n  onOpenTokens,\n}: {\n  rows: readonly FontTokenRow[];\n  faces: readonly FontFaceDef[];\n  searching: boolean;\n  onOpenTokens: (() => void) | undefined;\n}): React.JSX.Element | null {\n  if (searching && rows.length === 0) return null;\n  return (\n    <section className=\"nx-vars__group\" aria-labelledby=\"nx-fonts-variables\">\n      <div className=\"nx-vars__group-head\">\n        <h3 className=\"nx-vars__group-name\" id=\"nx-fonts-variables\">\n          {`Font ${words().variables}`}\n        </h3>\n      </div>\n      {rows.length === 0 ? (\n        <p className=\"nx-vars__empty\">\n          {`No font ${words().variables} yet. ${EDITOR_WORDS.variables} creates them.`}\n        </p>\n      ) : (\n        <ul className=\"nx-vars__list\">\n          {rows.map(row => (\n            <VariableRow\n              key={row.token.id ?? row.token.name}\n              row={row}\n              faces={faces}\n              onOpenTokens={onOpenTokens}\n            />\n          ))}\n        </ul>\n      )}\n    </section>\n  );\n}\n\n/** One font variable: drawn in its whole stack, with its first family named. */\nfunction VariableRow({\n  row,\n  onOpenTokens,\n}: {\n  row: FontTokenRow;\n  faces: readonly FontFaceDef[];\n  onOpenTokens: (() => void) | undefined;\n}): React.JSX.Element {\n  const label = labelOf(row);\n  const first = row.reading.firstChoice?.family ?? row.token.values.light;\n  const notes = tokenNotes(row);\n  const named = row.darkReading !== undefined;\n  const content = (\n    <>\n      {/* The whole stack, so what is drawn is what the page draws. */}\n      <span\n        className=\"nx-vars__specimen nx-fonts__lead\"\n        aria-hidden=\"true\"\n        style={{ fontFamily: row.token.values.light }}\n      >\n        Aa\n      </span>\n      <span className=\"nx-vars__name\" title={label} aria-hidden=\"true\">\n        {label}\n      </span>\n      <span className=\"nx-vars__chip\" aria-hidden=\"true\">\n        {first}\n      </span>\n      {/* The row's name, in one element: the name it shows, then the stack\n          its chip begins. Text rather than an aria-label, which must hold\n          every drawn word, the \"Aa\" included; one element, so no browser\n          puts a space before its comma. */}\n      <span className=\"nx-sr-only\">{`${label}, ${row.token.values.light}`}</span>\n    </>\n  );\n  return (\n    <li>\n      {onOpenTokens === undefined ? (\n        <div className=\"nx-vars__row nx-fonts__static-row\">{content}</div>\n      ) : (\n        <button type=\"button\" className=\"nx-vars__row\" onClick={onOpenTokens}>\n          {content}\n        </button>\n      )}\n      {notes.map(note => (\n        <p className=\"nx-fonts__attention\" key={note.mode}>\n          {named ? `In ${note.mode} mode: ${note.text}` : note.text}\n          {onOpenTokens === undefined ? null : (\n            <>\n              {\" \"}\n              <button\n                type=\"button\"\n                className=\"nx-vars__link\"\n                onClick={onOpenTokens}\n              >\n                Edit this variable\n              </button>\n            </>\n          )}\n        </p>\n      ))}\n    </li>\n  );\n}\n","\"use client\";\n\n/**\n * Which values of a selection each placement of a new component may change:\n * the picker a \"Turn into component\" form shows.\n *\n * It lists every block in the selection with the props a placement could set\n * (text, rich text, an image, a link, a choice) and a switch to let a\n * placement hide the block. Each pick is asked of the engine's\n * `planExposeProperty`, against the selection as the component it will\n * become, so a prop the engine would refuse is refused here first, in words:\n * a non-content prop inside an area locked to its content (`contentOnly`),\n * or a prop no placement could set. What it hands back are the nominations\n * the save and convert planners take, by node id in the page.\n *\n * Nothing is picked to start with: a component whose placements change\n * nothing is the ordinary case, and every pick is a decision the author\n * makes, as Figma and Webflow ask it.\n *\n * @module exposure-picker\n */\nimport {\n  COMPONENT_INSTANCE_TYPE,\n  exposureTypeForProp,\n  findNode,\n  planExposeProperty,\n  type BlockDocument,\n  type BlockNode,\n  type ComponentDocument,\n  type ExposedProperty,\n  type ExposedPropertyType,\n  type ExposureEditProblem,\n  type RequestedProperty,\n  type SlotDefaultSource,\n} from \"@nextlyhq/blocks-engine\";\nimport { Checkbox, Input, Label } from \"@nextlyhq/ui\";\nimport * as React from \"react\";\n\nimport { propLabel } from \"../inspector/inspector\";\nimport { layerLabel } from \"../panels/layers/layers\";\n\n/** Why a pick was refused, as an author reads it. */\nconst REFUSAL: Readonly<Record<ExposureEditProblem, string>> = {\n  \"not-a-component\": \"This selection can’t be read as a component.\",\n  \"unknown-exposure\": \"That value is no longer in this selection.\",\n  \"unknown-node\": \"That block is no longer in this selection.\",\n  \"unknown-prop\": \"That block no longer has this value.\",\n  \"not-exposable\": \"Pages have no control for this value.\",\n  \"content-only\":\n    \"This block is in an area locked to its content, and this isn’t content, so pages couldn’t change it.\",\n  \"invalid-label\": \"Give the field a name.\",\n  \"invalid-exposure\": \"This value can’t be changed per use.\",\n  \"exceeds-limits\": \"This selection is too large to offer more values.\",\n};\n\n/** One value a placement could be let change. */\ninterface Candidate {\n  readonly key: string;\n  readonly nodeId: string;\n  /** The prop, or `undefined` for the block's visibility. */\n  readonly prop: string | undefined;\n  readonly name: string;\n  readonly type: ExposedPropertyType;\n}\n\n/** One block of the selection, with its candidates, at its depth. */\ninterface BlockRow {\n  readonly node: BlockNode;\n  readonly depth: number;\n  readonly candidates: readonly Candidate[];\n}\n\nexport interface ExposurePickerProps {\n  /** The page the selection is in. */\n  readonly document: BlockDocument;\n  /** The selected roots, in the page's order. */\n  readonly selectedIds: readonly string[];\n  /** The block definitions: each prop's type and role, each slot's lock. */\n  readonly definitions: SlotDefaultSource;\n  /** The values picked so far. */\n  readonly value: readonly RequestedProperty[];\n  readonly onChange: (next: readonly RequestedProperty[]) => void;\n  /** Disables every control, while the form is being sent. */\n  readonly disabled?: boolean;\n}\n\n/**\n * The picker. Controlled: the form holds what is picked, so a refused save\n * keeps the author's picks for the next try.\n *\n * @experimental Settles when the composition API ships.\n */\nexport function ExposurePicker({\n  document,\n  selectedIds,\n  definitions,\n  value,\n  onChange,\n  disabled = false,\n}: ExposurePickerProps): React.JSX.Element {\n  const preview = React.useMemo(\n    () => selectionAsComponent(document, selectedIds),\n    [document, selectedIds]\n  );\n  const rows = React.useMemo(\n    () => blockRows(preview.nodes, definitions),\n    [preview, definitions]\n  );\n  // What each candidate would be refused on its own, so it is dimmed with the\n  // reason before it is pressed.\n  const refused = React.useMemo(() => {\n    const reasons = new Map<string, string>();\n    for (const row of rows) {\n      for (const candidate of row.candidates) {\n        const tried = expose(preview, [], candidate, definitions);\n        if (\"reason\" in tried) reasons.set(candidate.key, tried.reason);\n      }\n    }\n    return reasons;\n  }, [rows, preview, definitions]);\n  const [problem, setProblem] = React.useState<{\n    key: string;\n    reason: string;\n  } | null>(null);\n  const hintId = React.useId();\n\n  const picked = (candidate: Candidate) =>\n    value.find(\n      entry =>\n        entry.nodeId === candidate.nodeId &&\n        (candidate.prop === undefined\n          ? entry.type === \"visibility\"\n          : entry.type !== \"visibility\" && entry.propPath === candidate.prop)\n    );\n\n  const toggle = (candidate: Candidate, on: boolean) => {\n    setProblem(null);\n    const held = picked(candidate);\n    if (!on) {\n      onChange(value.filter(entry => entry !== held));\n      return;\n    }\n    if (held !== undefined) return;\n    const tried = expose(preview, value, candidate, definitions);\n    if (\"reason\" in tried) {\n      setProblem({ key: candidate.key, reason: tried.reason });\n      return;\n    }\n    onChange([...value, tried.property]);\n  };\n\n  const rename = (entry: RequestedProperty, label: string) => {\n    onChange(value.map(held => (held === entry ? { ...held, label } : held)));\n  };\n\n  const offered = rows.filter(row => row.candidates.length > 0);\n\n  return (\n    <fieldset\n      className=\"nx-expose-picker\"\n      aria-describedby={hintId}\n      disabled={disabled}\n    >\n      <legend className=\"nx-expose-picker__legend\">\n        What each use can change\n      </legend>\n      <p id={hintId} className=\"nx-expose-picker__hint\">\n        {offered.length === 0\n          ? \"Nothing in this selection can change from one use to another, so the component looks the same everywhere it is used.\"\n          : \"Anything left unticked looks the same everywhere it is used. You can change this later in the component’s own view.\"}\n      </p>\n      {offered.length === 0 ? null : (\n        <ul className=\"nx-expose-picker__blocks\">\n          {offered.map(row => (\n            <li\n              key={row.node.id}\n              className=\"nx-expose-picker__block\"\n              style={{ \"--nx-expose-depth\": row.depth } as React.CSSProperties}\n            >\n              <span className=\"nx-expose-picker__block-name\">\n                {layerLabel(row.node)}\n              </span>\n              <ul className=\"nx-expose-picker__values\">\n                {row.candidates.map(candidate => (\n                  <CandidateRow\n                    key={candidate.key}\n                    candidate={candidate}\n                    entry={picked(candidate)}\n                    unavailable={refused.get(candidate.key)}\n                    problem={\n                      problem?.key === candidate.key\n                        ? problem.reason\n                        : undefined\n                    }\n                    blockName={layerLabel(row.node)}\n                    onToggle={on => toggle(candidate, on)}\n                    onRename={rename}\n                  />\n                ))}\n              </ul>\n            </li>\n          ))}\n        </ul>\n      )}\n    </fieldset>\n  );\n}\n\n/** One value: its switch, its type, and its name once picked. */\nfunction CandidateRow({\n  candidate,\n  entry,\n  unavailable,\n  problem,\n  blockName,\n  onToggle,\n  onRename,\n}: {\n  candidate: Candidate;\n  entry: RequestedProperty | undefined;\n  unavailable: string | undefined;\n  problem: string | undefined;\n  blockName: string;\n  onToggle: (on: boolean) => void;\n  onRename: (entry: RequestedProperty, label: string) => void;\n}): React.JSX.Element {\n  const boxId = React.useId();\n  const reasonId = React.useId();\n  const said = problem ?? (entry === undefined ? unavailable : undefined);\n  return (\n    <li\n      className=\"nx-expose-picker__value\"\n      data-picked={entry === undefined ? undefined : \"\"}\n    >\n      <div className=\"nx-expose-picker__row\">\n        <Checkbox\n          id={boxId}\n          checked={entry !== undefined}\n          disabled={entry === undefined && unavailable !== undefined}\n          aria-describedby={said === undefined ? undefined : reasonId}\n          onCheckedChange={checked => onToggle(checked === true)}\n        />\n        <Label htmlFor={boxId} className=\"nx-expose-picker__name\">\n          {candidate.name}\n        </Label>\n      </div>\n      {entry === undefined ? null : (\n        <Input\n          className=\"nx-expose-picker__label\"\n          value={entry.label}\n          aria-label={`Name pages see for ${candidate.name} of ${blockName}`}\n          onChange={event => onRename(entry, event.target.value)}\n        />\n      )}\n      {said === undefined ? null : (\n        <p\n          id={reasonId}\n          className=\"nx-expose-picker__reason\"\n          role={problem === undefined ? undefined : \"alert\"}\n        >\n          {said}\n        </p>\n      )}\n    </li>\n  );\n}\n\n/**\n * The selection as the component it will become, under the page's own node\n * ids: the roots in the page's order, so the picks name nodes the planners\n * can find in the page.\n */\nexport function selectionAsComponent(\n  document: BlockDocument,\n  selectedIds: readonly string[]\n): ComponentDocument {\n  const nodes = selectedIds\n    .map(id => findNode(document.nodes, id))\n    .filter((node): node is BlockNode => node !== undefined);\n  return {\n    formatVersion: document.formatVersion,\n    kind: \"component\",\n    nodes,\n  };\n}\n\n/** Every block of the forest, depth first, with what it offers. */\nfunction blockRows(\n  nodes: readonly BlockNode[],\n  definitions: SlotDefaultSource\n): BlockRow[] {\n  const rows: BlockRow[] = [];\n  const visit = (node: BlockNode, depth: number) => {\n    rows.push({ node, depth, candidates: candidatesOf(node, definitions) });\n    for (const children of Object.values(node.slots ?? {})) {\n      for (const child of children) visit(child, depth + 1);\n    }\n  };\n  for (const node of nodes) visit(node, 0);\n  return rows;\n}\n\n/**\n * A block's candidate values: each prop of a type a placement could set, in\n * the order the block declares them, then its visibility. A placement inside\n * the selection offers none of its own here: its component's fields are that\n * component's to expose.\n */\nfunction candidatesOf(\n  node: BlockNode,\n  definitions: SlotDefaultSource\n): Candidate[] {\n  if (node.type === COMPONENT_INSTANCE_TYPE) return [];\n  const props = definitions.get(node.type)?.props ?? {};\n  const candidates: Candidate[] = [];\n  for (const [name, schema] of Object.entries(props)) {\n    const type = exposureTypeForProp(schema);\n    if (type === undefined || schema === undefined) continue;\n    candidates.push({\n      key: `${node.id}\\u0000${name}`,\n      nodeId: node.id,\n      prop: name,\n      // The block's own word for the property (\"HTML tag\"), not its name.\n      name: propLabel(name, schema),\n      type,\n    });\n  }\n  candidates.push({\n    key: `${node.id}\\u0000`,\n    nodeId: node.id,\n    prop: undefined,\n    name: \"Can be hidden\",\n    type: \"visibility\",\n  });\n  return candidates;\n}\n\n/**\n * One more pick, asked of the engine against the picks already made: the\n * nomination with the id it minted, or why it was refused.\n */\nfunction expose(\n  preview: ComponentDocument,\n  picked: readonly RequestedProperty[],\n  candidate: Candidate,\n  definitions: SlotDefaultSource\n): { property: RequestedProperty } | { reason: string } {\n  const draft: ComponentDocument = {\n    ...preview,\n    exposed: picked.map(toExposed),\n  };\n  const label = candidate.prop === undefined ? \"Hidden\" : candidate.name;\n  const result = planExposeProperty(\n    draft,\n    candidate.prop === undefined\n      ? { nodeId: candidate.nodeId, visibility: true, label }\n      : { nodeId: candidate.nodeId, propPath: candidate.prop, label },\n    { definitions }\n  );\n  if (\"problem\" in result) return { reason: REFUSAL[result.problem] };\n  const added = (result.document.exposed ?? []).find(\n    entry => entry.id === result.id\n  );\n  if (added === undefined) return { reason: REFUSAL[\"invalid-exposure\"] };\n  return { property: toRequested(added) };\n}\n\n/** A nomination as the envelope stores it, for the next pick to be judged with. */\nfunction toExposed(entry: RequestedProperty): ExposedProperty {\n  return {\n    id: entry.id,\n    label: entry.label,\n    nodeId: entry.nodeId,\n    propPath: entry.propPath,\n    type: entry.type,\n    ...(entry.options === undefined ? {} : { options: entry.options }),\n  };\n}\n\n/** An envelope entry as the planners take a nomination. */\nfunction toRequested(entry: ExposedProperty): RequestedProperty {\n  return {\n    id: entry.id,\n    label: entry.label,\n    nodeId: entry.nodeId,\n    propPath: entry.propPath,\n    type: entry.type,\n    ...(entry.options === undefined ? {} : { options: entry.options }),\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 * 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 * 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 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 * Walking the Page checks list while fixing, as the bar under the checks'\n * count shows it: \"Check 2 of 5\", with Previous and Next.\n *\n * The findings change under the author as they fix things, so the place is\n * kept by the finding's key, with its index as last seen. A finding that\n * goes is \"Fixed\", and Next then goes to the one that took its place, so the\n * walk carries on from where the author was rather than starting again.\n * Nothing here moves the author: the bar only says where they are until they\n * press Previous or Next.\n *\n * Pure, so the walk is tested without a bar.\n *\n * @module page-checks/fix-walk\n */\nimport type { PageFinding } from \"./page-checks\";\n\n/** The finding the author went to, and its index when they last saw it. */\nexport interface FixPlace {\n  readonly key: string;\n  readonly index: number;\n}\n\n/** Where the walk stands now. */\nexport type FixStep =\n  | {\n      readonly kind: \"at\";\n      readonly finding: PageFinding;\n      readonly index: number;\n      readonly total: number;\n    }\n  /** The finding is gone; `next` is the index Next goes to. */\n  | { readonly kind: \"fixed\"; readonly next: number; readonly total: number }\n  | { readonly kind: \"clear\" };\n\n/** Where the author is among the findings as they stand now. */\nexport function fixStep(\n  findings: readonly PageFinding[],\n  place: FixPlace\n): FixStep {\n  if (findings.length === 0) return { kind: \"clear\" };\n  const index = findings.findIndex(each => each.key === place.key);\n  const finding = findings[index];\n  if (finding !== undefined) {\n    return { kind: \"at\", finding, index, total: findings.length };\n  }\n  return {\n    kind: \"fixed\",\n    next: Math.min(Math.max(place.index, 0), findings.length),\n    total: findings.length,\n  };\n}\n\n/** The finding Previous (`-1`) or Next (`1`) goes to, if there is one. */\nexport function fixNeighbour(\n  findings: readonly PageFinding[],\n  step: FixStep,\n  direction: -1 | 1\n): PageFinding | undefined {\n  if (step.kind === \"clear\") return undefined;\n  if (step.kind === \"at\") return findings[step.index + direction];\n  return findings[direction === 1 ? step.next : step.next - 1];\n}\n\n/** What the bar says of where the author is. */\nexport function fixStepWords(step: FixStep): string {\n  if (step.kind === \"clear\") return \"All clear\";\n  if (step.kind === \"at\") {\n    return `Check ${String(step.index + 1)} of ${String(step.total)}`;\n  }\n  return `Fixed · ${String(step.total)} to go`;\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","\"use client\";\n\n/**\n * The Page checks list: the page's findings by group, each saying what is\n * wrong, on which block, why it matters and what to do, with a press taking\n * the author to the fix. Drawn from the groups handed in, which the editor\n * derives from the draft on screen, so an item fixed while the list is open\n * leaves it at once.\n *\n * The list is the same wherever it opens from; the editor's entry point\n * holds it (`page-checks-chip`).\n *\n * @module page-checks/page-checks-list\n */\nimport { ChevronRight, ExternalLink } from \"lucide-react\";\nimport * as React from \"react\";\n\nimport type { PageCheckGroupView, PageFinding } from \"./page-checks\";\n\nexport interface PageChecksListProps {\n  /** The groups to draw, in order, from `pageCheckGroups`. */\n  readonly groups: readonly PageCheckGroupView[];\n  /** The checks that couldn't run. */\n  readonly notRun: readonly string[];\n  /** Take the author to an item's fix. */\n  readonly onFix: (finding: PageFinding) => void;\n}\n\n/** How many items need attention, in words. */\nfunction attentionWords(count: number): string {\n  if (count === 0) return \"Nothing needs attention\";\n  return count === 1\n    ? \"1 item needs attention\"\n    : `${String(count)} items need attention`;\n}\n\n/** Up, Down, Home and End move between the list's items, as one list. */\nfunction moveBetweenItems(event: React.KeyboardEvent<HTMLElement>): void {\n  const items = [\n    ...event.currentTarget.querySelectorAll<HTMLElement>(\n      \".nx-page-checks__item\"\n    ),\n  ];\n  const at = items.indexOf(event.target as HTMLElement);\n  if (at === -1) return;\n  const to: Partial<Record<string, number>> = {\n    ArrowDown: Math.min(at + 1, items.length - 1),\n    ArrowUp: Math.max(at - 1, 0),\n    Home: 0,\n    End: items.length - 1,\n  };\n  const next = to[event.key];\n  if (next === undefined) return;\n  event.preventDefault();\n  items[next]?.focus();\n}\n\n/**\n * One item: the whole row takes the author to the fix.\n *\n * Named with every word it draws, in the order drawn: what is wrong, the\n * block, why it matters and what to do, so a speech-input user who says\n * what they see reaches it (WCAG 2.5.3). Each drawn part is a word apart\n * from the next, by a space between them that the layout doesn't draw.\n */\nfunction FindingItem({\n  finding,\n  onFix,\n}: {\n  finding: PageFinding;\n  onFix: (finding: PageFinding) => void;\n}): React.JSX.Element {\n  const what =\n    finding.block === undefined\n      ? finding.what\n      : `${finding.what}: ${finding.block}`;\n  const detail = (\n    <span className=\"nx-page-checks__detail\">\n      <span className=\"nx-page-checks__why\">{finding.why}</span>{\" \"}\n      <span className=\"nx-page-checks__todo\">{finding.todo}</span>\n    </span>\n  );\n  const said = `${finding.why} ${finding.todo}`;\n  // A fix outside this editor (a header's block, changed in its own\n  // editor): the item is a link there, opened beside the page, as the\n  // data meter offers it.\n  if (finding.opens !== undefined) {\n    return (\n      <li>\n        <a\n          className=\"nx-page-checks__item\"\n          href={finding.opens.href}\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n          // Where it goes last, in parentheses: said, and not drawn.\n          aria-label={`${what}. ${finding.opens.text}. ${said} (${finding.opens.name})`}\n        >\n          <span className=\"nx-page-checks__what\">\n            <span className=\"nx-page-checks__title\">{finding.what}</span>{\" \"}\n            <span className=\"nx-page-checks__block\">{finding.opens.text}</span>\n          </span>{\" \"}\n          {detail}\n          <ExternalLink aria-hidden=\"true\" className=\"nx-page-checks__go\" />\n        </a>\n      </li>\n    );\n  }\n  return (\n    <li>\n      <button\n        type=\"button\"\n        className=\"nx-page-checks__item\"\n        aria-label={`${what}. ${said}`}\n        onClick={() => onFix(finding)}\n      >\n        <span className=\"nx-page-checks__what\">\n          <span className=\"nx-page-checks__title\">{finding.what}</span>\n          {finding.block === undefined ? null : (\n            <>\n              {\" \"}\n              <span className=\"nx-page-checks__block\">{finding.block}</span>\n            </>\n          )}\n        </span>{\" \"}\n        {detail}\n        <ChevronRight aria-hidden=\"true\" className=\"nx-page-checks__go\" />\n      </button>\n    </li>\n  );\n}\n\n/** One group: its name and count, then its items or that none were found. */\nfunction GroupSection({\n  group,\n  onFix,\n}: {\n  group: PageCheckGroupView;\n  onFix: (finding: PageFinding) => void;\n}): React.JSX.Element {\n  // Named by the group alone; its heading also carries the count.\n  return (\n    <section className=\"nx-page-checks__group\" aria-label={group.label}>\n      <h3 className=\"nx-page-checks__group-name\">\n        {group.label}\n        <span\n          className=\"nx-page-checks__group-count\"\n          data-empty={group.findings.length === 0 ? \"\" : undefined}\n        >\n          {group.findings.length}\n        </span>\n      </h3>\n      {/* Its standing lines first, which are read whatever is found. */}\n      {group.notes.map(note => (\n        <p key={note} className=\"nx-page-checks__note\">\n          {note}\n        </p>\n      ))}\n      {group.findings.length === 0 ? (\n        <p className=\"nx-page-checks__none\">Nothing found.</p>\n      ) : (\n        <ul className=\"nx-page-checks__items\">\n          {group.findings.map(finding => (\n            <FindingItem key={finding.key} finding={finding} onFix={onFix} />\n          ))}\n        </ul>\n      )}\n    </section>\n  );\n}\n\n/** The list, with its heading, its groups and the note under them. */\nexport function PageChecksList({\n  groups,\n  notRun,\n  onFix,\n}: PageChecksListProps): React.JSX.Element {\n  const count = groups.reduce((sum, group) => sum + group.findings.length, 0);\n  return (\n    <div className=\"nx-page-checks\">\n      <div className=\"nx-page-checks__head\">\n        <h2 className=\"nx-page-checks__heading\">Page checks</h2>\n        <p className=\"nx-page-checks__count\">{attentionWords(count)}</p>\n      </div>\n      <div className=\"nx-page-checks__groups\" onKeyDown={moveBetweenItems}>\n        {groups.map(group => (\n          <GroupSection key={group.group} group={group} onFix={onFix} />\n        ))}\n      </div>\n      <div className=\"nx-page-checks__foot\">\n        {notRun.length === 0 ? null : (\n          <p className=\"nx-page-checks__not-run\">\n            {notRun.length === 1\n              ? \"1 check couldn’t run, so this list may be missing problems.\"\n              : `${String(notRun.length)} checks couldn’t run, so this list may be missing problems.`}\n          </p>\n        )}\n        <p className=\"nx-page-checks__note\">\n          Automatic checks catch common problems. They don’t replace an\n          accessibility review.\n        </p>\n      </div>\n    </div>\n  );\n}\n","\"use client\";\n\n/**\n * Where Page checks open: a quiet count beside Publish, \"2 checks\", or\n * \"Checks\" with a tick at none, which opens the list. Pressing an item\n * selects its block, brings it into view and opens the setting that fixes\n * it; the list then gives way to a slim bar under the count, \"Check 2 of 5\",\n * with Previous, Next and All checks, so the inspector where the fix opens\n * stays uncovered.\n *\n * The checks run over the draft the editor holds, unsaved changes included,\n * each time it changes, so the count, the list and the bar follow the\n * author's fixes as they type. Nothing here touches Save or Publish: a\n * finding is never a reason to hold either back.\n *\n * @module page-checks/page-checks-chip\n */\nimport { Popover, PopoverContent, PopoverTrigger } from \"@nextlyhq/ui\";\nimport {\n  Check,\n  ChevronLeft,\n  ChevronRight,\n  ExternalLink,\n  X,\n} from \"lucide-react\";\nimport * as React from \"react\";\n\nimport { revealNode } from \"../canvas/reveal-node\";\nimport type { EditorState } from \"../editor-state\";\nimport { ShowInspectorContext } from \"../shell/show-inspector\";\n\nimport { CORE_PAGE_CHECKS } from \"./core-checks\";\nimport {\n  fixNeighbour,\n  fixStep,\n  fixStepWords,\n  type FixPlace,\n  type FixStep,\n} from \"./fix-walk\";\nimport {\n  pageCheckGroups,\n  runPageChecks,\n  type CheckedPage,\n  type PageCheck,\n  type PageFinding,\n} from \"./page-checks\";\nimport { PageChecksList } from \"./page-checks-list\";\n\n/** How long \"All clear\" stays before the bar goes, in ms. */\nconst ALL_CLEAR_FOR = 4000;\n\nexport interface PageChecksChipProps {\n  /** The draft the checks judge, and the selection a fix moves. */\n  readonly editor: Pick<EditorState, \"document\" | \"select\" | \"askSetting\">;\n  /** The canvas, where a fixed block is brought into view. */\n  readonly canvas: HTMLElement | null;\n  /** The checks to run; the builder's own by default. */\n  readonly checks?: readonly PageCheck[];\n  /** The page's block definitions; the registry by default. */\n  readonly blocks?: CheckedPage[\"blocks\"];\n  /** The header and footer drawn around the page, read with it. */\n  readonly regions?: CheckedPage[\"regions\"];\n  /** The definitions the page's component placements are drawn from. */\n  readonly definitions?: CheckedPage[\"definitions\"];\n  /** The site's variables, which colours written as one are read through. */\n  readonly tokens?: CheckedPage[\"tokens\"];\n  /** The site's shared styles, its edits to block types' looks among them. */\n  readonly namedClasses?: CheckedPage[\"namedClasses\"];\n  /** Opens the document's settings at a tab, for a fix found there. */\n  readonly onOpenSettingsTab?: (tab: string) => void;\n  /** What the editor knows of the page beyond its document (`page-facts`). */\n  readonly facts?: CheckedPage[\"facts\"];\n}\n\n/** Whether the list, the bar, or neither is open. */\ntype Opened = \"closed\" | \"list\" | \"bar\";\n\n/** The count's words: \"2 checks\", or \"Checks\" beside a tick at none. */\nfunction chipWords(count: number): string {\n  if (count === 0) return \"Checks\";\n  return `${String(count)} ${count === 1 ? \"check\" : \"checks\"}`;\n}\n\n/**\n * The walk through the list while fixing: where the author is, kept by the\n * finding's key and its index as last seen, and \"All clear\" shown for a\n * moment once nothing is left before the bar closes.\n */\nfunction useFixWalk(\n  findings: readonly PageFinding[],\n  opened: Opened,\n  close: () => void\n): {\n  readonly step: FixStep | undefined;\n  readonly goTo: (finding: PageFinding) => void;\n} {\n  const [place, setPlace] = React.useState<FixPlace | undefined>(undefined);\n  const step = place === undefined ? undefined : fixStep(findings, place);\n  const at = step?.kind === \"at\" ? step.index : undefined;\n  // The index follows the finding while it moves, so a fix of the finding\n  // itself leaves Next where the author was.\n  React.useEffect(() => {\n    if (at !== undefined) {\n      setPlace(current =>\n        current === undefined || current.index === at\n          ? current\n          : { ...current, index: at }\n      );\n    }\n  }, [at]);\n  const clear = opened === \"bar\" && step?.kind === \"clear\";\n  const closeLater = React.useRef(close);\n  closeLater.current = close;\n  React.useEffect(() => {\n    if (!clear) return;\n    const timer = setTimeout(() => closeLater.current(), ALL_CLEAR_FOR);\n    return () => clearTimeout(timer);\n  }, [clear]);\n  const goTo = React.useCallback(\n    (finding: PageFinding) =>\n      setPlace({\n        key: finding.key,\n        index: findings.findIndex(each => each.key === finding.key),\n      }),\n    [findings]\n  );\n  return { step, goTo };\n}\n\n/** The slim bar under the count while the author fixes things. */\nfunction FixBar({\n  step,\n  onStep,\n  onAll,\n  onClose,\n}: {\n  step: FixStep;\n  /** Go to the finding before (`-1`) or after (`1`), where there is one. */\n  onStep: ((direction: -1 | 1) => void) | undefined;\n  onAll: () => void;\n  onClose: () => void;\n}): React.JSX.Element {\n  const clear = step.kind === \"clear\";\n  return (\n    <div\n      role=\"group\"\n      aria-label=\"Fixing page checks\"\n      className=\"nx-page-checks-bar\"\n      data-clear={clear ? \"\" : undefined}\n      // Escape from inside the bar closes it; elsewhere it stays the\n      // editor's key.\n      onKeyDown={event => {\n        if (event.key === \"Escape\") onClose();\n      }}\n    >\n      <span className=\"nx-page-checks-bar__where\" role=\"status\">\n        {clear ? (\n          <Check aria-hidden=\"true\" className=\"nx-page-checks-bar__tick\" />\n        ) : null}\n        {fixStepWords(step)}\n      </span>\n      {/* A check whose fix is in another editor (a header's block): the\n          way there, beside where the author is, as the list offers it. */}\n      {step.kind === \"at\" && step.finding.opens !== undefined ? (\n        <a\n          className=\"nx-page-checks-bar__open\"\n          href={step.finding.opens.href}\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n          // The words it draws first, as said; what is wrong after them, and\n          // where it goes last, in parentheses: said, and not drawn.\n          aria-label={`${step.finding.opens.text}: ${step.finding.what} (${step.finding.opens.name})`}\n        >\n          {step.finding.opens.text}\n          <ExternalLink aria-hidden=\"true\" />\n        </a>\n      ) : null}\n      {clear ? null : (\n        <>\n          <span className=\"nx-page-checks-bar__steps\">\n            <button\n              type=\"button\"\n              className=\"nx-page-checks-bar__step\"\n              aria-label=\"Previous check\"\n              title=\"Previous check\"\n              disabled={onStep === undefined || !canStep(step, -1)}\n              onClick={() => onStep?.(-1)}\n            >\n              <ChevronLeft aria-hidden=\"true\" />\n            </button>\n            <button\n              type=\"button\"\n              className=\"nx-page-checks-bar__step\"\n              aria-label=\"Next check\"\n              title=\"Next check\"\n              disabled={onStep === undefined || !canStep(step, 1)}\n              onClick={() => onStep?.(1)}\n            >\n              <ChevronRight aria-hidden=\"true\" />\n            </button>\n          </span>\n          <button\n            type=\"button\"\n            className=\"nx-page-checks-bar__all\"\n            onClick={onAll}\n          >\n            All checks\n          </button>\n        </>\n      )}\n      <button\n        type=\"button\"\n        className=\"nx-page-checks-bar__step\"\n        aria-label=\"Close\"\n        title=\"Close\"\n        onClick={onClose}\n      >\n        <X aria-hidden=\"true\" />\n      </button>\n    </div>\n  );\n}\n\n/** Whether Previous (`-1`) or Next (`1`) has somewhere to go. */\nfunction canStep(step: FixStep, direction: -1 | 1): boolean {\n  if (step.kind === \"clear\") return false;\n  if (step.kind === \"at\") {\n    const to = step.index + direction;\n    return to >= 0 && to < step.total;\n  }\n  return direction === 1 ? step.next < step.total : step.next > 0;\n}\n\n/** The count beside Publish, the list it opens, and the bar while fixing. */\nexport function PageChecksChip({\n  editor,\n  canvas,\n  checks = CORE_PAGE_CHECKS,\n  blocks,\n  regions,\n  definitions,\n  tokens,\n  namedClasses,\n  onOpenSettingsTab,\n  facts,\n}: PageChecksChipProps): React.JSX.Element {\n  // Checked a moment after each edit rather than inside it. The count only\n  // informs, and Save and Publish read nothing of it, while running every\n  // check over a large page delayed each keystroke reaching the canvas.\n  // Every edit is still checked; keys typed in quick succession together.\n  const document = React.useDeferredValue(editor.document);\n  const report = React.useMemo(\n    () =>\n      runPageChecks(\n        {\n          document,\n          ...(blocks === undefined ? {} : { blocks }),\n          ...(regions === undefined ? {} : { regions }),\n          ...(definitions === undefined ? {} : { definitions }),\n          ...(tokens === undefined ? {} : { tokens }),\n          ...(namedClasses === undefined ? {} : { namedClasses }),\n          ...(facts === undefined ? {} : { facts }),\n        },\n        checks\n      ),\n    [\n      document,\n      blocks,\n      regions,\n      definitions,\n      tokens,\n      namedClasses,\n      facts,\n      checks,\n    ]\n  );\n  const { findings } = report;\n  const [opened, setOpened] = React.useState<Opened>(\"closed\");\n  const close = React.useCallback(() => setOpened(\"closed\"), []);\n  const { step, goTo } = useFixWalk(findings, opened, close);\n  // The fix opens in the inspector, shown first where the author hid it.\n  const showInspector = React.useContext(ShowInspectorContext);\n  // Going to a fix from the list moves the cursor to the inspector: the list\n  // closing then must not take it back to the count. Set only on leaving the\n  // list, so Previous and Next leave no stale mark for its next close.\n  const fixing = React.useRef(false);\n  const fix = (finding: PageFinding): void => {\n    const { nodeId, fix: setting, settingsTab } = finding;\n    // A fix in another editor selects nothing here: the bar offers the way\n    // there, and no block of the page is left looking like the problem.\n    if (finding.opens !== undefined) editor.select(null);\n    // A fix in the document's settings opens them at its tab.\n    else if (settingsTab !== undefined) onOpenSettingsTab?.(settingsTab);\n    else if (nodeId !== undefined) {\n      if (setting === undefined) editor.select(nodeId);\n      else {\n        showInspector?.();\n        editor.askSetting?.(nodeId, setting);\n      }\n      if (canvas !== null) revealNode(canvas, nodeId);\n    }\n    goTo(finding);\n    if (opened === \"list\") fixing.current = true;\n    setOpened(\"bar\");\n  };\n  const count = findings.length;\n  return (\n    <span className=\"nx-page-checks-anchor\">\n      <Popover\n        open={opened === \"list\"}\n        onOpenChange={open => setOpened(open ? \"list\" : \"closed\")}\n      >\n        <PopoverTrigger asChild>\n          <button\n            type=\"button\"\n            className=\"nx-page-checks-chip\"\n            data-count={count}\n            aria-label={\n              count === 0 ? \"Checks: nothing needs attention\" : undefined\n            }\n          >\n            {count === 0 ? (\n              <Check aria-hidden=\"true\" className=\"nx-page-checks-chip__tick\" />\n            ) : (\n              <span aria-hidden=\"true\" className=\"nx-page-checks-chip__dot\" />\n            )}\n            {chipWords(count)}\n          </button>\n        </PopoverTrigger>\n        <PopoverContent\n          align=\"end\"\n          aria-label=\"Page checks\"\n          // Within the screen whatever its size, the list scrolling between\n          // its heading and its note.\n          className=\"nx-page-checks-popover flex max-h-[var(--radix-popover-content-available-height)] w-[min(420px,calc(100vw-2rem))] flex-col p-0\"\n          onCloseAutoFocus={event => {\n            if (fixing.current) event.preventDefault();\n            fixing.current = false;\n          }}\n        >\n          <PageChecksList\n            groups={pageCheckGroups(findings, checks, report.notes)}\n            notRun={report.notRun}\n            onFix={fix}\n          />\n        </PopoverContent>\n      </Popover>\n      {opened === \"bar\" && step !== undefined ? (\n        <FixBar\n          step={step}\n          onStep={direction => {\n            const to = fixNeighbour(findings, step, direction);\n            if (to !== undefined) fix(to);\n          }}\n          onAll={() => setOpened(\"list\")}\n          onClose={close}\n        />\n      ) : null}\n    </span>\n  );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmHA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAS,aAAa,OAA4B;CAChD,IAAI,CAAC,OAAO,SAAS,MAAM,KAAK,KAAK,MAAM,SAAS,GAClD,MAAM,IAAI,mBACR,oBAAoB,OAAO,MAAM,KAAK,EAAE,mEAE1C;CAEF,IAAI,CAAC,OAAO,SAAS,MAAM,OAAO,CAAC,KAAK,CAAC,OAAO,SAAS,MAAM,OAAO,CAAC,GACrE,MAAM,IAAI,mBACR,sBAAsB,OAAO,MAAM,OAAO,CAAC,EAAE,IAAI,OAAO,MAAM,OAAO,CAAC,EAAE,yDAE1E;AAEJ;;;;;;;;;;;;;;;AAmCA,SAAgB,mBACd,WACA,OACA,OACO;CACP,aAAa;EAAE,QAAQ;EAAW;CAAM,CAAC;CACzC,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,KAAK,CAAC,OAAO,SAAS,MAAM,GAAG,GAC5D,MAAM,IAAI,mBACR,qBAAqB,OAAO,MAAM,IAAI,EAAE,IAAI,OAAO,MAAM,GAAG,EAAE,mDAEhE;CAEF,OAAO;EACL,GAAG,UAAU,IAAI,MAAM,OAAO;EAC9B,GAAG,UAAU,IAAI,MAAM,MAAM;CAC/B;AACF;;AAGA,SAAgB,YAAY,OAAc,OAA6B;CACrE,aAAa,KAAK;CAClB,OAAO;EACL,GAAG,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