@elytracms/studio 0.0.57 → 0.0.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/components/ai/ai-chat-panel.js +44 -6
  2. package/dist/components/ai/ai-chat-panel.js.map +1 -1
  3. package/dist/components/ai/chat-ui.d.ts +1 -1
  4. package/dist/components/ai/chat-ui.js +11 -2
  5. package/dist/components/ai/chat-ui.js.map +1 -1
  6. package/dist/components/ai/proposal-card.d.ts +30 -7
  7. package/dist/components/ai/proposal-card.js +81 -21
  8. package/dist/components/ai/proposal-card.js.map +1 -1
  9. package/dist/components/builder/blocks-model.js +12 -7
  10. package/dist/components/builder/blocks-model.js.map +1 -1
  11. package/dist/components/builder/canvas-dnd.d.ts +59 -0
  12. package/dist/components/builder/canvas-dnd.js +207 -0
  13. package/dist/components/builder/canvas-dnd.js.map +1 -0
  14. package/dist/components/builder/canvas-dom.d.ts +11 -0
  15. package/dist/components/builder/canvas-dom.js +17 -0
  16. package/dist/components/builder/canvas-dom.js.map +1 -0
  17. package/dist/components/builder/canvas-inline-editing.d.ts +91 -0
  18. package/dist/components/builder/canvas-inline-editing.js +242 -0
  19. package/dist/components/builder/canvas-inline-editing.js.map +1 -0
  20. package/dist/components/builder/canvas-render-context.d.ts +83 -0
  21. package/dist/components/builder/canvas-render-context.js +196 -0
  22. package/dist/components/builder/canvas-render-context.js.map +1 -0
  23. package/dist/components/builder/canvas.d.ts +4 -1
  24. package/dist/components/builder/canvas.js +32 -567
  25. package/dist/components/builder/canvas.js.map +1 -1
  26. package/dist/components/builder/composition-field-editor.js +14 -4
  27. package/dist/components/builder/composition-field-editor.js.map +1 -1
  28. package/dist/components/builder/insert-context.d.ts +5 -2
  29. package/dist/components/builder/insert-context.js +1 -3
  30. package/dist/components/builder/insert-context.js.map +1 -1
  31. package/dist/components/builder/node-factory.d.ts +12 -0
  32. package/dist/components/builder/node-factory.js +18 -1
  33. package/dist/components/builder/node-factory.js.map +1 -1
  34. package/dist/components/cms/asset-field.d.ts +22 -0
  35. package/dist/components/cms/asset-field.js +300 -0
  36. package/dist/components/cms/asset-field.js.map +1 -0
  37. package/dist/components/cms/detail-editor.js +12 -0
  38. package/dist/components/cms/detail-editor.js.map +1 -1
  39. package/dist/components/cms/document-diff-view.d.ts +12 -1
  40. package/dist/components/cms/document-diff-view.js +119 -42
  41. package/dist/components/cms/document-diff-view.js.map +1 -1
  42. package/dist/components/cms/field-control-lib.d.ts +43 -0
  43. package/dist/components/cms/field-control-lib.js +98 -0
  44. package/dist/components/cms/field-control-lib.js.map +1 -0
  45. package/dist/components/cms/field-control.d.ts +7 -35
  46. package/dist/components/cms/field-control.js +13 -556
  47. package/dist/components/cms/field-control.js.map +1 -1
  48. package/dist/components/cms/object-array-field.d.ts +29 -0
  49. package/dist/components/cms/object-array-field.js +205 -0
  50. package/dist/components/cms/object-array-field.js.map +1 -0
  51. package/dist/components/cms/rich-text-preview.d.ts +15 -0
  52. package/dist/components/cms/rich-text-preview.js +81 -0
  53. package/dist/components/cms/rich-text-preview.js.map +1 -0
  54. package/dist/components/cms/version-compare-text.d.ts +26 -0
  55. package/dist/components/cms/version-compare-text.js +60 -0
  56. package/dist/components/cms/version-compare-text.js.map +1 -1
  57. package/dist/components/project-session.d.ts +19 -0
  58. package/dist/components/project-session.js +29 -2
  59. package/dist/components/project-session.js.map +1 -1
  60. package/dist/components/use-hydration-phase.d.ts +6 -4
  61. package/dist/components/use-hydration-phase.js.map +1 -1
  62. package/dist/lib/ai/apply-content.js +52 -10
  63. package/dist/lib/ai/apply-content.js.map +1 -1
  64. package/dist/lib/ai/chat-context.d.ts +19 -3
  65. package/dist/lib/ai/chat-context.js +33 -4
  66. package/dist/lib/ai/chat-context.js.map +1 -1
  67. package/dist/lib/ai/chat-state.d.ts +6 -3
  68. package/dist/lib/ai/chat-state.js.map +1 -1
  69. package/dist/lib/ai/fake-provider.d.ts +60 -5
  70. package/dist/lib/ai/fake-provider.js +74 -6
  71. package/dist/lib/ai/fake-provider.js.map +1 -1
  72. package/dist/lib/ai/index.d.ts +2 -0
  73. package/dist/lib/ai/index.js +2 -0
  74. package/dist/lib/ai/index.js.map +1 -1
  75. package/dist/lib/ai/rich-text-input.d.ts +27 -0
  76. package/dist/lib/ai/rich-text-input.js +25 -0
  77. package/dist/lib/ai/rich-text-input.js.map +1 -0
  78. package/dist/lib/ai/shape.d.ts +12 -1
  79. package/dist/lib/ai/shape.js +46 -20
  80. package/dist/lib/ai/shape.js.map +1 -1
  81. package/dist/lib/ai/tools.d.ts +88 -13
  82. package/dist/lib/ai/tools.js +253 -14
  83. package/dist/lib/ai/tools.js.map +1 -1
  84. package/dist/lib/ai/types.d.ts +20 -0
  85. package/dist/lib/ai/types.js.map +1 -1
  86. package/dist/lib/ai/update-fields.d.ts +68 -0
  87. package/dist/lib/ai/update-fields.js +296 -0
  88. package/dist/lib/ai/update-fields.js.map +1 -0
  89. package/dist/lib/ai-current-document.d.ts +53 -0
  90. package/dist/lib/ai-current-document.js +54 -0
  91. package/dist/lib/ai-current-document.js.map +1 -0
  92. package/dist/lib/cms-views/view-model.d.ts +6 -6
  93. package/dist/lib/data/collection-content.d.ts +12 -7
  94. package/dist/lib/data/collection-content.js +6 -4
  95. package/dist/lib/data/collection-content.js.map +1 -1
  96. package/dist/lib/i18n/messages.en.js +10 -1
  97. package/dist/lib/i18n/messages.en.js.map +1 -1
  98. package/dist/lib/operations/session-hydration.d.ts +4 -1
  99. package/dist/lib/operations/session-hydration.js +4 -1
  100. package/dist/lib/operations/session-hydration.js.map +1 -1
  101. package/dist/lib/persistence/index.js +13 -1
  102. package/dist/lib/persistence/index.js.map +1 -1
  103. package/dist/lib/workspace/index.d.ts +1 -1
  104. package/dist/lib/workspace/index.js +1 -1
  105. package/dist/lib/workspace/index.js.map +1 -1
  106. package/dist/lib/workspace/workspace-source.d.ts +17 -22
  107. package/dist/lib/workspace/workspace-source.js +1 -49
  108. package/dist/lib/workspace/workspace-source.js.map +1 -1
  109. package/package.json +2 -2
@@ -1,25 +1,20 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
3
  import { createPortal } from 'react-dom';
4
4
  import { renderPageComposition } from '@elytracms/core/runtime-renderer';
5
5
  import { useParams } from '@elytracms/studio/router';
6
- import { getNode, getParentInfo, staticProp } from '@elytracms/core/project-graph';
7
- import { canNestInto, containerFlowAxis, dropIndicatorFor, dropPositionForPoint, resolveDrop, } from '@elytracms/studio/lib/dnd/drop-rules';
8
- import { activeDrag, beginDrag, endDrag, onDragSessionEnd } from './drag-session.js';
9
- import { PRESERVE_NODE_ATTR, collectPreservedPairs, richTextDocFromDom, } from '@elytracms/core/rich-text';
6
+ import { PRESERVE_NODE_ATTR } from '@elytracms/core/rich-text';
10
7
  import { getStudioRegistry } from '@elytracms/studio/lib/registry';
11
8
  import { translate } from '@elytracms/studio/lib/i18n';
12
- import { useOptionalAssets } from '../assets/assets-store.js';
13
- import { resolveCanvasLink, resolveCanvasListing, resolveCanvasRelation, useData, } from '@elytracms/studio/lib/data';
14
- import { cmsBindingFallback, useStudioLocale } from '@elytracms/studio/lib/locale';
15
9
  import { getInstantiatedKit } from '@elytracms/studio/lib/starters/kit-session';
16
10
  import { getCanvasStylesheetUrl } from './canvas-stylesheet.js';
17
11
  import { useBuilder } from './builder-store.js';
18
- import { useReuse } from './reuse-context.js';
19
- import { reuseEmbedRef } from './reuse.js';
20
12
  import { useCanvasViewports, viewportWidth } from './canvas-breakpoints.js';
13
+ import { nodeIdAt } from './canvas-dom.js';
14
+ import { useCanvasDnd } from './canvas-dnd.js';
15
+ import { useCanvasInlineEditing } from './canvas-inline-editing.js';
16
+ import { useCanvasRenderContext } from './canvas-render-context.js';
21
17
  import { ClipboardNoticeOverlay, attachClipboardListeners, useStudioClipboard, } from './clipboard-actions.js';
22
- import { createInlineEditSession, createInlineRichTextSession, findInlineTextHost, resolveInlineEditableProp, resolveInlineRichTextProp, } from './inline-edit.js';
23
18
  import { RichTextToolbar } from './rich-text-toolbar.js';
24
19
  import { SpacingHandles, hasSpacingHandles } from './spacing-handles.js';
25
20
  /** Selection/hover outlines, scoped to the per-node editable wrappers. */
@@ -84,62 +79,28 @@ const OUTLINE_CSS = `
84
79
  .ec-editable[data-ec-drop='right'] { box-shadow: 3px 0 0 0 #a78bfa; background-color: rgba(167, 139, 250, 0.1); }
85
80
  .ec-editable[data-ec-drop='blocked'] { outline: 2px solid #ef4444; outline-offset: -2px; background-color: rgba(239, 68, 68, 0.08); cursor: not-allowed; }
86
81
  `;
87
- function nodeIdAt(target) {
88
- return wrapperAt(target)?.getAttribute('data-ec-node-id') ?? null;
89
- }
90
- function wrapperAt(target) {
91
- const el = target;
92
- return el?.closest?.('[data-ec-node-id]') ?? null;
93
- }
94
- /**
95
- * The rendered `.rich-text` element inside a node's wrapper — the rich-text
96
- * editing host (EC-159). Never crosses into a nested node's wrapper.
97
- */
98
- function findRichTextHost(wrapper) {
99
- const host = wrapper.querySelector('.rich-text');
100
- return host && host.closest('[data-ec-node-id]') === wrapper ? host : null;
101
- }
102
- /** Collect every node id under a root (the page subtree). */
103
- function collectIds(node, out = new Set()) {
104
- out.add(node.id);
105
- for (const children of Object.values(node.slots ?? {})) {
106
- for (const child of children)
107
- collectIds(child, out);
108
- }
109
- return out;
110
- }
111
82
  /**
112
83
  * Iframe-isolated page preview (brief §8.2, EC-061, EC-064). The graph renders
113
84
  * into a same-origin iframe via a React portal — true style isolation + true
114
85
  * responsive widths. Each node is wrapped with an editable marker so clicks
115
86
  * select and hover/selection draw outlines. Native listeners bridge the iframe
116
- * boundary (React's synthetic events don't cross frames).
87
+ * boundary (React's synthetic events don't cross frames); the two big gesture
88
+ * state machines live in their own tested modules (EC-330): drag & drop in
89
+ * `canvas-dnd`, inline text/rich-text editing in `canvas-inline-editing`, and
90
+ * the render-context assembly in `canvas-render-context`.
117
91
  */
118
92
  export function BuilderCanvas({ perspective = 'draft', } = {}) {
119
93
  const builder = useBuilder();
120
94
  const { dispatch } = builder;
121
95
  const studio = getStudioRegistry();
122
- const data = useData();
123
96
  // The edited composition root, composed for preview. EC-287 retired the project
124
97
  // graph and its published-graph preview; the canvas always renders the live,
125
98
  // editable draft (content publishing is per document).
126
99
  const activeRoot = builder.present;
127
100
  const iframeRef = useRef(null);
128
101
  const [doc, setDoc] = useState(null);
129
- // Inline editing (EC-158/EC-159): the active session lives in a ref — it is
130
- // imperative DOM state inside the iframe, not render state. Graph/page refs
131
- // let the native dblclick handler read the *current* graph without
132
- // re-subscribing listeners on every edit. The rich-text host additionally
133
- // mirrors into render state so the floating mark toolbar can mount.
134
- const editingRef = useRef(null);
135
- const [richEditHost, setRichEditHost] = useState(null);
136
- // A rich-text session mutates the rendered DOM behind React's back
137
- // (contenteditable + mark commands), so finishing one must REMOUNT the
138
- // node's subtree — bumping its epoch changes the decorate key, React
139
- // discards the edited DOM wholesale and re-renders from the graph (the
140
- // committed value, or the untouched original on cancel). Patching the old
141
- // fiber tree against editor-mutated DOM would leave stale artifacts.
142
- const [richEditEpochs, setRichEditEpochs] = useState({});
102
+ // Graph/selection refs let the native iframe listeners read the *current*
103
+ // state without re-subscribing on every edit.
143
104
  const presentRef = useRef(builder.present);
144
105
  presentRef.current = builder.present;
145
106
  const selectedIdRef = useRef(builder.selectedId);
@@ -194,6 +155,11 @@ export function BuilderCanvas({ perspective = 'draft', } = {}) {
194
155
  if (iframeRef.current?.contentDocument?.readyState === 'complete')
195
156
  wireUp();
196
157
  }, [wireUp]);
158
+ // Inline editing (EC-158/EC-159): the dblclick-to-edit state machine, the
159
+ // live session ref other listeners consult, the rich-text host (mark
160
+ // toolbar), and the per-node remount epochs (decorate keys).
161
+ const inline = useCanvasInlineEditing(doc, { presentRef, dispatch, studio });
162
+ const { editingRef, richEditHost, richEditEpochs } = inline;
197
163
  // Native selection/hover listeners inside the iframe document.
198
164
  useEffect(() => {
199
165
  if (!doc)
@@ -218,399 +184,9 @@ export function BuilderCanvas({ perspective = 'draft', } = {}) {
218
184
  doc.removeEventListener('mouseover', onOver);
219
185
  doc.removeEventListener('mouseleave', onLeave, true);
220
186
  };
221
- }, [doc, dispatch]);
222
- // Drag & drop on the canvas (EC-160). Eligibility is the pure shared rule
223
- // set (`lib/dnd/drop-rules`) — the same functions the page tree consumes —
224
- // evaluated live during `dragover`; the wrapper under the pointer shows the
225
- // resolution (`data-ec-drop`: into/before/after, or `blocked` for a visible
226
- // rejection). A completed drop dispatches exactly one builder action (move
227
- // or insert) → one operations command → one undo step. Ineligible targets
228
- // never `preventDefault`, so releasing over one is a native no-op.
229
- useEffect(() => {
230
- if (!doc)
231
- return;
232
- const getManifest = (id) => studio.registry.getManifest(id);
233
- const currentRoot = () => presentRef.current;
234
- let dropWrapper = null;
235
- let dropPlan = null;
236
- const clearIndicator = () => {
237
- dropWrapper?.removeAttribute('data-ec-drop');
238
- dropWrapper?.removeAttribute('data-ec-drop-axis');
239
- dropWrapper = null;
240
- dropPlan = null;
241
- };
242
- const showIndicator = (wrapper, state, axis) => {
243
- if (dropWrapper && dropWrapper !== wrapper) {
244
- dropWrapper.removeAttribute('data-ec-drop');
245
- dropWrapper.removeAttribute('data-ec-drop-axis');
246
- }
247
- dropWrapper = wrapper;
248
- if (!wrapper)
249
- return;
250
- if (state) {
251
- wrapper.setAttribute('data-ec-drop', state);
252
- // Before/after bars render along the parent's flow axis (EC-162).
253
- wrapper.setAttribute('data-ec-drop-axis', axis === 'horizontal' ? 'x' : 'y');
254
- }
255
- else {
256
- wrapper.removeAttribute('data-ec-drop');
257
- wrapper.removeAttribute('data-ec-drop-axis');
258
- }
259
- };
260
- // Wrappers are armed draggable per-gesture on mousedown, never via render
261
- // state: the active inline editor (EC-158) must keep native caret clicks
262
- // and text selection, so a press inside the editing host disarms its
263
- // wrapper instead of starting a node drag.
264
- const onMouseDown = (e) => {
265
- const wrapper = wrapperAt(e.target);
266
- if (!wrapper)
267
- return;
268
- const root = currentRoot();
269
- const nodeId = wrapper.getAttribute('data-ec-node-id');
270
- const inEditor = editingRef.current?.host.contains(e.target) ?? false;
271
- if (root && nodeId && nodeId !== root.id && !inEditor) {
272
- wrapper.setAttribute('draggable', 'true');
273
- }
274
- else {
275
- wrapper.removeAttribute('draggable');
276
- }
277
- };
278
- const onDragStart = (e) => {
279
- // Drags inside the live inline editor are native text drags — leave them alone.
280
- if (editingRef.current?.host.contains(e.target))
281
- return;
282
- const wrapper = wrapperAt(e.target);
283
- if (!wrapper)
284
- return;
285
- const root = currentRoot();
286
- const nodeId = wrapper.getAttribute('data-ec-node-id');
287
- const node = root ? getNode(root, nodeId) : undefined;
288
- if (!root || !node || nodeId === root.id) {
289
- e.preventDefault();
290
- return;
291
- }
292
- beginDrag({ subject: { kind: 'node', nodeId, componentId: node.componentId }, source: 'canvas', label: node.componentId }, e.dataTransfer);
293
- };
294
- const onDragOver = (e) => {
295
- const drag = activeDrag();
296
- if (!drag)
297
- return;
298
- const root = currentRoot();
299
- if (!root)
300
- return;
301
- const wrapper = wrapperAt(e.target);
302
- // Empty space around the page subtree targets the root slot (append).
303
- const refId = wrapper?.getAttribute('data-ec-node-id') ?? root.id;
304
- const refWrapper = wrapper ?? doc.querySelector(`[data-ec-node-id="${root.id}"]`);
305
- const refNode = getNode(root, refId);
306
- if (!refNode) {
307
- clearIndicator();
308
- return;
309
- }
310
- let position = 'into';
311
- let flow = 'vertical';
312
- if (wrapper && refId !== root.id) {
313
- const rect = wrapper.getBoundingClientRect();
314
- // Hit-bands follow the parent's flow axis (EC-162); the cross-axis
315
- // side bands of vertically flowing targets are the wrap gesture.
316
- flow = containerFlowAxis(getParentInfo(root, refId)?.parent);
317
- position = dropPositionForPoint({
318
- x: rect.width > 0 ? (e.clientX - rect.left) / rect.width : 0.5,
319
- y: rect.height > 0 ? (e.clientY - rect.top) / rect.height : 0.5,
320
- flow,
321
- nestable: canNestInto(getManifest, refNode.componentId),
322
- edges: true,
323
- wrappable: true,
324
- });
325
- }
326
- const resolution = resolveDrop({
327
- root,
328
- getManifest,
329
- subject: drag.subject,
330
- location: { nodeId: refId, position },
331
- });
332
- showIndicator(refWrapper, dropIndicatorFor(resolution, position), flow);
333
- if (resolution.eligible) {
334
- dropPlan = resolution;
335
- e.preventDefault();
336
- if (e.dataTransfer) {
337
- e.dataTransfer.dropEffect = drag.subject.kind === 'node' ? 'move' : 'copy';
338
- }
339
- }
340
- else {
341
- dropPlan = null;
342
- }
343
- };
344
- const onDrop = (e) => {
345
- const drag = activeDrag();
346
- if (!drag)
347
- return;
348
- const plan = dropPlan;
349
- clearIndicator();
350
- if (!plan)
351
- return;
352
- e.preventDefault();
353
- // Exactly one dispatch per completed drop (one undo step, one command).
354
- if (plan.kind === 'move') {
355
- dispatch({ type: 'move', id: plan.nodeId, target: plan.target });
356
- }
357
- else if (plan.kind === 'wrap') {
358
- // EC-162 gesture: reference + subject become a two-column Grid.
359
- const subject = plan.nodeId !== undefined
360
- ? { kind: 'node', nodeId: plan.nodeId }
361
- : drag.buildNode
362
- ? { kind: 'component', node: drag.buildNode() }
363
- : null;
364
- if (!subject) {
365
- endDrag('cancelled');
366
- return;
367
- }
368
- dispatch({ type: 'wrap', referenceId: plan.referenceId, side: plan.side, subject });
369
- }
370
- else if (drag.buildNode) {
371
- dispatch({ type: 'insert', target: plan.target, node: drag.buildNode() });
372
- }
373
- else {
374
- endDrag('cancelled');
375
- return;
376
- }
377
- endDrag('dropped');
378
- };
379
- const onDragEnd = () => {
380
- clearIndicator();
381
- endDrag('cancelled');
382
- };
383
- const onDragLeave = (e) => {
384
- // Leaving the iframe document entirely (relatedTarget is null).
385
- if (!e.relatedTarget)
386
- clearIndicator();
387
- };
388
- // Cleanup when the drag ends anywhere (e.g. dropped on the page tree).
389
- const unsubscribe = onDragSessionEnd(() => clearIndicator());
390
- doc.addEventListener('mousedown', onMouseDown, true);
391
- doc.addEventListener('dragstart', onDragStart);
392
- doc.addEventListener('dragover', onDragOver);
393
- doc.addEventListener('drop', onDrop);
394
- doc.addEventListener('dragend', onDragEnd);
395
- doc.addEventListener('dragleave', onDragLeave);
396
- return () => {
397
- unsubscribe();
398
- clearIndicator();
399
- doc.removeEventListener('mousedown', onMouseDown, true);
400
- doc.removeEventListener('dragstart', onDragStart);
401
- doc.removeEventListener('dragover', onDragOver);
402
- doc.removeEventListener('drop', onDrop);
403
- doc.removeEventListener('dragend', onDragEnd);
404
- doc.removeEventListener('dragleave', onDragLeave);
405
- };
406
- }, [doc, dispatch, studio]);
407
- // Inline editing (EC-158 plain text, EC-159 rich text): double-click on a
408
- // node whose manifest flags an inline-editable prop turns the *rendered
409
- // element itself* contenteditable — no overlay, no input swap, so typography
410
- // and layout are identical in edit and render states. A session finishes
411
- // exactly once, and a commit dispatches exactly one `setProp` action — one
412
- // undo step, mirrored as one `graph.setNodeProp` operations command by the
413
- // builder-store persister. The graph stays the single source of truth.
414
- //
415
- // Commit/cancel gestures: plain text commits on Enter or blur; rich text is
416
- // multiline, so plain Enter inserts a paragraph and the commit gesture is
417
- // Cmd/Ctrl+Enter or blur (Enter-to-commit would make multi-paragraph content
418
- // unauthorable in place). Esc always cancels, dispatching nothing.
419
- useEffect(() => {
420
- if (!doc)
421
- return;
422
- // ---- plain text (EC-158) ------------------------------------------------
423
- const beginText = (wrapper, host, session) => {
424
- let done = false;
425
- const finish = (mode) => {
426
- if (done)
427
- return;
428
- done = true;
429
- editingRef.current = null;
430
- const text = host.textContent ?? '';
431
- host.removeEventListener('keydown', onKeyDown);
432
- host.removeEventListener('blur', onBlur);
433
- host.removeAttribute('contenteditable');
434
- host.removeAttribute('data-ec-edit');
435
- wrapper.removeAttribute('data-ec-editing');
436
- if (mode === 'commit') {
437
- const outcome = session.commit(text);
438
- if (outcome) {
439
- dispatch({
440
- type: 'setProp',
441
- id: outcome.nodeId,
442
- name: outcome.propName,
443
- value: staticProp(outcome.value),
444
- });
445
- }
446
- }
447
- else {
448
- const outcome = session.cancel();
449
- if (outcome)
450
- host.textContent = outcome.value;
451
- }
452
- doc.getSelection()?.removeAllRanges();
453
- };
454
- const onKeyDown = (e) => {
455
- if (e.key === 'Enter') {
456
- e.preventDefault();
457
- e.stopPropagation();
458
- finish('commit');
459
- }
460
- else if (e.key === 'Escape') {
461
- e.preventDefault();
462
- e.stopPropagation();
463
- finish('cancel');
464
- }
465
- };
466
- const onBlur = () => finish('commit');
467
- // `plaintext-only` keeps paste/typing plain; fall back where unsupported.
468
- host.setAttribute('contenteditable', 'plaintext-only');
469
- if (!host.isContentEditable)
470
- host.setAttribute('contenteditable', 'true');
471
- host.setAttribute('data-ec-edit', 'text');
472
- wrapper.setAttribute('data-ec-editing', '');
473
- host.addEventListener('keydown', onKeyDown);
474
- host.addEventListener('blur', onBlur);
475
- editingRef.current = { nodeId: session.nodeId, host, finish };
476
- host.focus({ preventScroll: true });
477
- // Keep the gesture's native caret/word selection when it landed inside
478
- // the host; otherwise select the whole value.
479
- const sel = doc.getSelection();
480
- if (!sel || sel.rangeCount === 0 || !host.contains(sel.anchorNode)) {
481
- const range = doc.createRange();
482
- range.selectNodeContents(host);
483
- sel?.removeAllRanges();
484
- sel?.addRange(range);
485
- }
486
- };
487
- // ---- rich text (EC-159) -------------------------------------------------
488
- const beginRichText = (wrapper, nodeId, target) => {
489
- const host = findRichTextHost(wrapper);
490
- if (!host)
491
- return;
492
- // Pair the storage tree against the rendered DOM and stamp every
493
- // non-invertible node (custom blocks, unknown nodes, images, embeds)
494
- // with its exact JSON: they stay rendered *inside* the live editor as
495
- // non-editable atoms and survive the session byte-exact. A pairing
496
- // mismatch means the DOM diverged from the deterministic render —
497
- // refuse to start rather than risk lossy parsing ("polished or absent").
498
- const pairs = collectPreservedPairs(target.value.doc, host);
499
- if (!pairs)
500
- return;
501
- const session = createInlineRichTextSession({
502
- nodeId,
503
- propName: target.propName,
504
- original: target.value,
505
- });
506
- for (const pair of pairs) {
507
- const el = pair.element;
508
- el.setAttribute(PRESERVE_NODE_ATTR, JSON.stringify(pair.node));
509
- el.setAttribute('contenteditable', 'false');
510
- }
511
- let done = false;
512
- const finish = (mode) => {
513
- if (done)
514
- return;
515
- done = true;
516
- editingRef.current = null;
517
- setRichEditHost(null);
518
- // Parse the edited DOM, detach the session, then bump the node's
519
- // remount epoch: React discards the editor-mutated DOM and renders
520
- // fresh from the graph — committed content or, on cancel, the
521
- // untouched original. Never patch a fiber tree against DOM the
522
- // editing commands rewrote.
523
- const parsed = mode === 'commit' ? richTextDocFromDom(host) : null;
524
- host.removeEventListener('keydown', onKeyDown);
525
- host.removeEventListener('blur', onBlur);
526
- host.removeAttribute('contenteditable');
527
- host.removeAttribute('data-ec-edit');
528
- wrapper.removeAttribute('data-ec-editing');
529
- setRichEditEpochs((prev) => ({ ...prev, [nodeId]: (prev[nodeId] ?? 0) + 1 }));
530
- if (parsed) {
531
- // An unchanged document commits nothing: the stored value is never
532
- // rewritten, so untouched content round-trips byte-identical.
533
- const outcome = session.commit(parsed.doc);
534
- if (outcome) {
535
- dispatch({
536
- type: 'setProp',
537
- id: outcome.nodeId,
538
- name: outcome.propName,
539
- value: staticProp(outcome.value),
540
- });
541
- }
542
- }
543
- else {
544
- session.cancel();
545
- }
546
- doc.getSelection()?.removeAllRanges();
547
- };
548
- const onKeyDown = (e) => {
549
- if (e.key === 'Escape') {
550
- e.preventDefault();
551
- e.stopPropagation();
552
- finish('cancel');
553
- }
554
- else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
555
- e.preventDefault();
556
- e.stopPropagation();
557
- finish('commit');
558
- }
559
- // Plain Enter falls through: native paragraph insertion (multiline).
560
- };
561
- const onBlur = (e) => {
562
- // Interacting with the floating toolbar is part of the session.
563
- const next = e.relatedTarget;
564
- if (next?.closest?.('[data-ec-rt-toolbar]'))
565
- return;
566
- finish('commit');
567
- };
568
- host.setAttribute('contenteditable', 'true');
569
- host.setAttribute('data-ec-edit', 'rich');
570
- wrapper.setAttribute('data-ec-editing', '');
571
- host.addEventListener('keydown', onKeyDown);
572
- host.addEventListener('blur', onBlur);
573
- editingRef.current = { nodeId, host, finish };
574
- setRichEditHost(host);
575
- host.focus({ preventScroll: true });
576
- };
577
- const onDblClick = (e) => {
578
- const wrapper = wrapperAt(e.target);
579
- if (!wrapper)
580
- return;
581
- const nodeId = wrapper.getAttribute('data-ec-node-id');
582
- if (editingRef.current) {
583
- // Double-click inside the live editor is native word selection.
584
- if (editingRef.current.nodeId === nodeId)
585
- return;
586
- editingRef.current.finish('commit');
587
- }
588
- const node = getNode(presentRef.current, nodeId);
589
- if (!node)
590
- return;
591
- const manifest = studio.registry.getManifest(node.componentId);
592
- const target = resolveInlineEditableProp(manifest, node);
593
- if (target) {
594
- const host = findInlineTextHost(wrapper, target.value);
595
- if (!host || typeof host.focus !== 'function')
596
- return;
597
- dispatch({ type: 'select', id: nodeId });
598
- beginText(wrapper, host, createInlineEditSession({ nodeId, propName: target.propName, original: target.value }));
599
- return;
600
- }
601
- const richTarget = resolveInlineRichTextProp(manifest, node);
602
- if (!richTarget)
603
- return;
604
- dispatch({ type: 'select', id: nodeId });
605
- beginRichText(wrapper, nodeId, richTarget);
606
- };
607
- doc.addEventListener('dblclick', onDblClick, true);
608
- return () => {
609
- doc.removeEventListener('dblclick', onDblClick, true);
610
- // Teardown mid-session (doc swap/unmount): cancel — never dispatch from cleanup.
611
- editingRef.current?.finish('cancel');
612
- };
613
- }, [doc, dispatch, studio]);
187
+ }, [doc, dispatch, editingRef]);
188
+ // Drag & drop on the canvas (EC-160/EC-162) — see `canvas-dnd`.
189
+ useCanvasDnd(doc, { presentRef, dispatch, studio, editingRef });
614
190
  // Copy/cut/paste on the canvas (EC-175): the same studio clipboard the page
615
191
  // tree and blocks panel use, wired to the *iframe* document (events never
616
192
  // cross frames). Shortcuts stay inert while an inline editor is live and in
@@ -627,102 +203,18 @@ export function BuilderCanvas({ perspective = 'draft', } = {}) {
627
203
  asyncClipboard: doc.defaultView?.navigator.clipboard,
628
204
  getSelection: () => doc.getSelection(),
629
205
  });
630
- }, [doc, clipboard]);
631
- // Only page nodes are editable; layout chrome (rendered around the page) is
632
- // read-only context and must not be selectable (it isn't in the page tree).
633
- const pageNodeIds = useMemo(() => collectIds(builder.present), [builder.present]);
634
- // Bridge the renderer's untyped ItemContext (item: unknown) to the binding
635
- // layer's RepeaterItemContext (item: JsonValue). The renderer feeds back values
636
- // it resolved from JSON payloads, so the item is a JsonValue.
637
- const resolveBinding = useCallback((ref, item) => data.resolveValue(ref, item ? { item: item.item, index: item.index } : undefined), [data]);
638
- // EC-195: resolve an `asset`-typed Image prop (an asset id) to its url +
639
- // intrinsic dimensions from the live asset library, so the canvas previews
640
- // exactly what the host renders. A record without a resolved url (e.g. a
641
- // never-served seed) → null → the implementation's visible empty state.
642
- const assetsStore = useOptionalAssets();
643
- const resolveAsset = useCallback((assetId) => {
644
- const record = assetsStore?.assets.find((a) => a.id === assetId);
645
- if (!record?.url)
646
- return null;
647
- return {
648
- url: record.url,
649
- width: record.width ?? null,
650
- height: record.height ?? null,
651
- alt: record.alt ?? null,
652
- focalPoint: record.focalPoint ?? null,
653
- };
654
- }, [assetsStore]);
655
- // Locale-fallback chips (EC-176): a node whose bound content currently
656
- // previews via EC-018 locale fallback wears a corner chip naming the locale
657
- // the value actually came from. Same decision function as the inspector's
658
- // Content tab (`cmsBindingFallback`), so chip and label can never disagree.
659
- const { locale: activeLocale } = useStudioLocale();
660
- // EC-300: the reuse capability identifies a transcluding embed + its relation prop,
661
- // so the canvas can detect a HARD reference whose target doesn't resolve and show a
662
- // placeholder instead of an empty section. Null-safe (no provider / no capability).
663
- const reuse = useReuse();
664
- // EC-254: populate a block's `relation` prop (the editor's document pick — a
665
- // ProductGrid's products, a Reusable's element) to delivery shape from the
666
- // active content session, in the canvas's active locale, so the canvas previews
667
- // picked documents exactly as the host renders them. The studio analog of the
668
- // host's baked relations map. A missing/invisible target → null → the block's
669
- // own empty state.
670
- const resolveRelation = useCallback((ref) => resolveCanvasRelation(ref, activeLocale, perspective), [activeLocale, perspective]);
671
- // EC-255: resolve a listing block's query (a ProductGrid keyed to a category) to
672
- // its documents from the active content session, in the canvas's active locale, so
673
- // the canvas previews a dynamic grid exactly as the host renders it. The studio
674
- // analog of the host's baked listings map; an empty/invalid query → [] → the
675
- // block's own empty state.
676
- const resolveListing = useCallback((query) => resolveCanvasListing(query, activeLocale, perspective), [activeLocale, perspective]);
677
- // EC-291: resolve a rich-text internal link (`{type:'reference'}`) to its target's
678
- // URL path from the active content session, in the canvas's active locale — the
679
- // studio analog of the host's baked links map. A missing/unpublished/unroutable
680
- // target → null → the rich-text renderer shows the visible `unresolved-ref` issue.
681
- const resolveLink = useCallback((ref) => resolveCanvasLink(ref, activeLocale, perspective), [activeLocale, perspective]);
682
- // EC-300/AD-16: a transcluding embed whose target doesn't resolve in the active
683
- // perspective renders a placeholder, never an empty section. `unpublished` = the
684
- // target exists as a draft but isn't live (Published view of a draft-only reusable);
685
- // `missing` = no resolvable target at all (deleted). `null` = resolves fine, or the
686
- // node isn't an embed / has no target picked yet (its own empty state owns that).
687
- const unresolvedReuse = useCallback((node) => {
688
- const cap = reuse?.capability;
689
- if (!cap)
690
- return null;
691
- const ref = reuseEmbedRef(node, cap);
692
- if (!ref)
693
- return null;
694
- if (resolveCanvasRelation(ref, activeLocale, perspective))
695
- return null;
696
- return resolveCanvasRelation(ref, activeLocale, 'draft') ? 'unpublished' : 'missing';
697
- }, [reuse, activeLocale, perspective]);
698
- const localeFallbackOf = useCallback((node) => {
699
- for (const value of Object.values(node.props ?? {})) {
700
- if (value.kind !== 'binding')
701
- continue;
702
- const fallback = cmsBindingFallback(value.binding, data.getSource(value.binding.sourceId), activeLocale);
703
- if (fallback)
704
- return fallback.sourceLocale;
705
- }
706
- return undefined;
707
- }, [data, activeLocale]);
708
- const ctx = useMemo(() => ({
709
- registry: studio.registry,
710
- implementations: studio.implementations,
711
- resolveBinding,
712
- resolveAsset,
713
- resolveRelation,
714
- resolveListing,
715
- resolveLink,
716
- decorateNode: (node, rendered) => {
717
- if (!pageNodeIds.has(node.id))
718
- return rendered;
719
- // An unresolved hard reference shows the placeholder in place of the empty
720
- // transclusion; the node stays selectable, so its inspector relation chip
721
- // (EC-296) deep-links to the reusable to edit/publish it.
722
- const unresolved = unresolvedReuse(node);
723
- return (_jsx("div", { "data-ec-node-id": node.id, className: "ec-editable", "data-selected": node.id === builder.selectedId || undefined, "data-hovered": node.id === builder.hoveredId || undefined, "data-ec-locale-fallback": localeFallbackOf(node), children: unresolved ? _jsx(UnresolvedReusablePlaceholder, { status: unresolved }) : rendered }, `${node.id}#${richEditEpochs[node.id] ?? 0}`));
724
- },
725
- }), [studio, resolveBinding, resolveAsset, resolveRelation, resolveListing, resolveLink, unresolvedReuse, pageNodeIds, builder.selectedId, builder.hoveredId, localeFallbackOf, richEditEpochs]);
206
+ }, [doc, clipboard, editingRef]);
207
+ // The render context: the seven delivery-parity resolvers + the editable-
208
+ // wrapper decorator (selection/hover, locale chips, remount epochs) — see
209
+ // `canvas-render-context`.
210
+ const { ctx, pageNodeIds } = useCanvasRenderContext({
211
+ present: builder.present,
212
+ selectedId: builder.selectedId,
213
+ hoveredId: builder.hoveredId,
214
+ studio,
215
+ perspective,
216
+ richEditEpochs,
217
+ });
726
218
  // Tokenized spacing handles (EC-163): a selected Stack/Grid with 2+ children
727
219
  // gets draggable gap handles between them, portaled into the iframe.
728
220
  const spacingTarget = doc && hasSpacingHandles(builder.selectedNode) && pageNodeIds.has(builder.selectedNode.id)
@@ -739,31 +231,4 @@ export function BuilderCanvas({ perspective = 'draft', } = {}) {
739
231
  renderPageComposition(activeRoot, ctx), doc.body)
740
232
  : null, spacingTarget && doc ? (_jsx(SpacingHandles, { doc: doc, node: spacingTarget }, spacingTarget.id)) : null, richEditHost && doc ? _jsx(RichTextToolbar, { doc: doc, host: richEditHost }) : null] })] }));
741
233
  }
742
- /**
743
- * In-canvas placeholder for a transcluding embed whose target doesn't resolve
744
- * (EC-300/AD-16) — shown in place of the empty section so a hard reference never
745
- * silently vanishes. Rendered INTO the iframe (portal), which carries only the
746
- * project's stylesheet, so it uses inline styles rather than studio UI classes.
747
- * The node stays selectable; the inspector's `element` relation chip (EC-296)
748
- * deep-links to the reusable to edit or publish it.
749
- */
750
- function UnresolvedReusablePlaceholder({ status }) {
751
- const title = status === 'unpublished'
752
- ? translate('builder.canvas.reusableUnpublishedTitle')
753
- : translate('builder.canvas.reusableMissingTitle');
754
- const hint = status === 'unpublished'
755
- ? translate('builder.canvas.reusableUnpublishedHint')
756
- : translate('builder.canvas.reusableMissingHint');
757
- return (_jsxs("div", { style: {
758
- boxSizing: 'border-box',
759
- border: '1px dashed rgba(120,120,120,0.5)',
760
- borderRadius: 8,
761
- padding: '24px 28px',
762
- margin: '12px 16px',
763
- background: 'rgba(127,127,127,0.06)',
764
- color: 'rgba(90,90,90,0.95)',
765
- font: '14px/1.5 system-ui, -apple-system, sans-serif',
766
- textAlign: 'center',
767
- }, children: [_jsxs("div", { style: { fontWeight: 600 }, children: ["\u26A0 ", title] }), _jsx("div", { style: { marginTop: 6, fontSize: 13, opacity: 0.85 }, children: hint })] }));
768
- }
769
234
  //# sourceMappingURL=canvas.js.map