@elytracms/studio 0.0.20 → 0.0.21

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.
@@ -42,7 +42,7 @@ export function ReuseProvider({ children }) {
42
42
  const defaultName = manifestTitle ?? collection?.form?.labelSingular ?? collection?.form?.label ?? 'Reusable element';
43
43
  setPending({ nodeId, defaultName });
44
44
  }, [canMakeReusable, builder, manifests, capability, cms]);
45
- const confirmMakeReusable = useCallback((name) => {
45
+ const confirmMakeReusable = useCallback((name, publish) => {
46
46
  const cap = capability;
47
47
  if (!cap || !pending)
48
48
  return;
@@ -61,7 +61,18 @@ export function ReuseProvider({ children }) {
61
61
  // clones to a fresh id; the source `node` stays untouched in the new doc).
62
62
  builder.dispatch({ type: 'replace', id: pending.nodeId, nodes: [makeEmbedNode(cap, ref.id)] });
63
63
  setPending(null);
64
- toast.success(`Made “${name}” reusable — edit it from its document.`);
64
+ // EC-300: the new reusable is a separate document with its own lifecycle. A
65
+ // draft-only target resolves to nothing in the published perspective (delivery
66
+ // + the published canvas view), so the editor chooses at creation: PUBLISH keeps
67
+ // the section visible everywhere immediately (the continuity-preserving default);
68
+ // SAVE DRAFT keeps it editable, visible in the draft canvas, surfaced as a
69
+ // pending reference until published. No silent auto-publish (AD-16).
70
+ if (publish) {
71
+ void cms.publishDocument(ref).then(() => toast.success(`Made “${name}” reusable and published it.`), () => toast.error(`Made “${name}” reusable, but publishing failed — publish it from its document.`));
72
+ }
73
+ else {
74
+ toast.success(`Made “${name}” reusable (draft) — publish it to show on live pages.`);
75
+ }
65
76
  }, [capability, pending, builder, cms]);
66
77
  const detach = useCallback((nodeId) => {
67
78
  const cap = capability;
@@ -97,12 +108,11 @@ function MakeReusableDialog({ open, defaultName, onConfirm, onCancel, }) {
97
108
  setName(defaultName);
98
109
  setSeededFor(defaultName);
99
110
  }
100
- function submit(event) {
101
- event.preventDefault();
102
- const trimmed = name.trim();
103
- if (trimmed === '')
111
+ const empty = name.trim() === '';
112
+ function commit(publish) {
113
+ if (empty)
104
114
  return;
105
- onConfirm(trimmed);
115
+ onConfirm(name.trim(), publish);
106
116
  setSeededFor(null);
107
117
  }
108
118
  return (_jsx(Dialog, { open: open, onOpenChange: (next) => {
@@ -110,6 +120,9 @@ function MakeReusableDialog({ open, defaultName, onConfirm, onCancel, }) {
110
120
  onCancel();
111
121
  setSeededFor(null);
112
122
  }
113
- }, children: _jsxs(DialogContent, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Make reusable" }), _jsx(DialogDescription, { children: "Moves the selected block into a new reusable element and embeds it here. The same element can then be embedded on any page." })] }), _jsxs("form", { onSubmit: submit, children: [_jsx(Stack, { gap: "3", children: _jsx(Field, { label: "Name", htmlFor: "make-reusable-name", required: true, children: _jsx(Input, { id: "make-reusable-name", value: name, onChange: (event) => setName(event.target.value), placeholder: "Reservation CTA", autoFocus: true, required: true }) }) }), _jsxs(DialogFooter, { className: "mt-4", children: [_jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: onCancel, children: "Cancel" }), _jsx(Button, { type: "submit", size: "sm", disabled: name.trim() === '', "data-testid": "make-reusable", children: "Make reusable" })] })] })] }) }));
123
+ }, children: _jsxs(DialogContent, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Make reusable" }), _jsx(DialogDescription, { children: "Moves the selected block into a new reusable element and embeds it here. The same element can then be embedded on any page. Publish it now to keep the section visible everywhere, or save it as a draft to keep editing first." })] }), _jsxs("form", { onSubmit: (event) => {
124
+ event.preventDefault();
125
+ commit(true);
126
+ }, children: [_jsx(Stack, { gap: "3", children: _jsx(Field, { label: "Name", htmlFor: "make-reusable-name", required: true, children: _jsx(Input, { id: "make-reusable-name", value: name, onChange: (event) => setName(event.target.value), placeholder: "Reservation CTA", autoFocus: true, required: true }) }) }), _jsxs(DialogFooter, { className: "mt-4", children: [_jsx(Button, { type: "button", variant: "ghost", size: "sm", className: "mr-auto", onClick: onCancel, children: "Cancel" }), _jsx(Button, { type: "button", variant: "secondary", size: "sm", disabled: empty, onClick: () => commit(false), "data-testid": "make-reusable-draft", children: "Save Draft" }), _jsx(Button, { type: "submit", size: "sm", disabled: empty, "data-testid": "make-reusable-publish", children: "Publish" })] })] })] }) }));
114
127
  }
115
128
  //# sourceMappingURL=reuse-context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reuse-context.js","sourceRoot":"","sources":["../../../src/components/builder/reuse-context.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEjF,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAA;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAC1D,OAAO,EACL,MAAM,EACN,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,KAAK,EACL,KAAK,EACL,KAAK,EACL,KAAK,GACN,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAA;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAA;AA0BpF,MAAM,YAAY,GAAG,aAAa,CAAuB,IAAI,CAAC,CAAA;AAE9D,MAAM,UAAU,QAAQ;IACtB,OAAO,UAAU,CAAC,YAAY,CAAC,CAAA;AACjC,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,EAAE,QAAQ,EAA2B;IACjE,MAAM,OAAO,GAAG,UAAU,EAAE,CAAA;IAC5B,MAAM,GAAG,GAAG,MAAM,EAAE,CAAA;IACpB,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ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C,IAAI,EAAC,OAAO,EAAE,QAAQ,uBAExD,EACT,KAAC,MAAM,IAAC,IAAI,EAAC,QAAQ,EAAC,IAAI,EAAC,IAAI,EAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,iBAAc,eAAe,8BAEhF,IACI,IACV,IACO,GACT,CACV,CAAA;AACH,CAAC","sourcesContent":["import { createContext, useCallback, useContext, useMemo, useState } from 'react'\nimport type { FormEvent, ReactNode } from 'react'\nimport { blockRootsOf, getNode } from '@elytracms/core/project-graph'\nimport { readDocumentRef } from '@elytracms/core/cms-core'\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Field,\n Input,\n Stack,\n toast,\n} from '@elytracms/studio/ui'\nimport { getStudioRegistry } from '@elytracms/studio/lib/registry'\nimport { useCms } from '../cms/cms-store'\nimport { useBuilder } from './builder-store'\nimport { buildReusableValues, makeEmbedNode, resolveReuseCapability } from './reuse'\nimport type { ReuseCapability } from './reuse'\n\n/**\n * In-canvas reuse gestures (EC-282): \"Make reusable\" promotes a selected block to\n * a new reusable document and replaces it in place with a transcluding embed;\n * \"Detach to local copy\" inlines an embed's referenced blocks so a page can\n * diverge. Both round-trip through the existing persistence + in-Convex reference\n * index (EC-277), so where-used is correct immediately.\n *\n * The provider needs BOTH the builder store (the edited composition) and the CMS\n * store (to create/read the reusable document), so it mounts inside the\n * composition-field editor's `BuilderProvider`, itself inside the CMS document\n * editor. Where no provider is mounted (or the capability is absent), the menu\n * reads `null` and simply omits the gestures.\n */\nexport interface ReuseGestures {\n capability: ReuseCapability | null\n canMakeReusable: (nodeId: string) => boolean\n canDetach: (nodeId: string) => boolean\n /** Open the name dialog for promoting `nodeId`. */\n startMakeReusable: (nodeId: string) => void\n /** Replace a `Reusable` embed with an editable inline copy of its target's blocks. */\n detach: (nodeId: string) => void\n}\n\nconst ReuseContext = createContext<ReuseGestures | null>(null)\n\nexport function useReuse(): ReuseGestures | null {\n return useContext(ReuseContext)\n}\n\nexport function ReuseProvider({ children }: { children: ReactNode }) {\n const builder = useBuilder()\n const cms = useCms()\n const [pending, setPending] = useState<{ nodeId: string; defaultName: string } | null>(null)\n\n const manifests = useMemo(() => getStudioRegistry().registry.list(), [])\n const capability = useMemo(\n () => resolveReuseCapability(manifests, cms.collections),\n [manifests, cms.collections],\n )\n\n const canMakeReusable = useCallback(\n (nodeId: string): boolean => {\n if (!capability) return false\n const node = getNode(builder.present, nodeId)\n // Anything but the synthetic composition root can be promoted; nesting a\n // reusable inside a reusable is allowed (the renderer + bake are cycle-\n // guarded, EC-281), so an embed itself is still promotable.\n return node !== undefined && node.id !== builder.present.id\n },\n [capability, builder],\n )\n\n const canDetach = useCallback(\n (nodeId: string): boolean => {\n if (!capability) return false\n return getNode(builder.present, nodeId)?.componentId === capability.embedComponentId\n },\n [capability, builder],\n )\n\n const startMakeReusable = useCallback(\n (nodeId: string) => {\n if (!canMakeReusable(nodeId)) return\n const node = getNode(builder.present, nodeId)\n if (!node) return\n const manifestTitle = manifests.find((m) => m.id === node.componentId)?.title\n const collection = capability ? cms.getCollection(capability.collectionId) : undefined\n const defaultName =\n manifestTitle ?? collection?.form?.labelSingular ?? collection?.form?.label ?? 'Reusable element'\n setPending({ nodeId, defaultName })\n },\n [canMakeReusable, builder, manifests, capability, cms],\n )\n\n const confirmMakeReusable = useCallback(\n (name: string) => {\n const cap = capability\n if (!cap || !pending) return\n const node = getNode(builder.present, pending.nodeId)\n const collection = cms.getCollection(cap.collectionId)\n if (!node || !collection) {\n setPending(null)\n return\n }\n // Mint the reusable document, then write its title + content (createDocument\n // only seeds defaults). The new id is referenced by the embed below.\n const ref = cms.createDocument(cap.collectionId)\n const values = buildReusableValues(collection, cap, name, node, cms.documentsOf(cap.collectionId))\n cms.saveDocument({ collection: cap.collectionId, id: ref.id, values })\n // Replace the selection in place with a transcluding embed (the action\n // clones to a fresh id; the source `node` stays untouched in the new doc).\n builder.dispatch({ type: 'replace', id: pending.nodeId, nodes: [makeEmbedNode(cap, ref.id)] })\n setPending(null)\n toast.success(`Made “${name}” reusable — edit it from its document.`)\n },\n [capability, pending, builder, cms],\n )\n\n const detach = useCallback(\n (nodeId: string) => {\n const cap = capability\n if (!cap) return\n const node = getNode(builder.present, nodeId)\n if (!node || node.componentId !== cap.embedComponentId) return\n const prop = node.props?.[cap.relationProp]\n const ref = prop?.kind === 'static' ? readDocumentRef(prop.value) : undefined\n if (!ref) {\n toast.error('This element has no target to detach.')\n return\n }\n const target = cms.getDocument(ref)\n const blocks = blockRootsOf(target?.values?.[cap.contentField])\n if (blocks.length === 0) {\n toast.error('The referenced element has no content to detach.')\n return\n }\n builder.dispatch({ type: 'replace', id: nodeId, nodes: blocks })\n toast.success('Detached to an editable copy — the live link is broken.')\n },\n [capability, builder, cms],\n )\n\n const value = useMemo<ReuseGestures>(\n () => ({ capability, canMakeReusable, canDetach, startMakeReusable, detach }),\n [capability, canMakeReusable, canDetach, startMakeReusable, detach],\n )\n\n return (\n <ReuseContext.Provider value={value}>\n {children}\n <MakeReusableDialog\n open={pending !== null}\n defaultName={pending?.defaultName ?? ''}\n onConfirm={confirmMakeReusable}\n onCancel={() => setPending(null)}\n />\n </ReuseContext.Provider>\n )\n}\n\n/** Name-and-create dialog for the \"Make reusable\" gesture. */\nfunction MakeReusableDialog({\n open,\n defaultName,\n onConfirm,\n onCancel,\n}: {\n open: boolean\n defaultName: string\n onConfirm: (name: string) => void\n onCancel: () => void\n}) {\n const [name, setName] = useState(defaultName)\n // Re-seed the field each time the dialog opens for a new selection.\n const [seededFor, setSeededFor] = useState<string | null>(null)\n if (open && seededFor !== defaultName) {\n setName(defaultName)\n setSeededFor(defaultName)\n }\n\n function submit(event: FormEvent) {\n event.preventDefault()\n const trimmed = name.trim()\n if (trimmed === '') return\n onConfirm(trimmed)\n setSeededFor(null)\n }\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) {\n onCancel()\n setSeededFor(null)\n }\n }}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>Make reusable</DialogTitle>\n <DialogDescription>\n Moves the selected block into a new reusable element and embeds it here. The same element\n can then be embedded on any page.\n </DialogDescription>\n </DialogHeader>\n <form onSubmit={submit}>\n <Stack gap=\"3\">\n <Field label=\"Name\" htmlFor=\"make-reusable-name\" required>\n <Input\n id=\"make-reusable-name\"\n value={name}\n onChange={(event) => setName(event.target.value)}\n placeholder=\"Reservation CTA\"\n autoFocus\n required\n />\n </Field>\n </Stack>\n <DialogFooter className=\"mt-4\">\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={onCancel}>\n Cancel\n </Button>\n <Button type=\"submit\" size=\"sm\" disabled={name.trim() === ''} data-testid=\"make-reusable\">\n Make reusable\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n )\n}\n"]}
1
+ {"version":3,"file":"reuse-context.js","sourceRoot":"","sources":["../../../src/components/builder/reuse-context.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEjF,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAA;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAC1D,OAAO,EACL,MAAM,EACN,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,KAAK,EACL,KAAK,EACL,KAAK,EACL,KAAK,GACN,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAA;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAA;AA0BpF,MAAM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back, useContext, useMemo, useState } from 'react'\nimport type { FormEvent, ReactNode } from 'react'\nimport { blockRootsOf, getNode } from '@elytracms/core/project-graph'\nimport { readDocumentRef } from '@elytracms/core/cms-core'\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Field,\n Input,\n Stack,\n toast,\n} from '@elytracms/studio/ui'\nimport { getStudioRegistry } from '@elytracms/studio/lib/registry'\nimport { useCms } from '../cms/cms-store'\nimport { useBuilder } from './builder-store'\nimport { buildReusableValues, makeEmbedNode, resolveReuseCapability } from './reuse'\nimport type { ReuseCapability } from './reuse'\n\n/**\n * In-canvas reuse gestures (EC-282): \"Make reusable\" promotes a selected block to\n * a new reusable document and replaces it in place with a transcluding embed;\n * \"Detach to local copy\" inlines an embed's referenced blocks so a page can\n * diverge. Both round-trip through the existing persistence + in-Convex reference\n * index (EC-277), so where-used is correct immediately.\n *\n * The provider needs BOTH the builder store (the edited composition) and the CMS\n * store (to create/read the reusable document), so it mounts inside the\n * composition-field editor's `BuilderProvider`, itself inside the CMS document\n * editor. Where no provider is mounted (or the capability is absent), the menu\n * reads `null` and simply omits the gestures.\n */\nexport interface ReuseGestures {\n capability: ReuseCapability | null\n canMakeReusable: (nodeId: string) => boolean\n canDetach: (nodeId: string) => boolean\n /** Open the name dialog for promoting `nodeId`. */\n startMakeReusable: (nodeId: string) => void\n /** Replace a `Reusable` embed with an editable inline copy of its target's blocks. */\n detach: (nodeId: string) => void\n}\n\nconst ReuseContext = createContext<ReuseGestures | null>(null)\n\nexport function useReuse(): ReuseGestures | null {\n return useContext(ReuseContext)\n}\n\nexport function ReuseProvider({ children }: { children: ReactNode }) {\n const builder = useBuilder()\n const cms = useCms()\n const [pending, setPending] = useState<{ nodeId: string; defaultName: string } | null>(null)\n\n const manifests = useMemo(() => getStudioRegistry().registry.list(), [])\n const capability = useMemo(\n () => resolveReuseCapability(manifests, cms.collections),\n [manifests, cms.collections],\n )\n\n const canMakeReusable = useCallback(\n (nodeId: string): boolean => {\n if (!capability) return false\n const node = getNode(builder.present, nodeId)\n // Anything but the synthetic composition root can be promoted; nesting a\n // reusable inside a reusable is allowed (the renderer + bake are cycle-\n // guarded, EC-281), so an embed itself is still promotable.\n return node !== undefined && node.id !== builder.present.id\n },\n [capability, builder],\n )\n\n const canDetach = useCallback(\n (nodeId: string): boolean => {\n if (!capability) return false\n return getNode(builder.present, nodeId)?.componentId === capability.embedComponentId\n },\n [capability, builder],\n )\n\n const startMakeReusable = useCallback(\n (nodeId: string) => {\n if (!canMakeReusable(nodeId)) return\n const node = getNode(builder.present, nodeId)\n if (!node) return\n const manifestTitle = manifests.find((m) => m.id === node.componentId)?.title\n const collection = capability ? cms.getCollection(capability.collectionId) : undefined\n const defaultName =\n manifestTitle ?? collection?.form?.labelSingular ?? collection?.form?.label ?? 'Reusable element'\n setPending({ nodeId, defaultName })\n },\n [canMakeReusable, builder, manifests, capability, cms],\n )\n\n const confirmMakeReusable = useCallback(\n (name: string, publish: boolean) => {\n const cap = capability\n if (!cap || !pending) return\n const node = getNode(builder.present, pending.nodeId)\n const collection = cms.getCollection(cap.collectionId)\n if (!node || !collection) {\n setPending(null)\n return\n }\n // Mint the reusable document, then write its title + content (createDocument\n // only seeds defaults). The new id is referenced by the embed below.\n const ref = cms.createDocument(cap.collectionId)\n const values = buildReusableValues(collection, cap, name, node, cms.documentsOf(cap.collectionId))\n cms.saveDocument({ collection: cap.collectionId, id: ref.id, values })\n // Replace the selection in place with a transcluding embed (the action\n // clones to a fresh id; the source `node` stays untouched in the new doc).\n builder.dispatch({ type: 'replace', id: pending.nodeId, nodes: [makeEmbedNode(cap, ref.id)] })\n setPending(null)\n // EC-300: the new reusable is a separate document with its own lifecycle. A\n // draft-only target resolves to nothing in the published perspective (delivery\n // + the published canvas view), so the editor chooses at creation: PUBLISH keeps\n // the section visible everywhere immediately (the continuity-preserving default);\n // SAVE DRAFT keeps it editable, visible in the draft canvas, surfaced as a\n // pending reference until published. No silent auto-publish (AD-16).\n if (publish) {\n void cms.publishDocument(ref).then(\n () => toast.success(`Made “${name}” reusable and published it.`),\n () =>\n toast.error(\n `Made “${name}” reusable, but publishing failed — publish it from its document.`,\n ),\n )\n } else {\n toast.success(`Made “${name}” reusable (draft) — publish it to show on live pages.`)\n }\n },\n [capability, pending, builder, cms],\n )\n\n const detach = useCallback(\n (nodeId: string) => {\n const cap = capability\n if (!cap) return\n const node = getNode(builder.present, nodeId)\n if (!node || node.componentId !== cap.embedComponentId) return\n const prop = node.props?.[cap.relationProp]\n const ref = prop?.kind === 'static' ? readDocumentRef(prop.value) : undefined\n if (!ref) {\n toast.error('This element has no target to detach.')\n return\n }\n const target = cms.getDocument(ref)\n const blocks = blockRootsOf(target?.values?.[cap.contentField])\n if (blocks.length === 0) {\n toast.error('The referenced element has no content to detach.')\n return\n }\n builder.dispatch({ type: 'replace', id: nodeId, nodes: blocks })\n toast.success('Detached to an editable copy — the live link is broken.')\n },\n [capability, builder, cms],\n )\n\n const value = useMemo<ReuseGestures>(\n () => ({ capability, canMakeReusable, canDetach, startMakeReusable, detach }),\n [capability, canMakeReusable, canDetach, startMakeReusable, detach],\n )\n\n return (\n <ReuseContext.Provider value={value}>\n {children}\n <MakeReusableDialog\n open={pending !== null}\n defaultName={pending?.defaultName ?? ''}\n onConfirm={confirmMakeReusable}\n onCancel={() => setPending(null)}\n />\n </ReuseContext.Provider>\n )\n}\n\n/** Name-and-create dialog for the \"Make reusable\" gesture. */\nfunction MakeReusableDialog({\n open,\n defaultName,\n onConfirm,\n onCancel,\n}: {\n open: boolean\n defaultName: string\n /** `publish` chooses the new reusable's initial state (EC-300/AD-16). */\n onConfirm: (name: string, publish: boolean) => void\n onCancel: () => void\n}) {\n const [name, setName] = useState(defaultName)\n // Re-seed the field each time the dialog opens for a new selection.\n const [seededFor, setSeededFor] = useState<string | null>(null)\n if (open && seededFor !== defaultName) {\n setName(defaultName)\n setSeededFor(defaultName)\n }\n\n const empty = name.trim() === ''\n function commit(publish: boolean) {\n if (empty) return\n onConfirm(name.trim(), publish)\n setSeededFor(null)\n }\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) {\n onCancel()\n setSeededFor(null)\n }\n }}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>Make reusable</DialogTitle>\n <DialogDescription>\n Moves the selected block into a new reusable element and embeds it here. The same element\n can then be embedded on any page. Publish it now to keep the section visible everywhere,\n or save it as a draft to keep editing first.\n </DialogDescription>\n </DialogHeader>\n {/* Enter submits the primary action (Publish) — the continuity-preserving default. */}\n <form\n onSubmit={(event: FormEvent) => {\n event.preventDefault()\n commit(true)\n }}\n >\n <Stack gap=\"3\">\n <Field label=\"Name\" htmlFor=\"make-reusable-name\" required>\n <Input\n id=\"make-reusable-name\"\n value={name}\n onChange={(event) => setName(event.target.value)}\n placeholder=\"Reservation CTA\"\n autoFocus\n required\n />\n </Field>\n </Stack>\n <DialogFooter className=\"mt-4\">\n {/* Cancel pinned left; the two commit actions group right. */}\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"mr-auto\" onClick={onCancel}>\n Cancel\n </Button>\n <Button\n type=\"button\"\n variant=\"secondary\"\n size=\"sm\"\n disabled={empty}\n onClick={() => commit(false)}\n data-testid=\"make-reusable-draft\"\n >\n Save Draft\n </Button>\n <Button\n type=\"submit\"\n size=\"sm\"\n disabled={empty}\n data-testid=\"make-reusable-publish\"\n >\n Publish\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n )\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { ComponentManifest } from '@elytracms/core/component-registry';
2
- import type { CollectionDef } from '@elytracms/core/cms-core';
2
+ import type { CollectionDef, DocumentRef } from '@elytracms/core/cms-core';
3
3
  import type { ComponentNode } from '@elytracms/core/project-graph';
4
4
  /**
5
5
  * The reuse capability (EC-282): the engine-generic description of how a project
@@ -42,5 +42,18 @@ export declare function uniqueSlug(name: string, taken: ReadonlySet<string>): st
42
42
  export declare function buildReusableValues(collection: CollectionDef, capability: ReuseCapability, name: string, node: ComponentNode, existing: readonly {
43
43
  values?: Record<string, unknown>;
44
44
  }[]): Record<string, unknown>;
45
+ /**
46
+ * The document a reuse-embed `node` targets (EC-300), or null when `node` is not the
47
+ * embed component or has no static pick yet. Lets the canvas detect a HARD reference
48
+ * whose target doesn't resolve (→ placeholder) without reaching into prop internals.
49
+ */
50
+ export declare function reuseEmbedRef(node: ComponentNode, capability: ReuseCapability): DocumentRef | null;
51
+ /**
52
+ * Every reuse-embed target ref in a composition `blocks` value, at any depth
53
+ * (EC-300) — the hard references a publish-integrity check walks to find
54
+ * unpublished targets. Recurses slots; order is document order. Duplicates are
55
+ * kept (the caller dedupes by key if needed).
56
+ */
57
+ export declare function collectEmbedRefs(blocks: readonly ComponentNode[], capability: ReuseCapability): DocumentRef[];
45
58
  /** The `Reusable` embed node referencing the new document (id minted by the action). */
46
59
  export declare function makeEmbedNode(capability: ReuseCapability, documentId: string): ComponentNode;
@@ -1,5 +1,5 @@
1
1
  import { manifestPropFields } from '@elytracms/core/component-registry';
2
- import { seedDefaults, titleFieldOf } from '@elytracms/core/cms-core';
2
+ import { readDocumentRef, seedDefaults, titleFieldOf } from '@elytracms/core/cms-core';
3
3
  import { slugify } from '@elytracms/studio/lib/utils';
4
4
  /** The lone `relation` prop of a manifest (with its name), or null unless exactly one. */
5
5
  function soleRelationProp(manifest) {
@@ -69,6 +69,38 @@ export function buildReusableValues(collection, capability, name, node, existing
69
69
  values[capability.contentField] = capability.contentCardinality === 'one' ? node : [node];
70
70
  return values;
71
71
  }
72
+ /**
73
+ * The document a reuse-embed `node` targets (EC-300), or null when `node` is not the
74
+ * embed component or has no static pick yet. Lets the canvas detect a HARD reference
75
+ * whose target doesn't resolve (→ placeholder) without reaching into prop internals.
76
+ */
77
+ export function reuseEmbedRef(node, capability) {
78
+ if (node.componentId !== capability.embedComponentId)
79
+ return null;
80
+ const prop = node.props?.[capability.relationProp];
81
+ const ref = prop?.kind === 'static' ? readDocumentRef(prop.value) : undefined;
82
+ return ref ?? null;
83
+ }
84
+ /**
85
+ * Every reuse-embed target ref in a composition `blocks` value, at any depth
86
+ * (EC-300) — the hard references a publish-integrity check walks to find
87
+ * unpublished targets. Recurses slots; order is document order. Duplicates are
88
+ * kept (the caller dedupes by key if needed).
89
+ */
90
+ export function collectEmbedRefs(blocks, capability) {
91
+ const refs = [];
92
+ const visit = (node) => {
93
+ const ref = reuseEmbedRef(node, capability);
94
+ if (ref)
95
+ refs.push(ref);
96
+ for (const children of Object.values(node.slots ?? {}))
97
+ for (const child of children)
98
+ visit(child);
99
+ };
100
+ for (const node of blocks)
101
+ visit(node);
102
+ return refs;
103
+ }
72
104
  /** The `Reusable` embed node referencing the new document (id minted by the action). */
73
105
  export function makeEmbedNode(capability, documentId) {
74
106
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"reuse.js","sourceRoot":"","sources":["../../../src/components/builder/reuse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAA;AAEvE,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAGrE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAA;AA6BrD,0FAA0F;AAC1F,SAAS,gBAAgB,CACvB,QAA2B;IAE3B,MAAM,SAAS,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC,CAAA;IACnF,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;IAC9D,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,UAAU,IAAI,CAAC,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAA;IAClE,OAAO,EAAE,IAAI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YACD,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QAC9C,CAAC;IACH,CAAC;IACD,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC,GAAG,UAAU,CAAC,kBAAkB,KAAK,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IACzF,OAAO,MAAM,CAAA;AACf,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,aAAa,CAAC,UAA2B,EAAE,UAAkB;IAC3E,OAAO;QACL,EAAE,EAAE,aAAa;QACjB,WAAW,EAAE,UAAU,CAAC,gBAAgB;QACxC,KAAK,EAAE;YACL,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE;gBACzB,IAAI,EAAE,QAAQ;gBACd,KAAK,EAAE,EAAE,UAAU,EAAE,UAAU,CAAC,YAAY,EAAE,EAAE,EAAE,UAAU,EAAE;aAC/D;SACF;KACF,CAAA;AACH,CAAC","sourcesContent":["import { manifestPropFields } from '@elytracms/core/component-registry'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\nimport { seedDefaults, titleFieldOf } from '@elytracms/core/cms-core'\nimport type { CollectionDef } from '@elytracms/core/cms-core'\nimport type { ComponentNode } from '@elytracms/core/project-graph'\nimport { slugify } from '@elytracms/studio/lib/utils'\n\n/**\n * The reuse capability (EC-282): the engine-generic description of how a project\n * models reusable elements, DERIVED from config (manifests + collections) — no\n * new declaration, so a consumer that already has a transcluding embed gets the\n * in-canvas gestures for free (the EC-296 \"works automatically\" pattern).\n *\n * The derivation predicate for a \"reusable embed\" component: it contributes no\n * slots of its own and has exactly ONE `relation` prop (cardinality `one`) whose\n * target collection holds a `blocks` field — i.e. it embeds a single document and\n * renders that document's composition by transclusion (EC-254/EC-281). For\n * Konditorei that is uniquely `project.Reusable` → `element` → `reusable.content`.\n * If zero or more than one component matches, the capability is null and the\n * gestures stay hidden rather than guessing.\n */\nexport interface ReuseCapability {\n /** The embed component, e.g. `project.Reusable`. */\n embedComponentId: string\n /** The embed's relation prop that points at the reusable document, e.g. `element`. */\n relationProp: string\n /** The collection reusable documents live in, e.g. `reusable`. */\n collectionId: string\n /** The collection's composition field the embed transcludes, e.g. `content`. */\n contentField: string\n /** Whether that field holds a single block or a list. */\n contentCardinality: 'one' | 'many'\n}\n\n/** The lone `relation` prop of a manifest (with its name), or null unless exactly one. */\nfunction soleRelationProp(\n manifest: ComponentManifest,\n): { name: string; target: string; cardinality: 'one' | 'many' } | null {\n const relations = manifestPropFields(manifest).filter((f) => f.type === 'relation')\n const only = relations.length === 1 ? relations[0] : undefined\n if (!only || only.type !== 'relation' || !only.target) return null\n return { name: only.name, target: only.target, cardinality: only.cardinality }\n}\n\n/** Derive the project's reuse capability, or null when it is absent/ambiguous. */\nexport function resolveReuseCapability(\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n): ReuseCapability | null {\n const matches: ReuseCapability[] = []\n for (const manifest of manifests) {\n if (manifest.slots.length > 0) continue\n const relation = soleRelationProp(manifest)\n if (!relation || relation.cardinality !== 'one') continue\n const collection = collections.find((c) => c.id === relation.target)\n if (!collection) continue\n const blocksField = collection.fields.find((f) => f.type === 'blocks')\n if (!blocksField || blocksField.type !== 'blocks') continue\n matches.push({\n embedComponentId: manifest.id,\n relationProp: relation.name,\n collectionId: collection.id,\n contentField: blocksField.name,\n contentCardinality: blocksField.cardinality === 'one' ? 'one' : 'many',\n })\n }\n return matches.length === 1 ? matches[0]! : null\n}\n\n/** A slug for `name`, suffixed `-2`/`-3`/… until it is free among `taken`. */\nexport function uniqueSlug(name: string, taken: ReadonlySet<string>): string {\n const base = slugify(name) || 'element'\n let id = base\n for (let n = 2; taken.has(id); n += 1) id = `${base}-${n}`\n return id\n}\n\n/**\n * The values for a new reusable document promoted from `node` (EC-282): seeded\n * defaults, the given `name` on the title field, the node on the content field,\n * and a collision-safe slug on any UNIQUE text field (e.g. Konditorei's\n * `internalId`) so the created document is publish-valid without hardcoding that\n * field's name. Other required fields, if any, are completed by the editor when\n * they open the new reusable.\n */\nexport function buildReusableValues(\n collection: CollectionDef,\n capability: ReuseCapability,\n name: string,\n node: ComponentNode,\n existing: readonly { values?: Record<string, unknown> }[],\n): Record<string, unknown> {\n const values: Record<string, unknown> = { ...seedDefaults(collection) }\n const titleField = titleFieldOf(collection)?.name\n if (titleField) values[titleField] = name\n for (const field of collection.fields) {\n if (\n field.type === 'text' &&\n field.validation?.unique === true &&\n field.name !== titleField &&\n field.name !== capability.contentField\n ) {\n const taken = new Set(\n existing\n .map((d) => d.values?.[field.name])\n .filter((v): v is string => typeof v === 'string'),\n )\n values[field.name] = uniqueSlug(name, taken)\n }\n }\n values[capability.contentField] = capability.contentCardinality === 'one' ? node : [node]\n return values\n}\n\n/** The `Reusable` embed node referencing the new document (id minted by the action). */\nexport function makeEmbedNode(capability: ReuseCapability, documentId: string): ComponentNode {\n return {\n id: 'reuse-embed',\n componentId: capability.embedComponentId,\n props: {\n [capability.relationProp]: {\n kind: 'static',\n value: { collection: capability.collectionId, id: documentId },\n },\n },\n }\n}\n"]}
1
+ {"version":3,"file":"reuse.js","sourceRoot":"","sources":["../../../src/components/builder/reuse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAA;AAEvE,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAGtF,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAA;AA6BrD,0FAA0F;AAC1F,SAAS,gBAAgB,CACvB,QAA2B;IAE3B,MAAM,SAAS,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC,CAAA;IACnF,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CA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,MAAM,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;YAAE,KAAK,MAAM,KAAK,IAAI,QAAQ;gBAAE,KAAK,CAAC,KAAK,CAAC,CAAA;IACpG,CAAC,CAAA;IACD,KAAK,MAAM,IAAI,IAAI,MAAM;QAAE,KAAK,CAAC,IAAI,CAAC,CAAA;IACtC,OAAO,IAAI,CAAA;AACb,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,aAAa,CAAC,UAA2B,EAAE,UAAkB;IAC3E,OAAO;QACL,EAAE,EAAE,aAAa;QACjB,WAAW,EAAE,UAAU,CAAC,gBAAgB;QACxC,KAAK,EAAE;YACL,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE;gBACzB,IAAI,EAAE,QAAQ;gBACd,KAAK,EAAE,EAAE,UAAU,EAAE,UAAU,CAAC,YAAY,EAAE,EAAE,EAAE,UAAU,EAAE;aAC/D;SACF;KACF,CAAA;AACH,CAAC","sourcesContent":["import { manifestPropFields } from '@elytracms/core/component-registry'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\nimport { readDocumentRef, seedDefaults, titleFieldOf } from '@elytracms/core/cms-core'\nimport type { CollectionDef, DocumentRef } from '@elytracms/core/cms-core'\nimport type { ComponentNode } from '@elytracms/core/project-graph'\nimport { slugify } from '@elytracms/studio/lib/utils'\n\n/**\n * The reuse capability (EC-282): the engine-generic description of how a project\n * models reusable elements, DERIVED from config (manifests + collections) — no\n * new declaration, so a consumer that already has a transcluding embed gets the\n * in-canvas gestures for free (the EC-296 \"works automatically\" pattern).\n *\n * The derivation predicate for a \"reusable embed\" component: it contributes no\n * slots of its own and has exactly ONE `relation` prop (cardinality `one`) whose\n * target collection holds a `blocks` field — i.e. it embeds a single document and\n * renders that document's composition by transclusion (EC-254/EC-281). For\n * Konditorei that is uniquely `project.Reusable` → `element` → `reusable.content`.\n * If zero or more than one component matches, the capability is null and the\n * gestures stay hidden rather than guessing.\n */\nexport interface ReuseCapability {\n /** The embed component, e.g. `project.Reusable`. */\n embedComponentId: string\n /** The embed's relation prop that points at the reusable document, e.g. `element`. */\n relationProp: string\n /** The collection reusable documents live in, e.g. `reusable`. */\n collectionId: string\n /** The collection's composition field the embed transcludes, e.g. `content`. */\n contentField: string\n /** Whether that field holds a single block or a list. */\n contentCardinality: 'one' | 'many'\n}\n\n/** The lone `relation` prop of a manifest (with its name), or null unless exactly one. */\nfunction soleRelationProp(\n manifest: ComponentManifest,\n): { name: string; target: string; cardinality: 'one' | 'many' } | null {\n const relations = manifestPropFields(manifest).filter((f) => f.type === 'relation')\n const only = relations.length === 1 ? relations[0] : undefined\n if (!only || only.type !== 'relation' || !only.target) return null\n return { name: only.name, target: only.target, cardinality: only.cardinality }\n}\n\n/** Derive the project's reuse capability, or null when it is absent/ambiguous. */\nexport function resolveReuseCapability(\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n): ReuseCapability | null {\n const matches: ReuseCapability[] = []\n for (const manifest of manifests) {\n if (manifest.slots.length > 0) continue\n const relation = soleRelationProp(manifest)\n if (!relation || relation.cardinality !== 'one') continue\n const collection = collections.find((c) => c.id === relation.target)\n if (!collection) continue\n const blocksField = collection.fields.find((f) => f.type === 'blocks')\n if (!blocksField || blocksField.type !== 'blocks') continue\n matches.push({\n embedComponentId: manifest.id,\n relationProp: relation.name,\n collectionId: collection.id,\n contentField: blocksField.name,\n contentCardinality: blocksField.cardinality === 'one' ? 'one' : 'many',\n })\n }\n return matches.length === 1 ? matches[0]! : null\n}\n\n/** A slug for `name`, suffixed `-2`/`-3`/… until it is free among `taken`. */\nexport function uniqueSlug(name: string, taken: ReadonlySet<string>): string {\n const base = slugify(name) || 'element'\n let id = base\n for (let n = 2; taken.has(id); n += 1) id = `${base}-${n}`\n return id\n}\n\n/**\n * The values for a new reusable document promoted from `node` (EC-282): seeded\n * defaults, the given `name` on the title field, the node on the content field,\n * and a collision-safe slug on any UNIQUE text field (e.g. Konditorei's\n * `internalId`) so the created document is publish-valid without hardcoding that\n * field's name. Other required fields, if any, are completed by the editor when\n * they open the new reusable.\n */\nexport function buildReusableValues(\n collection: CollectionDef,\n capability: ReuseCapability,\n name: string,\n node: ComponentNode,\n existing: readonly { values?: Record<string, unknown> }[],\n): Record<string, unknown> {\n const values: Record<string, unknown> = { ...seedDefaults(collection) }\n const titleField = titleFieldOf(collection)?.name\n if (titleField) values[titleField] = name\n for (const field of collection.fields) {\n if (\n field.type === 'text' &&\n field.validation?.unique === true &&\n field.name !== titleField &&\n field.name !== capability.contentField\n ) {\n const taken = new Set(\n existing\n .map((d) => d.values?.[field.name])\n .filter((v): v is string => typeof v === 'string'),\n )\n values[field.name] = uniqueSlug(name, taken)\n }\n }\n values[capability.contentField] = capability.contentCardinality === 'one' ? node : [node]\n return values\n}\n\n/**\n * The document a reuse-embed `node` targets (EC-300), or null when `node` is not the\n * embed component or has no static pick yet. Lets the canvas detect a HARD reference\n * whose target doesn't resolve (→ placeholder) without reaching into prop internals.\n */\nexport function reuseEmbedRef(node: ComponentNode, capability: ReuseCapability): DocumentRef | null {\n if (node.componentId !== capability.embedComponentId) return null\n const prop = node.props?.[capability.relationProp]\n const ref = prop?.kind === 'static' ? readDocumentRef(prop.value) : undefined\n return ref ?? null\n}\n\n/**\n * Every reuse-embed target ref in a composition `blocks` value, at any depth\n * (EC-300) — the hard references a publish-integrity check walks to find\n * unpublished targets. Recurses slots; order is document order. Duplicates are\n * kept (the caller dedupes by key if needed).\n */\nexport function collectEmbedRefs(\n blocks: readonly ComponentNode[],\n capability: ReuseCapability,\n): DocumentRef[] {\n const refs: DocumentRef[] = []\n const visit = (node: ComponentNode): void => {\n const ref = reuseEmbedRef(node, capability)\n if (ref) refs.push(ref)\n for (const children of Object.values(node.slots ?? {})) for (const child of children) visit(child)\n }\n for (const node of blocks) visit(node)\n return refs\n}\n\n/** The `Reusable` embed node referencing the new document (id minted by the action). */\nexport function makeEmbedNode(capability: ReuseCapability, documentId: string): ComponentNode {\n return {\n id: 'reuse-embed',\n componentId: capability.embedComponentId,\n props: {\n [capability.relationProp]: {\n kind: 'static',\n value: { collection: capability.collectionId, id: documentId },\n },\n },\n }\n}\n"]}
@@ -3,7 +3,10 @@ import { Link, STUDIO_PROJECT_ROUTE, studioPath, useNavigate } from '@elytracms/
3
3
  import { CircleAlert, CircleCheck, ExternalLink, Eye, EyeOff, History, Languages, Loader2, Lock, MoreHorizontal, Tag, Trash2, } from 'lucide-react';
4
4
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
5
5
  import { SIDEBAR_FIELD_GROUP, clearHiddenValues, documentKey, hasAliases, isBlocksField, isFieldHidden, isFieldLocalized, isSingleton, resolveField, sidebarFields, staticFieldHidden, urlForDocument, } from '@elytracms/core/cms-core';
6
- import { Badge, Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Field, Heading, Panel, PanelHeader, Row, Spacer, Stack, Text, toast, } from '@elytracms/studio/ui';
6
+ import { blockRootsOf } from '@elytracms/core/project-graph';
7
+ import { Badge, Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Field, Heading, Panel, PanelHeader, Row, Spacer, Stack, Text, toast, } from '@elytracms/studio/ui';
8
+ import { getStudioRegistry } from '@elytracms/studio/lib/registry';
9
+ import { collectEmbedRefs, resolveReuseCapability } from '../builder/reuse';
7
10
  import { cn } from '@elytracms/studio/lib/utils';
8
11
  import { LocaleSwitcher, displayedFieldFallback, hasLocaleVariant, localeChipLabel, setStudioLocale, } from '@elytracms/studio/lib/locale';
9
12
  import { parseDocumentFieldPath } from '@elytracms/studio/lib/references';
@@ -93,9 +96,17 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
93
96
  const viewDoc = viewReadOnly && publishedSnapshot.status === 'ready' ? publishedSnapshot.doc : draft;
94
97
  const publishedPending = viewReadOnly && publishedSnapshot.status !== 'ready';
95
98
  const dirty = JSON.stringify(draft) !== JSON.stringify(doc);
96
- const issues = useMemo(() => cms.validate(draft), [cms, draft]);
97
- const errorCount = issues.filter((i) => i.severity === 'error').length;
99
+ const schemaIssues = useMemo(() => cms.validate(draft), [cms, draft]);
100
+ // EC-300/AD-16: composition embeds (hard references) whose target isn't published
101
+ // would render empty on the live site. Surface them as errors in the Issues panel,
102
+ // but they DON'T gate the Publish button (schema errors do) — publishing is
103
+ // confirm-through, so the editor can publish the page and the reusable together
104
+ // knowingly. The publish guard below catches them.
105
+ const referenceIssues = useMemo(() => unpublishedEmbedIssues(collection, draft, cms), [collection, draft, cms]);
106
+ const issues = useMemo(() => [...schemaIssues, ...referenceIssues], [schemaIssues, referenceIssues]);
107
+ const errorCount = schemaIssues.filter((i) => i.severity === 'error').length;
98
108
  const hasErrors = errorCount > 0;
109
+ const hasUnpublishedRefs = referenceIssues.length > 0;
99
110
  // --- Autosave (EC-225) -----------------------------------------------------
100
111
  // The draft persists automatically 1s after the last edit; there is no manual
101
112
  // Save button. Refs let the unmount flush read the latest values without
@@ -297,7 +308,7 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
297
308
  id: 'issues',
298
309
  label: 'Issues',
299
310
  icon: _jsx(CircleAlert, { className: "size-3.5" }),
300
- badge: issues.length === 0 ? undefined : (_jsx(Badge, { variant: errorCount > 0 ? 'error' : 'warning', className: "px-1.5 py-0 leading-none", children: issues.length })),
311
+ badge: issues.length === 0 ? undefined : (_jsx(Badge, { variant: issues.some((i) => i.severity === 'error') ? 'error' : 'warning', className: "px-1.5 py-0 leading-none", children: issues.length })),
301
312
  render: () => (_jsx(IssuesPane, { issues: issues, collection: collection, onJumpToField: focusField })),
302
313
  }), [issues, errorCount, collection, focusField]);
303
314
  // EC-284 + EC-285: the document-metadata pane — slot assignment (EC-284) and/or
@@ -328,7 +339,19 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
328
339
  // EC-268: the Publish button is its own indicator — pending while the publish
329
340
  // round-trips, a brief success, and an error toast if it rejects at transport.
330
341
  const [publishState, setPublishState] = useState('idle');
331
- async function handlePublish() {
342
+ // EC-300/AD-16: confirm-through guard when the page embeds unpublished reusables.
343
+ const [publishConfirm, setPublishConfirm] = useState(false);
344
+ // Gate publish on the confirm-through dialog when there are unpublished hard
345
+ // references (they'd render empty on the live site); schema errors already
346
+ // disable the button, so they never reach here.
347
+ function handlePublish() {
348
+ if (hasUnpublishedRefs) {
349
+ setPublishConfirm(true);
350
+ return;
351
+ }
352
+ void doPublish();
353
+ }
354
+ async function doPublish() {
332
355
  // EC-273: clean conditionally-hidden values from the draft AT PUBLISH TIME.
333
356
  // While editing, the draft keeps them so an accidental hide (e.g. flipping a
334
357
  // link's type) is recoverable; publishing is the intentional moment we commit
@@ -432,7 +455,7 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
432
455
  ? 'Loading the live URL…'
433
456
  : !cms.isPublished(ref)
434
457
  ? 'Publish to view the live page'
435
- : 'Set frontendUrl in elytra.config.ts to enable', children: [_jsx(ExternalLink, {}), " View live"] }))) : null, _jsx(Button, { size: "sm", onClick: () => void handlePublish(), disabled: hasErrors || viewReadOnly || publishState === 'pending', title: viewReadOnly
458
+ : 'Set frontendUrl in elytra.config.ts to enable', children: [_jsx(ExternalLink, {}), " View live"] }))) : null, _jsx(Button, { size: "sm", onClick: handlePublish, disabled: hasErrors || viewReadOnly || publishState === 'pending', title: viewReadOnly
436
459
  ? 'Switch to Draft to publish'
437
460
  : hasErrors
438
461
  ? `Fix ${errorCount} ${errorCount === 1 ? 'issue' : 'issues'} to publish`
@@ -451,7 +474,55 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
451
474
  }) }) }) }), _jsx(InspectorSidebar, { panes: trailingPanes, activeId: inspectorPaneId, onActiveChange: setInspectorPaneId, className: "w-[320px] shrink-0 border-l border-border" })] })), confirmAction !== null ? (_jsx(ReferenceConfirmDialog, { projectId: projectId, action: confirmAction, targets: confirmTargets, open: true, onOpenChange: (open) => {
452
475
  if (!open)
453
476
  setConfirmAction(null);
454
- }, onConfirm: handleConfirmedAction })) : null] }) }));
477
+ }, onConfirm: handleConfirmedAction })) : null, _jsx(Dialog, { open: publishConfirm, onOpenChange: (open) => { if (!open)
478
+ setPublishConfirm(false); }, children: _jsxs(DialogContent, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Publish with unpublished references?" }), _jsx(DialogDescription, { children: "This page embeds reusable elements that aren\u2019t published yet. They will be empty on the live site until you publish them too." })] }), _jsx(Stack, { gap: "1", children: referenceIssues.map((issue, i) => (_jsxs(Text, { size: "xs", tone: "muted", children: ["\u2022 ", issue.message] }, `${issue.meta?.id ?? i}`))) }), _jsxs(DialogFooter, { className: "mt-4", children: [_jsx(Button, { variant: "ghost", size: "sm", onClick: () => setPublishConfirm(false), children: "Cancel" }), _jsx(Button, { size: "sm", "data-testid": "publish-anyway", onClick: () => {
479
+ setPublishConfirm(false);
480
+ void doPublish();
481
+ }, children: "Publish anyway" })] })] }) })] }) }));
482
+ }
483
+ /**
484
+ * EC-300/AD-16 — errors for composition embeds (hard references) whose target isn't
485
+ * published: they render empty on the live site. Walks every `blocks` field of the
486
+ * document for reuse embeds; a missing target is an `unknown-relation-target` error,
487
+ * an unpublished one an `unpublished-relation-target` error. Publishing is
488
+ * confirm-through (not blocked), so these feed the Issues panel + the publish
489
+ * confirmation, never the button's disabled gate. No reuse capability → none.
490
+ */
491
+ function unpublishedEmbedIssues(collection, draft, cms) {
492
+ const capability = resolveReuseCapability(getStudioRegistry().registry.list(), cms.collections);
493
+ if (!capability)
494
+ return [];
495
+ const issues = [];
496
+ const seen = new Set();
497
+ for (const field of collection.fields) {
498
+ if (!isBlocksField(field))
499
+ continue;
500
+ for (const ref of collectEmbedRefs(blockRootsOf(draft.values?.[field.name]), capability)) {
501
+ const key = `${ref.collection}:${ref.id}`;
502
+ if (seen.has(key))
503
+ continue;
504
+ seen.add(key);
505
+ const exists = cms.getDocument(ref) !== undefined;
506
+ if (exists && cms.isPublished(ref))
507
+ continue;
508
+ issues.push(unpublishedEmbedIssue(collection, draft, field.name, ref, exists, cms));
509
+ }
510
+ }
511
+ return issues;
512
+ }
513
+ /** One unpublished/missing reuse-embed issue (EC-300). */
514
+ function unpublishedEmbedIssue(collection, draft, field, ref, exists, cms) {
515
+ return {
516
+ code: exists ? 'unpublished-relation-target' : 'unknown-relation-target',
517
+ severity: 'error',
518
+ message: exists
519
+ ? `Embeds the reusable “${cms.titleOf(ref)}”, which isn’t published — it will be empty on the live site until you publish it.`
520
+ : `Embeds a reusable that no longer exists (“${ref.id}”) — fix or remove the embed.`,
521
+ path: [field],
522
+ collectionId: collection.id,
523
+ documentId: draft.id,
524
+ meta: { field, target: ref.collection, id: ref.id },
525
+ };
455
526
  }
456
527
  /**
457
528
  * A segmented-control button for the Draft/Published view toggle (EC-226). The