@elytracms/studio 0.0.100 → 0.0.101
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.
- package/convex/analytics-cost.test.ts +1 -1
- package/convex/redirect-migration.test.ts +1 -1
- package/convex/redirects.ts +2 -2
- package/convex/shared-capture.convex.test.ts +165 -0
- package/dist/components/ai/ai-chat-panel-lazy.js +7 -2
- package/dist/components/ai/ai-chat-panel-lazy.js.map +1 -1
- package/dist/components/ai/proposal-card.js +2 -1
- package/dist/components/ai/proposal-card.js.map +1 -1
- package/dist/components/ai/proposal-unfilled.d.ts +14 -0
- package/dist/components/ai/proposal-unfilled.js +33 -0
- package/dist/components/ai/proposal-unfilled.js.map +1 -0
- package/dist/components/ai/translate-document-action.js +8 -6
- package/dist/components/ai/translate-document-action.js.map +1 -1
- package/dist/components/app-views/studio-config.d.ts +12 -12
- package/dist/components/app-views/studio-config.js.map +1 -1
- package/dist/components/builder/builder-store.d.ts +37 -1
- package/dist/components/builder/builder-store.js +21 -6
- package/dist/components/builder/builder-store.js.map +1 -1
- package/dist/components/builder/canvas-chrome-css.d.ts +1 -1
- package/dist/components/builder/canvas-chrome-css.js +1 -1
- package/dist/components/builder/canvas-chrome-css.js.map +1 -1
- package/dist/components/builder/canvas-chrome.d.ts +1 -1
- package/dist/components/builder/canvas-chrome.js +1 -1
- package/dist/components/builder/canvas-chrome.js.map +1 -1
- package/dist/components/builder/canvas-rebase.d.ts +4 -4
- package/dist/components/builder/canvas-rebase.js +3 -2
- package/dist/components/builder/canvas-rebase.js.map +1 -1
- package/dist/components/builder/canvas-render-context.d.ts +1 -1
- package/dist/components/builder/canvas-render-context.js +1 -1
- package/dist/components/builder/canvas-render-context.js.map +1 -1
- package/dist/components/builder/composition-field-editor-lazy.js +2 -1
- package/dist/components/builder/composition-field-editor-lazy.js.map +1 -1
- package/dist/components/builder/reuse-context.d.ts +8 -2
- package/dist/components/builder/reuse-context.js +62 -7
- package/dist/components/builder/reuse-context.js.map +1 -1
- package/dist/components/builder/reuse.d.ts +106 -70
- package/dist/components/builder/reuse.js +125 -108
- package/dist/components/builder/reuse.js.map +1 -1
- package/dist/components/cms/cms-store.d.ts +9 -1
- package/dist/components/cms/cms-store.js +1 -0
- package/dist/components/cms/cms-store.js.map +1 -1
- package/dist/components/cms/detail-editor.js +13 -13
- package/dist/components/cms/detail-editor.js.map +1 -1
- package/dist/components/cms/prop-fields.js +1 -1
- package/dist/components/cms/prop-fields.js.map +1 -1
- package/dist/components/cms/rich-text/lazy.js +2 -1
- package/dist/components/cms/rich-text/lazy.js.map +1 -1
- package/dist/components/cms/rich-text/toolbar-state.d.ts +1 -1
- package/dist/components/cms/rich-text/toolbar-state.js +1 -1
- package/dist/components/cms/rich-text/toolbar-state.js.map +1 -1
- package/dist/components/cms/use-field-focus.js +3 -3
- package/dist/components/cms/use-field-focus.js.map +1 -1
- package/dist/components/cms/version-compare-lazy.js +2 -1
- package/dist/components/cms/version-compare-lazy.js.map +1 -1
- package/dist/components/components/components-index.js +1 -1
- package/dist/components/components/components-index.js.map +1 -1
- package/dist/components/deployment-setup-gate.d.ts +1 -1
- package/dist/components/deployment-setup-gate.js +1 -1
- package/dist/components/deployment-setup-gate.js.map +1 -1
- package/dist/components/load-failure.d.ts +62 -0
- package/dist/components/load-failure.js +110 -0
- package/dist/components/load-failure.js.map +1 -0
- package/dist/components/notifications/shell-findings.js +3 -3
- package/dist/components/notifications/shell-findings.js.map +1 -1
- package/dist/customization.d.ts +3 -3
- package/dist/customization.js.map +1 -1
- package/dist/lib/ai/apply-content.js +99 -28
- package/dist/lib/ai/apply-content.js.map +1 -1
- package/dist/lib/ai/chat-context.d.ts +73 -7
- package/dist/lib/ai/chat-context.js +133 -14
- package/dist/lib/ai/chat-context.js.map +1 -1
- package/dist/lib/ai/chat-state.d.ts +7 -1
- package/dist/lib/ai/chat-state.js.map +1 -1
- package/dist/lib/ai/constraints.d.ts +5 -0
- package/dist/lib/ai/constraints.js +21 -6
- package/dist/lib/ai/constraints.js.map +1 -1
- package/dist/lib/ai/fake-provider.d.ts +76 -26
- package/dist/lib/ai/fake-provider.js +210 -66
- package/dist/lib/ai/fake-provider.js.map +1 -1
- package/dist/lib/ai/index.d.ts +1 -0
- package/dist/lib/ai/index.js +1 -0
- package/dist/lib/ai/index.js.map +1 -1
- package/dist/lib/ai/keyless-assistant.d.ts +37 -0
- package/dist/lib/ai/keyless-assistant.js +193 -0
- package/dist/lib/ai/keyless-assistant.js.map +1 -0
- package/dist/lib/ai/shape.d.ts +25 -2
- package/dist/lib/ai/shape.js +58 -7
- package/dist/lib/ai/shape.js.map +1 -1
- package/dist/lib/ai/tools.d.ts +11 -1
- package/dist/lib/ai/tools.js +51 -6
- package/dist/lib/ai/tools.js.map +1 -1
- package/dist/lib/ai/translate-document.js +6 -5
- package/dist/lib/ai/translate-document.js.map +1 -1
- package/dist/lib/ai/types.d.ts +22 -7
- package/dist/lib/ai/types.js.map +1 -1
- package/dist/lib/ai/update-fields.js +9 -6
- package/dist/lib/ai/update-fields.js.map +1 -1
- package/dist/lib/ai/writer-form.d.ts +11 -3
- package/dist/lib/ai/writer-form.js +105 -18
- package/dist/lib/ai/writer-form.js.map +1 -1
- package/dist/lib/auth-errors.d.ts +1 -1
- package/dist/lib/auth-errors.js +1 -1
- package/dist/lib/auth-errors.js.map +1 -1
- package/dist/lib/engine-version.d.ts +1 -1
- package/dist/lib/engine-version.js +1 -1
- package/dist/lib/engine-version.js.map +1 -1
- package/dist/lib/i18n/messages.de.d.ts +1 -1
- package/dist/lib/i18n/messages.de.js +23 -7
- package/dist/lib/i18n/messages.de.js.map +1 -1
- package/dist/lib/i18n/messages.en.d.ts +18 -3
- package/dist/lib/i18n/messages.en.js +29 -9
- package/dist/lib/i18n/messages.en.js.map +1 -1
- package/dist/lib/operations/cms-persistence.d.ts +18 -0
- package/dist/lib/operations/cms-persistence.js +47 -0
- package/dist/lib/operations/cms-persistence.js.map +1 -1
- package/dist/lib/workspace/index.d.ts +3 -3
- package/dist/lib/workspace/index.js +3 -3
- package/dist/lib/workspace/index.js.map +1 -1
- package/dist/router/navigate-once.d.ts +1 -1
- package/dist/router/navigate-once.js.map +1 -1
- package/dist/router/root.d.ts +3 -2
- package/dist/router/root.js +25 -4
- package/dist/router/root.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { manifestPropFields
|
|
2
|
-
import { fieldAllowList, itemLimit, readDocumentRef, referenceNode, seedDefaults, titleFieldOf, writeField, } from '@elytracms/core/cms-core';
|
|
3
|
-
import { editBlockRoots, isStaticProp, replacePlacementRefusal, valuePlacementRefusal } from '@elytracms/core/project-graph';
|
|
1
|
+
import { manifestPropFields } from '@elytracms/core/component-registry';
|
|
2
|
+
import { documentKey, fieldAllowList, itemLimit, readDocumentRef, referenceNode, seedDefaults, titleFieldOf, writeField, } from '@elytracms/core/cms-core';
|
|
3
|
+
import { editBlockRoots, isStaticProp, replacePlacementRefusal, staticProp, valuePlacementRefusal, } from '@elytracms/core/project-graph';
|
|
4
4
|
import { slugify } from '../../lib/utils.js';
|
|
5
5
|
import { fieldLabel } from '../cms/cms-labels.js';
|
|
6
6
|
/** The customization point name stamped onto every reuse issue (EC-236 locator). */
|
|
@@ -11,13 +11,7 @@ function relationPropsOf(manifest) {
|
|
|
11
11
|
for (const field of manifestPropFields(manifest)) {
|
|
12
12
|
if (field.type !== 'relation')
|
|
13
13
|
continue;
|
|
14
|
-
|
|
15
|
-
props.push({
|
|
16
|
-
name: field.name,
|
|
17
|
-
target: field.target,
|
|
18
|
-
multiple: field.multiple === true,
|
|
19
|
-
conditional: hidden !== undefined && hidden !== false,
|
|
20
|
-
});
|
|
14
|
+
props.push({ name: field.name, target: field.target, multiple: field.multiple === true });
|
|
21
15
|
}
|
|
22
16
|
return props;
|
|
23
17
|
}
|
|
@@ -47,7 +41,6 @@ const REUSE_KEYS = {
|
|
|
47
41
|
ambiguousRelationProp: 'builder.reuse.config.ambiguousRelationProp',
|
|
48
42
|
unknownCollection: 'builder.reuse.config.unknownCollection',
|
|
49
43
|
noBlocksField: 'builder.reuse.config.noBlocksField',
|
|
50
|
-
ambiguousInference: 'builder.reuse.config.ambiguousInference',
|
|
51
44
|
};
|
|
52
45
|
function reuseIssue(code, severity, message, messageRef, id) {
|
|
53
46
|
return {
|
|
@@ -64,54 +57,11 @@ function quotedList(names) {
|
|
|
64
57
|
return names.map((name) => `"${name}"`).join(', ');
|
|
65
58
|
}
|
|
66
59
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const matches = [];
|
|
73
|
-
for (const manifest of manifests) {
|
|
74
|
-
// EC-591 (COMPOSITION #15): the DERIVED slots — a `blocks` prop is a child
|
|
75
|
-
// region (`manifestSlots`), so a manifest with `slots: []` and a blocks prop is
|
|
76
|
-
// NOT slot-less; reading raw `manifest.slots` inferred it as a reuse embed.
|
|
77
|
-
if (manifestSlots(manifest).length > 0)
|
|
78
|
-
continue;
|
|
79
|
-
// EC-462: a `listing` manifest is a query host by its own declaration — its
|
|
80
|
-
// relation prop is the filter source, never an embed pointer.
|
|
81
|
-
if (manifest.listing)
|
|
82
|
-
continue;
|
|
83
|
-
// The heuristic requires the relation to be UNAMBIGUOUS within the manifest:
|
|
84
|
-
// exactly ONE relation prop of any kind, which must then be targeted,
|
|
85
|
-
// cardinality-one and unconditional. (Counting all relation props — not just
|
|
86
|
-
// the embeddable ones — is deliberate: a component with a second, list-valued
|
|
87
|
-
// relation is not the single-purpose shape the heuristic is allowed to claim.)
|
|
88
|
-
const relations = relationPropsOf(manifest);
|
|
89
|
-
const relation = relations.length === 1 ? relations[0] : undefined;
|
|
90
|
-
if (!relation || relation.target === undefined || relation.multiple || relation.conditional)
|
|
91
|
-
continue;
|
|
92
|
-
const collection = collections.find((c) => c.id === relation.target);
|
|
93
|
-
if (!collection)
|
|
94
|
-
continue;
|
|
95
|
-
const blocksField = blocksFieldOf(collection);
|
|
96
|
-
if (!blocksField)
|
|
97
|
-
continue;
|
|
98
|
-
matches.push({
|
|
99
|
-
embedComponentId: manifest.id,
|
|
100
|
-
relationProp: relation.name,
|
|
101
|
-
collectionId: collection.id,
|
|
102
|
-
contentField: blocksField.name,
|
|
103
|
-
contentCardinality: itemLimit(blocksField) === 1 ? 'one' : 'many',
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
return matches;
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Resolve the DECLARED embed (EC-467, AD-b). An explicit declaration is the
|
|
110
|
-
* developer's authority, so the inference disqualifiers are NOT applied here: a
|
|
111
|
-
* declared component may have slots, may declare `listing`, and its relation prop
|
|
112
|
-
* may be `form.hidden` — those exist to stop the engine GUESSING, not to overrule
|
|
113
|
-
* a stated intent. Only structural impossibilities are issues (see AD-c row 2):
|
|
114
|
-
* an unknown component id, no usable relation prop (or an ambiguous set with no
|
|
60
|
+
* Resolve the DECLARED embed (EC-467, AD-b). The declaration is the developer's
|
|
61
|
+
* authority: a declared component may have slots, may declare `listing`, and its
|
|
62
|
+
* relation prop may be `form.hidden` — the engine does not second-guess a stated
|
|
63
|
+
* intent. Only structural impossibilities are issues (see AD-c row 2): an unknown
|
|
64
|
+
* component id, no usable relation prop (or an ambiguous set with no
|
|
115
65
|
* `relationProp`), an undefined target collection, or a target with no `blocks`
|
|
116
66
|
* field — each of which would leave nothing coherent to transclude.
|
|
117
67
|
*/
|
|
@@ -126,7 +76,7 @@ function resolveDeclaredReuse(declaration, manifests, collections) {
|
|
|
126
76
|
return {
|
|
127
77
|
capability: null,
|
|
128
78
|
issues: [
|
|
129
|
-
reuseIssue('unknown-override-target', 'error', `Reusable elements: studio config declares reuse.component "${component}", which is not a registered component. Fix the id
|
|
79
|
+
reuseIssue('unknown-override-target', 'error', `Reusable elements: studio config declares reuse.component "${component}", which is not a registered component. Fix the id to name your embed component — until then the reuse gestures are off.`, { key: REUSE_KEYS.unknownComponent, vars: { component } }, component),
|
|
130
80
|
],
|
|
131
81
|
};
|
|
132
82
|
}
|
|
@@ -181,51 +131,30 @@ function resolveDeclaredReuse(declaration, manifests, collections) {
|
|
|
181
131
|
};
|
|
182
132
|
}
|
|
183
133
|
/**
|
|
184
|
-
* Resolve the project's ONE reuse capability (AD-a) plus any config issues —
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
* | Declaration | Candidates | Result |
|
|
188
|
-
* | --- | --- | --- |
|
|
189
|
-
* | present, resolves | any | the declared capability, no issue |
|
|
190
|
-
* | present, does not resolve | any | `null` + an ERROR issue (misconfiguration) |
|
|
191
|
-
* | absent | exactly 1 | that candidate, no issue (the zero-config default) |
|
|
192
|
-
* | absent | 2 or more | `null` + a WARNING issue naming every candidate |
|
|
193
|
-
* | absent | 0 | `null`, **no issue** — a project need not use reusable elements |
|
|
134
|
+
* Resolve the project's ONE reuse capability (AD-a) plus any config issues — EC-728's
|
|
135
|
+
* matrix (declare, never infer):
|
|
194
136
|
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
137
|
+
* | Declaration | Result |
|
|
138
|
+
* | --- | --- |
|
|
139
|
+
* | present, resolves | the declared capability, no issue |
|
|
140
|
+
* | present, does not resolve | `null` + an ERROR issue (misconfiguration) |
|
|
141
|
+
* | absent | `null`, **no issue** — the project has no reusable elements |
|
|
199
142
|
*
|
|
200
|
-
* The
|
|
201
|
-
* that
|
|
143
|
+
* The absent row is deliberately silent: a project need not use reusable elements,
|
|
144
|
+
* and naming a component that "looks like an embed" would be the guess again, as
|
|
145
|
+
* advice (EC-728). An unresolvable declaration disables the gestures and is reported
|
|
146
|
+
* once, in the header Issues popover.
|
|
202
147
|
*/
|
|
203
148
|
export function resolveReuse(manifests, collections, declaration) {
|
|
204
|
-
if (declaration)
|
|
205
|
-
return resolveDeclaredReuse(declaration, manifests, collections);
|
|
206
|
-
const candidates = inferredEmbedCandidates(manifests, collections);
|
|
207
|
-
if (candidates.length === 1)
|
|
208
|
-
return { capability: candidates[0], issues: [] };
|
|
209
|
-
if (candidates.length === 0)
|
|
149
|
+
if (!declaration)
|
|
210
150
|
return { capability: null, issues: [] };
|
|
211
|
-
return
|
|
212
|
-
capability: null,
|
|
213
|
-
issues: [
|
|
214
|
-
reuseIssue('ambiguous-inference', 'warning', `Reusable elements: ${candidates.length} components have the reusable-embed shape (${quotedList(candidates.map((c) => c.embedComponentId))}). A project has exactly one reusable-element embed, so the studio will not guess — declare it in studio.config as reuse: { component: '<id>' }. Until then the reuse gestures are off.`, {
|
|
215
|
-
key: REUSE_KEYS.ambiguousInference,
|
|
216
|
-
vars: {
|
|
217
|
-
count: candidates.length,
|
|
218
|
-
components: quotedList(candidates.map((c) => c.embedComponentId)),
|
|
219
|
-
},
|
|
220
|
-
}),
|
|
221
|
-
],
|
|
222
|
-
};
|
|
151
|
+
return resolveDeclaredReuse(declaration, manifests, collections);
|
|
223
152
|
}
|
|
224
153
|
/**
|
|
225
|
-
* The project's reuse capability alone, or `null` when it is
|
|
154
|
+
* The project's reuse capability alone, or `null` when it is undeclared or
|
|
226
155
|
* misdeclared — for callers that act on the capability and do not surface config
|
|
227
|
-
* issues themselves (the
|
|
228
|
-
* the shell
|
|
156
|
+
* issues themselves (the gestures, the canvas placeholder). The issues are surfaced
|
|
157
|
+
* ONCE, by the shell; see {@link resolveReuse}.
|
|
229
158
|
*/
|
|
230
159
|
export function resolveReuseCapability(manifests, collections, declaration) {
|
|
231
160
|
return resolveReuse(manifests, collections, declaration).capability;
|
|
@@ -241,7 +170,7 @@ export function uniqueSlug(name, taken) {
|
|
|
241
170
|
/**
|
|
242
171
|
* The values for a new reusable document promoted from `node` (EC-282): seeded
|
|
243
172
|
* defaults, the given `name` on the title field, the node on the content field,
|
|
244
|
-
* and a collision-safe slug on any UNIQUE text field (e.g.
|
|
173
|
+
* and a collision-safe slug on any UNIQUE text field (e.g. a production site's
|
|
245
174
|
* `internalId`) so the created document is publish-valid without hardcoding that
|
|
246
175
|
* field's name. Other required fields, if any, are completed by the editor when
|
|
247
176
|
* they open the new reusable.
|
|
@@ -285,17 +214,23 @@ export function reuseEmbedRef(node, capability) {
|
|
|
285
214
|
const ref = isStaticProp(prop) ? readDocumentRef(prop.value) : undefined;
|
|
286
215
|
return ref ?? null;
|
|
287
216
|
}
|
|
288
|
-
/**
|
|
217
|
+
/**
|
|
218
|
+
* The `Reusable` embed node referencing the new document (id minted by the action).
|
|
219
|
+
*
|
|
220
|
+
* EC-728 — CANONICAL from the first write: the prop is core's `staticProp` (bare `{ value }`,
|
|
221
|
+
* EC-312), never `{ kind: 'static', value }`. The canvas commits its node patches raw, while
|
|
222
|
+
* the draft takes the same write through the self-typing lens, which strips a redundant
|
|
223
|
+
* `kind`; a non-canonical node therefore made the two views of the canvas field disagree, the
|
|
224
|
+
* draft reported the disagreement as a change made underneath the canvas, and the rebase
|
|
225
|
+
* dropped *Make reusable*'s own undo step (`reuse-undo.test.ts`).
|
|
226
|
+
*/
|
|
289
227
|
export function makeEmbedNode(capability, documentId) {
|
|
290
228
|
return {
|
|
291
229
|
id: 'reuse-embed',
|
|
292
230
|
componentId: capability.embedComponentId,
|
|
293
231
|
props: {
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
// EC-589 / EC-586: a reference is a typed envelope from the first write.
|
|
297
|
-
value: referenceNode({ collection: capability.collectionId, id: documentId }),
|
|
298
|
-
},
|
|
232
|
+
// EC-589 / EC-586: a reference is a typed envelope from the first write.
|
|
233
|
+
[capability.relationProp]: staticProp(referenceNode({ collection: capability.collectionId, id: documentId })),
|
|
299
234
|
},
|
|
300
235
|
};
|
|
301
236
|
}
|
|
@@ -339,8 +274,9 @@ export function detachRefusal(args) {
|
|
|
339
274
|
/**
|
|
340
275
|
* Run "Make reusable" (EC-282) — the preflight first (EC-584: a refusal creates,
|
|
341
276
|
* publishes and replaces NOTHING), then ONE insert-if-absent create of the reusable
|
|
342
|
-
* document (EC-595 A2), the in-place swap for the embed
|
|
343
|
-
*
|
|
277
|
+
* document (EC-595 A2), the in-place swap for the embed — one canvas history entry that
|
|
278
|
+
* records the created document (EC-728) — and the chosen publish, whose success notice is
|
|
279
|
+
* shown only when the document is actually published.
|
|
344
280
|
*/
|
|
345
281
|
export async function runPromote(args) {
|
|
346
282
|
const { root, nodeId, node, name, capability, collection, placement, canvasFieldLabel, effects } = args;
|
|
@@ -351,8 +287,9 @@ export async function runPromote(args) {
|
|
|
351
287
|
}
|
|
352
288
|
const ref = { collection: capability.collectionId, id: effects.newDocumentId() };
|
|
353
289
|
const content = buildReusableValues(collection, capability, name, node, args.existing, args.locales);
|
|
354
|
-
|
|
355
|
-
effects.
|
|
290
|
+
const document = { ...ref, ...content };
|
|
291
|
+
effects.insertDocument(document);
|
|
292
|
+
effects.replaceInCanvas(nodeId, makeEmbedNode(capability, ref.id), { kind: 'reusable-created', ref, name, document });
|
|
356
293
|
if (!args.publish) {
|
|
357
294
|
effects.madeDraft(name);
|
|
358
295
|
return 'draft';
|
|
@@ -365,4 +302,84 @@ export async function runPromote(args) {
|
|
|
365
302
|
effects.publishFailed(name);
|
|
366
303
|
return 'publish-failed';
|
|
367
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* EC-728 — Undo of *Make reusable*, the document side. The created document is deleted ONLY
|
|
307
|
+
* when every authoritative fact at Undo time says nobody else has it: never published (the
|
|
308
|
+
* record), referenced nowhere — after the page's own restore has landed — (the reference
|
|
309
|
+
* index, both variants), and unchanged since its create (the delete's revision precondition,
|
|
310
|
+
* checked by the store in its own step, which also refuses a strict referrer). Anything else
|
|
311
|
+
* keeps it, with the reason. A read that throws keeps it too: an unproven fact never deletes.
|
|
312
|
+
*/
|
|
313
|
+
export async function undoPromote(effect, deps) {
|
|
314
|
+
try {
|
|
315
|
+
await deps.flush();
|
|
316
|
+
const record = await deps.read(effect.ref);
|
|
317
|
+
if (!record)
|
|
318
|
+
return 'gone';
|
|
319
|
+
if (record.published)
|
|
320
|
+
return 'published';
|
|
321
|
+
if ((await deps.referrers(effect.ref)) > 0)
|
|
322
|
+
return 'referenced';
|
|
323
|
+
switch (await deps.deleteCreated(effect.ref)) {
|
|
324
|
+
case 'deleted':
|
|
325
|
+
return 'deleted';
|
|
326
|
+
case 'gone':
|
|
327
|
+
return 'gone';
|
|
328
|
+
case 'changed':
|
|
329
|
+
return 'edited';
|
|
330
|
+
case 'referenced':
|
|
331
|
+
return 'referenced';
|
|
332
|
+
default:
|
|
333
|
+
return 'failed';
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
return 'failed';
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** The notice for a KEPT document (EC-728 — it names the document and why); none when it went. */
|
|
341
|
+
export function undoPromoteNotice(outcome) {
|
|
342
|
+
switch (outcome) {
|
|
343
|
+
case 'published':
|
|
344
|
+
return 'builder.reuse.undoKeptPublished';
|
|
345
|
+
case 'edited':
|
|
346
|
+
return 'builder.reuse.undoKeptEdited';
|
|
347
|
+
case 'referenced':
|
|
348
|
+
return 'builder.reuse.undoKeptReferenced';
|
|
349
|
+
case 'failed':
|
|
350
|
+
return 'builder.reuse.undoKeptFailed';
|
|
351
|
+
default:
|
|
352
|
+
return undefined;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* EC-728 — the document side of every Undo/Redo that crosses a *Make reusable* step, for one
|
|
357
|
+
* canvas. Crossings run strictly in order (a Redo waits for the Undo before it), so a fast
|
|
358
|
+
* Undo → Redo never re-inserts a document whose removal is still in flight. Redo re-inserts
|
|
359
|
+
* (the same id, insert-if-absent) exactly the documents ITS Undo removed or found gone — never
|
|
360
|
+
* one Undo kept (it is still there) — and the canvas entry re-swaps the embed.
|
|
361
|
+
*/
|
|
362
|
+
export function createPromoteHistory(deps) {
|
|
363
|
+
const removed = new Set();
|
|
364
|
+
let chain = Promise.resolve();
|
|
365
|
+
return {
|
|
366
|
+
crossed(step) {
|
|
367
|
+
chain = chain.then(async () => {
|
|
368
|
+
const key = documentKey(step.effect.ref);
|
|
369
|
+
if (step.direction === 'redo') {
|
|
370
|
+
if (removed.delete(key))
|
|
371
|
+
deps.insert(step.effect.document);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const outcome = await undoPromote(step.effect, deps);
|
|
375
|
+
if (outcome === 'deleted' || outcome === 'gone')
|
|
376
|
+
removed.add(key);
|
|
377
|
+
const notice = undoPromoteNotice(outcome);
|
|
378
|
+
if (notice)
|
|
379
|
+
deps.notify(notice, step.effect.name);
|
|
380
|
+
});
|
|
381
|
+
return chain;
|
|
382
|
+
},
|
|
383
|
+
};
|
|
384
|
+
}
|
|
368
385
|
//# sourceMappingURL=reuse.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reuse.js","sourceRoot":"","sources":["../../../src/components/builder/reuse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAA;AAEtF,OAAO,EACL,cAAc,EACd,SAAS,EACT,eAAe,EACf,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,UAAU,GACX,MAAM,0BAA0B,CAAA;AAEjC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAG5H,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAqG9C,oFAAoF;AACpF,MAAM,WAAW,GAAG,OAAO,CAAA;AAY3B,iEAAiE;AACjE,SAAS,eAAe,CAAC,QAA2B;IAClD,MAAM,KAAK,GAAmB,EAAE,CAAA;IAChC,KAAK,MAAM,KAAK,IAAI,kBAAkB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACjD,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YAAE,SAAQ;QACvC,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,EAAE,MA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AAI,CAAC,CAAA;QACvB,OAAO,OAAO,CAAA;IAChB,CAAC;IACD,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAA;IAC/D,IAAI,SAAS,EAAE,CAAC;QACd,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;QAC3B,OAAO,WAAW,CAAA;IACpB,CAAC;IACD,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;IAC3B,OAAO,gBAAgB,CAAA;AACzB,CAAC","sourcesContent":["import { manifestPropFields, manifestSlots } from '@elytracms/core/component-registry'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\nimport {\n fieldAllowList,\n itemLimit,\n readDocumentRef,\n referenceNode,\n seedDefaults,\n titleFieldOf,\n writeField,\n} from '@elytracms/core/cms-core'\nimport type { CmsDocument, CollectionDef, DocumentRef, LocaleConfig } from '@elytracms/core/cms-core'\nimport { editBlockRoots, isStaticProp, replacePlacementRefusal, valuePlacementRefusal } from '@elytracms/core/project-graph'\nimport type { ComponentNode, PlacementScope, PlacementVerdict } from '@elytracms/core/project-graph'\nimport type { CustomizationIssue, CustomizationMessageRef } from '@elytracms/core/studio-core'\nimport { slugify } from '../../lib/utils'\nimport { fieldLabel } from '../cms/cms-labels'\n\n/**\n * The reuse capability (EC-282): the engine-generic description of how a project\n * models reusable elements. **AD-a (EC-467): reusable elements are SINGULAR per\n * project** — exactly one embed component and exactly one reusable collection.\n * Multiple reuse collections are deliberately not supported, which is why this is\n * one value and never a list.\n *\n * The capability is normally DERIVED from config (manifests + collections) — no\n * declaration needed, so a consumer that already has a transcluding embed gets the\n * in-canvas gestures for free (the EC-296 \"works automatically\" pattern). The\n * derivation predicate for a \"reusable embed\" component: it contributes no slots of\n * its own and has exactly ONE `relation` prop (cardinality `one`) whose target\n * collection holds a `blocks` field — i.e. it embeds a single document and renders\n * that document's composition by transclusion (EC-254/EC-281). For Konditorei that\n * is uniquely `project.Reusable` → `element` → `reusable.content`.\n *\n * EC-462 — the predicate additionally DISQUALIFIES a candidate whose own manifest\n * explicitly declares its relation prop to be something other than an embed\n * pointer. The shape test alone proved unsound the moment a relation prop's\n * target collection gains a `blocks` field of its own (a category/page with a\n * canvas — a completely natural content shape): the EC-276 sprint's ProductGrid\n * and the demo's OptionBox were both claimed as \"the embed\", so their ordinary\n * relation picks rendered the reusable-element placeholder, grew Detach/Make-\n * reusable gestures, and fed embed-worded publish-integrity issues. Two\n * explicit-declaration disqualifiers close the observed class:\n *\n * - a manifest with a `listing` declaration is a QUERY host (EC-255) — its\n * relation prop feeds the query (a `{ prop }` operand of `listing.where`),\n * never a transclusion pointer;\n * - a relation prop with `form.hidden` (predicate or `true`) is conditional/\n * auxiliary — EC-394 strips a hidden relation's ref at publish, so it cannot\n * coherently be what the component transcludes.\n *\n * Both read only the CANDIDATE manifest's own declarations (never the target's\n * contents) and can only EXCLUDE, so a genuine pure embed (which declares\n * neither) is always kept. EC-462's residual — a bare unconditional\n * single-relation display component (e.g. a page teaser) is at rest\n * indistinguishable from a genuine embed — is closed by EC-467's optional\n * {@link StudioReuseConfig} declaration: a project that hits ambiguity declares\n * its way out, and the ambiguity is LOUD instead of silently disabling the\n * gestures. See {@link resolveReuse}.\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/**\n * EC-467 (AD-b) — the OPTIONAL studio-config declaration of the reuse embed:\n * `defineStudio({ reuse: { component: 'project.Reusable' } })`. See\n * {@link import('../app-views/studio-config').StudioConfig.reuse} for the\n * consumer-facing contract; this is the shape {@link resolveReuse} consumes.\n *\n * One identifier is enough because the rest DERIVES from it (its single-document\n * relation prop → that prop's target collection → that collection's `blocks`\n * field), and because reusable elements are singular per project (AD-a).\n */\nexport interface StudioReuseConfig {\n /** The embed component's registry id, e.g. `'project.Reusable'`. */\n component: string\n /**\n * Which relation prop points at the reusable document. Needed ONLY when the\n * declared component legitimately has more than one single-document relation\n * prop — otherwise the sole one is derived.\n */\n relationProp?: string\n}\n\n/**\n * EC-467 — the resolution of the project's reuse capability: the capability (or\n * `null`), plus the config issues a developer must SEE.\n *\n * The issues ride the EC-236 {@link CustomizationIssue} surface (`point: 'reuse'`),\n * exactly like the sidebar's and the field renderers' — so they render at the\n * studio rail foot on every surface, which is the studio's home for\n * project-CONFIGURATION problems (the document-scoped Issues pane is the wrong\n * home: this is not a content problem in one document).\n *\n * EC-478: each issue carries a `messageRef` (catalog key + identifier values)\n * alongside its prebuilt English, so the rail foot renders it in the active UI\n * locale. This module stays pure — it names a key, it never calls `translate`;\n * `lib/persona/labels.ts` resolves it at the render site. That is what makes the\n * whole list localize together, which is the mixed-language outcome EC-467\n * declined to create by localizing only its own half.\n */\nexport interface ReuseResolution {\n capability: ReuseCapability | null\n /** Empty whenever the capability is unambiguous — including \"this project has none\". */\n issues: CustomizationIssue[]\n}\n\n/** The customization point name stamped onto every reuse issue (EC-236 locator). */\nconst REUSE_POINT = 'reuse'\n\n/** A `relation` prop of a manifest, normalized for both resolution paths. */\ninterface RelationProp {\n name: string\n /** The target collection id; `undefined` when the manifest declares none. */\n target: string | undefined\n multiple: boolean\n /** EC-462: `form.hidden` present and not literally `false` (predicate or `true`). */\n conditional: boolean\n}\n\n/** Every `relation` prop of a manifest, in declaration order. */\nfunction relationPropsOf(manifest: ComponentManifest): RelationProp[] {\n const props: RelationProp[] = []\n for (const field of manifestPropFields(manifest)) {\n if (field.type !== 'relation') continue\n const hidden = field.form?.hidden\n props.push({\n name: field.name,\n target: field.target,\n multiple: field.multiple === true,\n conditional: hidden !== undefined && hidden !== false,\n })\n }\n return props\n}\n\n/**\n * The relation props a DECLARED embed could plausibly transclude through: targeted\n * and cardinality-one. A cardinality-`many` (or targetless) relation is excluded\n * structurally, not heuristically — an embed transcludes exactly one document and\n * {@link makeEmbedNode} writes exactly one `{collection,id}`, which a list-valued\n * or target-less prop cannot hold.\n */\nfunction embeddableRelationProps(manifest: ComponentManifest): TargetedRelationProp[] {\n return relationPropsOf(manifest).filter(\n (r): r is TargetedRelationProp => r.target !== undefined && !r.multiple,\n )\n}\ntype TargetedRelationProp = RelationProp & { target: string }\n\n/** The collection's first composition field — what an embed of it transcludes. */\nfunction blocksFieldOf(collection: CollectionDef) {\n const field = collection.fields.find((f) => f.type === 'blocks')\n return field?.type === 'blocks' ? field : undefined\n}\n\n/**\n * The catalog keys for the reuse config issues (EC-478), in the `builder.reuse.config.*`\n * namespace. Named here so the producer and the catalog-parity test agree on one list.\n */\nconst REUSE_KEYS = {\n unknownComponent: 'builder.reuse.config.unknownComponent',\n noRelationProp: 'builder.reuse.config.noRelationProp',\n unknownRelationProp: 'builder.reuse.config.unknownRelationProp',\n ambiguousRelationProp: 'builder.reuse.config.ambiguousRelationProp',\n unknownCollection: 'builder.reuse.config.unknownCollection',\n noBlocksField: 'builder.reuse.config.noBlocksField',\n ambiguousInference: 'builder.reuse.config.ambiguousInference',\n} as const\n\nfunction reuseIssue(\n code: CustomizationIssue['code'],\n severity: CustomizationIssue['severity'],\n message: string,\n messageRef: CustomizationMessageRef,\n id?: string,\n): CustomizationIssue {\n return {\n code,\n severity,\n message,\n messageRef,\n point: REUSE_POINT,\n ...(id === undefined ? {} : { id }),\n }\n}\n\n/** `\"a\", \"b\"` — a readable list of prop/component ids for an issue message. */\nfunction quotedList(names: readonly string[]): string {\n return names.map((name) => `\"${name}\"`).join(', ')\n}\n\n/**\n * The components whose SHAPE makes them plausible reuse embeds (the zero-config\n * heuristic + EC-462's disqualifiers), in manifest order. Exported for the tests\n * and for issue copy; the resolution rule lives in {@link resolveReuse}.\n */\nexport function inferredEmbedCandidates(\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n): ReuseCapability[] {\n const matches: ReuseCapability[] = []\n for (const manifest of manifests) {\n // EC-591 (COMPOSITION #15): the DERIVED slots — a `blocks` prop is a child\n // region (`manifestSlots`), so a manifest with `slots: []` and a blocks prop is\n // NOT slot-less; reading raw `manifest.slots` inferred it as a reuse embed.\n if (manifestSlots(manifest).length > 0) continue\n // EC-462: a `listing` manifest is a query host by its own declaration — its\n // relation prop is the filter source, never an embed pointer.\n if (manifest.listing) continue\n // The heuristic requires the relation to be UNAMBIGUOUS within the manifest:\n // exactly ONE relation prop of any kind, which must then be targeted,\n // cardinality-one and unconditional. (Counting all relation props — not just\n // the embeddable ones — is deliberate: a component with a second, list-valued\n // relation is not the single-purpose shape the heuristic is allowed to claim.)\n const relations = relationPropsOf(manifest)\n const relation = relations.length === 1 ? relations[0]! : undefined\n if (!relation || relation.target === undefined || relation.multiple || relation.conditional)\n continue\n const collection = collections.find((c) => c.id === relation.target)\n if (!collection) continue\n const blocksField = blocksFieldOf(collection)\n if (!blocksField) continue\n matches.push({\n embedComponentId: manifest.id,\n relationProp: relation.name,\n collectionId: collection.id,\n contentField: blocksField.name,\n contentCardinality: itemLimit(blocksField) === 1 ? 'one' : 'many',\n })\n }\n return matches\n}\n\n/**\n * Resolve the DECLARED embed (EC-467, AD-b). An explicit declaration is the\n * developer's authority, so the inference disqualifiers are NOT applied here: a\n * declared component may have slots, may declare `listing`, and its relation prop\n * may be `form.hidden` — those exist to stop the engine GUESSING, not to overrule\n * a stated intent. Only structural impossibilities are issues (see AD-c row 2):\n * an unknown component id, no usable relation prop (or an ambiguous set with no\n * `relationProp`), an undefined target collection, or a target with no `blocks`\n * field — each of which would leave nothing coherent to transclude.\n */\nfunction resolveDeclaredReuse(\n declaration: StudioReuseConfig,\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n): ReuseResolution {\n const { component, relationProp } = declaration\n const fail = (message: string, messageRef: CustomizationMessageRef): ReuseResolution => ({\n capability: null,\n issues: [reuseIssue('invalid-override', 'error', message, messageRef, component)],\n })\n\n const manifest = manifests.find((m) => m.id === component)\n if (!manifest) {\n return {\n capability: null,\n issues: [\n reuseIssue(\n 'unknown-override-target',\n 'error',\n `Reusable elements: studio config declares reuse.component \"${component}\", which is not a registered component. Fix the id, or remove the reuse block to let the studio infer the embed.`,\n { key: REUSE_KEYS.unknownComponent, vars: { component } },\n component,\n ),\n ],\n }\n }\n\n const relations = embeddableRelationProps(manifest)\n if (relations.length === 0) {\n return fail(\n `Reusable elements: the declared embed \"${component}\" has no single-document relation prop, so it cannot point at a reusable document. An embed needs one relation prop with cardinality one.`,\n { key: REUSE_KEYS.noRelationProp, vars: { component } },\n )\n }\n const names = relations.map((r) => r.name)\n let relation: TargetedRelationProp\n if (relationProp !== undefined) {\n const named = relations.find((r) => r.name === relationProp)\n if (!named) {\n return fail(\n `Reusable elements: the declared embed \"${component}\" has no single-document relation prop named \"${relationProp}\". Its relation props are: ${quotedList(names)}.`,\n {\n key: REUSE_KEYS.unknownRelationProp,\n vars: { component, relationProp, props: quotedList(names) },\n },\n )\n }\n relation = named\n } else if (relations.length === 1) {\n relation = relations[0]!\n } else {\n return fail(\n `Reusable elements: the declared embed \"${component}\" has ${relations.length} single-document relation props (${quotedList(names)}) — add reuse.relationProp to say which one points at the reusable document.`,\n {\n key: REUSE_KEYS.ambiguousRelationProp,\n vars: { component, count: relations.length, props: quotedList(names) },\n },\n )\n }\n\n const collection = collections.find((c) => c.id === relation.target)\n if (!collection) {\n return fail(\n `Reusable elements: \"${component}.${relation.name}\" targets the collection \"${relation.target}\", which this project does not define.`,\n {\n key: REUSE_KEYS.unknownCollection,\n vars: { component, relationProp: relation.name, collection: relation.target },\n },\n )\n }\n const blocksField = blocksFieldOf(collection)\n if (!blocksField) {\n return fail(\n `Reusable elements: the collection \"${collection.id}\" behind \"${component}.${relation.name}\" has no blocks (composition) field, so there is nothing for the embed to transclude.`,\n {\n key: REUSE_KEYS.noBlocksField,\n vars: { component, relationProp: relation.name, collection: collection.id },\n },\n )\n }\n\n return {\n capability: {\n embedComponentId: manifest.id,\n relationProp: relation.name,\n collectionId: collection.id,\n contentField: blocksField.name,\n contentCardinality: itemLimit(blocksField) === 1 ? 'one' : 'many',\n },\n issues: [],\n }\n}\n\n/**\n * Resolve the project's ONE reuse capability (AD-a) plus any config issues —\n * EC-467's full matrix (AD-c):\n *\n * | Declaration | Candidates | Result |\n * | --- | --- | --- |\n * | present, resolves | any | the declared capability, no issue |\n * | present, does not resolve | any | `null` + an ERROR issue (misconfiguration) |\n * | absent | exactly 1 | that candidate, no issue (the zero-config default) |\n * | absent | 2 or more | `null` + a WARNING issue naming every candidate |\n * | absent | 0 | `null`, **no issue** — a project need not use reusable elements |\n *\n * Severity is the honest split: a declaration that cannot resolve is broken\n * config the developer asked for (error); inference ambiguity is nothing broken —\n * the engine declines to guess and asks for one line (warning). Both disable the\n * gestures, and both render identically in the rail's issue list.\n *\n * The zero-candidate row is deliberately silent: crying wolf at every project\n * that has no reusable elements would train developers to ignore the surface.\n */\nexport function resolveReuse(\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n declaration?: StudioReuseConfig,\n): ReuseResolution {\n if (declaration) return resolveDeclaredReuse(declaration, manifests, collections)\n\n const candidates = inferredEmbedCandidates(manifests, collections)\n if (candidates.length === 1) return { capability: candidates[0]!, issues: [] }\n if (candidates.length === 0) return { capability: null, issues: [] }\n return {\n capability: null,\n issues: [\n reuseIssue(\n 'ambiguous-inference',\n 'warning',\n `Reusable elements: ${candidates.length} components have the reusable-embed shape (${quotedList(\n candidates.map((c) => c.embedComponentId),\n )}). A project has exactly one reusable-element embed, so the studio will not guess — declare it in studio.config as reuse: { component: '<id>' }. Until then the reuse gestures are off.`,\n {\n key: REUSE_KEYS.ambiguousInference,\n vars: {\n count: candidates.length,\n components: quotedList(candidates.map((c) => c.embedComponentId)),\n },\n },\n ),\n ],\n }\n}\n\n/**\n * The project's reuse capability alone, or `null` when it is absent, ambiguous, or\n * misdeclared — for callers that act on the capability and do not surface config\n * issues themselves (the publish-integrity walk). The issues are surfaced ONCE, by\n * the shell rail; see {@link resolveReuse}.\n */\nexport function resolveReuseCapability(\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n declaration?: StudioReuseConfig,\n): ReuseCapability | null {\n return resolveReuse(manifests, collections, declaration).capability\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 *\n * EC-580: every write goes through core's `writeField` in the project's DEFAULT\n * locale — the new document is created in its default bucket, so a localized title\n * or content field lands under `localized[default]`, never on the shared bag.\n */\nexport function buildReusableValues(\n collection: CollectionDef,\n capability: ReuseCapability,\n name: string,\n node: ComponentNode,\n existing: readonly { values?: Record<string, unknown> }[],\n locales: LocaleConfig,\n): Pick<CmsDocument, 'values' | 'localized'> {\n const at = locales.default\n let doc: CmsDocument = { collection: collection.id, id: '', ...seedDefaults(collection, locales) }\n const titleField = titleFieldOf(collection)?.name\n if (titleField) doc = writeField(collection, doc, titleField, at, 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 doc = writeField(collection, doc, field.name, at, uniqueSlug(name, taken))\n }\n }\n // EC-576: the converged v2 sequence holding the tagged node, through the core\n // write path — never the pre-0.0.84 bare node/array. Cardinality is a\n // constraint over that one shape, not a second shape (EC-500 D2).\n doc = writeField(collection, doc, capability.contentField, at, editBlockRoots(undefined, () => [node]))\n return { values: doc.values, ...(doc.localized !== undefined ? { localized: doc.localized } : {}) }\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 = isStaticProp(prop) ? readDocumentRef(prop.value) : undefined\n return ref ?? null\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 // EC-589 / EC-586: a reference is a typed envelope from the first write.\n value: referenceNode({ collection: capability.collectionId, id: documentId }),\n },\n },\n }\n}\n\n// --- The placement preflight (EC-584, closes EC-560) --------------------------------\n\n/**\n * Why a reuse gesture is refused before it does anything: the one core placement\n * judge's verdict, and the label of the FIELD it names when the refusal is at a\n * field's top level (the canvas field, or the reusable collection's content field).\n */\nexport interface ReuseRefusal {\n verdict: PlacementVerdict\n fieldLabel: string\n}\n\n/**\n * EC-584 / EC-560 — \"Make reusable\" preflight, run BEFORE any side effect (the\n * reusable document is created — and maybe published — before the canvas swaps the\n * block for the embed). Two placements, both judged by the one core judge the\n * builder reducer enforces:\n *\n * 1. the EMBED lands where the promoted block was (the canvas field's `allow` at the\n * root, or the slot's `allow` when the block sits in a slot);\n * 2. the promoted BLOCK lands at the top level of the reusable collection's content\n * field (that field's effective vocabulary, `fieldAllowList`).\n *\n * `null` when both are admitted. The reducer still enforces (1) on its own.\n */\nexport function promoteRefusal(args: {\n root: ComponentNode\n nodeId: string\n node: ComponentNode\n capability: ReuseCapability\n collection: CollectionDef\n placement: PlacementScope\n canvasFieldLabel: string\n}): ReuseRefusal | null {\n const { root, nodeId, node, capability, collection, placement, canvasFieldLabel } = args\n const embed = replacePlacementRefusal(root, nodeId, [makeEmbedNode(capability, 'preflight')], placement)\n if (embed) return { verdict: embed, fieldLabel: canvasFieldLabel }\n const contentField = collection.fields.find((field) => field.name === capability.contentField)\n const contentAllow = contentField ? fieldAllowList(contentField) : undefined\n if (contentField && contentAllow) {\n const into = valuePlacementRefusal([node], { components: placement.components, fieldAllow: contentAllow })\n if (into) return { verdict: into, fieldLabel: fieldLabel(contentField) }\n }\n return null\n}\n\n/**\n * EC-584 / EC-560 — \"Detach to local copy\" preflight: the reusable's content blocks\n * land where the embed was. Refusing the WHOLE gesture when one inlined block is\n * outside the vocabulary keeps the reference in place (EC-560's frame: refuse\n * visibly, dispatch nothing) — the editor sees why and decides.\n */\nexport function detachRefusal(args: {\n root: ComponentNode\n nodeId: string\n blocks: readonly ComponentNode[]\n placement: PlacementScope\n canvasFieldLabel: string\n}): ReuseRefusal | null {\n const verdict = replacePlacementRefusal(args.root, args.nodeId, args.blocks, args.placement)\n return verdict ? { verdict, fieldLabel: args.canvasFieldLabel } : null\n}\n\n/** The effects \"Make reusable\" performs — injected, so the order and the refusal are testable. */\nexport interface PromoteEffects {\n newDocumentId(): string\n insertDocument(doc: CmsDocument): void\n replaceInCanvas(nodeId: string, embed: ComponentNode): void\n /** Publish the new reusable; resolves `true` only when the document IS published afterwards. */\n publish(ref: DocumentRef): Promise<boolean>\n refused(refusal: ReuseRefusal): void\n madeDraft(name: string): void\n madePublished(name: string): void\n publishFailed(name: string): void\n}\n\n/**\n * Run \"Make reusable\" (EC-282) — the preflight first (EC-584: a refusal creates,\n * publishes and replaces NOTHING), then ONE insert-if-absent create of the reusable\n * document (EC-595 A2), the in-place swap for the embed, and the chosen publish,\n * whose success notice is shown only when the document is actually published.\n */\nexport async function runPromote(args: {\n root: ComponentNode\n nodeId: string\n node: ComponentNode\n name: string\n publish: boolean\n capability: ReuseCapability\n collection: CollectionDef\n existing: readonly { values?: Record<string, unknown> }[]\n locales: LocaleConfig\n placement: PlacementScope\n canvasFieldLabel: string\n effects: PromoteEffects\n}): Promise<'refused' | 'draft' | 'published' | 'publish-failed'> {\n const { root, nodeId, node, name, capability, collection, placement, canvasFieldLabel, effects } = args\n const refusal = promoteRefusal({ root, nodeId, node, capability, collection, placement, canvasFieldLabel })\n if (refusal) {\n effects.refused(refusal)\n return 'refused'\n }\n const ref = { collection: capability.collectionId, id: effects.newDocumentId() }\n const content = buildReusableValues(collection, capability, name, node, args.existing, args.locales)\n effects.insertDocument({ ...ref, ...content })\n effects.replaceInCanvas(nodeId, makeEmbedNode(capability, ref.id))\n if (!args.publish) {\n effects.madeDraft(name)\n return 'draft'\n }\n const published = await effects.publish(ref).catch(() => false)\n if (published) {\n effects.madePublished(name)\n return 'published'\n }\n effects.publishFailed(name)\n return 'publish-failed'\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,EACL,WAAW,EACX,cAAc,EACd,SAAS,EACT,eAAe,EACf,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,UAAU,GACX,MAAM,0BAA0B,CAAA;AAEjC,OAAO,EACL,cAAc,EACd,YAAY,EACZ,uBAAuB,EACvB,UAAU,EACV,qBAAqB,GACtB,MAAM,+BAA+B,CAAA;AAKtC,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAoF9C,oFAAoF;AACpF,MAAM,WAAW,GAAG,OAAO,CAAA;AAU3B,iEAAiE;AACjE,SAAS,eAAe,CAAC,QAA2B;IAClD,MAAM,KAAK,GAAmB,EAAE,CAAA;IAChC,KAAK,MAAM,KAAK,IAAI,kBAAkB,CAAC,QAA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AC1D,OAAM;gBACR,CAAC;gBACD,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;gBACpD,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,MAAM;oBAAE,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;gBACjE,MAAM,MAAM,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAA;gBACzC,IAAI,MAAM;oBAAE,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;YACnD,CAAC,CAAC,CAAA;YACF,OAAO,KAAK,CAAA;QACd,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["import { manifestPropFields } from '@elytracms/core/component-registry'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\nimport {\n documentKey,\n fieldAllowList,\n itemLimit,\n readDocumentRef,\n referenceNode,\n seedDefaults,\n titleFieldOf,\n writeField,\n} from '@elytracms/core/cms-core'\nimport type { CmsDocument, CollectionDef, DocumentRef, LocaleConfig } from '@elytracms/core/cms-core'\nimport {\n editBlockRoots,\n isStaticProp,\n replacePlacementRefusal,\n staticProp,\n valuePlacementRefusal,\n} from '@elytracms/core/project-graph'\nimport type { ComponentNode, PlacementScope, PlacementVerdict } from '@elytracms/core/project-graph'\nimport type { CustomizationIssue, CustomizationMessageRef } from '@elytracms/core/studio-core'\nimport type { DeleteCreatedOutcome } from '../../lib/operations/cms-persistence'\nimport type { CanvasHistoryEffect } from './builder-store'\nimport { slugify } from '../../lib/utils'\nimport { fieldLabel } from '../cms/cms-labels'\n\n/**\n * The reuse capability (EC-282): the engine-generic description of how a project\n * models reusable elements. **AD-a (EC-467): reusable elements are SINGULAR per\n * project** — exactly one embed component and exactly one reusable collection.\n * Multiple reuse collections are deliberately not supported, which is why this is\n * one value and never a list.\n *\n * **EC-728 (owner ruling 2026-10-31, \"Declare, never infer\"): the capability exists\n * only when the project DECLARES its embed** — `defineStudio({ reuse: { component } })`\n * ({@link StudioReuseConfig}). The engine never guesses one from a component's shape.\n * The shape test it used to run (no slots, exactly one cardinality-one `relation`\n * prop whose target collection holds a `blocks` field) cannot tell an embed from an\n * ordinary card that links to a page with a canvas: EC-462 refused the guess when two\n * components matched, and EC-728 measured the one-candidate guess crowning a \"read\n * next\" link card — *Make reusable* then moved a block's content into a new document\n * and left a link card in its place. A guess with a destructive gesture attached is\n * the bug, so there is no guess.\n *\n * What the capability drives (and therefore what an undeclared project does not get):\n * the in-canvas gestures (*Make reusable* / *Detach to local copy*), the canvas\n * placeholder for an embed whose target is a draft or missing (EC-300), and the reuse\n * config issues. Transclusion itself does not depend on it — the runtime renderer\n * injects `renderBlocks` for every manifest that consumes relations.\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/**\n * EC-467 (AD-b) → EC-728 — THE declaration of the reuse embed (absent: the project has\n * no reusable elements): `defineStudio({ reuse: { component: 'project.Reusable' } })`. See\n * {@link import('../app-views/studio-config').StudioConfig.reuse} for the\n * consumer-facing contract; this is the shape {@link resolveReuse} consumes.\n *\n * One identifier is enough because the rest DERIVES from it (its single-document\n * relation prop → that prop's target collection → that collection's `blocks`\n * field), and because reusable elements are singular per project (AD-a).\n */\nexport interface StudioReuseConfig {\n /** The embed component's registry id, e.g. `'project.Reusable'`. */\n component: string\n /**\n * Which relation prop points at the reusable document. Needed ONLY when the\n * declared component legitimately has more than one single-document relation\n * prop — otherwise the sole one is derived.\n */\n relationProp?: string\n}\n\n/**\n * EC-467 — the resolution of the project's reuse capability: the capability (or\n * `null`), plus the config issues a developer must SEE (a declaration that cannot\n * resolve).\n *\n * The issues ride the EC-236 {@link CustomizationIssue} surface (`point: 'reuse'`),\n * exactly like the sidebar's and the field renderers' — so they render in the header\n * Issues popover on every surface (EC-690's one issues tray), the studio's home for\n * project-CONFIGURATION problems (the document-scoped Issues pane is the wrong\n * home: this is not a content problem in one document).\n *\n * EC-478: each issue carries a `messageRef` (catalog key + identifier values)\n * alongside its prebuilt English, so the tray renders it in the active UI\n * locale. This module stays pure — it names a key, it never calls `translate`;\n * `lib/persona/labels.ts` resolves it at the render site. That is what makes the\n * whole list localize together, which is the mixed-language outcome EC-467\n * declined to create by localizing only its own half.\n */\nexport interface ReuseResolution {\n capability: ReuseCapability | null\n /** Empty whenever the declaration resolves — and when there is none (\"this project has none\"). */\n issues: CustomizationIssue[]\n}\n\n/** The customization point name stamped onto every reuse issue (EC-236 locator). */\nconst REUSE_POINT = 'reuse'\n\n/** A `relation` prop of a manifest. */\ninterface RelationProp {\n name: string\n /** The target collection id; `undefined` when the manifest declares none. */\n target: string | undefined\n multiple: boolean\n}\n\n/** Every `relation` prop of a manifest, in declaration order. */\nfunction relationPropsOf(manifest: ComponentManifest): RelationProp[] {\n const props: RelationProp[] = []\n for (const field of manifestPropFields(manifest)) {\n if (field.type !== 'relation') continue\n props.push({ name: field.name, target: field.target, multiple: field.multiple === true })\n }\n return props\n}\n\n/**\n * The relation props a DECLARED embed could plausibly transclude through: targeted\n * and cardinality-one. A cardinality-`many` (or targetless) relation is excluded\n * structurally, not heuristically — an embed transcludes exactly one document and\n * {@link makeEmbedNode} writes exactly one `{collection,id}`, which a list-valued\n * or target-less prop cannot hold.\n */\nfunction embeddableRelationProps(manifest: ComponentManifest): TargetedRelationProp[] {\n return relationPropsOf(manifest).filter(\n (r): r is TargetedRelationProp => r.target !== undefined && !r.multiple,\n )\n}\ntype TargetedRelationProp = RelationProp & { target: string }\n\n/** The collection's first composition field — what an embed of it transcludes. */\nfunction blocksFieldOf(collection: CollectionDef) {\n const field = collection.fields.find((f) => f.type === 'blocks')\n return field?.type === 'blocks' ? field : undefined\n}\n\n/**\n * The catalog keys for the reuse config issues (EC-478), in the `builder.reuse.config.*`\n * namespace. Named here so the producer and the catalog-parity test agree on one list.\n */\nconst REUSE_KEYS = {\n unknownComponent: 'builder.reuse.config.unknownComponent',\n noRelationProp: 'builder.reuse.config.noRelationProp',\n unknownRelationProp: 'builder.reuse.config.unknownRelationProp',\n ambiguousRelationProp: 'builder.reuse.config.ambiguousRelationProp',\n unknownCollection: 'builder.reuse.config.unknownCollection',\n noBlocksField: 'builder.reuse.config.noBlocksField',\n} as const\n\nfunction reuseIssue(\n code: CustomizationIssue['code'],\n severity: CustomizationIssue['severity'],\n message: string,\n messageRef: CustomizationMessageRef,\n id?: string,\n): CustomizationIssue {\n return {\n code,\n severity,\n message,\n messageRef,\n point: REUSE_POINT,\n ...(id === undefined ? {} : { id }),\n }\n}\n\n/** `\"a\", \"b\"` — a readable list of prop/component ids for an issue message. */\nfunction quotedList(names: readonly string[]): string {\n return names.map((name) => `\"${name}\"`).join(', ')\n}\n\n/**\n * Resolve the DECLARED embed (EC-467, AD-b). The declaration is the developer's\n * authority: a declared component may have slots, may declare `listing`, and its\n * relation prop may be `form.hidden` — the engine does not second-guess a stated\n * intent. Only structural impossibilities are issues (see AD-c row 2): an unknown\n * component id, no usable relation prop (or an ambiguous set with no\n * `relationProp`), an undefined target collection, or a target with no `blocks`\n * field — each of which would leave nothing coherent to transclude.\n */\nfunction resolveDeclaredReuse(\n declaration: StudioReuseConfig,\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n): ReuseResolution {\n const { component, relationProp } = declaration\n const fail = (message: string, messageRef: CustomizationMessageRef): ReuseResolution => ({\n capability: null,\n issues: [reuseIssue('invalid-override', 'error', message, messageRef, component)],\n })\n\n const manifest = manifests.find((m) => m.id === component)\n if (!manifest) {\n return {\n capability: null,\n issues: [\n reuseIssue(\n 'unknown-override-target',\n 'error',\n `Reusable elements: studio config declares reuse.component \"${component}\", which is not a registered component. Fix the id to name your embed component — until then the reuse gestures are off.`,\n { key: REUSE_KEYS.unknownComponent, vars: { component } },\n component,\n ),\n ],\n }\n }\n\n const relations = embeddableRelationProps(manifest)\n if (relations.length === 0) {\n return fail(\n `Reusable elements: the declared embed \"${component}\" has no single-document relation prop, so it cannot point at a reusable document. An embed needs one relation prop with cardinality one.`,\n { key: REUSE_KEYS.noRelationProp, vars: { component } },\n )\n }\n const names = relations.map((r) => r.name)\n let relation: TargetedRelationProp\n if (relationProp !== undefined) {\n const named = relations.find((r) => r.name === relationProp)\n if (!named) {\n return fail(\n `Reusable elements: the declared embed \"${component}\" has no single-document relation prop named \"${relationProp}\". Its relation props are: ${quotedList(names)}.`,\n {\n key: REUSE_KEYS.unknownRelationProp,\n vars: { component, relationProp, props: quotedList(names) },\n },\n )\n }\n relation = named\n } else if (relations.length === 1) {\n relation = relations[0]!\n } else {\n return fail(\n `Reusable elements: the declared embed \"${component}\" has ${relations.length} single-document relation props (${quotedList(names)}) — add reuse.relationProp to say which one points at the reusable document.`,\n {\n key: REUSE_KEYS.ambiguousRelationProp,\n vars: { component, count: relations.length, props: quotedList(names) },\n },\n )\n }\n\n const collection = collections.find((c) => c.id === relation.target)\n if (!collection) {\n return fail(\n `Reusable elements: \"${component}.${relation.name}\" targets the collection \"${relation.target}\", which this project does not define.`,\n {\n key: REUSE_KEYS.unknownCollection,\n vars: { component, relationProp: relation.name, collection: relation.target },\n },\n )\n }\n const blocksField = blocksFieldOf(collection)\n if (!blocksField) {\n return fail(\n `Reusable elements: the collection \"${collection.id}\" behind \"${component}.${relation.name}\" has no blocks (composition) field, so there is nothing for the embed to transclude.`,\n {\n key: REUSE_KEYS.noBlocksField,\n vars: { component, relationProp: relation.name, collection: collection.id },\n },\n )\n }\n\n return {\n capability: {\n embedComponentId: manifest.id,\n relationProp: relation.name,\n collectionId: collection.id,\n contentField: blocksField.name,\n contentCardinality: itemLimit(blocksField) === 1 ? 'one' : 'many',\n },\n issues: [],\n }\n}\n\n/**\n * Resolve the project's ONE reuse capability (AD-a) plus any config issues — EC-728's\n * matrix (declare, never infer):\n *\n * | Declaration | Result |\n * | --- | --- |\n * | present, resolves | the declared capability, no issue |\n * | present, does not resolve | `null` + an ERROR issue (misconfiguration) |\n * | absent | `null`, **no issue** — the project has no reusable elements |\n *\n * The absent row is deliberately silent: a project need not use reusable elements,\n * and naming a component that \"looks like an embed\" would be the guess again, as\n * advice (EC-728). An unresolvable declaration disables the gestures and is reported\n * once, in the header Issues popover.\n */\nexport function resolveReuse(\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n declaration?: StudioReuseConfig,\n): ReuseResolution {\n if (!declaration) return { capability: null, issues: [] }\n return resolveDeclaredReuse(declaration, manifests, collections)\n}\n\n/**\n * The project's reuse capability alone, or `null` when it is undeclared or\n * misdeclared — for callers that act on the capability and do not surface config\n * issues themselves (the gestures, the canvas placeholder). The issues are surfaced\n * ONCE, by the shell; see {@link resolveReuse}.\n */\nexport function resolveReuseCapability(\n manifests: readonly ComponentManifest[],\n collections: readonly CollectionDef[],\n declaration?: StudioReuseConfig,\n): ReuseCapability | null {\n return resolveReuse(manifests, collections, declaration).capability\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. a production site'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 *\n * EC-580: every write goes through core's `writeField` in the project's DEFAULT\n * locale — the new document is created in its default bucket, so a localized title\n * or content field lands under `localized[default]`, never on the shared bag.\n */\nexport function buildReusableValues(\n collection: CollectionDef,\n capability: ReuseCapability,\n name: string,\n node: ComponentNode,\n existing: readonly { values?: Record<string, unknown> }[],\n locales: LocaleConfig,\n): Pick<CmsDocument, 'values' | 'localized'> {\n const at = locales.default\n let doc: CmsDocument = { collection: collection.id, id: '', ...seedDefaults(collection, locales) }\n const titleField = titleFieldOf(collection)?.name\n if (titleField) doc = writeField(collection, doc, titleField, at, 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 doc = writeField(collection, doc, field.name, at, uniqueSlug(name, taken))\n }\n }\n // EC-576: the converged v2 sequence holding the tagged node, through the core\n // write path — never the pre-0.0.84 bare node/array. Cardinality is a\n // constraint over that one shape, not a second shape (EC-500 D2).\n doc = writeField(collection, doc, capability.contentField, at, editBlockRoots(undefined, () => [node]))\n return { values: doc.values, ...(doc.localized !== undefined ? { localized: doc.localized } : {}) }\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 = isStaticProp(prop) ? readDocumentRef(prop.value) : undefined\n return ref ?? null\n}\n\n/**\n * The `Reusable` embed node referencing the new document (id minted by the action).\n *\n * EC-728 — CANONICAL from the first write: the prop is core's `staticProp` (bare `{ value }`,\n * EC-312), never `{ kind: 'static', value }`. The canvas commits its node patches raw, while\n * the draft takes the same write through the self-typing lens, which strips a redundant\n * `kind`; a non-canonical node therefore made the two views of the canvas field disagree, the\n * draft reported the disagreement as a change made underneath the canvas, and the rebase\n * dropped *Make reusable*'s own undo step (`reuse-undo.test.ts`).\n */\nexport function makeEmbedNode(capability: ReuseCapability, documentId: string): ComponentNode {\n return {\n id: 'reuse-embed',\n componentId: capability.embedComponentId,\n props: {\n // EC-589 / EC-586: a reference is a typed envelope from the first write.\n [capability.relationProp]: staticProp(referenceNode({ collection: capability.collectionId, id: documentId })),\n },\n }\n}\n\n// --- The placement preflight (EC-584, closes EC-560) --------------------------------\n\n/**\n * Why a reuse gesture is refused before it does anything: the one core placement\n * judge's verdict, and the label of the FIELD it names when the refusal is at a\n * field's top level (the canvas field, or the reusable collection's content field).\n */\nexport interface ReuseRefusal {\n verdict: PlacementVerdict\n fieldLabel: string\n}\n\n/**\n * EC-584 / EC-560 — \"Make reusable\" preflight, run BEFORE any side effect (the\n * reusable document is created — and maybe published — before the canvas swaps the\n * block for the embed). Two placements, both judged by the one core judge the\n * builder reducer enforces:\n *\n * 1. the EMBED lands where the promoted block was (the canvas field's `allow` at the\n * root, or the slot's `allow` when the block sits in a slot);\n * 2. the promoted BLOCK lands at the top level of the reusable collection's content\n * field (that field's effective vocabulary, `fieldAllowList`).\n *\n * `null` when both are admitted. The reducer still enforces (1) on its own.\n */\nexport function promoteRefusal(args: {\n root: ComponentNode\n nodeId: string\n node: ComponentNode\n capability: ReuseCapability\n collection: CollectionDef\n placement: PlacementScope\n canvasFieldLabel: string\n}): ReuseRefusal | null {\n const { root, nodeId, node, capability, collection, placement, canvasFieldLabel } = args\n const embed = replacePlacementRefusal(root, nodeId, [makeEmbedNode(capability, 'preflight')], placement)\n if (embed) return { verdict: embed, fieldLabel: canvasFieldLabel }\n const contentField = collection.fields.find((field) => field.name === capability.contentField)\n const contentAllow = contentField ? fieldAllowList(contentField) : undefined\n if (contentField && contentAllow) {\n const into = valuePlacementRefusal([node], { components: placement.components, fieldAllow: contentAllow })\n if (into) return { verdict: into, fieldLabel: fieldLabel(contentField) }\n }\n return null\n}\n\n/**\n * EC-584 / EC-560 — \"Detach to local copy\" preflight: the reusable's content blocks\n * land where the embed was. Refusing the WHOLE gesture when one inlined block is\n * outside the vocabulary keeps the reference in place (EC-560's frame: refuse\n * visibly, dispatch nothing) — the editor sees why and decides.\n */\nexport function detachRefusal(args: {\n root: ComponentNode\n nodeId: string\n blocks: readonly ComponentNode[]\n placement: PlacementScope\n canvasFieldLabel: string\n}): ReuseRefusal | null {\n const verdict = replacePlacementRefusal(args.root, args.nodeId, args.blocks, args.placement)\n return verdict ? { verdict, fieldLabel: args.canvasFieldLabel } : null\n}\n\n/** The effects \"Make reusable\" performs — injected, so the order and the refusal are testable. */\nexport interface PromoteEffects {\n newDocumentId(): string\n insertDocument(doc: CmsDocument): void\n /**\n * The in-place swap — ONE history entry carrying `effect` (EC-728: the created document, so\n * Undo can remove it when that is safe and Redo can re-insert it).\n */\n replaceInCanvas(nodeId: string, embed: ComponentNode, effect: CanvasHistoryEffect): void\n /** Publish the new reusable; resolves `true` only when the document IS published afterwards. */\n publish(ref: DocumentRef): Promise<boolean>\n refused(refusal: ReuseRefusal): void\n madeDraft(name: string): void\n madePublished(name: string): void\n publishFailed(name: string): void\n}\n\n/**\n * Run \"Make reusable\" (EC-282) — the preflight first (EC-584: a refusal creates,\n * publishes and replaces NOTHING), then ONE insert-if-absent create of the reusable\n * document (EC-595 A2), the in-place swap for the embed — one canvas history entry that\n * records the created document (EC-728) — and the chosen publish, whose success notice is\n * shown only when the document is actually published.\n */\nexport async function runPromote(args: {\n root: ComponentNode\n nodeId: string\n node: ComponentNode\n name: string\n publish: boolean\n capability: ReuseCapability\n collection: CollectionDef\n existing: readonly { values?: Record<string, unknown> }[]\n locales: LocaleConfig\n placement: PlacementScope\n canvasFieldLabel: string\n effects: PromoteEffects\n}): Promise<'refused' | 'draft' | 'published' | 'publish-failed'> {\n const { root, nodeId, node, name, capability, collection, placement, canvasFieldLabel, effects } = args\n const refusal = promoteRefusal({ root, nodeId, node, capability, collection, placement, canvasFieldLabel })\n if (refusal) {\n effects.refused(refusal)\n return 'refused'\n }\n const ref = { collection: capability.collectionId, id: effects.newDocumentId() }\n const content = buildReusableValues(collection, capability, name, node, args.existing, args.locales)\n const document: CmsDocument = { ...ref, ...content }\n effects.insertDocument(document)\n effects.replaceInCanvas(nodeId, makeEmbedNode(capability, ref.id), { kind: 'reusable-created', ref, name, document })\n if (!args.publish) {\n effects.madeDraft(name)\n return 'draft'\n }\n const published = await effects.publish(ref).catch(() => false)\n if (published) {\n effects.madePublished(name)\n return 'published'\n }\n effects.publishFailed(name)\n return 'publish-failed'\n}\n\n// --- Undo / Redo of \"Make reusable\" (EC-728) ------------------------------------------\n\n/**\n * What Undo did with the document *Make reusable* created: `deleted`, or already `gone`, or\n * KEPT — because it is `published`, was `edited` since it was made, is `referenced` elsewhere,\n * or the removal `failed`. The block is restored in every case (the canvas entry is a snapshot).\n */\nexport type PromoteUndoOutcome = 'deleted' | 'gone' | 'published' | 'edited' | 'referenced' | 'failed'\n\n/** The authoritative reads and the one write Undo needs — injected, so every branch is testable. */\nexport interface PromoteUndoDeps {\n /** Await every queued write: the page's restored value lands before anything is judged. */\n flush(): Promise<void>\n /** The document's record now (`undefined`: it no longer exists). */\n read(ref: DocumentRef): Promise<{ published: boolean } | undefined>\n /** How many reference-index entries (draft or published, any document) point at it now. */\n referrers(ref: DocumentRef): Promise<number>\n /** The conditional delete — at the revision this session's create landed at (`CmsPersister.deleteCreated`). */\n deleteCreated(ref: DocumentRef): Promise<DeleteCreatedOutcome>\n}\n\n/**\n * EC-728 — Undo of *Make reusable*, the document side. The created document is deleted ONLY\n * when every authoritative fact at Undo time says nobody else has it: never published (the\n * record), referenced nowhere — after the page's own restore has landed — (the reference\n * index, both variants), and unchanged since its create (the delete's revision precondition,\n * checked by the store in its own step, which also refuses a strict referrer). Anything else\n * keeps it, with the reason. A read that throws keeps it too: an unproven fact never deletes.\n */\nexport async function undoPromote(effect: CanvasHistoryEffect, deps: PromoteUndoDeps): Promise<PromoteUndoOutcome> {\n try {\n await deps.flush()\n const record = await deps.read(effect.ref)\n if (!record) return 'gone'\n if (record.published) return 'published'\n if ((await deps.referrers(effect.ref)) > 0) return 'referenced'\n switch (await deps.deleteCreated(effect.ref)) {\n case 'deleted':\n return 'deleted'\n case 'gone':\n return 'gone'\n case 'changed':\n return 'edited'\n case 'referenced':\n return 'referenced'\n default:\n return 'failed'\n }\n } catch {\n return 'failed'\n }\n}\n\n/** The catalog keys of the kept-document notices (EN + DE in the studio catalogs). */\nexport type ReuseUndoNoticeKey =\n | 'builder.reuse.undoKeptPublished'\n | 'builder.reuse.undoKeptEdited'\n | 'builder.reuse.undoKeptReferenced'\n | 'builder.reuse.undoKeptFailed'\n\n/** The notice for a KEPT document (EC-728 — it names the document and why); none when it went. */\nexport function undoPromoteNotice(outcome: PromoteUndoOutcome): ReuseUndoNoticeKey | undefined {\n switch (outcome) {\n case 'published':\n return 'builder.reuse.undoKeptPublished'\n case 'edited':\n return 'builder.reuse.undoKeptEdited'\n case 'referenced':\n return 'builder.reuse.undoKeptReferenced'\n case 'failed':\n return 'builder.reuse.undoKeptFailed'\n default:\n return undefined\n }\n}\n\n/**\n * EC-728 — the document side of every Undo/Redo that crosses a *Make reusable* step, for one\n * canvas. Crossings run strictly in order (a Redo waits for the Undo before it), so a fast\n * Undo → Redo never re-inserts a document whose removal is still in flight. Redo re-inserts\n * (the same id, insert-if-absent) exactly the documents ITS Undo removed or found gone — never\n * one Undo kept (it is still there) — and the canvas entry re-swaps the embed.\n */\nexport function createPromoteHistory(\n deps: PromoteUndoDeps & {\n insert(document: CmsDocument): void\n notify(key: ReuseUndoNoticeKey, name: string): void\n },\n): { crossed(step: { direction: 'undo' | 'redo'; effect: CanvasHistoryEffect }): Promise<void> } {\n const removed = new Set<string>()\n let chain: Promise<void> = Promise.resolve()\n return {\n crossed(step) {\n chain = chain.then(async () => {\n const key = documentKey(step.effect.ref)\n if (step.direction === 'redo') {\n if (removed.delete(key)) deps.insert(step.effect.document)\n return\n }\n const outcome = await undoPromote(step.effect, deps)\n if (outcome === 'deleted' || outcome === 'gone') removed.add(key)\n const notice = undoPromoteNotice(outcome)\n if (notice) deps.notify(notice, step.effect.name)\n })\n return chain\n },\n }\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import type { ReactNode } from 'react';
|
|
|
2
2
|
import type { CmsDocument, CmsValidationIssue, CollectionDef, CollectionRegistry, DocumentPatch, DocumentRef, FieldDef, ValuePath, Locale, LocaleConfig, LocalizedString, RestoreScope, ValidateDocumentOptions } from '@elytracms/core/cms-core';
|
|
3
3
|
import type { CmsDocumentRecord, DocumentVersionRecord, IdFactory, PresenceEntry } from '@elytracms/core/persistence';
|
|
4
4
|
import type { ImportRejection } from './import-batch.js';
|
|
5
|
-
import type { CommitOutcome, DocumentConflict, OperationError, OperationsClient } from '../../lib/operations/index.js';
|
|
5
|
+
import type { CommitOutcome, DeleteCreatedOutcome, DocumentConflict, OperationError, OperationsClient } from '../../lib/operations/index.js';
|
|
6
6
|
import type { TableViewState } from '../../lib/cms-views/index.js';
|
|
7
7
|
import type { CellCommitInput, CellCommitOutcome } from './cell-edit.js';
|
|
8
8
|
import type { BulkAction, BulkReport, BulkSetField } from './bulk-actions.js';
|
|
@@ -123,6 +123,14 @@ export interface CmsStore {
|
|
|
123
123
|
*/
|
|
124
124
|
replaceDocument(doc: CmsDocument, revision: number | undefined, authoredOn?: CmsDocument): void;
|
|
125
125
|
deleteDocument(ref: DocumentRef): void;
|
|
126
|
+
/**
|
|
127
|
+
* EC-728 — delete a document this session created, only while it is exactly as created
|
|
128
|
+
* (the persister's `deleteCreated`: conditioned on its create receipt, refused by the
|
|
129
|
+
* store on any write since or a strict referrer). The session drops it only once deleted;
|
|
130
|
+
* a refusal is returned, never reported. A fixture session (no persister) answers
|
|
131
|
+
* `not-created` — nothing is judged there, so nothing is deleted.
|
|
132
|
+
*/
|
|
133
|
+
deleteCreatedDocument(ref: DocumentRef): Promise<DeleteCreatedOutcome>;
|
|
126
134
|
/**
|
|
127
135
|
* Is this document currently published? Sourced from the version POINTER
|
|
128
136
|
* (EC-224), not the flat `state` enum — seeded from hydration and updated by
|
|
@@ -1053,6 +1053,7 @@ function CmsSession({ children, projectId, initialCollections, initialDocuments,
|
|
|
1053
1053
|
persistError,
|
|
1054
1054
|
clearPersistError: () => setPersistError(null),
|
|
1055
1055
|
flushPersistence: (ref) => persisterRef.current?.flush(ref) ?? Promise.resolve(),
|
|
1056
|
+
deleteCreatedDocument: (ref) => persisterRef.current?.deleteCreated(ref) ?? Promise.resolve('not-created'),
|
|
1056
1057
|
}), [
|
|
1057
1058
|
projectId,
|
|
1058
1059
|
collections,
|