@elytracms/studio 0.0.104 → 0.0.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/components/app-views/module.d.ts +4 -0
  2. package/dist/components/app-views/module.js.map +1 -1
  3. package/dist/components/builder/builder-store.d.ts +19 -3
  4. package/dist/components/builder/builder-store.js +24 -13
  5. package/dist/components/builder/builder-store.js.map +1 -1
  6. package/dist/components/builder/clipboard-actions.js +6 -5
  7. package/dist/components/builder/clipboard-actions.js.map +1 -1
  8. package/dist/components/builder/composition-field-editor.js +4 -2
  9. package/dist/components/builder/composition-field-editor.js.map +1 -1
  10. package/dist/components/cms/document-diff-view.js +43 -7
  11. package/dist/components/cms/document-diff-view.js.map +1 -1
  12. package/dist/components/cms/duplicate-document.js +5 -5
  13. package/dist/components/cms/duplicate-document.js.map +1 -1
  14. package/dist/components/cms/rich-text/editor.d.ts +7 -1
  15. package/dist/components/cms/rich-text/editor.js +9 -4
  16. package/dist/components/cms/rich-text/editor.js.map +1 -1
  17. package/dist/components/cms/rich-text/embed-identity.d.ts +36 -0
  18. package/dist/components/cms/rich-text/embed-identity.js +114 -0
  19. package/dist/components/cms/rich-text/embed-identity.js.map +1 -0
  20. package/dist/components/cms/rich-text/extensions.d.ts +7 -1
  21. package/dist/components/cms/rich-text/extensions.js +7 -1
  22. package/dist/components/cms/rich-text/extensions.js.map +1 -1
  23. package/dist/components/cms/rich-text/insert.d.ts +10 -5
  24. package/dist/components/cms/rich-text/insert.js +10 -12
  25. package/dist/components/cms/rich-text/insert.js.map +1 -1
  26. package/dist/components/components/component-preview.d.ts +0 -2
  27. package/dist/components/components/component-preview.js +0 -4
  28. package/dist/components/components/component-preview.js.map +1 -1
  29. package/dist/components/components/transfer-dialog.js +3 -1
  30. package/dist/components/components/transfer-dialog.js.map +1 -1
  31. package/dist/components/components/transfer.d.ts +12 -8
  32. package/dist/components/components/transfer.js +16 -15
  33. package/dist/components/components/transfer.js.map +1 -1
  34. package/dist/components/redirects/redirects-schema.d.ts +31 -0
  35. package/dist/components/redirects/redirects-schema.js +12 -6
  36. package/dist/components/redirects/redirects-schema.js.map +1 -1
  37. package/dist/lib/ai/translate-document.d.ts +4 -1
  38. package/dist/lib/ai/translate-document.js +87 -47
  39. package/dist/lib/ai/translate-document.js.map +1 -1
  40. package/dist/lib/ai/writer-form.d.ts +48 -5
  41. package/dist/lib/ai/writer-form.js +119 -64
  42. package/dist/lib/ai/writer-form.js.map +1 -1
  43. package/dist/lib/engine-version.d.ts +1 -1
  44. package/dist/lib/engine-version.js +1 -1
  45. package/dist/lib/engine-version.js.map +1 -1
  46. package/dist/lib/i18n/messages.de.js +20 -1
  47. package/dist/lib/i18n/messages.de.js.map +1 -1
  48. package/dist/lib/i18n/messages.en.d.ts +20 -1
  49. package/dist/lib/i18n/messages.en.js +21 -2
  50. package/dist/lib/i18n/messages.en.js.map +1 -1
  51. package/dist/lib/persona/labels.js +2 -0
  52. package/dist/lib/persona/labels.js.map +1 -1
  53. package/dist/lib/registry/preview.d.ts +2 -1
  54. package/dist/lib/registry/preview.js +8 -3
  55. package/dist/lib/registry/preview.js.map +1 -1
  56. package/dist/lib/workspace/index.d.ts +9 -1
  57. package/dist/lib/workspace/index.js +13 -2
  58. package/dist/lib/workspace/index.js.map +1 -1
  59. package/package.json +3 -3
@@ -150,6 +150,10 @@ export interface AppViewModule {
150
150
  * Parse this view's trailing path segments into a deep-link, or `null` for an
151
151
  * unroutable path (→ not-found). Omitted → a FLAT view ({@link flatPath}): only
152
152
  * the bare path is valid, any trailing segment is not-found.
153
+ *
154
+ * **The segments arrive DECODED by the router** (`/p/view/a%25b` → `['a%b']`): each IS the
155
+ * value, and is never decoded again — a second decode throws on a value holding `%` (`50%`)
156
+ * and reads `a%41` as another value (`aA`). One decoder per address (EC-768).
153
157
  */
154
158
  parsePath?: (segments: string[]) => AppViewDeepLink | null;
155
159
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"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A;AACb,CAAC;AAED,gCAAgC;AAEhC;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAgB,EAAE,MAAqB;IACxE,OAAO,MAAM,CAAC,mBAAmB;QAC/B,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC,mBAAmB,CAAC;QAClF,CAAC,CAAC,WAAW,CAAA;AACjB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,KAA+B,EAC/B,OAAgB;IAEhB,OAAO,KAAK,CAAC,IAAI,CACf,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,kBAAkB,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,aAAa,CAC9E,CAAA;AACH,CAAC","sourcesContent":["import type { ReactNode } from 'react'\nimport type { LucideIcon } from 'lucide-react'\nimport { availabilityOf } from '@elytracms/core/studio-core'\nimport type { Project, SectionAvailability, SectionId } from '@elytracms/core/studio-core'\nimport type { CollectionDef } from '@elytracms/core/cms-core'\nimport type { ProjectRole } from '@elytracms/core/persistence'\nimport type { StudioSearch } from '@elytracms/studio/router/search'\nimport type { Locale } from '@elytracms/core/cms-core'\nimport type { OperationsClient } from '@elytracms/core/operations'\nimport type { AuthUser } from '../../lib/auth'\nimport type { useOperationCache, useOperationQuery } from '../../lib/query'\nimport type { NavIssue } from '../nav-issues-registry'\n\n/**\n * The studio **view** contract + the **sidebar node** model — the internal types\n * the consumer-facing `nav.*` builders (EC-237/239, customization seam EC-236)\n * produce.\n *\n * A studio surface (the CMS, Routes, Assets view, or a net-new one) is a\n * self-contained {@link AppViewModule}: a stable id + display metadata + a React\n * `render` + an optional deep-link parser. A {@link SidebarNode} is one rail entry\n * — a view, a labelled group of views, or a separator — and a **view node carries\n * its view object DIRECTLY**, not a string id. This is the redesign's core: there\n * is no separate \"register a view, then reference it by `moduleId`\" indirection\n * and no shared id-keyspace, so the section rail IS the set of views, the router\n * registry is DERIVED from it, and the duplicate-id / both-highlighted class of\n * bug is gone by construction.\n *\n * The boundary principle: everything here is studio-only live code passed by\n * reference (no string keys). A string only crosses the serializable boundary for\n * field controls (`form.control`), where the field lives in delivery-shared schema.\n *\n * Reuse-not-copy (EC-239): a focused view like \"Catalog\" is the CMS surface\n * instantiated with config (`nav.cms({ collections })`), not a fork — the same\n * surface code backs many views, each its own addressable node.\n */\n\n/** The deep-link a view parses out of its trailing path segments (e.g. `{ collectionId, documentId }`). */\nexport type AppViewDeepLink = Record<string, string | null>\n\n/**\n * What an OPTIONAL nav-permission predicate sees (EC-240, vision AD-18): the\n * project + the signed-in user's resolved role (`null` while it loads, or for a\n * non-member). Kept minimal — policy that needs more should live server-side.\n */\nexport interface NavPermissionContext {\n project: Project\n role: ProjectRole | null\n}\n\n/**\n * An OPTIONAL, **default-open** per-nav-item visibility predicate (AD-18). Returns\n * `false` to HIDE the item for this principal; absent ⇒ visible. Permissions\n * RESTRICT — they never grant a baseline. This is the general mechanism (applies\n * to EVERY nav item, not a Users special-case); the concrete policy ships in the\n * starter project, never the engine. UI reflection only — the server chokepoint\n * stays the real boundary, and hidden views remain URL-addressable (EC-221).\n */\nexport type NavPermission = (ctx: NavPermissionContext) => boolean\n\n/**\n * Everything a view's surface needs to render (EC-239), and — since EC-616 — what an\n * addon's view reaches the studio through, instead of importing internals: the\n * operations client (the one chokepoint every read and write goes through), the query\n * hooks over the one cache (AD-17), the ambient content locale, and the signed-in user\n * with their role on this project.\n *\n * **The chrome contract** (ruling § 6b item 1): the SHELL draws the top bar, the\n * breadcrumb (its section crumb is the view's `label`; deeper crumbs are contributed with\n * `useSetBreadcrumb`), the rail, the issues badge and tray in the header (findings\n * contributed with `useNavIssues`, EC-690) and the theme. The VIEW owns the whole scrollable content area under it,\n * including its own title header — the shell adds no frame, title or padding.\n */\nexport interface AppViewContext {\n project: Project\n projectId: string\n /** The view's parsed deep-link; `{}` for a flat view with no nested resource. */\n deepLink: AppViewDeepLink\n /** The validated `?…` search (forced state, focused field/asset, …). */\n search: StudioSearch\n /** The studio's operations client — every read and write, authorized at the chokepoint. */\n operations(): Promise<OperationsClient>\n /** The query hooks over the studio's one operations-backed cache (AD-17). */\n query: AppViewQueryHooks\n /** The ambient content locale (`null` until the project's locale config is installed). */\n locale: Locale | null\n /** The signed-in user (`null` while signed out). */\n user: AuthUser | null\n /** The user's role on this project (`null` while it loads, or for a non-member). */\n role: ProjectRole | null\n}\n\n/** The cache hooks a view reads and writes through (`useOperationQuery` / `useOperationCache`). */\nexport interface AppViewQueryHooks {\n useOperationQuery: typeof useOperationQuery\n useOperationCache: typeof useOperationCache\n}\n\n/**\n * EC-616 — a view's ALWAYS-ON findings: a React hook the studio shell mounts for every\n * view that declares one (whether or not the view is open), publishing what it returns\n * through `useNavIssues` to the shell's issues tray (EC-690; it used to be the rail foot).\n * Use it for a problem the developer must see from any surface (an addon's broken\n * configuration); a finding that only matters while the view is open is published from\n * the view with `useNavIssues` directly.\n */\nexport type NavIssuesHook = (ctx: { project: Project; projectId: string }) => readonly NavIssue[]\n\n/**\n * EC-476/477 — how a view's id came to be, when the builder **derived** it instead of\n * taking an explicit `config.id`.\n *\n * Diagnostics only: nothing routes, renders or resolves on this. It exists because the\n * derived-vs-explicit distinction is otherwise UNRECOVERABLE downstream, and the two\n * must not behave the same. `nav.view({ id: 'cms' })` names a built-in on purpose —\n * that is the documented override feature (EC-236). `nav.view({ label: 'CMS' })` names\n * a *label*, and `slugify` happening to produce `cms` is an accident that costs an\n * entire built-in surface. `resolveSidebar` cannot tell those apart from the finished\n * view: every built-in's own English label slugifies onto its own id\n * (`settingsView().label` = \"Settings\" → `settings`), so inferring \"was this derived?\"\n * by re-slugifying the label misfires on the DEFAULT RAIL. Hence a carried marker.\n *\n * Present only on a derived id — an explicit `config.id` leaves it absent, which is\n * what makes \"the developer meant it\" checkable.\n */\nexport type DerivedViewId =\n /** Slugified from a custom view's LABEL (`nav.view({ label })`); the label is carried for the message. */\n | { from: 'label'; label: string }\n /**\n * Joined from a MULTI-collection CMS focus with the `-` separator\n * (`nav.cms({ collections: ['a','b'] })` → `cms:a-b`). The single-collection leaf and\n * the one-item `cms-group:` parent are deliberately NOT marked: their ids are\n * unambiguous by construction (EC-468), so there is nothing to diagnose.\n */\n | { from: 'collection-join'; collections: readonly string[] }\n\nexport interface AppViewModule {\n /** Stable id — the first path segment under the project + the registry key. */\n id: string\n /**\n * EC-476/477 — DIAGNOSTIC provenance for an id the builder DERIVED rather than took\n * from an explicit `config.id`. Absent → the id was declared. See {@link DerivedViewId}.\n */\n derivedId?: DerivedViewId\n label: string\n description: string\n icon: LucideIcon\n /** Render the surface; it mounts its own providers/gates. */\n render: (ctx: AppViewContext) => ReactNode\n /**\n * Parse this view's trailing path segments into a deep-link, or `null` for an\n * unroutable path (→ not-found). Omitted → a FLAT view ({@link flatPath}): only\n * the bare path is valid, any trailing segment is not-found.\n */\n parsePath?: (segments: string[]) => AppViewDeepLink | null\n /**\n * The availability section this view rides on (EC-221 gating): an `unavailable`\n * section hides the view from the rail. Omitted → always available (a custom\n * view defaults to visible).\n */\n availabilitySection?: SectionId\n /**\n * OPTIONAL, default-open per-nav-item visibility (EC-240, vision AD-18). Absent\n * → visible. Evaluated with the signed-in user's role so devs can configure\n * role-based sidebars for ANY nav item (not just Users). Distinct from\n * {@link availabilitySection} (project-config gating): this is per-principal.\n * See {@link NavPermission}. (Phase-0 contract; the rail wires it in EC-240c —\n * `resolveSidebar`/`SectionNav` thread the role through and honour a `false`.)\n */\n visible?: NavPermission\n /** A redirect-only / utility view the stock rail does not list (e.g. `builder`). */\n hidden?: boolean\n /** EC-616 — always-on findings for the shell's issues tray (see {@link NavIssuesHook}). */\n useIssues?: NavIssuesHook\n /**\n * EC-690 — the record kind a record rail lists (`nav.rail(kind)`, `nav.redirects`), so a\n * finding located at a record (`{ kind: 'record', recordKind, id }`) opens this view's row\n * whatever id the consumer gave the view. Set by `railView`; absent on every other view.\n */\n recordKind?: string\n}\n\n// --- The sidebar node model (what `nav.*` produces) ---\n\n/**\n * A rail entry that mounts a view. Carries the view object directly — no string id.\n *\n * EC-293: a view node may NEST one level. `children` is a static list of sub-views;\n * `expand` derives them at resolve time from the project's collections (CMS\n * auto-expand). Children render indented under the parent — indentation signals\n * parent→child, distinct from a flat labelled {@link SidebarGroupNode}. `children`\n * (explicit) wins over `expand` when both are set.\n */\nexport interface SidebarViewNode {\n kind: 'view'\n view: AppViewModule\n /** Static sub-views, rendered indented under this view (one level of nesting). */\n children?: SidebarViewNode[]\n /**\n * Resolve-time children from the project's collections (e.g. CMS expanding each\n * collection into a focused-lens child). Run by `resolveSidebar` with the\n * config-sourced collections; the result renders as {@link children}.\n */\n expand?: (collections: readonly CollectionDef[]) => SidebarViewNode[]\n}\n/**\n * A labelled group of view entries. Groups are presentation only — never routable,\n * and **flat**: their children render aligned with the top-level items (the heading\n * is the only grouping signal). Group children do not nest — use a parent-with-\n * children ({@link SidebarViewNode.expand}/`children`) for nesting (EC-293).\n */\nexport interface SidebarGroupNode {\n kind: 'group'\n label: string\n children: SidebarViewNode[]\n}\n/** A divider between rail sections. */\nexport interface SidebarSeparatorNode {\n kind: 'separator'\n}\nexport type SidebarNode = SidebarViewNode | SidebarGroupNode | SidebarSeparatorNode\n\n/** Wrap a view as a rail entry. */\nexport function viewNode(view: AppViewModule): SidebarViewNode {\n return { kind: 'view', view }\n}\n/** A labelled group of view entries (sub-views under a header). */\nexport function groupNode(label: string, children: SidebarViewNode[]): SidebarGroupNode {\n return { kind: 'group', label, children }\n}\n/** A rail divider. */\nexport function separatorNode(): SidebarSeparatorNode {\n return { kind: 'separator' }\n}\n\n// --- Deep-link parsers (shared by the built-in views + reused by factories) ---\n\n/** A flat view: only the bare path resolves; any trailing segment is not-found. */\nexport function flatPath(segments: string[]): AppViewDeepLink | null {\n return segments.length === 0 ? {} : null\n}\n\n/** CMS arity: `[]` index · `[c]` collection · `[c, d]` document; deeper is not-found. */\nexport function cmsDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { collectionId: null, documentId: null }\n if (segments.length === 1) return { collectionId: segments[0]!, documentId: null }\n if (segments.length === 2) return { collectionId: segments[0]!, documentId: segments[1]! }\n return null\n}\n\n/** Components arity: `[]` index · `[id]` detail; deeper is not-found. */\nexport function componentsDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { componentId: null }\n if (segments.length === 1) return { componentId: segments[0]! }\n return null\n}\n\n/** Users arity (EC-240): `[]` list · `[userId]` member detail; deeper is not-found. */\nexport function usersDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { userId: null }\n if (segments.length === 1) return { userId: segments[0]! }\n return null\n}\n\n/**\n * A record rail's arity (EC-616): `[]` list · `[id]` one record's detail, under the kind's\n * `idKey`; deeper is not-found.\n */\nexport function recordDeepLink(idKey: string): (segments: string[]) => AppViewDeepLink | null {\n return (segments) => {\n if (segments.length === 0) return { [idKey]: null }\n if (segments.length === 1) return { [idKey]: segments[0]! }\n return null\n }\n}\n\n/** Redirects arity (EC-303): `[]` list · `[redirectId]` detail; deeper is not-found — the redirect kind's {@link recordDeepLink}. */\nexport const redirectsDeepLink = recordDeepLink('redirectId')\n\n/** Assets arity (EC-319): `[]` list · `[assetId]` detail; deeper is not-found. */\nexport function assetsDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { assetId: null }\n if (segments.length === 1) return { assetId: segments[0]! }\n return null\n}\n\n// --- Availability (EC-221) ---\n\n/**\n * A view's availability for a project (EC-221): the section it rides on, or always\n * `available` when it declares none (a custom view). Drives both the rail (hide\n * `unavailable`) and the bare-project landing target.\n */\nexport function moduleAvailability(project: Project, module: AppViewModule): SectionAvailability {\n return module.availabilitySection\n ? availabilityOf(project.settings.sectionAvailability, module.availabilitySection)\n : 'available'\n}\n\n/**\n * The view a project should open to from its bare URL: the first listed\n * (non-hidden), non-`unavailable` view in rail order. Callers pass the resolved\n * registry's view list (rail order); `undefined` only if every view is\n * hidden/unavailable (the resolver guarantees Settings, so in practice never).\n */\nexport function firstAvailableView(\n views: readonly AppViewModule[],\n project: Project,\n): AppViewModule | undefined {\n return views.find(\n (view) => !view.hidden && moduleAvailability(project, view) !== 'unavailable',\n )\n}\n"]}
1
+ {"version":3,"file":"module.js","sourceRoot":"","sources":["../../../src/components/app-views/module.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAgO5D,mCAAmC;AACnC,MAAM,UAAU,QAAQ,CAAC,IAAmB;IAC1C,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAA;AAC/B,CAAC;AACD,mEAAmE;AACnE,MAAM,UAAU,SAAS,CAAC,KAAa,EAAE,QAA2B;IAClE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAA;AAC3C,CAAC;AACD,sBAAsB;AACtB,MAAM,UAAU,aAAa;IAC3B,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAA;AAC9B,CAAC;AAED,iFAAiF;AAEjF,mFAAmF;AACnF,MAAM,UAAU,QAAQ,CAAC,QAAkB;IACzC,OAAO,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAA;AAC1C,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,WAAW,CAAC,QAAkB;IAC5C,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAA;IAC1E,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAA;IAClF,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC,C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O,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;IACnD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAE,EAAE,CAAA;IAC3D,OAAO,IAAI,CAAA;AACb,CAAC;AAED,gCAAgC;AAEhC;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAgB,EAAE,MAAqB;IACxE,OAAO,MAAM,CAAC,mBAAmB;QAC/B,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC,mBAAmB,CAAC;QAClF,CAAC,CAAC,WAAW,CAAA;AACjB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,KAA+B,EAC/B,OAAgB;IAEhB,OAAO,KAAK,CAAC,IAAI,CACf,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,kBAAkB,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,aAAa,CAC9E,CAAA;AACH,CAAC","sourcesContent":["import type { ReactNode } from 'react'\nimport type { LucideIcon } from 'lucide-react'\nimport { availabilityOf } from '@elytracms/core/studio-core'\nimport type { Project, SectionAvailability, SectionId } from '@elytracms/core/studio-core'\nimport type { CollectionDef } from '@elytracms/core/cms-core'\nimport type { ProjectRole } from '@elytracms/core/persistence'\nimport type { StudioSearch } from '@elytracms/studio/router/search'\nimport type { Locale } from '@elytracms/core/cms-core'\nimport type { OperationsClient } from '@elytracms/core/operations'\nimport type { AuthUser } from '../../lib/auth'\nimport type { useOperationCache, useOperationQuery } from '../../lib/query'\nimport type { NavIssue } from '../nav-issues-registry'\n\n/**\n * The studio **view** contract + the **sidebar node** model — the internal types\n * the consumer-facing `nav.*` builders (EC-237/239, customization seam EC-236)\n * produce.\n *\n * A studio surface (the CMS, Routes, Assets view, or a net-new one) is a\n * self-contained {@link AppViewModule}: a stable id + display metadata + a React\n * `render` + an optional deep-link parser. A {@link SidebarNode} is one rail entry\n * — a view, a labelled group of views, or a separator — and a **view node carries\n * its view object DIRECTLY**, not a string id. This is the redesign's core: there\n * is no separate \"register a view, then reference it by `moduleId`\" indirection\n * and no shared id-keyspace, so the section rail IS the set of views, the router\n * registry is DERIVED from it, and the duplicate-id / both-highlighted class of\n * bug is gone by construction.\n *\n * The boundary principle: everything here is studio-only live code passed by\n * reference (no string keys). A string only crosses the serializable boundary for\n * field controls (`form.control`), where the field lives in delivery-shared schema.\n *\n * Reuse-not-copy (EC-239): a focused view like \"Catalog\" is the CMS surface\n * instantiated with config (`nav.cms({ collections })`), not a fork — the same\n * surface code backs many views, each its own addressable node.\n */\n\n/** The deep-link a view parses out of its trailing path segments (e.g. `{ collectionId, documentId }`). */\nexport type AppViewDeepLink = Record<string, string | null>\n\n/**\n * What an OPTIONAL nav-permission predicate sees (EC-240, vision AD-18): the\n * project + the signed-in user's resolved role (`null` while it loads, or for a\n * non-member). Kept minimal — policy that needs more should live server-side.\n */\nexport interface NavPermissionContext {\n project: Project\n role: ProjectRole | null\n}\n\n/**\n * An OPTIONAL, **default-open** per-nav-item visibility predicate (AD-18). Returns\n * `false` to HIDE the item for this principal; absent ⇒ visible. Permissions\n * RESTRICT — they never grant a baseline. This is the general mechanism (applies\n * to EVERY nav item, not a Users special-case); the concrete policy ships in the\n * starter project, never the engine. UI reflection only — the server chokepoint\n * stays the real boundary, and hidden views remain URL-addressable (EC-221).\n */\nexport type NavPermission = (ctx: NavPermissionContext) => boolean\n\n/**\n * Everything a view's surface needs to render (EC-239), and — since EC-616 — what an\n * addon's view reaches the studio through, instead of importing internals: the\n * operations client (the one chokepoint every read and write goes through), the query\n * hooks over the one cache (AD-17), the ambient content locale, and the signed-in user\n * with their role on this project.\n *\n * **The chrome contract** (ruling § 6b item 1): the SHELL draws the top bar, the\n * breadcrumb (its section crumb is the view's `label`; deeper crumbs are contributed with\n * `useSetBreadcrumb`), the rail, the issues badge and tray in the header (findings\n * contributed with `useNavIssues`, EC-690) and the theme. The VIEW owns the whole scrollable content area under it,\n * including its own title header — the shell adds no frame, title or padding.\n */\nexport interface AppViewContext {\n project: Project\n projectId: string\n /** The view's parsed deep-link; `{}` for a flat view with no nested resource. */\n deepLink: AppViewDeepLink\n /** The validated `?…` search (forced state, focused field/asset, …). */\n search: StudioSearch\n /** The studio's operations client — every read and write, authorized at the chokepoint. */\n operations(): Promise<OperationsClient>\n /** The query hooks over the studio's one operations-backed cache (AD-17). */\n query: AppViewQueryHooks\n /** The ambient content locale (`null` until the project's locale config is installed). */\n locale: Locale | null\n /** The signed-in user (`null` while signed out). */\n user: AuthUser | null\n /** The user's role on this project (`null` while it loads, or for a non-member). */\n role: ProjectRole | null\n}\n\n/** The cache hooks a view reads and writes through (`useOperationQuery` / `useOperationCache`). */\nexport interface AppViewQueryHooks {\n useOperationQuery: typeof useOperationQuery\n useOperationCache: typeof useOperationCache\n}\n\n/**\n * EC-616 — a view's ALWAYS-ON findings: a React hook the studio shell mounts for every\n * view that declares one (whether or not the view is open), publishing what it returns\n * through `useNavIssues` to the shell's issues tray (EC-690; it used to be the rail foot).\n * Use it for a problem the developer must see from any surface (an addon's broken\n * configuration); a finding that only matters while the view is open is published from\n * the view with `useNavIssues` directly.\n */\nexport type NavIssuesHook = (ctx: { project: Project; projectId: string }) => readonly NavIssue[]\n\n/**\n * EC-476/477 — how a view's id came to be, when the builder **derived** it instead of\n * taking an explicit `config.id`.\n *\n * Diagnostics only: nothing routes, renders or resolves on this. It exists because the\n * derived-vs-explicit distinction is otherwise UNRECOVERABLE downstream, and the two\n * must not behave the same. `nav.view({ id: 'cms' })` names a built-in on purpose —\n * that is the documented override feature (EC-236). `nav.view({ label: 'CMS' })` names\n * a *label*, and `slugify` happening to produce `cms` is an accident that costs an\n * entire built-in surface. `resolveSidebar` cannot tell those apart from the finished\n * view: every built-in's own English label slugifies onto its own id\n * (`settingsView().label` = \"Settings\" → `settings`), so inferring \"was this derived?\"\n * by re-slugifying the label misfires on the DEFAULT RAIL. Hence a carried marker.\n *\n * Present only on a derived id — an explicit `config.id` leaves it absent, which is\n * what makes \"the developer meant it\" checkable.\n */\nexport type DerivedViewId =\n /** Slugified from a custom view's LABEL (`nav.view({ label })`); the label is carried for the message. */\n | { from: 'label'; label: string }\n /**\n * Joined from a MULTI-collection CMS focus with the `-` separator\n * (`nav.cms({ collections: ['a','b'] })` → `cms:a-b`). The single-collection leaf and\n * the one-item `cms-group:` parent are deliberately NOT marked: their ids are\n * unambiguous by construction (EC-468), so there is nothing to diagnose.\n */\n | { from: 'collection-join'; collections: readonly string[] }\n\nexport interface AppViewModule {\n /** Stable id — the first path segment under the project + the registry key. */\n id: string\n /**\n * EC-476/477 — DIAGNOSTIC provenance for an id the builder DERIVED rather than took\n * from an explicit `config.id`. Absent → the id was declared. See {@link DerivedViewId}.\n */\n derivedId?: DerivedViewId\n label: string\n description: string\n icon: LucideIcon\n /** Render the surface; it mounts its own providers/gates. */\n render: (ctx: AppViewContext) => ReactNode\n /**\n * Parse this view's trailing path segments into a deep-link, or `null` for an\n * unroutable path (→ not-found). Omitted → a FLAT view ({@link flatPath}): only\n * the bare path is valid, any trailing segment is not-found.\n *\n * **The segments arrive DECODED by the router** (`/p/view/a%25b` → `['a%b']`): each IS the\n * value, and is never decoded again — a second decode throws on a value holding `%` (`50%`)\n * and reads `a%41` as another value (`aA`). One decoder per address (EC-768).\n */\n parsePath?: (segments: string[]) => AppViewDeepLink | null\n /**\n * The availability section this view rides on (EC-221 gating): an `unavailable`\n * section hides the view from the rail. Omitted → always available (a custom\n * view defaults to visible).\n */\n availabilitySection?: SectionId\n /**\n * OPTIONAL, default-open per-nav-item visibility (EC-240, vision AD-18). Absent\n * → visible. Evaluated with the signed-in user's role so devs can configure\n * role-based sidebars for ANY nav item (not just Users). Distinct from\n * {@link availabilitySection} (project-config gating): this is per-principal.\n * See {@link NavPermission}. (Phase-0 contract; the rail wires it in EC-240c —\n * `resolveSidebar`/`SectionNav` thread the role through and honour a `false`.)\n */\n visible?: NavPermission\n /** A redirect-only / utility view the stock rail does not list (e.g. `builder`). */\n hidden?: boolean\n /** EC-616 — always-on findings for the shell's issues tray (see {@link NavIssuesHook}). */\n useIssues?: NavIssuesHook\n /**\n * EC-690 — the record kind a record rail lists (`nav.rail(kind)`, `nav.redirects`), so a\n * finding located at a record (`{ kind: 'record', recordKind, id }`) opens this view's row\n * whatever id the consumer gave the view. Set by `railView`; absent on every other view.\n */\n recordKind?: string\n}\n\n// --- The sidebar node model (what `nav.*` produces) ---\n\n/**\n * A rail entry that mounts a view. Carries the view object directly — no string id.\n *\n * EC-293: a view node may NEST one level. `children` is a static list of sub-views;\n * `expand` derives them at resolve time from the project's collections (CMS\n * auto-expand). Children render indented under the parent — indentation signals\n * parent→child, distinct from a flat labelled {@link SidebarGroupNode}. `children`\n * (explicit) wins over `expand` when both are set.\n */\nexport interface SidebarViewNode {\n kind: 'view'\n view: AppViewModule\n /** Static sub-views, rendered indented under this view (one level of nesting). */\n children?: SidebarViewNode[]\n /**\n * Resolve-time children from the project's collections (e.g. CMS expanding each\n * collection into a focused-lens child). Run by `resolveSidebar` with the\n * config-sourced collections; the result renders as {@link children}.\n */\n expand?: (collections: readonly CollectionDef[]) => SidebarViewNode[]\n}\n/**\n * A labelled group of view entries. Groups are presentation only — never routable,\n * and **flat**: their children render aligned with the top-level items (the heading\n * is the only grouping signal). Group children do not nest — use a parent-with-\n * children ({@link SidebarViewNode.expand}/`children`) for nesting (EC-293).\n */\nexport interface SidebarGroupNode {\n kind: 'group'\n label: string\n children: SidebarViewNode[]\n}\n/** A divider between rail sections. */\nexport interface SidebarSeparatorNode {\n kind: 'separator'\n}\nexport type SidebarNode = SidebarViewNode | SidebarGroupNode | SidebarSeparatorNode\n\n/** Wrap a view as a rail entry. */\nexport function viewNode(view: AppViewModule): SidebarViewNode {\n return { kind: 'view', view }\n}\n/** A labelled group of view entries (sub-views under a header). */\nexport function groupNode(label: string, children: SidebarViewNode[]): SidebarGroupNode {\n return { kind: 'group', label, children }\n}\n/** A rail divider. */\nexport function separatorNode(): SidebarSeparatorNode {\n return { kind: 'separator' }\n}\n\n// --- Deep-link parsers (shared by the built-in views + reused by factories) ---\n\n/** A flat view: only the bare path resolves; any trailing segment is not-found. */\nexport function flatPath(segments: string[]): AppViewDeepLink | null {\n return segments.length === 0 ? {} : null\n}\n\n/** CMS arity: `[]` index · `[c]` collection · `[c, d]` document; deeper is not-found. */\nexport function cmsDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { collectionId: null, documentId: null }\n if (segments.length === 1) return { collectionId: segments[0]!, documentId: null }\n if (segments.length === 2) return { collectionId: segments[0]!, documentId: segments[1]! }\n return null\n}\n\n/** Components arity: `[]` index · `[id]` detail; deeper is not-found. */\nexport function componentsDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { componentId: null }\n if (segments.length === 1) return { componentId: segments[0]! }\n return null\n}\n\n/** Users arity (EC-240): `[]` list · `[userId]` member detail; deeper is not-found. */\nexport function usersDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { userId: null }\n if (segments.length === 1) return { userId: segments[0]! }\n return null\n}\n\n/**\n * A record rail's arity (EC-616): `[]` list · `[id]` one record's detail, under the kind's\n * `idKey`; deeper is not-found.\n */\nexport function recordDeepLink(idKey: string): (segments: string[]) => AppViewDeepLink | null {\n return (segments) => {\n if (segments.length === 0) return { [idKey]: null }\n if (segments.length === 1) return { [idKey]: segments[0]! }\n return null\n }\n}\n\n/** Redirects arity (EC-303): `[]` list · `[redirectId]` detail; deeper is not-found — the redirect kind's {@link recordDeepLink}. */\nexport const redirectsDeepLink = recordDeepLink('redirectId')\n\n/** Assets arity (EC-319): `[]` list · `[assetId]` detail; deeper is not-found. */\nexport function assetsDeepLink(segments: string[]): AppViewDeepLink | null {\n if (segments.length === 0) return { assetId: null }\n if (segments.length === 1) return { assetId: segments[0]! }\n return null\n}\n\n// --- Availability (EC-221) ---\n\n/**\n * A view's availability for a project (EC-221): the section it rides on, or always\n * `available` when it declares none (a custom view). Drives both the rail (hide\n * `unavailable`) and the bare-project landing target.\n */\nexport function moduleAvailability(project: Project, module: AppViewModule): SectionAvailability {\n return module.availabilitySection\n ? availabilityOf(project.settings.sectionAvailability, module.availabilitySection)\n : 'available'\n}\n\n/**\n * The view a project should open to from its bare URL: the first listed\n * (non-hidden), non-`unavailable` view in rail order. Callers pass the resolved\n * registry's view list (rail order); `undefined` only if every view is\n * hidden/unavailable (the resolver guarantees Settings, so in practice never).\n */\nexport function firstAvailableView(\n views: readonly AppViewModule[],\n project: Project,\n): AppViewModule | undefined {\n return views.find(\n (view) => !view.hidden && moduleAvailability(project, view) !== 'unavailable',\n )\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { ReactNode } from 'react';
2
2
  import type { AllowList, ComponentLookup, ComponentNode, InsertTarget, LayoutContainerIds, PlacementScope, PlacementVerdict, PropValue } from '@elytracms/core/project-graph';
3
3
  import type { IdFactory } from '@elytracms/core/persistence';
4
- import type { CmsDocument, DocumentRef } from '@elytracms/core/cms-core';
4
+ import type { CmsDocument, DocumentRef, PropFieldLookup } from '@elytracms/core/cms-core';
5
5
  import type { PreservedItem } from './canvas-runs.js';
6
6
  /**
7
7
  * A canvas preview-width key (EC-250): `'full'` (unconstrained) or a configured
@@ -257,10 +257,16 @@ type Action = BuilderAction;
257
257
  * paste — can place what the field, a slot or canvas eligibility forbids, and the
258
258
  * publish gate (which calls the same judge) cannot disagree with the canvas.
259
259
  *
260
+ * EC-776 — and with the project's prop declarations (`lookupManifest`): every action that
261
+ * COPIES a subtree into the composition (`insert`, `duplicate`, `replace`, a built `wrap`
262
+ * partner) mints every id of it through `withFreshNodeIds` — the slot children AND the nodes
263
+ * the props hold (a rich-text prop's embeds, a composition host's value). Required, so no
264
+ * store can copy a subtree whose prop-held nodes keep their ids.
265
+ *
260
266
  * Exported (with `initialBuilderState`) for unit tests — gesture determinism and
261
267
  * normalization lockstep are reducer-level properties, not render behavior.
262
268
  */
263
- export declare function createBuilderReducer(placement: PlacementScope): (state: BuilderState, action: Action) => BuilderState;
269
+ export declare function createBuilderReducer(placement: PlacementScope, lookupManifest: PropFieldLookup): (state: BuilderState, action: Action) => BuilderState;
264
270
  /**
265
271
  * The composition FIELD whose value the store edits (EC-554). Static for the
266
272
  * store's lifetime and deliberately NOT reducer state: it is the declaration the
@@ -292,6 +298,11 @@ export interface BuilderStore extends BuilderState {
292
298
  * offer, the reuse preflight) read the SAME scope, so an indicator and the sink agree.
293
299
  */
294
300
  placement: PlacementScope;
301
+ /**
302
+ * EC-776 — the project's prop declarations the reducer mints copies with; a gesture that mints
303
+ * a subtree itself (paste, which names the ids that land in its notice) reads the SAME lookup.
304
+ */
305
+ lookupManifest: PropFieldLookup;
295
306
  dispatch: (action: Action) => void;
296
307
  }
297
308
  declare const useBuilder: () => BuilderStore;
@@ -309,7 +320,7 @@ preserved?: readonly PreservedItem[]): BuilderState;
309
320
  * absorbed by the present AND every snapshot (`rebase`, `canvas-rebase.ts`), so an undo
310
321
  * never reverts it.
311
322
  */
312
- export declare function BuilderProvider({ composition, preserved, field, components, layout, idFactory, children, }: {
323
+ export declare function BuilderProvider({ composition, preserved, field, components, layout, lookupManifest, idFactory, children, }: {
313
324
  /** The composition root to edit (the composition-field editor's synthetic root). */
314
325
  composition: ComponentNode;
315
326
  /** EC-549 — the field value's typography items (`splitBlockRoots(value).preserved`). */
@@ -320,6 +331,11 @@ export declare function BuilderProvider({ composition, preserved, field, compone
320
331
  components: ComponentLookup;
321
332
  /** The layout-role component ids (EC-591, `ComponentRegistry.layout`) — required. */
322
333
  layout: LayoutContainerIds;
334
+ /**
335
+ * EC-776 — the project's prop declarations (`studioManifestLookup()`) — required: every copy
336
+ * the store makes re-mints the nodes its props hold, which only the declarations reach.
337
+ */
338
+ lookupManifest: PropFieldLookup;
323
339
  /**
324
340
  * EC-578 — the node-id factory. Defaults to UUIDs (`createUuidIdFactory`, one per
325
341
  * store); fixtures inject a deterministic factory.
@@ -1,7 +1,8 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useMemo, useReducer, useState } from 'react';
3
- import { DEFAULT_SLOT, cloneWithNewIds, duplicateNode, getNode, getParentInfo, gridContainerNode, insertNode, moveNode, normalizeContainers, removeNode, removeNodeProp, reorderNode, replaceNode, replacePlacementRefusal, setNodeProp, subtreePlacementRefusal, } from '@elytracms/core/project-graph';
3
+ import { DEFAULT_SLOT, duplicateNode, getNode, getParentInfo, gridContainerNode, insertNode, moveNode, normalizeContainers, removeNode, removeNodeProp, reorderNode, replaceNode, replacePlacementRefusal, setNodeProp, subtreePlacementRefusal, } from '@elytracms/core/project-graph';
4
4
  import { createUuidIdFactory } from '@elytracms/core/persistence';
5
+ import { withFreshNodeIds } from '@elytracms/core/cms-core';
5
6
  import { WRAP_GRID_OPTIONS, applyWrap } from '../../lib/dnd/drop-rules.js';
6
7
  import { replaceRun, runByKey } from './canvas-runs.js';
7
8
  import { rebaseCanvas } from './canvas-rebase.js';
@@ -92,14 +93,22 @@ function refuse(state, action, verdict) {
92
93
  * paste — can place what the field, a slot or canvas eligibility forbids, and the
93
94
  * publish gate (which calls the same judge) cannot disagree with the canvas.
94
95
  *
96
+ * EC-776 — and with the project's prop declarations (`lookupManifest`): every action that
97
+ * COPIES a subtree into the composition (`insert`, `duplicate`, `replace`, a built `wrap`
98
+ * partner) mints every id of it through `withFreshNodeIds` — the slot children AND the nodes
99
+ * the props hold (a rich-text prop's embeds, a composition host's value). Required, so no
100
+ * store can copy a subtree whose prop-held nodes keep their ids.
101
+ *
95
102
  * Exported (with `initialBuilderState`) for unit tests — gesture determinism and
96
103
  * normalization lockstep are reducer-level properties, not render behavior.
97
104
  */
98
- export function createBuilderReducer(placement) {
99
- return (state, action) => transition(state, action, placement);
105
+ export function createBuilderReducer(placement, lookupManifest) {
106
+ return (state, action) => transition(state, action, placement, lookupManifest);
100
107
  }
101
- function transition(state, action, placement) {
108
+ function transition(state, action, placement, lookupManifest) {
102
109
  const root = state.present;
110
+ // EC-776: THE copy of a subtree — fresh ids at every depth, from the store's factory.
111
+ const fresh = (node) => withFreshNodeIds(node, state.newId, { lookupManifest });
103
112
  switch (action.type) {
104
113
  case 'select':
105
114
  return { ...state, selectedId: action.id, selectedRun: action.id === null ? state.selectedRun : null, refusal: null };
@@ -169,7 +178,7 @@ function transition(state, action, placement) {
169
178
  };
170
179
  }
171
180
  case 'insert': {
172
- const node = action.minted ? action.node : cloneWithNewIds(action.node, state.newId);
181
+ const node = action.minted ? action.node : fresh(action.node);
173
182
  const verdict = subtreePlacementRefusal(root, node, landingOf(action.target), placement);
174
183
  if (verdict)
175
184
  return refuse(state, action, verdict);
@@ -193,7 +202,7 @@ function transition(state, action, placement) {
193
202
  if (verdict)
194
203
  return refuse(state, action, verdict);
195
204
  }
196
- const { root: next, newId } = duplicateNode(root, action.id, state.newId);
205
+ const { root: next, newId } = duplicateNode(root, action.id, fresh);
197
206
  return commit(state, next, { selectedId: newId ?? state.selectedId });
198
207
  }
199
208
  case 'reorder':
@@ -214,10 +223,10 @@ function transition(state, action, placement) {
214
223
  return commit(state, moveNode(root, action.id, action.target));
215
224
  }
216
225
  case 'replace': {
217
- // Mint fresh ids for the incoming nodes (page-local namespace) so a detached
218
- // copy never collides with the page, and a promoted block's source subtree
226
+ // Mint fresh ids for the incoming nodes — every depth, props included (EC-776) — so a
227
+ // detached copy never collides with the page, and a promoted block's source subtree
219
228
  // (kept for the new reusable document) stays untouched.
220
- const cloned = action.nodes.map((n) => cloneWithNewIds(n, state.newId));
229
+ const cloned = action.nodes.map(fresh);
221
230
  // EC-560: promote (one embed) and detach (the reusable's content) land where the
222
231
  // replaced node was — judged there like any insert (the reuse preflight asks the
223
232
  // same `replacePlacementRefusal` before any side effect).
@@ -239,7 +248,7 @@ function transition(state, action, placement) {
239
248
  // whole gesture.
240
249
  const partner = action.subject.kind === 'node'
241
250
  ? { kind: 'node', nodeId: action.subject.nodeId }
242
- : { kind: 'subtree', node: cloneWithNewIds(action.subject.node, state.newId) };
251
+ : { kind: 'subtree', node: fresh(action.subject.node) };
243
252
  // EC-591: the gesture builds the `layout.grid` component; with none, it is off
244
253
  // (the drop rules refuse it before dispatch — this guard keeps the reducer total).
245
254
  const gridComponentId = state.layout.grid;
@@ -326,12 +335,13 @@ preserved = []) {
326
335
  * absorbed by the present AND every snapshot (`rebase`, `canvas-rebase.ts`), so an undo
327
336
  * never reverts it.
328
337
  */
329
- export function BuilderProvider({ composition, preserved, field, components, layout, idFactory, children, }) {
338
+ export function BuilderProvider({ composition, preserved, field, components, layout, lookupManifest, idFactory, children, }) {
330
339
  const [newId] = useState(() => idFactory ?? createUuidIdFactory());
331
340
  // EC-584: the reducer is constructed ONCE with the scope it judges by — the field
332
341
  // and the lookup are static for the store's lifetime (a remount re-reads them).
333
342
  const [placement] = useState(() => ({ components, fieldAllow: field.allow }));
334
- const [reducer] = useState(() => createBuilderReducer(placement));
343
+ const [propFields] = useState(() => lookupManifest);
344
+ const [reducer] = useState(() => createBuilderReducer(placement, propFields));
335
345
  // EC-287: nothing persists a graph — committed edits are lifted into the CMS
336
346
  // document by the composition-field editor's `onChange`. `useReducer` drives the
337
347
  // pure reducer (consecutive dispatches in one gesture apply in sequence); the
@@ -348,9 +358,10 @@ export function BuilderProvider({ composition, preserved, field, components, lay
348
358
  selectedNode,
349
359
  field,
350
360
  placement,
361
+ lookupManifest: propFields,
351
362
  dispatch,
352
363
  };
353
- }, [state, field, placement, dispatch]);
364
+ }, [state, field, placement, propFields, dispatch]);
354
365
  return _jsx(BuilderContext.Provider, { value: store, children: children });
355
366
  }
356
367
  export { useBuilder };
@@ -1 +1 @@
1
- {"version":3,"file":"builder-store.js","sourceRoot":"","sources":["../../../src/components/builder/builder-store.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAErD,OAAO,EACL,YAAY,EACZ,eAAe,EACf,aAA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'\nimport type { ReactNode } from 'react'\nimport {\n DEFAULT_SLOT,\n cloneWithNewIds,\n duplicateNode,\n getNode,\n getParentInfo,\n gridContainerNode,\n insertNode,\n moveNode,\n normalizeContainers,\n removeNode,\n removeNodeProp,\n reorderNode,\n replaceNode,\n replacePlacementRefusal,\n setNodeProp,\n subtreePlacementRefusal,\n} from '@elytracms/core/project-graph'\nimport type {\n AllowList,\n ComponentLookup,\n ComponentNode,\n InsertTarget,\n LayoutContainerIds,\n PlacementScope,\n PlacementVerdict,\n PropValue,\n} from '@elytracms/core/project-graph'\nimport { createUuidIdFactory } from '@elytracms/core/persistence'\nimport type { IdFactory } from '@elytracms/core/persistence'\nimport type { CmsDocument, DocumentRef } from '@elytracms/core/cms-core'\nimport { WRAP_GRID_OPTIONS, applyWrap } from '../../lib/dnd/drop-rules'\nimport { replaceRun, runByKey } from './canvas-runs'\nimport type { PreservedItem } from './canvas-runs'\nimport { rebaseCanvas } from './canvas-rebase'\nimport { createRequiredContext } from '../../lib/required-context'\n\nconst HISTORY_LIMIT = 100\n\n/**\n * A canvas preview-width key (EC-250): `'full'` (unconstrained) or a configured\n * breakpoint name (`'sm'`, `'md'`, …). Dynamic because the set is sourced from\n * the consuming site's breakpoints, so it is a string, not a fixed union — the\n * switcher resolves the available options via {@link resolveCanvasViewports}.\n */\nexport type Viewport = string\n\n/**\n * The builder store's action union. EC-287 retired the DB-resident project graph\n * and its persistence mirror, so these actions are pure in-memory editor state —\n * no action maps to a persisted `graph.*` command anymore. The block-field editor\n * lifts committed edits into the CMS document via `onChange`\n * (`composition-field-editor`); nothing persists a graph.\n */\nexport type BuilderAction =\n | { type: 'select'; id: string | null }\n | { type: 'hover'; id: string | null }\n | { type: 'viewport'; viewport: Viewport }\n | { type: 'undo' }\n | { type: 'redo' }\n /**\n * Insert a node (its subtree re-id'd from the store's id factory). `minted` — the\n * node ALREADY carries fresh ids from the same factory (the paste path mints first\n * so its issue deep links name exactly the ids that land); the reducer then inserts\n * it as given.\n */\n | { type: 'insert'; target: InsertTarget; node: ComponentNode; select?: boolean; minted?: true }\n | { type: 'remove'; id: string }\n | { type: 'duplicate'; id: string }\n | { type: 'reorder'; id: string; delta: -1 | 1 }\n | { type: 'move'; id: string; target: InsertTarget }\n /**\n * EC-282 reuse gesture: replace a node with zero or more nodes at its\n * position (clone-with-fresh-ids, like `insert`). Promote → 1 embed node;\n * detach → the referenced element's inline blocks. One atomic structural\n * edit, one undo step. EC-728: `effect` — what the step did OUTSIDE the canvas\n * (promote created a reusable document), recorded on that one history entry.\n */\n | { type: 'replace'; id: string; nodes: ComponentNode[]; select?: boolean; effect?: CanvasHistoryEffect }\n /**\n * EC-162 layout gesture: wrap the reference node and the dragged subject in\n * a two-column Grid container as ONE atomic structural edit (one undo step).\n */\n | {\n type: 'wrap'\n referenceId: string\n side: 'left' | 'right'\n subject: { kind: 'node'; nodeId: string } | { kind: 'component'; node: ComponentNode }\n }\n | { type: 'setProp'; id: string; name: string; value: PropValue; coalesceKey?: string }\n | { type: 'removeProp'; id: string; name: string }\n /** EC-584: the editor dismissed the visible refusal ({@link BuilderState.refusal}). */\n | { type: 'clearRefusal' }\n /**\n * EC-549 — select a typography RUN by its key (`canvas-runs.ts`: the index of its\n * first preserved item); `null` clears it. A run and a node are never both selected.\n */\n | { type: 'selectRun'; run: number | null }\n /** EC-549 — delete a typography run: a real, undoable edit of the preserved list. */\n | { type: 'removeRun'; run: number }\n /**\n * EC-549 — replace a run's typography with `content` (the inspector's rich-text\n * editor on that run; consecutive same-key edits coalesce into one undo step). Empty\n * `content` deletes the run.\n */\n | { type: 'setRun'; run: number; content: readonly unknown[]; coalesceKey?: string }\n /**\n * EC-630 — the field's value changed UNDERNEATH the canvas (a colleague's patch by\n * subscription, a write's canonical row, a resolved conflict), from `from` to `to` (the\n * draft's values before and after): the present absorbs the change and the history and\n * selection rebase onto it (`canvas-rebase.ts`) — never a remount. Not an edit: it adds\n * no history entry, and the canvas writes nothing for it.\n */\n | { type: 'rebase'; from: unknown; to: unknown }\n\n/** The structural actions the placement judge rules on (EC-584): every node that enters or moves. */\nexport type PlacingAction = Extract<BuilderAction, { type: 'insert' | 'replace' | 'move' | 'wrap' | 'duplicate' }>\n\n/** A refused placement (EC-584): the judge's verdict and the action it refused. */\nexport interface PlacementRefusal {\n action: PlacingAction['type']\n verdict: PlacementVerdict\n}\n\n/**\n * EC-728 — what a canvas step did OUTSIDE the canvas, so Undo can reverse it and Redo repeat\n * it: *Make reusable* created a reusable document (the canvas half of the gesture — the block\n * swapped for its embed — is the entry's snapshot like any edit's). The store only CARRIES it:\n * the reuse provider performs the document side when an Undo or Redo crosses the step\n * ({@link BuilderState.historyEffect}).\n */\nexport interface CanvasHistoryEffect {\n readonly kind: 'reusable-created'\n readonly ref: DocumentRef\n /** The name the editor gave it — what a notice names. */\n readonly name: string\n /** The document as created — what Redo re-inserts (the same id, insert-if-absent). */\n readonly document: CmsDocument\n}\n\n/**\n * One history entry (EC-549): the component tree AND the preserved typography — so a\n * run's deletion or edit is undone exactly like a block's.\n *\n * EC-728 — `effect` belongs to the STEP between this entry and its neighbour toward the\n * present: on an undo entry (`past`), the step forward from it; on a redo entry (`future`),\n * the step forward to it. Undo and Redo move it with the step, so it is reversed and\n * repeated exactly once per crossing.\n */\nexport interface CanvasSnapshot {\n root: ComponentNode\n preserved: readonly PreservedItem[]\n effect?: CanvasHistoryEffect\n}\n\n/**\n * EC-728 — the last Undo or Redo that crossed a step with an effect outside the canvas:\n * which way, and the effect. `seq` increases with every such crossing, so a consumer handles\n * each exactly once.\n */\nexport interface HistoryEffectStep {\n readonly seq: number\n readonly direction: 'undo' | 'redo'\n readonly effect: CanvasHistoryEffect\n}\n\nexport interface BuilderState {\n /**\n * The edited composition: one root-bearing component tree (EC-287). The canvas\n * wraps a page document's `body` blocks into a synthetic root and edits it\n * directly — no page/layout wrapper. Undo/redo snapshot it with the preserved\n * typography ({@link CanvasSnapshot}).\n */\n past: CanvasSnapshot[]\n present: ComponentNode\n future: CanvasSnapshot[]\n /**\n * EC-549 — the field value's typography items (no ids, EC-500 D1), each anchored by\n * how many component roots preceded it (`componentPrefix`); the field value is\n * `mergeBlockRoots(present's roots, preserved)`. In the store, so selecting,\n * deleting and editing a run is a real action with truthful undo.\n */\n preserved: readonly PreservedItem[]\n selectedId: string | null\n /** EC-549 — the selected typography run's key, or `null` (exclusive with {@link selectedId}). */\n selectedRun: number | null\n hoveredId: string | null\n viewport: Viewport\n /**\n * EC-578 / EC-595 A2 — THE node-id factory (injected; UUIDs in the studio, a\n * sequential factory in fixtures). It replaced the per-session `node-<n>` counter,\n * which two sessions editing one page advanced identically — both minted the same\n * next id, a `duplicate-node-id` on the second save. Stored ids are untouched.\n */\n newId: IdFactory\n /** Coalescing key of the last edit (consecutive same-key edits don't stack history). */\n lastCoalesceKey: string | null\n /**\n * The components filling the layout roles (EC-591, `ComponentRegistry.layout`),\n * fixed for the store's lifetime: which nodes container normalization treats as\n * Stack/Grid, and the Grid the wrap gesture builds. No hardcoded engine id.\n */\n layout: LayoutContainerIds\n /**\n * EC-584 — the last REFUSED placement, with its reason: the reducer judged an\n * `insert`/`replace`/`move`/`wrap`/`duplicate` against the field and slot\n * vocabularies and canvas eligibility (the core placement judge) and left the\n * composition unchanged. Transient — the next edit, selection, undo or redo clears\n * it — and never silent: the canvas shows it (`PlacementRefusalNotice`). A refused\n * action changes no tree, so it adds no history entry and emits no canvas patch.\n */\n refusal: PlacementRefusal | null\n /**\n * EC-630 — how many `rebase` actions the store has applied (external changes of its\n * field). The canvas sync reads it to tell a store value from before a rebase it\n * dispatched from one after it (`createCanvasSync`).\n */\n rebased: number\n /** EC-728 — see {@link HistoryEffectStep}; `null` until an Undo or Redo crosses an effectful step. */\n historyEffect: HistoryEffectStep | null\n}\n\ntype Action = BuilderAction\n\n/**\n * Push a new graph onto history, coalescing consecutive edits with the same key.\n *\n * Every commit normalizes layout containers (EC-162 ledger fix): the\n * operations layer normalizes every persisted `graph.*` write (EC-161), so\n * the optimistic working graph must apply the same `normalizeContainers` pass\n * or the UI state diverges from the persisted revision after\n * container-emptying moves/removes. The mirrored command stays un-normalized\n * (`graphInvocationFor` sees the raw action); both sides normalize\n * identically, so they land on the same graph.\n */\nfunction commit(\n state: BuilderState,\n root: ComponentNode,\n opts: {\n coalesceKey?: string\n selectedId?: string | null\n preserved?: readonly PreservedItem[]\n selectedRun?: number | null\n /** EC-728 — the step's effect outside the canvas (never coalesced: it is its own step). */\n effect?: CanvasHistoryEffect\n } = {},\n): BuilderState {\n const normalized = normalizeContainers(root, state.layout)\n const present = normalized\n const preserved = opts.preserved ?? state.preserved\n const coalesce = opts.effect === undefined && opts.coalesceKey != null && opts.coalesceKey === state.lastCoalesceKey\n // Normalization can dissolve the node a caller wanted selected (e.g. the\n // parent container of a removed child) — selection never points at a ghost.\n const desired = opts.selectedId !== undefined ? opts.selectedId : state.selectedId\n const selectedId = desired !== null && getNode(normalized, desired) ? desired : null\n const desiredRun = opts.selectedRun !== undefined ? opts.selectedRun : state.selectedRun\n return {\n ...state,\n past: coalesce ? state.past : [...state.past, snapshotOf(state, opts.effect)].slice(-HISTORY_LIMIT),\n present,\n preserved,\n future: [],\n lastCoalesceKey: opts.coalesceKey ?? null,\n selectedId,\n selectedRun: liveRun(present, preserved, desiredRun),\n refusal: null,\n }\n}\n\nfunction snapshotOf(state: BuilderState, effect?: CanvasHistoryEffect): CanvasSnapshot {\n return { root: state.present, preserved: state.preserved, ...(effect ? { effect } : {}) }\n}\n\n/** EC-728 — the crossing to report when an Undo/Redo moves across a step carrying `effect`. */\nfunction crossing(\n state: BuilderState,\n direction: HistoryEffectStep['direction'],\n effect: CanvasHistoryEffect | undefined,\n): HistoryEffectStep | null {\n if (!effect) return state.historyEffect\n return { seq: (state.historyEffect?.seq ?? 0) + 1, direction, effect }\n}\n\n/** The run key if that run still exists in this state, else `null` (never a ghost selection). */\nfunction liveRun(root: ComponentNode, preserved: readonly PreservedItem[], run: number | null): number | null {\n if (run === null) return null\n return runByKey(rootCount(root), preserved, run) ? run : null\n}\n\n/** How many component roots the composition has (the synthetic root's children). */\nfunction rootCount(root: ComponentNode): number {\n return root.slots?.[DEFAULT_SLOT]?.length ?? 0\n}\n\n/** Restore a history entry (undo/redo), keeping a selection only where it still exists. */\nfunction restore(state: BuilderState, to: CanvasSnapshot, past: CanvasSnapshot[], future: CanvasSnapshot[]): BuilderState {\n return {\n ...state,\n past,\n present: to.root,\n preserved: to.preserved,\n future,\n lastCoalesceKey: null,\n selectedId: getNode(to.root, state.selectedId ?? '') ? state.selectedId : null,\n selectedRun: liveRun(to.root, to.preserved, state.selectedRun),\n refusal: null,\n }\n}\n\n/** Leave the composition untouched and say why (EC-584 — never a silent no-op). */\nfunction refuse(state: BuilderState, action: PlacingAction, verdict: PlacementVerdict): BuilderState {\n return { ...state, refusal: { action: action.type, verdict } }\n}\n\n/**\n * The builder's pure state transition, CONSTRUCTED with the placement scope it judges\n * by (EC-584, owner-ratified 4a): the field's effective top-level vocabulary and the\n * manifest lookup. The scope is static per store and deliberately not reducer STATE\n * (it is the declaration the tree is judged against, not part of the tree) — the\n * reducer RECEIVES it, so there is no `(state, action)` to call without it.\n *\n * Every structural action that places a node — `insert`, `replace`, `move`, `wrap`,\n * `duplicate` — runs the ONE core judge (`subtreePlacementRefusal`) over every node\n * that enters or moves, BEFORE committing. A refusal returns the composition\n * unchanged, with the verdict in {@link BuilderState.refusal}: so no gesture — a\n * forgotten pre-check, promote, detach, a fixture's `slotChildren`, a server-only\n * paste — can place what the field, a slot or canvas eligibility forbids, and the\n * publish gate (which calls the same judge) cannot disagree with the canvas.\n *\n * Exported (with `initialBuilderState`) for unit tests — gesture determinism and\n * normalization lockstep are reducer-level properties, not render behavior.\n */\nexport function createBuilderReducer(\n placement: PlacementScope,\n): (state: BuilderState, action: Action) => BuilderState {\n return (state, action) => transition(state, action, placement)\n}\n\nfunction transition(state: BuilderState, action: Action, placement: PlacementScope): BuilderState {\n const root = state.present\n switch (action.type) {\n case 'select':\n return { ...state, selectedId: action.id, selectedRun: action.id === null ? state.selectedRun : null, refusal: null }\n case 'selectRun':\n return {\n ...state,\n selectedRun: liveRun(root, state.preserved, action.run),\n selectedId: action.run === null ? state.selectedId : null,\n refusal: null,\n }\n case 'removeRun': {\n const run = runByKey(rootCount(root), state.preserved, action.run)\n if (!run) return state\n return commit(state, root, { preserved: replaceRun(state.preserved, run, []), selectedRun: null })\n }\n case 'setRun': {\n const run = runByKey(rootCount(root), state.preserved, action.run)\n if (!run) return state\n return commit(state, root, {\n preserved: replaceRun(state.preserved, run, action.content),\n coalesceKey: action.coalesceKey,\n selectedRun: action.content.length > 0 ? action.run : null,\n })\n }\n case 'hover':\n return state.hoveredId === action.id ? state : { ...state, hoveredId: action.id }\n case 'viewport':\n return { ...state, viewport: action.viewport }\n case 'clearRefusal':\n return state.refusal === null ? state : { ...state, refusal: null }\n\n case 'undo': {\n const prev = state.past.at(-1)\n if (!prev) return state\n // EC-728: the step's effect moves with it — onto the redo entry that repeats it.\n return {\n ...restore(state, prev, state.past.slice(0, -1), [snapshotOf(state, prev.effect), ...state.future]),\n historyEffect: crossing(state, 'undo', prev.effect),\n }\n }\n case 'redo': {\n const next = state.future[0]\n if (!next) return state\n return {\n ...restore(state, next, [...state.past, snapshotOf(state, next.effect)], state.future.slice(1)),\n historyEffect: crossing(state, 'redo', next.effect),\n }\n }\n case 'rebase': {\n // EC-630: undo never reverts the external change — every snapshot absorbs it. The\n // next edit starts a new undo step (the step it would coalesce into may have been\n // dropped by the rebase, and an edit must never land in a step it cannot undo).\n const rebased = rebaseCanvas(state, action.from, action.to)\n // Counted even when it changes nothing: the canvas sync waits for every rebase it dispatched.\n if (!rebased) return { ...state, rebased: state.rebased + 1 }\n return {\n ...state,\n ...rebased,\n past: [...rebased.past],\n future: [...rebased.future],\n lastCoalesceKey: null,\n rebased: state.rebased + 1,\n }\n }\n\n case 'insert': {\n const node = action.minted ? action.node : cloneWithNewIds(action.node, state.newId)\n const verdict = subtreePlacementRefusal(root, node, landingOf(action.target), placement)\n if (verdict) return refuse(state, action, verdict)\n const next = insertNode(root, action.target, node)\n return commit(state, next, {\n selectedId: action.select === false ? state.selectedId : node.id,\n })\n }\n case 'remove': {\n const parent = getParentInfo(root, action.id)\n const next = removeNode(root, action.id)\n const selectedId =\n state.selectedId === action.id ? (parent?.parent.id ?? null) : state.selectedId\n return commit(state, next, { selectedId })\n }\n case 'duplicate': {\n // The copy (and every node of its subtree) ENTERS beside the original.\n const info = getParentInfo(root, action.id)\n const source = getNode(root, action.id)\n if (info && source) {\n const verdict = subtreePlacementRefusal(root, source, { parentId: info.parent.id, slot: info.slot }, placement)\n if (verdict) return refuse(state, action, verdict)\n }\n const { root: next, newId } = duplicateNode(root, action.id, state.newId)\n return commit(state, next, { selectedId: newId ?? state.selectedId })\n }\n case 'reorder':\n // Same parent, same slot: the placement does not change — nothing to judge.\n return commit(state, reorderNode(root, action.id, action.delta))\n case 'move': {\n // A node that changes parent or slot lands somewhere new (its descendants keep\n // their own slots, so only it is judged); a move within its own slot is a\n // reorder and leaves the placement as it was.\n const info = getParentInfo(root, action.id)\n const node = getNode(root, action.id)\n const relocates = !info || info.parent.id !== action.target.parentId || info.slot !== action.target.slot\n if (node && relocates) {\n const verdict = subtreePlacementRefusal(root, withoutSlots(node), landingOf(action.target), placement)\n if (verdict) return refuse(state, action, verdict)\n }\n return commit(state, moveNode(root, action.id, action.target))\n }\n case 'replace': {\n // Mint fresh ids for the incoming nodes (page-local namespace) so a detached\n // copy never collides with the page, and a promoted block's source subtree\n // (kept for the new reusable document) stays untouched.\n const cloned = action.nodes.map((n) => cloneWithNewIds(n, state.newId))\n // EC-560: promote (one embed) and detach (the reusable's content) land where the\n // replaced node was — judged there like any insert (the reuse preflight asks the\n // same `replacePlacementRefusal` before any side effect).\n const verdict = replacePlacementRefusal(root, action.id, cloned, placement)\n if (verdict) return refuse(state, action, verdict)\n const next = replaceNode(root, action.id, cloned)\n if (next === root) return state // root or absent id — no-op\n return commit(state, next, {\n selectedId: action.select === false ? state.selectedId : (cloned[0]?.id ?? state.selectedId),\n ...(action.effect ? { effect: action.effect } : {}),\n })\n }\n case 'wrap': {\n // Layout gesture (EC-162): the reference and the dragged subject become\n // the two columns of a new Grid container — ONE structural edit, one\n // history entry, one mirrored command, so a single undo dissolves the\n // whole gesture.\n const partner =\n action.subject.kind === 'node'\n ? { kind: 'node' as const, nodeId: action.subject.nodeId }\n : { kind: 'subtree' as const, node: cloneWithNewIds(action.subject.node, state.newId) }\n // EC-591: the gesture builds the `layout.grid` component; with none, it is off\n // (the drop rules refuse it before dispatch — this guard keeps the reducer total).\n const gridComponentId = state.layout.grid\n if (gridComponentId === undefined) return state\n // EC-584: the Grid lands where the reference is; the reference and the partner\n // land in the Grid's column slot. A moved partner keeps its own subtree (only it\n // relocates); a new one (a blocks-panel tile) enters whole.\n const reference = getNode(root, action.referenceId)\n const referenceInfo = getParentInfo(root, action.referenceId)\n const partnerNode = partner.kind === 'node' ? getNode(root, partner.nodeId) : partner.node\n if (reference && referenceInfo && partnerNode) {\n const columns = [withoutSlots(reference), partner.kind === 'node' ? withoutSlots(partnerNode) : partnerNode]\n const probe = gridContainerNode(gridComponentId, 'wrap', WRAP_GRID_OPTIONS, columns)\n const verdict = subtreePlacementRefusal(\n root,\n probe,\n { parentId: referenceInfo.parent.id, slot: referenceInfo.slot },\n placement,\n )\n if (verdict) return refuse(state, action, verdict)\n }\n const containerId = state.newId()\n const wrapped = applyWrap({\n root,\n gridComponentId,\n referenceId: action.referenceId,\n side: action.side,\n partner,\n containerId,\n })\n if (!wrapped) return state\n return commit(state, wrapped.root, { selectedId: containerId })\n }\n case 'setProp':\n return commit(state, setNodeProp(root, action.id, action.name, action.value), {\n coalesceKey: action.coalesceKey,\n })\n case 'removeProp':\n return commit(state, removeNodeProp(root, action.id, action.name))\n default:\n return state\n }\n}\n\nfunction landingOf(target: InsertTarget): { parentId: string; slot?: string } {\n return { parentId: target.parentId, slot: target.slot }\n}\n\n/** The node alone — a move relocates it; its descendants keep their own slots. */\nfunction withoutSlots(node: ComponentNode): ComponentNode {\n const { slots: _slots, ...rest } = node\n return rest\n}\n\n/**\n * The composition FIELD whose value the store edits (EC-554). Static for the\n * store's lifetime and deliberately NOT reducer state: it is the declaration the\n * edited tree is judged against, not part of the tree. It travels WITH the store\n * so every placement surface under the provider — the canvas and page-tree\n * drag-and-drop, paste (canvas, tree, keyboard), and the insert offer — reads the\n * same value from the one context it already requires; none can be mounted\n * without it, and `BuilderProvider` cannot be mounted without declaring it.\n */\nexport interface CompositionFieldScope {\n /** The field's display label — what a refusal notice names (e.g. \"Canvas\"). */\n label: string\n /**\n * The field's EFFECTIVE top-level vocabulary (EC-188; EC-584 — `fieldAllowList(field)`:\n * its `allow`, else the `blocks` type's default). The judge applies it only to\n * direct children of the composition root (`allowAt`, core `placement.ts`).\n */\n allow: AllowList\n}\n\nexport interface BuilderStore extends BuilderState {\n canUndo: boolean\n canRedo: boolean\n selectedNode: ComponentNode | null\n /** The composition field being edited (EC-554) — see {@link CompositionFieldScope}. */\n field: CompositionFieldScope\n /**\n * EC-584 — what the reducer judges every placement by: the manifest lookup and the\n * field's vocabulary. The gestures' own pre-checks (drag-and-drop, paste, the insert\n * offer, the reuse preflight) read the SAME scope, so an indicator and the sink agree.\n */\n placement: PlacementScope\n dispatch: (action: Action) => void\n}\n\nconst { Context: BuilderContext, useRequired: useBuilder } =\n createRequiredContext<BuilderStore>('Builder')\n\nexport function initialBuilderState(\n composition: ComponentNode,\n layout: LayoutContainerIds,\n newId: IdFactory,\n /** EC-549 — the field value's typography items with their anchors (`splitBlockRoots`). */\n preserved: readonly PreservedItem[] = [],\n): BuilderState {\n // Start container-normal (idempotent on healthy trees) so the session and the\n // lifted baseline agree from the first edit.\n const present = normalizeContainers(composition, layout)\n return {\n past: [],\n present,\n future: [],\n preserved,\n selectedId: present.id,\n selectedRun: null,\n hoveredId: null,\n viewport: 'full',\n // EC-578: fresh ids come from the injected factory — never a counter seeded past\n // the tree's `node-<n>` ids (EC-203), which two sessions advanced identically.\n newId,\n lastCoalesceKey: null,\n layout,\n refusal: null,\n rebased: 0,\n historyEffect: null,\n }\n}\n\n/**\n * Undo/redo design (EC-141): the history stack is *UI state* — an in-memory\n * stack of composition-root snapshots. EC-287 retired the DB-resident project\n * graph and its append-only revision log, so the store no longer mirrors edits onto a\n * persistence layer: it is a pure in-memory editor. The block-field editor lifts\n * its committed composition into the open CMS document via `onChange`\n * (`composition-field-editor`); the document's own Save persists it as content.\n * EC-630: a change of the field made underneath the store (a colleague's patch) is\n * absorbed by the present AND every snapshot (`rebase`, `canvas-rebase.ts`), so an undo\n * never reverts it.\n */\nexport function BuilderProvider({\n composition,\n preserved,\n field,\n components,\n layout,\n idFactory,\n children,\n}: {\n /** The composition root to edit (the composition-field editor's synthetic root). */\n composition: ComponentNode\n /** EC-549 — the field value's typography items (`splitBlockRoots(value).preserved`). */\n preserved?: readonly PreservedItem[]\n /** The field the composition is the value of (EC-554) — required, never defaulted. */\n field: CompositionFieldScope\n /** The manifest lookup the placement judge reads (EC-584, `registry.lookup`) — required. */\n components: ComponentLookup\n /** The layout-role component ids (EC-591, `ComponentRegistry.layout`) — required. */\n layout: LayoutContainerIds\n /**\n * EC-578 — the node-id factory. Defaults to UUIDs (`createUuidIdFactory`, one per\n * store); fixtures inject a deterministic factory.\n */\n idFactory?: IdFactory\n children: ReactNode\n}) {\n const [newId] = useState<IdFactory>(() => idFactory ?? createUuidIdFactory())\n // EC-584: the reducer is constructed ONCE with the scope it judges by — the field\n // and the lookup are static for the store's lifetime (a remount re-reads them).\n const [placement] = useState<PlacementScope>(() => ({ components, fieldAllow: field.allow }))\n const [reducer] = useState(() => createBuilderReducer(placement))\n // EC-287: nothing persists a graph — committed edits are lifted into the CMS\n // document by the composition-field editor's `onChange`. `useReducer` drives the\n // pure reducer (consecutive dispatches in one gesture apply in sequence); the\n // store below decorates the state with the derived undo/redo + selection flags.\n const [state, dispatch] = useReducer(reducer, { composition, layout, newId, preserved }, (init) =>\n initialBuilderState(init.composition, init.layout, init.newId, init.preserved),\n )\n\n const store = useMemo<BuilderStore>(() => {\n const selectedNode = state.selectedId\n ? (getNode(state.present, state.selectedId) ?? null)\n : null\n return {\n ...state,\n canUndo: state.past.length > 0,\n canRedo: state.future.length > 0,\n selectedNode,\n field,\n placement,\n dispatch,\n }\n }, [state, field, placement, dispatch])\n\n return <BuilderContext.Provider value={store}>{children}</BuilderContext.Provider>\n}\n\nexport { useBuilder }\n"]}
1
+ {"version":3,"file":"builder-store.js","sourceRoot":"","sources":["../../../src/components/builder/builder-store.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAErD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,OAAO,EACP,aAAa,EACb,iBAAiB,EACjB,UAAU,EACV,QAAQ,EACR,mBAAmB,EACnB,UAAU,EACV,cAAc,EACd,WAAW,EACX,WAAW,EACX,uBAAuB,EACvB,WAAW,EACX,uBAAuB,GACxB,MAAM,+BAA+B,CAAA;AAWtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAA;AAEjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAA;AAE3D,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AACvE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAEpD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAA;AAElE,MAAM,aAAa,GAAG,GAAG,CAAA;AA2LzB;;;;;;;;;;GAUG;AACH,SAAS,MAAM,CACb,KAAmB,EACnB,IAAmB,EACnB,OAOI,EAAE;IAEN,MAAM,UAAU,GAAG,mBAAmB,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;IAC1D,MAAM,OAAO,GAAG,UA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SAAS,CAAC,CAC/E,CAAA;IAED,MAAM,KAAK,GAAG,OAAO,CAAe,GAAG,EAAE;QACvC,MAAM,YAAY,GAAG,KAAK,CAAC,UAAU;YACnC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC;YACpD,CAAC,CAAC,IAAI,CAAA;QACR,OAAO;YACL,GAAG,KAAK;YACR,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC;YAC9B,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;YAChC,YAAY;YACZ,KAAK;YACL,SAAS;YACT,cAAc,EAAE,UAAU;YAC1B,QAAQ;SACT,CAAA;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAA;IAEnD,OAAO,KAAC,cAAc,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA2B,CAAA;AACpF,CAAC;AAED,OAAO,EAAE,UAAU,EAAE,CAAA","sourcesContent":["import { useMemo, useReducer, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport {\n DEFAULT_SLOT,\n duplicateNode,\n getNode,\n getParentInfo,\n gridContainerNode,\n insertNode,\n moveNode,\n normalizeContainers,\n removeNode,\n removeNodeProp,\n reorderNode,\n replaceNode,\n replacePlacementRefusal,\n setNodeProp,\n subtreePlacementRefusal,\n} from '@elytracms/core/project-graph'\nimport type {\n AllowList,\n ComponentLookup,\n ComponentNode,\n InsertTarget,\n LayoutContainerIds,\n PlacementScope,\n PlacementVerdict,\n PropValue,\n} from '@elytracms/core/project-graph'\nimport { createUuidIdFactory } from '@elytracms/core/persistence'\nimport type { IdFactory } from '@elytracms/core/persistence'\nimport { withFreshNodeIds } from '@elytracms/core/cms-core'\nimport type { CmsDocument, DocumentRef, PropFieldLookup } from '@elytracms/core/cms-core'\nimport { WRAP_GRID_OPTIONS, applyWrap } from '../../lib/dnd/drop-rules'\nimport { replaceRun, runByKey } from './canvas-runs'\nimport type { PreservedItem } from './canvas-runs'\nimport { rebaseCanvas } from './canvas-rebase'\nimport { createRequiredContext } from '../../lib/required-context'\n\nconst HISTORY_LIMIT = 100\n\n/**\n * A canvas preview-width key (EC-250): `'full'` (unconstrained) or a configured\n * breakpoint name (`'sm'`, `'md'`, …). Dynamic because the set is sourced from\n * the consuming site's breakpoints, so it is a string, not a fixed union — the\n * switcher resolves the available options via {@link resolveCanvasViewports}.\n */\nexport type Viewport = string\n\n/**\n * The builder store's action union. EC-287 retired the DB-resident project graph\n * and its persistence mirror, so these actions are pure in-memory editor state —\n * no action maps to a persisted `graph.*` command anymore. The block-field editor\n * lifts committed edits into the CMS document via `onChange`\n * (`composition-field-editor`); nothing persists a graph.\n */\nexport type BuilderAction =\n | { type: 'select'; id: string | null }\n | { type: 'hover'; id: string | null }\n | { type: 'viewport'; viewport: Viewport }\n | { type: 'undo' }\n | { type: 'redo' }\n /**\n * Insert a node (its subtree re-id'd from the store's id factory). `minted` — the\n * node ALREADY carries fresh ids from the same factory (the paste path mints first\n * so its issue deep links name exactly the ids that land); the reducer then inserts\n * it as given.\n */\n | { type: 'insert'; target: InsertTarget; node: ComponentNode; select?: boolean; minted?: true }\n | { type: 'remove'; id: string }\n | { type: 'duplicate'; id: string }\n | { type: 'reorder'; id: string; delta: -1 | 1 }\n | { type: 'move'; id: string; target: InsertTarget }\n /**\n * EC-282 reuse gesture: replace a node with zero or more nodes at its\n * position (clone-with-fresh-ids, like `insert`). Promote → 1 embed node;\n * detach → the referenced element's inline blocks. One atomic structural\n * edit, one undo step. EC-728: `effect` — what the step did OUTSIDE the canvas\n * (promote created a reusable document), recorded on that one history entry.\n */\n | { type: 'replace'; id: string; nodes: ComponentNode[]; select?: boolean; effect?: CanvasHistoryEffect }\n /**\n * EC-162 layout gesture: wrap the reference node and the dragged subject in\n * a two-column Grid container as ONE atomic structural edit (one undo step).\n */\n | {\n type: 'wrap'\n referenceId: string\n side: 'left' | 'right'\n subject: { kind: 'node'; nodeId: string } | { kind: 'component'; node: ComponentNode }\n }\n | { type: 'setProp'; id: string; name: string; value: PropValue; coalesceKey?: string }\n | { type: 'removeProp'; id: string; name: string }\n /** EC-584: the editor dismissed the visible refusal ({@link BuilderState.refusal}). */\n | { type: 'clearRefusal' }\n /**\n * EC-549 — select a typography RUN by its key (`canvas-runs.ts`: the index of its\n * first preserved item); `null` clears it. A run and a node are never both selected.\n */\n | { type: 'selectRun'; run: number | null }\n /** EC-549 — delete a typography run: a real, undoable edit of the preserved list. */\n | { type: 'removeRun'; run: number }\n /**\n * EC-549 — replace a run's typography with `content` (the inspector's rich-text\n * editor on that run; consecutive same-key edits coalesce into one undo step). Empty\n * `content` deletes the run.\n */\n | { type: 'setRun'; run: number; content: readonly unknown[]; coalesceKey?: string }\n /**\n * EC-630 — the field's value changed UNDERNEATH the canvas (a colleague's patch by\n * subscription, a write's canonical row, a resolved conflict), from `from` to `to` (the\n * draft's values before and after): the present absorbs the change and the history and\n * selection rebase onto it (`canvas-rebase.ts`) — never a remount. Not an edit: it adds\n * no history entry, and the canvas writes nothing for it.\n */\n | { type: 'rebase'; from: unknown; to: unknown }\n\n/** The structural actions the placement judge rules on (EC-584): every node that enters or moves. */\nexport type PlacingAction = Extract<BuilderAction, { type: 'insert' | 'replace' | 'move' | 'wrap' | 'duplicate' }>\n\n/** A refused placement (EC-584): the judge's verdict and the action it refused. */\nexport interface PlacementRefusal {\n action: PlacingAction['type']\n verdict: PlacementVerdict\n}\n\n/**\n * EC-728 — what a canvas step did OUTSIDE the canvas, so Undo can reverse it and Redo repeat\n * it: *Make reusable* created a reusable document (the canvas half of the gesture — the block\n * swapped for its embed — is the entry's snapshot like any edit's). The store only CARRIES it:\n * the reuse provider performs the document side when an Undo or Redo crosses the step\n * ({@link BuilderState.historyEffect}).\n */\nexport interface CanvasHistoryEffect {\n readonly kind: 'reusable-created'\n readonly ref: DocumentRef\n /** The name the editor gave it — what a notice names. */\n readonly name: string\n /** The document as created — what Redo re-inserts (the same id, insert-if-absent). */\n readonly document: CmsDocument\n}\n\n/**\n * One history entry (EC-549): the component tree AND the preserved typography — so a\n * run's deletion or edit is undone exactly like a block's.\n *\n * EC-728 — `effect` belongs to the STEP between this entry and its neighbour toward the\n * present: on an undo entry (`past`), the step forward from it; on a redo entry (`future`),\n * the step forward to it. Undo and Redo move it with the step, so it is reversed and\n * repeated exactly once per crossing.\n */\nexport interface CanvasSnapshot {\n root: ComponentNode\n preserved: readonly PreservedItem[]\n effect?: CanvasHistoryEffect\n}\n\n/**\n * EC-728 — the last Undo or Redo that crossed a step with an effect outside the canvas:\n * which way, and the effect. `seq` increases with every such crossing, so a consumer handles\n * each exactly once.\n */\nexport interface HistoryEffectStep {\n readonly seq: number\n readonly direction: 'undo' | 'redo'\n readonly effect: CanvasHistoryEffect\n}\n\nexport interface BuilderState {\n /**\n * The edited composition: one root-bearing component tree (EC-287). The canvas\n * wraps a page document's `body` blocks into a synthetic root and edits it\n * directly — no page/layout wrapper. Undo/redo snapshot it with the preserved\n * typography ({@link CanvasSnapshot}).\n */\n past: CanvasSnapshot[]\n present: ComponentNode\n future: CanvasSnapshot[]\n /**\n * EC-549 — the field value's typography items (no ids, EC-500 D1), each anchored by\n * how many component roots preceded it (`componentPrefix`); the field value is\n * `mergeBlockRoots(present's roots, preserved)`. In the store, so selecting,\n * deleting and editing a run is a real action with truthful undo.\n */\n preserved: readonly PreservedItem[]\n selectedId: string | null\n /** EC-549 — the selected typography run's key, or `null` (exclusive with {@link selectedId}). */\n selectedRun: number | null\n hoveredId: string | null\n viewport: Viewport\n /**\n * EC-578 / EC-595 A2 — THE node-id factory (injected; UUIDs in the studio, a\n * sequential factory in fixtures). It replaced the per-session `node-<n>` counter,\n * which two sessions editing one page advanced identically — both minted the same\n * next id, a `duplicate-node-id` on the second save. Stored ids are untouched.\n */\n newId: IdFactory\n /** Coalescing key of the last edit (consecutive same-key edits don't stack history). */\n lastCoalesceKey: string | null\n /**\n * The components filling the layout roles (EC-591, `ComponentRegistry.layout`),\n * fixed for the store's lifetime: which nodes container normalization treats as\n * Stack/Grid, and the Grid the wrap gesture builds. No hardcoded engine id.\n */\n layout: LayoutContainerIds\n /**\n * EC-584 — the last REFUSED placement, with its reason: the reducer judged an\n * `insert`/`replace`/`move`/`wrap`/`duplicate` against the field and slot\n * vocabularies and canvas eligibility (the core placement judge) and left the\n * composition unchanged. Transient — the next edit, selection, undo or redo clears\n * it — and never silent: the canvas shows it (`PlacementRefusalNotice`). A refused\n * action changes no tree, so it adds no history entry and emits no canvas patch.\n */\n refusal: PlacementRefusal | null\n /**\n * EC-630 — how many `rebase` actions the store has applied (external changes of its\n * field). The canvas sync reads it to tell a store value from before a rebase it\n * dispatched from one after it (`createCanvasSync`).\n */\n rebased: number\n /** EC-728 — see {@link HistoryEffectStep}; `null` until an Undo or Redo crosses an effectful step. */\n historyEffect: HistoryEffectStep | null\n}\n\ntype Action = BuilderAction\n\n/**\n * Push a new graph onto history, coalescing consecutive edits with the same key.\n *\n * Every commit normalizes layout containers (EC-162 ledger fix): the\n * operations layer normalizes every persisted `graph.*` write (EC-161), so\n * the optimistic working graph must apply the same `normalizeContainers` pass\n * or the UI state diverges from the persisted revision after\n * container-emptying moves/removes. The mirrored command stays un-normalized\n * (`graphInvocationFor` sees the raw action); both sides normalize\n * identically, so they land on the same graph.\n */\nfunction commit(\n state: BuilderState,\n root: ComponentNode,\n opts: {\n coalesceKey?: string\n selectedId?: string | null\n preserved?: readonly PreservedItem[]\n selectedRun?: number | null\n /** EC-728 — the step's effect outside the canvas (never coalesced: it is its own step). */\n effect?: CanvasHistoryEffect\n } = {},\n): BuilderState {\n const normalized = normalizeContainers(root, state.layout)\n const present = normalized\n const preserved = opts.preserved ?? state.preserved\n const coalesce = opts.effect === undefined && opts.coalesceKey != null && opts.coalesceKey === state.lastCoalesceKey\n // Normalization can dissolve the node a caller wanted selected (e.g. the\n // parent container of a removed child) — selection never points at a ghost.\n const desired = opts.selectedId !== undefined ? opts.selectedId : state.selectedId\n const selectedId = desired !== null && getNode(normalized, desired) ? desired : null\n const desiredRun = opts.selectedRun !== undefined ? opts.selectedRun : state.selectedRun\n return {\n ...state,\n past: coalesce ? state.past : [...state.past, snapshotOf(state, opts.effect)].slice(-HISTORY_LIMIT),\n present,\n preserved,\n future: [],\n lastCoalesceKey: opts.coalesceKey ?? null,\n selectedId,\n selectedRun: liveRun(present, preserved, desiredRun),\n refusal: null,\n }\n}\n\nfunction snapshotOf(state: BuilderState, effect?: CanvasHistoryEffect): CanvasSnapshot {\n return { root: state.present, preserved: state.preserved, ...(effect ? { effect } : {}) }\n}\n\n/** EC-728 — the crossing to report when an Undo/Redo moves across a step carrying `effect`. */\nfunction crossing(\n state: BuilderState,\n direction: HistoryEffectStep['direction'],\n effect: CanvasHistoryEffect | undefined,\n): HistoryEffectStep | null {\n if (!effect) return state.historyEffect\n return { seq: (state.historyEffect?.seq ?? 0) + 1, direction, effect }\n}\n\n/** The run key if that run still exists in this state, else `null` (never a ghost selection). */\nfunction liveRun(root: ComponentNode, preserved: readonly PreservedItem[], run: number | null): number | null {\n if (run === null) return null\n return runByKey(rootCount(root), preserved, run) ? run : null\n}\n\n/** How many component roots the composition has (the synthetic root's children). */\nfunction rootCount(root: ComponentNode): number {\n return root.slots?.[DEFAULT_SLOT]?.length ?? 0\n}\n\n/** Restore a history entry (undo/redo), keeping a selection only where it still exists. */\nfunction restore(state: BuilderState, to: CanvasSnapshot, past: CanvasSnapshot[], future: CanvasSnapshot[]): BuilderState {\n return {\n ...state,\n past,\n present: to.root,\n preserved: to.preserved,\n future,\n lastCoalesceKey: null,\n selectedId: getNode(to.root, state.selectedId ?? '') ? state.selectedId : null,\n selectedRun: liveRun(to.root, to.preserved, state.selectedRun),\n refusal: null,\n }\n}\n\n/** Leave the composition untouched and say why (EC-584 — never a silent no-op). */\nfunction refuse(state: BuilderState, action: PlacingAction, verdict: PlacementVerdict): BuilderState {\n return { ...state, refusal: { action: action.type, verdict } }\n}\n\n/**\n * The builder's pure state transition, CONSTRUCTED with the placement scope it judges\n * by (EC-584, owner-ratified 4a): the field's effective top-level vocabulary and the\n * manifest lookup. The scope is static per store and deliberately not reducer STATE\n * (it is the declaration the tree is judged against, not part of the tree) — the\n * reducer RECEIVES it, so there is no `(state, action)` to call without it.\n *\n * Every structural action that places a node — `insert`, `replace`, `move`, `wrap`,\n * `duplicate` — runs the ONE core judge (`subtreePlacementRefusal`) over every node\n * that enters or moves, BEFORE committing. A refusal returns the composition\n * unchanged, with the verdict in {@link BuilderState.refusal}: so no gesture — a\n * forgotten pre-check, promote, detach, a fixture's `slotChildren`, a server-only\n * paste — can place what the field, a slot or canvas eligibility forbids, and the\n * publish gate (which calls the same judge) cannot disagree with the canvas.\n *\n * EC-776 — and with the project's prop declarations (`lookupManifest`): every action that\n * COPIES a subtree into the composition (`insert`, `duplicate`, `replace`, a built `wrap`\n * partner) mints every id of it through `withFreshNodeIds` — the slot children AND the nodes\n * the props hold (a rich-text prop's embeds, a composition host's value). Required, so no\n * store can copy a subtree whose prop-held nodes keep their ids.\n *\n * Exported (with `initialBuilderState`) for unit tests — gesture determinism and\n * normalization lockstep are reducer-level properties, not render behavior.\n */\nexport function createBuilderReducer(\n placement: PlacementScope,\n lookupManifest: PropFieldLookup,\n): (state: BuilderState, action: Action) => BuilderState {\n return (state, action) => transition(state, action, placement, lookupManifest)\n}\n\nfunction transition(\n state: BuilderState,\n action: Action,\n placement: PlacementScope,\n lookupManifest: PropFieldLookup,\n): BuilderState {\n const root = state.present\n // EC-776: THE copy of a subtree — fresh ids at every depth, from the store's factory.\n const fresh = (node: ComponentNode): ComponentNode => withFreshNodeIds(node, state.newId, { lookupManifest })\n switch (action.type) {\n case 'select':\n return { ...state, selectedId: action.id, selectedRun: action.id === null ? state.selectedRun : null, refusal: null }\n case 'selectRun':\n return {\n ...state,\n selectedRun: liveRun(root, state.preserved, action.run),\n selectedId: action.run === null ? state.selectedId : null,\n refusal: null,\n }\n case 'removeRun': {\n const run = runByKey(rootCount(root), state.preserved, action.run)\n if (!run) return state\n return commit(state, root, { preserved: replaceRun(state.preserved, run, []), selectedRun: null })\n }\n case 'setRun': {\n const run = runByKey(rootCount(root), state.preserved, action.run)\n if (!run) return state\n return commit(state, root, {\n preserved: replaceRun(state.preserved, run, action.content),\n coalesceKey: action.coalesceKey,\n selectedRun: action.content.length > 0 ? action.run : null,\n })\n }\n case 'hover':\n return state.hoveredId === action.id ? state : { ...state, hoveredId: action.id }\n case 'viewport':\n return { ...state, viewport: action.viewport }\n case 'clearRefusal':\n return state.refusal === null ? state : { ...state, refusal: null }\n\n case 'undo': {\n const prev = state.past.at(-1)\n if (!prev) return state\n // EC-728: the step's effect moves with it — onto the redo entry that repeats it.\n return {\n ...restore(state, prev, state.past.slice(0, -1), [snapshotOf(state, prev.effect), ...state.future]),\n historyEffect: crossing(state, 'undo', prev.effect),\n }\n }\n case 'redo': {\n const next = state.future[0]\n if (!next) return state\n return {\n ...restore(state, next, [...state.past, snapshotOf(state, next.effect)], state.future.slice(1)),\n historyEffect: crossing(state, 'redo', next.effect),\n }\n }\n case 'rebase': {\n // EC-630: undo never reverts the external change — every snapshot absorbs it. The\n // next edit starts a new undo step (the step it would coalesce into may have been\n // dropped by the rebase, and an edit must never land in a step it cannot undo).\n const rebased = rebaseCanvas(state, action.from, action.to)\n // Counted even when it changes nothing: the canvas sync waits for every rebase it dispatched.\n if (!rebased) return { ...state, rebased: state.rebased + 1 }\n return {\n ...state,\n ...rebased,\n past: [...rebased.past],\n future: [...rebased.future],\n lastCoalesceKey: null,\n rebased: state.rebased + 1,\n }\n }\n\n case 'insert': {\n const node = action.minted ? action.node : fresh(action.node)\n const verdict = subtreePlacementRefusal(root, node, landingOf(action.target), placement)\n if (verdict) return refuse(state, action, verdict)\n const next = insertNode(root, action.target, node)\n return commit(state, next, {\n selectedId: action.select === false ? state.selectedId : node.id,\n })\n }\n case 'remove': {\n const parent = getParentInfo(root, action.id)\n const next = removeNode(root, action.id)\n const selectedId =\n state.selectedId === action.id ? (parent?.parent.id ?? null) : state.selectedId\n return commit(state, next, { selectedId })\n }\n case 'duplicate': {\n // The copy (and every node of its subtree) ENTERS beside the original.\n const info = getParentInfo(root, action.id)\n const source = getNode(root, action.id)\n if (info && source) {\n const verdict = subtreePlacementRefusal(root, source, { parentId: info.parent.id, slot: info.slot }, placement)\n if (verdict) return refuse(state, action, verdict)\n }\n const { root: next, newId } = duplicateNode(root, action.id, fresh)\n return commit(state, next, { selectedId: newId ?? state.selectedId })\n }\n case 'reorder':\n // Same parent, same slot: the placement does not change — nothing to judge.\n return commit(state, reorderNode(root, action.id, action.delta))\n case 'move': {\n // A node that changes parent or slot lands somewhere new (its descendants keep\n // their own slots, so only it is judged); a move within its own slot is a\n // reorder and leaves the placement as it was.\n const info = getParentInfo(root, action.id)\n const node = getNode(root, action.id)\n const relocates = !info || info.parent.id !== action.target.parentId || info.slot !== action.target.slot\n if (node && relocates) {\n const verdict = subtreePlacementRefusal(root, withoutSlots(node), landingOf(action.target), placement)\n if (verdict) return refuse(state, action, verdict)\n }\n return commit(state, moveNode(root, action.id, action.target))\n }\n case 'replace': {\n // Mint fresh ids for the incoming nodes — every depth, props included (EC-776) — so a\n // detached copy never collides with the page, and a promoted block's source subtree\n // (kept for the new reusable document) stays untouched.\n const cloned = action.nodes.map(fresh)\n // EC-560: promote (one embed) and detach (the reusable's content) land where the\n // replaced node was — judged there like any insert (the reuse preflight asks the\n // same `replacePlacementRefusal` before any side effect).\n const verdict = replacePlacementRefusal(root, action.id, cloned, placement)\n if (verdict) return refuse(state, action, verdict)\n const next = replaceNode(root, action.id, cloned)\n if (next === root) return state // root or absent id — no-op\n return commit(state, next, {\n selectedId: action.select === false ? state.selectedId : (cloned[0]?.id ?? state.selectedId),\n ...(action.effect ? { effect: action.effect } : {}),\n })\n }\n case 'wrap': {\n // Layout gesture (EC-162): the reference and the dragged subject become\n // the two columns of a new Grid container — ONE structural edit, one\n // history entry, one mirrored command, so a single undo dissolves the\n // whole gesture.\n const partner =\n action.subject.kind === 'node'\n ? { kind: 'node' as const, nodeId: action.subject.nodeId }\n : { kind: 'subtree' as const, node: fresh(action.subject.node) }\n // EC-591: the gesture builds the `layout.grid` component; with none, it is off\n // (the drop rules refuse it before dispatch — this guard keeps the reducer total).\n const gridComponentId = state.layout.grid\n if (gridComponentId === undefined) return state\n // EC-584: the Grid lands where the reference is; the reference and the partner\n // land in the Grid's column slot. A moved partner keeps its own subtree (only it\n // relocates); a new one (a blocks-panel tile) enters whole.\n const reference = getNode(root, action.referenceId)\n const referenceInfo = getParentInfo(root, action.referenceId)\n const partnerNode = partner.kind === 'node' ? getNode(root, partner.nodeId) : partner.node\n if (reference && referenceInfo && partnerNode) {\n const columns = [withoutSlots(reference), partner.kind === 'node' ? withoutSlots(partnerNode) : partnerNode]\n const probe = gridContainerNode(gridComponentId, 'wrap', WRAP_GRID_OPTIONS, columns)\n const verdict = subtreePlacementRefusal(\n root,\n probe,\n { parentId: referenceInfo.parent.id, slot: referenceInfo.slot },\n placement,\n )\n if (verdict) return refuse(state, action, verdict)\n }\n const containerId = state.newId()\n const wrapped = applyWrap({\n root,\n gridComponentId,\n referenceId: action.referenceId,\n side: action.side,\n partner,\n containerId,\n })\n if (!wrapped) return state\n return commit(state, wrapped.root, { selectedId: containerId })\n }\n case 'setProp':\n return commit(state, setNodeProp(root, action.id, action.name, action.value), {\n coalesceKey: action.coalesceKey,\n })\n case 'removeProp':\n return commit(state, removeNodeProp(root, action.id, action.name))\n default:\n return state\n }\n}\n\nfunction landingOf(target: InsertTarget): { parentId: string; slot?: string } {\n return { parentId: target.parentId, slot: target.slot }\n}\n\n/** The node alone — a move relocates it; its descendants keep their own slots. */\nfunction withoutSlots(node: ComponentNode): ComponentNode {\n const { slots: _slots, ...rest } = node\n return rest\n}\n\n/**\n * The composition FIELD whose value the store edits (EC-554). Static for the\n * store's lifetime and deliberately NOT reducer state: it is the declaration the\n * edited tree is judged against, not part of the tree. It travels WITH the store\n * so every placement surface under the provider — the canvas and page-tree\n * drag-and-drop, paste (canvas, tree, keyboard), and the insert offer — reads the\n * same value from the one context it already requires; none can be mounted\n * without it, and `BuilderProvider` cannot be mounted without declaring it.\n */\nexport interface CompositionFieldScope {\n /** The field's display label — what a refusal notice names (e.g. \"Canvas\"). */\n label: string\n /**\n * The field's EFFECTIVE top-level vocabulary (EC-188; EC-584 — `fieldAllowList(field)`:\n * its `allow`, else the `blocks` type's default). The judge applies it only to\n * direct children of the composition root (`allowAt`, core `placement.ts`).\n */\n allow: AllowList\n}\n\nexport interface BuilderStore extends BuilderState {\n canUndo: boolean\n canRedo: boolean\n selectedNode: ComponentNode | null\n /** The composition field being edited (EC-554) — see {@link CompositionFieldScope}. */\n field: CompositionFieldScope\n /**\n * EC-584 — what the reducer judges every placement by: the manifest lookup and the\n * field's vocabulary. The gestures' own pre-checks (drag-and-drop, paste, the insert\n * offer, the reuse preflight) read the SAME scope, so an indicator and the sink agree.\n */\n placement: PlacementScope\n /**\n * EC-776 — the project's prop declarations the reducer mints copies with; a gesture that mints\n * a subtree itself (paste, which names the ids that land in its notice) reads the SAME lookup.\n */\n lookupManifest: PropFieldLookup\n dispatch: (action: Action) => void\n}\n\nconst { Context: BuilderContext, useRequired: useBuilder } =\n createRequiredContext<BuilderStore>('Builder')\n\nexport function initialBuilderState(\n composition: ComponentNode,\n layout: LayoutContainerIds,\n newId: IdFactory,\n /** EC-549 — the field value's typography items with their anchors (`splitBlockRoots`). */\n preserved: readonly PreservedItem[] = [],\n): BuilderState {\n // Start container-normal (idempotent on healthy trees) so the session and the\n // lifted baseline agree from the first edit.\n const present = normalizeContainers(composition, layout)\n return {\n past: [],\n present,\n future: [],\n preserved,\n selectedId: present.id,\n selectedRun: null,\n hoveredId: null,\n viewport: 'full',\n // EC-578: fresh ids come from the injected factory — never a counter seeded past\n // the tree's `node-<n>` ids (EC-203), which two sessions advanced identically.\n newId,\n lastCoalesceKey: null,\n layout,\n refusal: null,\n rebased: 0,\n historyEffect: null,\n }\n}\n\n/**\n * Undo/redo design (EC-141): the history stack is *UI state* — an in-memory\n * stack of composition-root snapshots. EC-287 retired the DB-resident project\n * graph and its append-only revision log, so the store no longer mirrors edits onto a\n * persistence layer: it is a pure in-memory editor. The block-field editor lifts\n * its committed composition into the open CMS document via `onChange`\n * (`composition-field-editor`); the document's own Save persists it as content.\n * EC-630: a change of the field made underneath the store (a colleague's patch) is\n * absorbed by the present AND every snapshot (`rebase`, `canvas-rebase.ts`), so an undo\n * never reverts it.\n */\nexport function BuilderProvider({\n composition,\n preserved,\n field,\n components,\n layout,\n lookupManifest,\n idFactory,\n children,\n}: {\n /** The composition root to edit (the composition-field editor's synthetic root). */\n composition: ComponentNode\n /** EC-549 — the field value's typography items (`splitBlockRoots(value).preserved`). */\n preserved?: readonly PreservedItem[]\n /** The field the composition is the value of (EC-554) — required, never defaulted. */\n field: CompositionFieldScope\n /** The manifest lookup the placement judge reads (EC-584, `registry.lookup`) — required. */\n components: ComponentLookup\n /** The layout-role component ids (EC-591, `ComponentRegistry.layout`) — required. */\n layout: LayoutContainerIds\n /**\n * EC-776 — the project's prop declarations (`studioManifestLookup()`) — required: every copy\n * the store makes re-mints the nodes its props hold, which only the declarations reach.\n */\n lookupManifest: PropFieldLookup\n /**\n * EC-578 — the node-id factory. Defaults to UUIDs (`createUuidIdFactory`, one per\n * store); fixtures inject a deterministic factory.\n */\n idFactory?: IdFactory\n children: ReactNode\n}) {\n const [newId] = useState<IdFactory>(() => idFactory ?? createUuidIdFactory())\n // EC-584: the reducer is constructed ONCE with the scope it judges by — the field\n // and the lookup are static for the store's lifetime (a remount re-reads them).\n const [placement] = useState<PlacementScope>(() => ({ components, fieldAllow: field.allow }))\n const [propFields] = useState<PropFieldLookup>(() => lookupManifest)\n const [reducer] = useState(() => createBuilderReducer(placement, propFields))\n // EC-287: nothing persists a graph — committed edits are lifted into the CMS\n // document by the composition-field editor's `onChange`. `useReducer` drives the\n // pure reducer (consecutive dispatches in one gesture apply in sequence); the\n // store below decorates the state with the derived undo/redo + selection flags.\n const [state, dispatch] = useReducer(reducer, { composition, layout, newId, preserved }, (init) =>\n initialBuilderState(init.composition, init.layout, init.newId, init.preserved),\n )\n\n const store = useMemo<BuilderStore>(() => {\n const selectedNode = state.selectedId\n ? (getNode(state.present, state.selectedId) ?? null)\n : null\n return {\n ...state,\n canUndo: state.past.length > 0,\n canRedo: state.future.length > 0,\n selectedNode,\n field,\n placement,\n lookupManifest: propFields,\n dispatch,\n }\n }, [state, field, placement, propFields, dispatch])\n\n return <BuilderContext.Provider value={store}>{children}</BuilderContext.Provider>\n}\n\nexport { useBuilder }\n"]}
@@ -1,7 +1,8 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useMemo, useRef, useSyncExternalStore } from 'react';
3
3
  import { AlertTriangle, CircleCheck, Crosshair, X } from 'lucide-react';
4
- import { cloneWithNewIds, subtreePlacementRefusal } from '@elytracms/core/project-graph';
4
+ import { subtreePlacementRefusal } from '@elytracms/core/project-graph';
5
+ import { withFreshNodeIds } from '@elytracms/core/cms-core';
5
6
  import { buildFragmentFromComposition } from '@elytracms/core/clipboard';
6
7
  import { readFragmentFromClipboard, readFragmentFromDataTransfer, resolvePasteTarget, diffPastedSubtree, pasteSummaryMessage, writeFragmentToClipboard, writeFragmentToDataTransfer, } from '../../lib/clipboard/index.js';
7
8
  import { getStudioRegistry } from '../../lib/registry/index.js';
@@ -122,10 +123,10 @@ export function useStudioClipboard() {
122
123
  return;
123
124
  }
124
125
  const { target, destinationLabel } = resolution;
125
- // Mint the inserted subtree's ids HERE, from the store's own factory (EC-578), and
126
- // insert exactly that subtree (`minted`) — so the issue deep links point at the
127
- // very ids that land, with no mirror to diverge.
128
- const inserted = cloneWithNewIds(pasted, b.newId);
126
+ // Mint the inserted subtree's ids HERE, from the store's own factory (EC-578) — every
127
+ // depth, the nodes its props hold included (EC-776) — and insert exactly that subtree
128
+ // (`minted`), so the issue deep links point at the very ids that land.
129
+ const inserted = withFreshNodeIds(pasted, b.newId, { lookupManifest: b.lookupManifest });
129
130
  // EC-584: the reducer judges the WHOLE pasted subtree; ask the same judge first so
130
131
  // the notice never claims a paste the sink refuses (a nested child outside its slot).
131
132
  const verdict = subtreePlacementRefusal(root, inserted, { parentId: target.parentId, slot: target.slot }, b.placement);