@nuxt-atelier/editor 0.0.0-stage → 0.1.0

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