@nuxt-atelier/editor 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,885 @@
1
+ <script setup>
2
+ import { computed, nextTick, onBeforeUnmount, onMounted, provide, ref, watch } from "vue";
3
+ import { navigateTo, useAdminI18n, useAtelierAdmin, useAtelierAdminSchema, useAtelierComments, useAtelierEntryForm, useRoute, useRuntimeConfig } from "#imports";
4
+ import CommentsPanel from "#atelier-admin-runtime/components/CommentsPanel.vue";
5
+ import FieldInput from "#atelier-admin-runtime/components/FieldInput.vue";
6
+ import CnAlert from "#atelier-admin-runtime/crystal-neuo/components/Alert.vue";
7
+ import CnButton from "#atelier-admin-runtime/crystal-neuo/components/Button.vue";
8
+ import CnSelect from "#atelier-admin-runtime/crystal-neuo/components/Select.vue";
9
+ import { useAdminToast } from "#atelier-admin-runtime/toast";
10
+ import { copyBlocks, resolveShared, SHARED_BLOCK, SHARED_BLOCKS } from "#atelier/shared/blocks";
11
+ import { BRIDGE_VERSION, ChildMessage, readMessage } from "#atelier/shared/bridge";
12
+ import styles from "./editor.css?raw";
13
+ import CommandPalette from "./CommandPalette.vue";
14
+ import { addedBlockActions, addedCommands } from "./commands";
15
+ import { dndKey } from "./dnd";
16
+ import { createHistory } from "./history";
17
+ import StructureList from "./StructureList.vue";
18
+ import { accepts, allLists, blockTree, duplicate, get, insert, locate, move, newBlock, remove } from "./tree";
19
+ const route = useRoute();
20
+ const { t } = useAdminI18n();
21
+ const { api, to } = useAtelierAdmin();
22
+ const toast = useAdminToast();
23
+ const { schema } = useAtelierAdminSchema();
24
+ const presets = useRuntimeConfig().public.atelierEditor?.presets ?? [];
25
+ const name = String(route.query.type ?? "");
26
+ const id = typeof route.query.id === "string" ? route.query.id : void 0;
27
+ const kind = computed(() => schema.value?.singletons.some((s) => s.name === name) ? "singleton" : "collection");
28
+ const edit = useAtelierEntryForm(() => ({ kind: kind.value, name, id }));
29
+ const { form, type } = edit;
30
+ const values = form.useStore((state) => state.values);
31
+ const registry = computed(() => schema.value?.blocks ?? {});
32
+ const lists = computed(() => type.value ? blockTree(values.value, type.value.fields, registry.value) : []);
33
+ const canSave = computed(() => !!type.value?.can.update);
34
+ const frame = ref(null);
35
+ const src = ref("");
36
+ const failure = ref("");
37
+ const width = ref(presets[0]?.width ?? 1280);
38
+ const presetOptions = computed(() => presets.map((p) => ({ value: String(p.width), label: `${p.label} (${p.width}px)` })));
39
+ const stage = ref(null);
40
+ const stageWidth = ref(0);
41
+ const scale = computed(() => stageWidth.value && width.value > stageWidth.value ? stageWidth.value / width.value : 1);
42
+ let resizes;
43
+ onMounted(() => {
44
+ resizes = new ResizeObserver(([entry]) => stageWidth.value = entry.contentRect.width);
45
+ resizes.observe(stage.value);
46
+ });
47
+ onBeforeUnmount(() => resizes?.disconnect());
48
+ onMounted(async () => {
49
+ try {
50
+ src.value = (await api("/editor/token", { method: "POST", body: { type: name, ...id ? { id } : {} } })).url;
51
+ } catch (e) {
52
+ failure.value = e.message ?? "";
53
+ }
54
+ });
55
+ const geometry = ref(null);
56
+ const hovered = ref(null);
57
+ const selected = ref(null);
58
+ const announcement = ref("");
59
+ function clone(value) {
60
+ return JSON.parse(JSON.stringify(value ?? null));
61
+ }
62
+ let pending = 0;
63
+ function sendState() {
64
+ if (pending)
65
+ return;
66
+ pending = requestAnimationFrame(() => {
67
+ pending = 0;
68
+ frame.value?.contentWindow?.postMessage({ type: "atelier:state", version: BRIDGE_VERSION, id: id ?? name, data: clone(values.value) }, location.origin);
69
+ });
70
+ }
71
+ function onMessage(event) {
72
+ const message = readMessage(ChildMessage, event, { origin: location.origin, source: frame.value?.contentWindow });
73
+ if (!message)
74
+ return;
75
+ if (message.type === "atelier:ready")
76
+ sendState();
77
+ else if (message.type === "atelier:geometry")
78
+ geometry.value = message;
79
+ else if (message.type === "atelier:select")
80
+ selected.value = message.id;
81
+ else if (message.type === "atelier:hover")
82
+ hovered.value = message.id;
83
+ else if (message.type === "atelier:inline")
84
+ applyInline(message.path, message.value);
85
+ else if (message.type === "atelier:key")
86
+ shortcut(message.key, message.shift);
87
+ }
88
+ onMounted(() => addEventListener("message", onMessage));
89
+ onBeforeUnmount(() => removeEventListener("message", onMessage));
90
+ watch(selected, (blockId) => frame.value?.contentWindow?.postMessage({ type: "atelier:select", version: BRIDGE_VERSION, id: blockId }, location.origin));
91
+ const boxOf = (blockId) => {
92
+ const found = blockId ? geometry.value?.blocks.find((b) => b.id === blockId) : void 0;
93
+ return found && { left: `${found.rect.x}px`, top: `${found.rect.y}px`, width: `${found.rect.width}px`, height: `${found.rect.height}px` };
94
+ };
95
+ const history = createHistory();
96
+ let last = clone(values.value);
97
+ let nextKind = "typing";
98
+ let restoring = false;
99
+ watch(values, (current) => {
100
+ const loaded = Object.keys(last ?? {}).length > 0;
101
+ if (!restoring && loaded && JSON.stringify(last) !== JSON.stringify(current))
102
+ history.record(last, nextKind);
103
+ nextKind = "typing";
104
+ restoring = false;
105
+ last = clone(current);
106
+ sendState();
107
+ }, { deep: true });
108
+ function setData(data, how) {
109
+ if (how === "restore")
110
+ restoring = true;
111
+ else
112
+ nextKind = "operation";
113
+ for (const key of Object.keys(type.value?.fields ?? {})) {
114
+ if (JSON.stringify(data[key]) !== JSON.stringify(values.value[key]))
115
+ form.setFieldValue(key, clone(data[key]));
116
+ }
117
+ }
118
+ function undo() {
119
+ const previous = history.undo(clone(values.value));
120
+ if (previous)
121
+ setData(previous, "restore");
122
+ }
123
+ function redo() {
124
+ const next = history.redo(clone(values.value));
125
+ if (next)
126
+ setData(next, "restore");
127
+ }
128
+ function applyInline(path, value) {
129
+ const [blockId, field] = path.includes("/") ? path.split("/") : [null, path];
130
+ const at = blockId ? locate(lists.value, blockId) : void 0;
131
+ if (blockId && !at)
132
+ return;
133
+ form.setFieldValue(at ? `${at.block.path}.props.${field}` : field, value);
134
+ }
135
+ const selectedAt = computed(() => selected.value ? locate(lists.value, selected.value) : void 0);
136
+ const selectedSchema = computed(() => selectedAt.value ? registry.value[selectedAt.value.block.type] : void 0);
137
+ const selectedFields = computed(() => Object.entries({ ...selectedSchema.value?.fields, ...selectedSchema.value?.options }));
138
+ function moveBy(blockId, by) {
139
+ const at = locate(lists.value, blockId);
140
+ if (!at)
141
+ return;
142
+ const index = at.index + (by === 1 ? 2 : -1);
143
+ if (index < 0 || index > at.list.blocks.length)
144
+ return;
145
+ const moved = move(values.value, lists.value, registry.value, blockId, at.list.path, index);
146
+ if (moved) {
147
+ setData(moved, "operation");
148
+ announcement.value = t("editor.moved", { block: at.block.label, position: at.index + by + 1, list: at.list.label });
149
+ }
150
+ }
151
+ function removeBlock(blockId) {
152
+ setData(remove(values.value, lists.value, blockId), "operation");
153
+ if (selected.value === blockId)
154
+ selected.value = null;
155
+ }
156
+ function duplicateBlock(blockId) {
157
+ const copied = duplicate(values.value, lists.value, registry.value, blockId);
158
+ if (copied) {
159
+ setData(copied.data, "operation");
160
+ selected.value = copied.id;
161
+ }
162
+ }
163
+ const target = computed(() => selectedAt.value ? { list: selectedAt.value.list.path, index: selectedAt.value.index + 1 } : lists.value[0] ? { list: lists.value[0].path, index: lists.value[0].blocks.length } : void 0);
164
+ const palette = computed(() => Object.values(registry.value).filter((b) => !type.value?.blockTypes || type.value.blockTypes.includes(b.name)).map((b) => ({ name: b.name, label: b.label ?? b.name })));
165
+ const listAt = (path) => allLists(lists.value).find((l) => l.path === path);
166
+ function canPlace(dragged, at) {
167
+ if (dragged.kind === "block")
168
+ return !!move(values.value, lists.value, registry.value, dragged.id, at.list, at.index);
169
+ const list = listAt(at.list);
170
+ return !!list && accepts(list, dragged.type, registry.value);
171
+ }
172
+ function place(dragged, at) {
173
+ if (!canPlace(dragged, at))
174
+ return;
175
+ if (dragged.kind === "block") {
176
+ setData(move(values.value, lists.value, registry.value, dragged.id, at.list, at.index), "operation");
177
+ selected.value = dragged.id;
178
+ return;
179
+ }
180
+ const block = newBlock(dragged.type, registry.value);
181
+ setData(insert(values.value, at.list, at.index, block), "operation");
182
+ selected.value = block.id;
183
+ }
184
+ const dragging = ref(null);
185
+ const dropAt = ref(null);
186
+ const dnd = {
187
+ dragging,
188
+ dropAt,
189
+ start(event, dragged) {
190
+ event.dataTransfer?.setData("text/plain", dragged.kind === "block" ? dragged.id : dragged.type);
191
+ if (event.dataTransfer)
192
+ event.dataTransfer.effectAllowed = dragged.kind === "block" ? "move" : "copy";
193
+ dragging.value = dragged;
194
+ },
195
+ over(event, at) {
196
+ const ok = !!dragging.value && canPlace(dragging.value, at);
197
+ dropAt.value = ok ? at : null;
198
+ if (ok)
199
+ event.preventDefault();
200
+ },
201
+ drop(event) {
202
+ event.preventDefault();
203
+ if (dragging.value && dropAt.value)
204
+ place(dragging.value, dropAt.value);
205
+ dragging.value = null;
206
+ dropAt.value = null;
207
+ },
208
+ end() {
209
+ dragging.value = null;
210
+ dropAt.value = null;
211
+ }
212
+ };
213
+ provide(dndKey, dnd);
214
+ const overlay = ref(null);
215
+ const previewLine = ref(null);
216
+ function blocksUnder(event) {
217
+ const origin = overlay.value.getBoundingClientRect();
218
+ const x = (event.clientX - origin.left) / scale.value;
219
+ const y = (event.clientY - origin.top) / scale.value;
220
+ const under = (geometry.value?.blocks ?? []).filter((b) => x >= b.rect.x && x <= b.rect.x + b.rect.width && y >= b.rect.y && y <= b.rect.y + b.rect.height).sort((a, b) => a.rect.width * a.rect.height - b.rect.width * b.rect.height);
221
+ return { under, y };
222
+ }
223
+ function overPreview(event) {
224
+ if (isFileDrag(event))
225
+ return overWithFile(event);
226
+ const { under, y } = blocksUnder(event);
227
+ for (const hit of under) {
228
+ const at = locate(lists.value, hit.id);
229
+ const after = y > hit.rect.y + hit.rect.height / 2;
230
+ const spot = at && { list: at.list.path, index: at.index + (after ? 1 : 0) };
231
+ if (spot && dragging.value && canPlace(dragging.value, spot)) {
232
+ dnd.over(event, spot);
233
+ previewLine.value = { left: `${hit.rect.x}px`, top: `${after ? hit.rect.y + hit.rect.height : hit.rect.y}px`, width: `${hit.rect.width}px` };
234
+ return;
235
+ }
236
+ }
237
+ dropAt.value = null;
238
+ previewLine.value = null;
239
+ }
240
+ watch(dropAt, (at) => {
241
+ if (!at)
242
+ previewLine.value = null;
243
+ });
244
+ const draggingFiles = ref(false);
245
+ const fileTarget = ref(null);
246
+ const isFileDrag = (event) => !!event.dataTransfer?.types.includes("Files");
247
+ function mediaFieldOf(blockType, mime) {
248
+ const fields = registry.value[blockType]?.fields ?? {};
249
+ return Object.entries(fields).find(([, f]) => f.type === "media" && (!f.accept || f.accept.some((a) => a === mime || a.endsWith("/*") && mime.startsWith(a.slice(0, -1)))))?.[0];
250
+ }
251
+ const draggedMime = (event) => [...event.dataTransfer?.items ?? []].find((i) => i.kind === "file")?.type ?? "";
252
+ function overWithFile(event) {
253
+ const mime = draggedMime(event);
254
+ const hit = blocksUnder(event).under.find((b) => {
255
+ const at = locate(lists.value, b.id);
256
+ return at && mediaFieldOf(at.block.type, mime);
257
+ });
258
+ fileTarget.value = hit?.id ?? null;
259
+ if (hit)
260
+ event.preventDefault();
261
+ }
262
+ async function dropFile(event) {
263
+ event.preventDefault();
264
+ const blockId = fileTarget.value;
265
+ const file = event.dataTransfer?.files[0];
266
+ draggingFiles.value = false;
267
+ fileTarget.value = null;
268
+ const at = blockId ? locate(lists.value, blockId) : void 0;
269
+ const field = at && file && mediaFieldOf(at.block.type, file.type);
270
+ if (!at || !file || !field)
271
+ return;
272
+ try {
273
+ const item = await api("/media", { method: "POST", query: { filename: file.name }, body: file });
274
+ const block = blockOf(at.block.path);
275
+ context.setProps(blockId, { ...block.props, [field]: item.id });
276
+ announce(t("editor.uploaded", { file: file.name }));
277
+ } catch (error) {
278
+ toast.add({ color: "error", title: error.message ?? String(error) });
279
+ }
280
+ }
281
+ function onWindowDrag(event) {
282
+ if (event.type === "dragenter" && isFileDrag(event))
283
+ draggingFiles.value = true;
284
+ else if (event.type === "dragleave" && !event.relatedTarget || event.type === "drop") {
285
+ draggingFiles.value = false;
286
+ fileTarget.value = null;
287
+ }
288
+ }
289
+ onMounted(() => ["dragenter", "dragleave", "drop"].forEach((type2) => addEventListener(type2, onWindowDrag)));
290
+ onBeforeUnmount(() => ["dragenter", "dragleave", "drop"].forEach((type2) => removeEventListener(type2, onWindowDrag)));
291
+ const commandsOpen = ref(false);
292
+ function shortcut(key, shift) {
293
+ if (key === "k") {
294
+ commandsOpen.value = !commandsOpen.value;
295
+ return true;
296
+ }
297
+ if (commandsOpen.value)
298
+ return false;
299
+ if (key === "z" && !shift)
300
+ undo();
301
+ else if (key === "z" && shift || key === "y")
302
+ redo();
303
+ else
304
+ return false;
305
+ return true;
306
+ }
307
+ function onKey(event) {
308
+ if ((event.ctrlKey || event.metaKey) && !event.altKey && shortcut(event.key.toLowerCase(), event.shiftKey)) {
309
+ event.preventDefault();
310
+ event.stopImmediatePropagation();
311
+ }
312
+ }
313
+ onMounted(() => addEventListener("keydown", onKey, { capture: true }));
314
+ onBeforeUnmount(() => removeEventListener("keydown", onKey, { capture: true }));
315
+ const context = {
316
+ get selected() {
317
+ return selected.value;
318
+ },
319
+ select: (blockId) => {
320
+ selected.value = blockId;
321
+ },
322
+ insert: (blockType) => {
323
+ if (!target.value || !canPlace({ kind: "new", type: blockType }, target.value))
324
+ return false;
325
+ place({ kind: "new", type: blockType }, target.value);
326
+ return true;
327
+ },
328
+ data: () => clone(values.value),
329
+ setData: (data) => setData(data, "operation"),
330
+ undo,
331
+ redo,
332
+ save: () => save(),
333
+ setProps: (blockId, props) => {
334
+ const at = locate(lists.value, blockId);
335
+ if (at)
336
+ replaceAt(at.block.path, { ...blockOf(at.block.path), props: clone(props) });
337
+ }
338
+ };
339
+ const pluginActions = computed(() => selectedBlock.value ? addedBlockActions(clone(selectedBlock.value), context) : []);
340
+ const commentsTarget = computed(() => type.value && !type.value.adapter ? { type: name, id: kind.value === "singleton" ? name : id ?? "" } : null);
341
+ const comments = useAtelierComments(commentsTarget);
342
+ const panel = ref("block");
343
+ const aside = ref(null);
344
+ const markers = computed(() => {
345
+ const open = /* @__PURE__ */ new Map();
346
+ for (const thread of comments.threads.value) {
347
+ if (thread.block && !thread.resolvedAt && !thread.orphaned)
348
+ open.set(thread.block, [...open.get(thread.block) ?? [], thread.id]);
349
+ }
350
+ return [...open].flatMap(([blockId, threads]) => {
351
+ const at = geometry.value?.blocks.find((b) => b.id === blockId);
352
+ const label = locate(lists.value, blockId)?.block.label ?? "";
353
+ return at ? [{ blockId, threads, label, style: { left: `${at.rect.x}px`, top: `${at.rect.y}px` } }] : [];
354
+ });
355
+ });
356
+ async function openThread(blockId, thread) {
357
+ selected.value = blockId;
358
+ panel.value = "comments";
359
+ await nextTick();
360
+ const el = aside.value?.querySelector(`[data-comment="${thread}"]`);
361
+ el?.scrollIntoView({ block: "nearest" });
362
+ el?.setAttribute("data-highlighted", "");
363
+ setTimeout(() => el?.removeAttribute("data-highlighted"), 2e3);
364
+ }
365
+ const patterns = ref([]);
366
+ const loadedShared = ref([]);
367
+ const sharedBlocks = computed(() => type.value?.adapter ? [] : loadedShared.value);
368
+ async function loadReusable() {
369
+ const [found, shared] = await Promise.all([
370
+ api("/patterns").catch(() => []),
371
+ schema.value?.collections.some((c) => c.name === SHARED_BLOCKS) ? api(`/collections/${SHARED_BLOCKS}`, { query: { draft: "true", limit: 100, sort: "title" } }).catch(() => ({ items: [] })) : { items: [] }
372
+ ]);
373
+ patterns.value = found;
374
+ loadedShared.value = shared.items.filter((e) => e.data.block?.[0]).map((e) => ({ id: e.id, label: e.data.title ?? e.id, block: e.data.block[0] }));
375
+ }
376
+ onMounted(loadReusable);
377
+ function fits(blocks, at) {
378
+ const list = listAt(at.list);
379
+ return !!list && blocks.length > 0 && blocks.every((b) => accepts(list, b.type, registry.value, true)) && (list.rules.max === void 0 || list.blocks.length + blocks.length <= list.rules.max);
380
+ }
381
+ function insertBlocks(blocks, at = target.value) {
382
+ if (!at || !fits(blocks, at)) {
383
+ announce(t("editor.cantPlace", { block: blocks.map((b) => labelOf(b.type)).join(", ") }));
384
+ return false;
385
+ }
386
+ let data = values.value;
387
+ blocks.forEach((block, i) => data = insert(data, at.list, at.index + i, block));
388
+ setData(data, "operation");
389
+ selected.value = blocks[0].id;
390
+ return true;
391
+ }
392
+ const labelOf = (blockType) => registry.value[blockType]?.label ?? blockType;
393
+ const insertPattern = (pattern) => insertBlocks(copyBlocks(clone(pattern.blocks)));
394
+ const insertShared = (shared) => insertBlocks([resolveShared([{ id: crypto.randomUUID(), type: SHARED_BLOCK, props: { ref: shared.id } }], () => clone(shared.block))[0]]);
395
+ function replaceAt(path, block) {
396
+ const at = locate(lists.value, get(values.value, path).id);
397
+ setData(insert(remove(values.value, lists.value, at.block.id), at.list.path, at.index, block), "operation");
398
+ selected.value = block.id;
399
+ }
400
+ const selectedBlock = computed(() => selectedAt.value ? blockOf(selectedAt.value.block.path) : void 0);
401
+ const reuseTitle = ref("");
402
+ async function saveAs(kind2) {
403
+ const block = selectedBlock.value;
404
+ const title = reuseTitle.value.trim();
405
+ if (!block || !title)
406
+ return;
407
+ try {
408
+ const [copy] = copyBlocks([clone(block)]);
409
+ if (kind2 === "pattern") {
410
+ await api(`/collections/atelier-patterns`, { method: "POST", body: { data: { title, blocks: [copy] } } });
411
+ } else {
412
+ const created = await api(`/collections/${SHARED_BLOCKS}`, { method: "POST", body: { data: { title, block: [copy] } } });
413
+ replaceAt(selectedAt.value.block.path, { ...block, shared: created.id });
414
+ }
415
+ reuseTitle.value = "";
416
+ toast.add({ color: "success", title: t(kind2 === "shared" ? "editor.savedShared" : "editor.savedPattern", { title }) });
417
+ await loadReusable();
418
+ } catch (e) {
419
+ toast.add({ color: "error", title: e.message ?? "" });
420
+ }
421
+ }
422
+ function detach() {
423
+ if (selectedBlock.value?.shared)
424
+ replaceAt(selectedAt.value.block.path, copyBlocks([clone(selectedBlock.value)])[0]);
425
+ }
426
+ const CLIPBOARD = "atelier/blocks";
427
+ const editable = (event) => {
428
+ const el = event.composedPath()[0];
429
+ return !!el && (el.isContentEditable || /^(?:INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
430
+ };
431
+ function onCopy(event) {
432
+ if (editable(event) || !selectedBlock.value || !event.clipboardData)
433
+ return;
434
+ event.preventDefault();
435
+ event.clipboardData.setData("text/plain", JSON.stringify({ [CLIPBOARD]: [selectedBlock.value] }));
436
+ announce(t("editor.copied", { block: selectedAt.value.block.label }));
437
+ }
438
+ function onPaste(event) {
439
+ if (editable(event) || !event.clipboardData)
440
+ return;
441
+ let blocks;
442
+ try {
443
+ blocks = JSON.parse(event.clipboardData.getData("text/plain"))[CLIPBOARD];
444
+ } catch {
445
+ return;
446
+ }
447
+ if (!Array.isArray(blocks) || !blocks.every((b) => b && typeof b === "object" && typeof b.type === "string" && registry.value[b.type]))
448
+ return;
449
+ event.preventDefault();
450
+ insertBlocks(copyBlocks(blocks));
451
+ }
452
+ onMounted(() => {
453
+ addEventListener("copy", onCopy);
454
+ addEventListener("paste", onPaste);
455
+ });
456
+ onBeforeUnmount(() => {
457
+ removeEventListener("copy", onCopy);
458
+ removeEventListener("paste", onPaste);
459
+ });
460
+ function announce(text) {
461
+ announcement.value = text;
462
+ }
463
+ const commands = computed(() => {
464
+ const blocks = t("editor.groupBlocks");
465
+ const editing = t("editor.groupEdit");
466
+ const at = selectedAt.value;
467
+ return [
468
+ ...target.value ? palette.value.filter((b) => canPlace({ kind: "new", type: b.name }, target.value)).map((b) => ({ id: `insert:${b.name}`, label: t("editor.insert", { block: b.label }), group: blocks, run: () => void context.insert(b.name) })) : [],
469
+ ...at ? [
470
+ { id: "move-up", label: t("editor.moveUp"), group: editing, run: () => moveBy(at.block.id, -1) },
471
+ { id: "move-down", label: t("editor.moveDown"), group: editing, run: () => moveBy(at.block.id, 1) },
472
+ { id: "duplicate", label: t("editor.duplicate"), group: editing, run: () => duplicateBlock(at.block.id) },
473
+ { id: "delete", label: t("editor.delete"), group: editing, run: () => removeBlock(at.block.id) },
474
+ ...pluginActions.value.map((a) => ({ ...a, group: a.group ?? editing }))
475
+ ] : [],
476
+ ...patterns.value.map((p) => ({ id: `pattern:${p.id}`, label: t("editor.insert", { block: p.label }), group: t("editor.patterns"), run: () => void insertPattern(p) })),
477
+ ...sharedBlocks.value.map((b) => ({ id: `shared:${b.id}`, label: t("editor.insert", { block: b.label }), group: t("editor.sharedBlocks"), run: () => void insertShared(b) })),
478
+ ...selectedBlock.value?.shared ? [{ id: "detach", label: t("editor.detach"), group: editing, run: detach }] : [],
479
+ { id: "undo", label: t("editor.undo"), group: editing, run: undo },
480
+ { id: "redo", label: t("editor.redo"), group: editing, run: redo },
481
+ ...canSave.value ? [{ id: "save", label: type.value?.versioned ? t("entry.saveDraft") : t("common.save"), group: editing, run: save }] : [],
482
+ ...commandsOpen.value ? addedCommands(context) : []
483
+ ];
484
+ });
485
+ async function runCommand(command) {
486
+ try {
487
+ await command.run(context);
488
+ } catch (e) {
489
+ toast.add({ color: "error", title: e.message ?? "" });
490
+ }
491
+ }
492
+ async function save() {
493
+ try {
494
+ await edit.submit();
495
+ if (form.state.isSubmitSuccessful)
496
+ toast.add({ color: "success", title: t("editor.saved") });
497
+ } catch (e) {
498
+ toast.add({ color: "error", title: e.message ?? "" });
499
+ }
500
+ }
501
+ const back = () => navigateTo(kind.value === "singleton" ? to("singletons", name) : to("collections", name, id ?? ""));
502
+ const blockOf = (path) => get(values.value, path);
503
+ const targetLabel = computed(() => (target.value && listAt(target.value.list)?.label) ?? "");
504
+ </script>
505
+
506
+ <template>
507
+ <div
508
+ class="ate-editor"
509
+ data-visual-editor
510
+ >
511
+ <component :is="'style'">
512
+ {{ styles }}
513
+ </component>
514
+ <header class="ate-editor__bar">
515
+ <CnButton
516
+ variant="ghost"
517
+ size="sm"
518
+ @click="back"
519
+ >
520
+ {{ t("editor.backToForm") }}
521
+ </CnButton>
522
+ <CnSelect
523
+ :model-value="String(width)"
524
+ :label="t('editor.viewport')"
525
+ :options="presetOptions"
526
+ size="sm"
527
+ @update:model-value="(v) => width = Number(v)"
528
+ />
529
+ <label class="cn-field ate-editor__width">
530
+ <span class="cn-field__label">{{ t("editor.custom") }}</span>
531
+ <input
532
+ v-model.number="width"
533
+ type="number"
534
+ min="240"
535
+ max="3840"
536
+ class="cn-input cn-input--size-sm"
537
+ >
538
+ </label>
539
+ <CnButton
540
+ variant="ghost"
541
+ size="sm"
542
+ :aria-label="t('editor.undo')"
543
+ @click="undo"
544
+ >
545
+ {{ t("editor.undo") }}
546
+ </CnButton>
547
+ <CnButton
548
+ variant="ghost"
549
+ size="sm"
550
+ :aria-label="t('editor.redo')"
551
+ @click="redo"
552
+ >
553
+ {{ t("editor.redo") }}
554
+ </CnButton>
555
+ <CnButton
556
+ v-if="canSave"
557
+ size="sm"
558
+ :loading="form.state.isSubmitting"
559
+ @click="save"
560
+ >
561
+ {{ type?.versioned ? t("entry.saveDraft") : t("common.save") }}
562
+ </CnButton>
563
+ </header>
564
+ <CnAlert
565
+ v-if="failure"
566
+ variant="danger"
567
+ >
568
+ {{ failure }}
569
+ </CnAlert>
570
+ <div class="ate-editor__body">
571
+ <nav
572
+ class="ate-editor__structure"
573
+ :aria-label="t('editor.structure')"
574
+ >
575
+ <template
576
+ v-for="list in lists"
577
+ :key="list.path"
578
+ >
579
+ <p class="ate-tree__area">
580
+ {{ list.label }}
581
+ </p>
582
+ <StructureList
583
+ :list="list"
584
+ :selected="selected"
585
+ :hovered="hovered"
586
+ :depth="0"
587
+ :empty-label="t('editor.empty')"
588
+ @select="selected = $event"
589
+ @hover="hovered = $event"
590
+ @move="moveBy"
591
+ @remove="removeBlock"
592
+ />
593
+ </template>
594
+ <p class="ate-tree__area">
595
+ {{ t("editor.addTo", { list: targetLabel }) }}
596
+ </p>
597
+ <ul
598
+ class="ate-palette"
599
+ :aria-label="t('editor.add')"
600
+ >
601
+ <li
602
+ v-for="b in palette"
603
+ :key="b.name"
604
+ >
605
+ <button
606
+ type="button"
607
+ class="ate-palette__block"
608
+ draggable="true"
609
+ :disabled="!target || !canPlace({ kind: 'new', type: b.name }, target)"
610
+ :data-palette-block="b.name"
611
+ @click="target && place({ kind: 'new', type: b.name }, target)"
612
+ @dragstart="dnd.start($event, { kind: 'new', type: b.name })"
613
+ @dragend="dnd.end()"
614
+ >
615
+ {{ b.label }}
616
+ </button>
617
+ </li>
618
+ </ul>
619
+ <template
620
+ v-for="group in [{ label: t('editor.patterns'), items: patterns.map((p) => ({ id: p.id, label: p.label, insert: () => insertPattern(p) })), attr: 'data-pattern' }, { label: t('editor.sharedBlocks'), items: sharedBlocks.map((b2) => ({ id: b2.id, label: b2.label, insert: () => insertShared(b2) })), attr: 'data-shared-block' }]"
621
+ :key="group.attr"
622
+ >
623
+ <template v-if="group.items.length">
624
+ <p class="ate-tree__area">
625
+ {{ group.label }}
626
+ </p>
627
+ <ul
628
+ class="ate-palette"
629
+ :aria-label="group.label"
630
+ >
631
+ <li
632
+ v-for="item in group.items"
633
+ :key="item.id"
634
+ >
635
+ <button
636
+ type="button"
637
+ class="ate-palette__block"
638
+ v-bind="{ [group.attr]: item.id }"
639
+ @click="item.insert()"
640
+ >
641
+ {{ item.label }}
642
+ </button>
643
+ </li>
644
+ </ul>
645
+ </template>
646
+ </template>
647
+ </nav>
648
+ <div
649
+ ref="stage"
650
+ class="ate-editor__stage"
651
+ role="region"
652
+ tabindex="0"
653
+ :aria-label="t('editor.preview')"
654
+ >
655
+ <div
656
+ class="ate-editor__viewport"
657
+ :style="{ 'width': `${width}px`, '--ate-scale': scale }"
658
+ >
659
+ <iframe
660
+ v-if="src"
661
+ ref="frame"
662
+ :src="src"
663
+ :title="t('editor.preview')"
664
+ class="ate-editor__frame"
665
+ />
666
+ <div
667
+ ref="overlay"
668
+ class="ate-editor__overlay"
669
+ :class="{ 'ate-editor__overlay--dropping': dragging || draggingFiles }"
670
+ aria-hidden="true"
671
+ data-preview-drop
672
+ @dragover="overPreview"
673
+ @dragleave="previewLine = null"
674
+ @drop="isFileDrag($event) ? dropFile($event) : dnd.drop($event)"
675
+ >
676
+ <div
677
+ v-if="fileTarget && boxOf(fileTarget)"
678
+ class="ate-editor__box ate-editor__box--selected"
679
+ data-file-target
680
+ :style="boxOf(fileTarget)"
681
+ />
682
+ <div
683
+ v-if="previewLine"
684
+ class="ate-editor__drop"
685
+ :style="previewLine"
686
+ />
687
+ <div
688
+ v-if="hovered && hovered !== selected && boxOf(hovered)"
689
+ class="ate-editor__box ate-editor__box--hover"
690
+ :style="boxOf(hovered)"
691
+ />
692
+ <div
693
+ v-if="boxOf(selected)"
694
+ class="ate-editor__box ate-editor__box--selected"
695
+ :class="{ 'ate-editor__box--top': (geometry?.blocks.find((b2) => b2.id === selected)?.rect.y ?? 0) < 20 }"
696
+ :style="boxOf(selected)"
697
+ data-overlay-selected
698
+ >
699
+ <span
700
+ class="ate-editor__tag"
701
+ draggable="true"
702
+ data-overlay-handle
703
+ @dragstart="selected && dnd.start($event, { kind: 'block', id: selected })"
704
+ @dragend="dnd.end()"
705
+ >{{ selectedAt?.block.label }}</span>
706
+ </div>
707
+ </div>
708
+ <div class="ate-editor__markers">
709
+ <button
710
+ v-for="marker in markers"
711
+ :key="marker.blockId"
712
+ type="button"
713
+ class="ate-editor__marker"
714
+ :style="marker.style"
715
+ :data-comment-marker="marker.blockId"
716
+ :aria-label="t('editor.commentsOn', { count: marker.threads.length, block: marker.label })"
717
+ @click="openThread(marker.blockId, marker.threads[0])"
718
+ >
719
+ {{ marker.threads.length }}
720
+ </button>
721
+ </div>
722
+ </div>
723
+ </div>
724
+ <aside
725
+ ref="aside"
726
+ class="ate-editor__panel"
727
+ :aria-label="panel === 'comments' ? t('editor.comments') : t('editor.block')"
728
+ >
729
+ <div
730
+ v-if="commentsTarget"
731
+ class="app-row ate-editor__tabs"
732
+ role="group"
733
+ :aria-label="t('editor.panel')"
734
+ >
735
+ <CnButton
736
+ :variant="panel === 'block' ? 'secondary' : 'ghost'"
737
+ size="sm"
738
+ :aria-pressed="panel === 'block'"
739
+ @click="panel = 'block'"
740
+ >
741
+ {{ t("editor.block") }}
742
+ </CnButton>
743
+ <CnButton
744
+ :variant="panel === 'comments' ? 'secondary' : 'ghost'"
745
+ size="sm"
746
+ :aria-pressed="panel === 'comments'"
747
+ data-comments-tab
748
+ @click="panel = 'comments'"
749
+ >
750
+ {{ t("editor.comments") }}
751
+ </CnButton>
752
+ </div>
753
+ <CommentsPanel
754
+ v-if="panel === 'comments' && commentsTarget"
755
+ :id="commentsTarget.id"
756
+ :type="commentsTarget.type"
757
+ :data="values"
758
+ :can-comment="!!type?.can.comment"
759
+ />
760
+ <template v-else-if="selectedAt && selectedSchema">
761
+ <h2 class="app-section__title">
762
+ {{ selectedAt.block.label }}
763
+ </h2>
764
+ <div class="app-row">
765
+ <CnButton
766
+ variant="ghost"
767
+ size="sm"
768
+ @click="moveBy(selectedAt.block.id, -1)"
769
+ >
770
+ {{ t("editor.moveUp") }}
771
+ </CnButton>
772
+ <CnButton
773
+ variant="ghost"
774
+ size="sm"
775
+ @click="moveBy(selectedAt.block.id, 1)"
776
+ >
777
+ {{ t("editor.moveDown") }}
778
+ </CnButton>
779
+ <CnButton
780
+ variant="ghost"
781
+ size="sm"
782
+ @click="duplicateBlock(selectedAt.block.id)"
783
+ >
784
+ {{ t("editor.duplicate") }}
785
+ </CnButton>
786
+ <CnButton
787
+ variant="ghost"
788
+ size="sm"
789
+ @click="removeBlock(selectedAt.block.id)"
790
+ >
791
+ {{ t("editor.delete") }}
792
+ </CnButton>
793
+ <CnButton
794
+ v-for="action in pluginActions"
795
+ :key="action.id"
796
+ variant="ghost"
797
+ size="sm"
798
+ :data-block-action="action.id"
799
+ @click="runCommand(action)"
800
+ >
801
+ {{ action.label }}
802
+ </CnButton>
803
+ </div>
804
+ <p
805
+ v-if="selectedBlock?.shared"
806
+ class="app-row"
807
+ >
808
+ <span class="app-muted">{{ t("editor.isShared") }}</span>
809
+ <CnButton
810
+ variant="ghost"
811
+ size="sm"
812
+ data-detach
813
+ @click="detach"
814
+ >
815
+ {{ t("editor.detach") }}
816
+ </CnButton>
817
+ </p>
818
+ <details
819
+ v-else-if="!type?.adapter"
820
+ class="ate-editor__reuse"
821
+ >
822
+ <summary>{{ t("editor.reuse") }}</summary>
823
+ <label class="cn-field">
824
+ <span class="cn-field__label">{{ t("editor.reuseTitle") }}</span>
825
+ <input
826
+ v-model="reuseTitle"
827
+ class="cn-input cn-input--size-sm"
828
+ >
829
+ </label>
830
+ <div class="app-row">
831
+ <CnButton
832
+ variant="ghost"
833
+ size="sm"
834
+ :disabled="!reuseTitle.trim()"
835
+ @click="saveAs('shared')"
836
+ >
837
+ {{ t("editor.saveAsShared") }}
838
+ </CnButton>
839
+ <CnButton
840
+ variant="ghost"
841
+ size="sm"
842
+ :disabled="!reuseTitle.trim()"
843
+ @click="saveAs('pattern')"
844
+ >
845
+ {{ t("editor.saveAsPattern") }}
846
+ </CnButton>
847
+ </div>
848
+ </details>
849
+ <div
850
+ class="app-form"
851
+ data-block-form
852
+ >
853
+ <FieldInput
854
+ v-for="[key, field] in selectedFields"
855
+ :key="`${selectedAt.block.id}:${key}`"
856
+ :form="form"
857
+ :name="`${selectedAt.block.path}.props.${key}`"
858
+ :field="field"
859
+ :root="values"
860
+ :sibling="blockOf(selectedAt.block.path)?.props ?? {}"
861
+ :read-only="!canSave"
862
+ />
863
+ </div>
864
+ </template>
865
+ <p
866
+ v-else
867
+ class="app-muted"
868
+ >
869
+ {{ t("editor.noSelection") }}
870
+ </p>
871
+ </aside>
872
+ </div>
873
+ <CommandPalette
874
+ v-model:open="commandsOpen"
875
+ :commands="commands"
876
+ @run="runCommand"
877
+ />
878
+ <p
879
+ class="sr-only"
880
+ aria-live="polite"
881
+ >
882
+ {{ announcement }}
883
+ </p>
884
+ </div>
885
+ </template>