@velocity-astro/cms-admin 0.1.0-beta.4 → 0.1.0-beta.6

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 (42) hide show
  1. package/app-dist/assets/{RichTextEditor-B1fSHY4y.js → RichTextEditor-BiKJJtkz.js} +1 -1
  2. package/app-dist/assets/{index-DmVwReEd.js → index-BgVjqwy6.js} +11 -11
  3. package/app-dist/assets/index-BvWFILf6.css +2 -0
  4. package/app-dist/index.html +2 -2
  5. package/dist/fields/BlocksControl.d.ts.map +1 -1
  6. package/dist/fields/BlocksControl.js +122 -14
  7. package/dist/fields/BlocksControl.js.map +1 -1
  8. package/dist/fields/FieldGrid.d.ts +10 -1
  9. package/dist/fields/FieldGrid.d.ts.map +1 -1
  10. package/dist/fields/FieldGrid.js +4 -3
  11. package/dist/fields/FieldGrid.js.map +1 -1
  12. package/dist/fields/controls.d.ts.map +1 -1
  13. package/dist/fields/controls.js +30 -3
  14. package/dist/fields/controls.js.map +1 -1
  15. package/dist/fields/field-control.d.ts +13 -0
  16. package/dist/fields/field-control.d.ts.map +1 -1
  17. package/dist/fields/field-control.js.map +1 -1
  18. package/dist/fields/page-focus.d.ts +30 -2
  19. package/dist/fields/page-focus.d.ts.map +1 -1
  20. package/dist/fields/page-focus.js +33 -2
  21. package/dist/fields/page-focus.js.map +1 -1
  22. package/dist/messages/en.d.ts +11 -1
  23. package/dist/messages/en.d.ts.map +1 -1
  24. package/dist/messages/en.js +11 -1
  25. package/dist/messages/en.js.map +1 -1
  26. package/dist/page-bridge/index.d.ts +7 -0
  27. package/dist/page-bridge/index.d.ts.map +1 -0
  28. package/dist/page-bridge/index.js +7 -0
  29. package/dist/page-bridge/index.js.map +1 -0
  30. package/dist/page-bridge/preview-bridge.d.ts +35 -0
  31. package/dist/page-bridge/preview-bridge.d.ts.map +1 -0
  32. package/dist/page-bridge/preview-bridge.js +702 -0
  33. package/dist/page-bridge/preview-bridge.js.map +1 -0
  34. package/dist/screens/EntryEditor/EntryForm.d.ts.map +1 -1
  35. package/dist/screens/EntryEditor/EntryForm.js +18 -8
  36. package/dist/screens/EntryEditor/EntryForm.js.map +1 -1
  37. package/dist/screens/EntryEditor/PagePane.d.ts +19 -1
  38. package/dist/screens/EntryEditor/PagePane.d.ts.map +1 -1
  39. package/dist/screens/EntryEditor/PagePane.js +25 -6
  40. package/dist/screens/EntryEditor/PagePane.js.map +1 -1
  41. package/package.json +9 -5
  42. package/app-dist/assets/index-CczBKhBz.css +0 -2
@@ -0,0 +1,702 @@
1
+ /**
2
+ * What the page beside the editor's form runs: the page's side of the conversation with the
3
+ * editor. It is sent to the browser as text (`PREVIEW_BRIDGE_SCRIPT`), so the function must stand
4
+ * alone: its argument only, no imports and nothing from this file.
5
+ *
6
+ * It is in parts, each a few functions that close over the same page:
7
+ *
8
+ * - messaging: what the page and the editor say to each other, and to nobody else
9
+ * - marks: which section, and which field of it, an element of the page belongs to
10
+ * - layer: outlines drawn above the page, so nothing of the template's own markup is changed
11
+ * - tools: a small bar on the section the pointer is in (move, copy, remove) and a button at each
12
+ * of its edges that adds a section there, all in the layer and all said to the editor, which
13
+ * makes the change
14
+ * - events: what a pointer over the page and a click on it mean
15
+ * - typing: words typed straight into a field on the page, said to the editor as they are typed
16
+ * - scroll: the page stays where it was when it is drawn again
17
+ *
18
+ * A template says what is what with two attributes: `data-cms-section` holds a section's id, and
19
+ * `data-cms-field` inside it holds a field's place in the section, as keys (`title`,
20
+ * `items.0.text`). A page with no field marks still works: a section that says what it holds
21
+ * (`data-cms-values`, a list of place and words) has its fields found by what they show, so a
22
+ * template whose blocks hand their words to components of its own needs no mark on each. A mark
23
+ * the template wrote always comes first, and a click that finds no field chooses the section.
24
+ *
25
+ * Words can be typed on the page only where the editor says a field holds plain words and the page
26
+ * shows them exactly as they are held: the one run of text that shows them is changed, and nothing
27
+ * else of the element can be.
28
+ *
29
+ * The layer's look is set from script, which a page's content rules allow where a style written
30
+ * into the page would not be.
31
+ */
32
+ export function previewBridge(page) {
33
+ if (page.parent === page)
34
+ return;
35
+ const doc = page.document;
36
+ const origin = page.location.origin;
37
+ const SOURCE = 'velocity-cms';
38
+ // Messaging.
39
+ const say = (message) => page.parent.postMessage({ source: SOURCE, ...message }, origin);
40
+ const isElement = (target) => typeof target === 'object' && target !== null && target.nodeType === 1;
41
+ // What a section's fields were found to be by what they show: nothing is written on the page.
42
+ const guessed = new WeakMap();
43
+ const guesses = new WeakMap();
44
+ // The run of text that shows a field's words in an element, where there is exactly such a run.
45
+ const runOf = new WeakMap();
46
+ // Every run that shows a field, by section and field, so all of them follow what is typed in one.
47
+ const shownIn = new WeakMap();
48
+ const squeeze = (text) => (text ?? '').replace(/\s+/g, '');
49
+ const guess = (section) => {
50
+ const known = guesses.get(section);
51
+ if (known)
52
+ return known;
53
+ const first = new Map();
54
+ guesses.set(section, first);
55
+ const shows = new Map();
56
+ shownIn.set(section, shows);
57
+ let values;
58
+ try {
59
+ values = JSON.parse(section.dataset['cmsValues'] ?? '[]');
60
+ }
61
+ catch {
62
+ return first;
63
+ }
64
+ if (!Array.isArray(values))
65
+ return first;
66
+ // Each element by all it says (the innermost of those that say the same), and by each run of words in it.
67
+ const whole = new Map();
68
+ const runs = new Map();
69
+ const pictures = [];
70
+ const add = (into, text, element) => {
71
+ if (text === '')
72
+ return;
73
+ const list = into.get(text) ?? [];
74
+ const last = list[list.length - 1];
75
+ if (last === element)
76
+ return;
77
+ if (last?.contains(element))
78
+ list[list.length - 1] = element;
79
+ else
80
+ list.push(element);
81
+ into.set(text, list);
82
+ };
83
+ for (const element of section.querySelectorAll('*')) {
84
+ if (element.closest('script, style, template, noscript'))
85
+ continue;
86
+ if (element.tagName === 'IMG')
87
+ pictures.push(element);
88
+ add(whole, squeeze(element.textContent), element);
89
+ for (const node of element.childNodes)
90
+ if (node.nodeType === 3)
91
+ add(runs, squeeze(node.nodeValue), element);
92
+ }
93
+ // Fields that say the same words share the elements that show them, in order.
94
+ const wanted = new Map();
95
+ const sources = [];
96
+ // Fields held as plain words, by what they say: only those can be typed on the page.
97
+ const plain = new Map();
98
+ for (const value of values) {
99
+ if (!Array.isArray(value) || typeof value[0] !== 'string' || typeof value[1] !== 'string')
100
+ continue;
101
+ const path = value[0];
102
+ if ([...section.querySelectorAll('[data-cms-field]')].some((marked) => marked.dataset['cmsField'] === path))
103
+ continue;
104
+ let text = value[1];
105
+ if (value[2] === 'html') {
106
+ const holder = doc.createElement('template');
107
+ holder.innerHTML = text;
108
+ text = holder.content.textContent ?? '';
109
+ }
110
+ else if (text.length > 1 && !/\s/.test(text)) {
111
+ sources.push([path, text]);
112
+ }
113
+ const words = squeeze(text);
114
+ if (words !== '')
115
+ wanted.set(words, [...(wanted.get(words) ?? []), path]);
116
+ if (value[2] !== 'html')
117
+ plain.set(path, words);
118
+ }
119
+ const claim = (element, path) => {
120
+ if (!first.has(path))
121
+ first.set(path, element);
122
+ if (guessed.has(element))
123
+ return false;
124
+ guessed.set(element, path);
125
+ return true;
126
+ };
127
+ for (const [words, paths] of wanted) {
128
+ const elements = whole.get(words) ?? runs.get(words) ?? [];
129
+ elements.forEach((element, at) => {
130
+ const path = paths[Math.min(paths.length - 1, Math.floor((at * paths.length) / elements.length))] ?? '';
131
+ if (!claim(element, path) || plain.get(path) !== words)
132
+ return;
133
+ const held = [...element.childNodes].filter((node) => node.nodeType === 3 && squeeze(node.nodeValue) === words);
134
+ const run = held.length === 1 ? held[0] : undefined;
135
+ if (!run)
136
+ return;
137
+ runOf.set(element, run);
138
+ shows.set(path, [...(shows.get(path) ?? []), run]);
139
+ });
140
+ }
141
+ // A picture is found by its name in its address: a whole part of it, not letters inside a longer name.
142
+ const names = (address) => {
143
+ try {
144
+ return decodeURIComponent(address);
145
+ }
146
+ catch {
147
+ return address;
148
+ }
149
+ };
150
+ for (const [path, name] of sources) {
151
+ if (first.has(path))
152
+ continue;
153
+ for (const picture of pictures) {
154
+ const address = names(picture.getAttribute('src') ?? '');
155
+ const at = address.indexOf(name);
156
+ if (at < 0)
157
+ continue;
158
+ const before = name.startsWith('/') || at === 0 ? '/' : (address[at - 1] ?? '');
159
+ const after = address[at + name.length] ?? '';
160
+ if ((before === '/' || before === '=') && (after === '' || './?&'.includes(after)))
161
+ claim(picture, path);
162
+ }
163
+ }
164
+ return first;
165
+ };
166
+ const markOf = (target) => {
167
+ if (!isElement(target))
168
+ return null;
169
+ const section = target.closest('[data-cms-section]');
170
+ const id = section?.dataset['cmsSection'];
171
+ if (!section || !id)
172
+ return null;
173
+ guess(section);
174
+ // A field counts only inside the section the pointer is in, and the nearest one is meant.
175
+ for (let element = target; element && element !== section; element = element.parentElement) {
176
+ const path = element.dataset?.['cmsField'] ?? guessed.get(element);
177
+ if (path)
178
+ return { element: element, section: id, field: path };
179
+ }
180
+ return { element: section, section: id };
181
+ };
182
+ const find = (section, field) => {
183
+ const found = [...doc.querySelectorAll('[data-cms-section]')].find((candidate) => candidate.dataset['cmsSection'] === section);
184
+ if (!found)
185
+ return null;
186
+ if (field !== undefined) {
187
+ const inner = [...found.querySelectorAll('[data-cms-field]')].find((candidate) => candidate.dataset['cmsField'] === field) ?? guess(found).get(field);
188
+ if (inner)
189
+ return { element: inner, section, field };
190
+ }
191
+ return { element: found, section };
192
+ };
193
+ // Layer.
194
+ // The editor's own orange and the ink that goes on it (`--brand-500` and `--brand-ink` in the design
195
+ // system's tokens), written out because the bridge can import nothing. What the editor draws on a
196
+ // page looks like the editor, whatever the page's own colours are.
197
+ const ACCENT = 'oklch(62.5% 0.22 38)';
198
+ const ACCENT_INK = 'oklch(14% 0 0)';
199
+ const layer = doc.createElement('div');
200
+ layer.setAttribute('data-cms-layer', '');
201
+ layer.setAttribute('aria-hidden', 'true');
202
+ Object.assign(layer.style, { position: 'fixed', inset: '0', pointerEvents: 'none', zIndex: '2147483647' });
203
+ const outline = (name, width) => {
204
+ const box = doc.createElement('div');
205
+ box.setAttribute('data-cms-outline', name);
206
+ Object.assign(box.style, { position: 'absolute', display: 'none', boxSizing: 'border-box', border: `${width} solid ${ACCENT}`, borderRadius: '4px' });
207
+ layer.append(box);
208
+ return box;
209
+ };
210
+ const boxes = { over: outline('over', '1px'), chosen: outline('chosen', '2px') };
211
+ const marks = { over: null, chosen: null };
212
+ const place = (box, mark) => {
213
+ // A mark whose element has left the page, or has no size, is not drawn.
214
+ const rect = mark?.element.isConnected ? mark.element.getBoundingClientRect() : null;
215
+ if (!rect || (rect.width === 0 && rect.height === 0)) {
216
+ box.style.display = 'none';
217
+ return;
218
+ }
219
+ Object.assign(box.style, { display: 'block', top: `${rect.top}px`, left: `${rect.left}px`, width: `${rect.width}px`, height: `${rect.height}px` });
220
+ };
221
+ let placeTools = () => undefined;
222
+ const draw = () => {
223
+ place(boxes.chosen, marks.chosen);
224
+ // One outline is enough where the pointer is over what is chosen.
225
+ place(boxes.over, marks.over && marks.over.element === marks.chosen?.element ? null : marks.over);
226
+ placeTools();
227
+ };
228
+ let waiting = false;
229
+ const redraw = () => {
230
+ if (waiting)
231
+ return;
232
+ waiting = true;
233
+ page.requestAnimationFrame(() => {
234
+ waiting = false;
235
+ draw();
236
+ });
237
+ };
238
+ doc.documentElement.append(layer);
239
+ page.addEventListener('scroll', redraw, { capture: true, passive: true });
240
+ page.addEventListener('resize', redraw);
241
+ // Pictures arrive and fonts change after the page is drawn, and move what is outlined.
242
+ if (typeof page.ResizeObserver === 'function')
243
+ new page.ResizeObserver(redraw).observe(doc.documentElement);
244
+ // Typing.
245
+ let typable = {};
246
+ let typing = null;
247
+ /** The run of text words can be typed into for a mark, where the editor and the page both allow it. */
248
+ const runFor = (mark) => {
249
+ if (!mark || mark.field === undefined || mark.element.hasAttribute('data-cms-field'))
250
+ return null;
251
+ const places = typable[mark.section];
252
+ if (!Array.isArray(places) || !places.includes(mark.field))
253
+ return null;
254
+ // A button takes a space for a press, and a field of a form is the visitor's to fill.
255
+ if (mark.element.closest('button, input, textarea, select, [contenteditable="false"]'))
256
+ return null;
257
+ const run = runOf.get(mark.element);
258
+ return run?.isConnected ? run : null;
259
+ };
260
+ // Where the words are in the run being typed into: the space a template leaves around them (before the next words of a heading) is not theirs.
261
+ const wordsAt = (now) => [Math.min(now.lead, now.run.length), Math.max(now.lead, now.run.length - now.trail)];
262
+ // Spaces in a row show as one, so they are held as one; a new line the field already had is kept.
263
+ const wordsOf = (run) => (run.nodeValue ?? '').replace(/[ \t\u00a0]+/g, ' ').trim();
264
+ const tellWords = (now) => {
265
+ const words = wordsOf(now.run);
266
+ const section = now.mark.element.closest('[data-cms-section]');
267
+ // The same field shown elsewhere in the section says the same.
268
+ for (const other of (section && shownIn.get(section)?.get(now.mark.field ?? '')) ?? [])
269
+ if (other !== now.run && other.isConnected)
270
+ other.nodeValue = words;
271
+ say({ type: 'words', id: now.mark.section, field: now.mark.field, words });
272
+ redraw();
273
+ };
274
+ const stopTyping = () => {
275
+ if (!typing)
276
+ return;
277
+ const { mark, was, outline } = typing;
278
+ typing = null;
279
+ mark.element.style.outline = outline;
280
+ if (was === null)
281
+ mark.element.removeAttribute('contenteditable');
282
+ else
283
+ mark.element.setAttribute('contenteditable', was);
284
+ redraw();
285
+ };
286
+ const startTyping = (mark, run) => {
287
+ if (typing?.mark.element === mark.element)
288
+ return;
289
+ stopTyping();
290
+ const text = run.nodeValue ?? '';
291
+ const lead = /^[ \t\n\r]*/.exec(text)?.[0].length ?? 0;
292
+ const trail = lead === text.length ? 0 : (/[ \t\n\r]*$/.exec(text)?.[0].length ?? 0);
293
+ typing = { mark, run, before: text, was: mark.element.getAttribute('contenteditable'), outline: mark.element.style.outline, lead, trail };
294
+ mark.element.setAttribute('contenteditable', 'plaintext-only');
295
+ // A browser that does not know plain text only is given the ordinary kind; what is pasted is made plain below.
296
+ if (mark.element.contentEditable !== 'plaintext-only')
297
+ mark.element.setAttribute('contenteditable', 'true');
298
+ // The layer's outline says where the typing goes: the browser's own would sit under it.
299
+ mark.element.style.outline = 'none';
300
+ redraw();
301
+ };
302
+ // The element is made ready as the pointer goes down, so the caret lands where it was pressed.
303
+ doc.addEventListener('mousedown', (event) => {
304
+ const mark = markOf(event.target);
305
+ const run = runFor(mark);
306
+ if (mark && run)
307
+ startTyping(mark, run);
308
+ else if (typing && !(isElement(event.target) && typing.mark.element.contains(event.target)))
309
+ stopTyping();
310
+ }, true);
311
+ // The caret stays in the run: an arrow or End that would carry it into other words of the element stops at the run's edge.
312
+ doc.addEventListener('selectionchange', () => {
313
+ const selection = page.getSelection();
314
+ if (!typing || !selection || selection.rangeCount === 0 || !typing.run.isConnected)
315
+ return;
316
+ const { run } = typing;
317
+ const range = selection.getRangeAt(0);
318
+ if (!typing.mark.element.contains(range.commonAncestorContainer))
319
+ return;
320
+ const [from, to] = wordsAt(typing);
321
+ const edge = (node, offset) => {
322
+ if (node === run)
323
+ return offset < from ? from : offset > to ? to : null;
324
+ const point = doc.createRange();
325
+ point.setStart(node, offset);
326
+ return point.comparePoint(run, 0) === -1 ? to : from;
327
+ };
328
+ const start = edge(range.startContainer, range.startOffset);
329
+ const end = edge(range.endContainer, range.endOffset);
330
+ if (start === null && end === null)
331
+ return;
332
+ selection.setBaseAndExtent(run, start ?? range.startOffset, run, end ?? range.endOffset);
333
+ });
334
+ doc.addEventListener('focusout', (event) => {
335
+ if (typing && event.target === typing.mark.element)
336
+ stopTyping();
337
+ });
338
+ // Only the run of text that shows the field may change: what else the element holds (an icon, other words) stays.
339
+ doc.addEventListener('beforeinput', (event) => {
340
+ if (!typing || !isElement(event.target) || !typing.mark.element.contains(event.target))
341
+ return;
342
+ const { run } = typing;
343
+ const kind = event.inputType;
344
+ if (kind === 'insertParagraph' || kind === 'insertLineBreak' || kind.startsWith('format') || kind.startsWith('history') || kind === 'insertFromDrop') {
345
+ event.preventDefault();
346
+ return;
347
+ }
348
+ // What the change would touch: as the browser says, or else what is selected.
349
+ const selection = page.getSelection();
350
+ const said = event.getTargetRanges();
351
+ const ranges = said.length > 0 ? said : selection && selection.rangeCount > 0 ? [selection.getRangeAt(0)] : [];
352
+ if (ranges.length !== 1 || !ranges[0]) {
353
+ event.preventDefault();
354
+ return;
355
+ }
356
+ // The part of the words inside it. A change that would reach outside them is kept to them, and one
357
+ // wholly outside (a key pressed before the caret was brought back) is made at their nearest end.
358
+ const [from, to] = wordsAt(typing);
359
+ const within = (node, offset) => {
360
+ if (node === run)
361
+ return Math.min(to, Math.max(from, offset));
362
+ const point = doc.createRange();
363
+ point.setStart(node, offset);
364
+ return point.comparePoint(run, 0) === -1 ? to : from;
365
+ };
366
+ let start = within(ranges[0].startContainer, ranges[0].startOffset);
367
+ let end = within(ranges[0].endContainer, ranges[0].endOffset);
368
+ // A browser that does not say how much a key would delete says only where the caret is: the reach is worked out here.
369
+ if (start === end && kind.startsWith('delete')) {
370
+ const text = run.data;
371
+ const pair = (at) => (at >= 0 && at < text.length - 1 && text.charCodeAt(at) >= 0xd800 && text.charCodeAt(at) <= 0xdbff ? 2 : 1);
372
+ if (kind.endsWith('Backward')) {
373
+ const word = text.slice(from, start).search(/\S+\s*$/);
374
+ start = kind.includes('Line') ? from : kind.includes('Word') ? from + Math.max(0, word) : Math.max(from, start - pair(start - 2));
375
+ }
376
+ else if (kind.endsWith('Forward')) {
377
+ const word = /^\s*\S+/.exec(text.slice(end, to))?.[0].length ?? 0;
378
+ end = kind.includes('Line') ? to : kind.includes('Word') ? end + word : Math.min(to, end + pair(end));
379
+ }
380
+ }
381
+ // The change is made here and never by the browser, which would tidy the spaces around the words and take an emptied run away.
382
+ event.preventDefault();
383
+ // What is pasted, or put in place of a word, goes in as plain words on one line.
384
+ const data = kind.startsWith('delete') ? '' : (event.data ?? event.dataTransfer?.getData('text/plain').replace(/\s+/g, ' '));
385
+ if (typeof data !== 'string' || (start === end && data === ''))
386
+ return;
387
+ // A space typed at either end of the words would be lost among the template's own, so it is one that shows.
388
+ const added = data === ' ' && (start === from || end === to) ? '\u00a0' : data;
389
+ run.replaceData(start, end - start, added);
390
+ selection?.collapse(run, start + added.length);
391
+ tellWords(typing);
392
+ }, true);
393
+ doc.addEventListener('input', (event) => {
394
+ if (typing && isElement(event.target) && typing.mark.element.contains(event.target) && typing.run.isConnected)
395
+ tellWords(typing);
396
+ }, true);
397
+ doc.addEventListener('keydown', (event) => {
398
+ if (!typing || event.isComposing)
399
+ return;
400
+ if (event.key !== 'Enter' && event.key !== 'Escape')
401
+ return;
402
+ event.preventDefault();
403
+ const now = typing;
404
+ // Escape puts back what the field said when the typing began.
405
+ if (event.key === 'Escape' && now.run.isConnected && now.run.nodeValue !== now.before) {
406
+ now.run.nodeValue = now.before;
407
+ tellWords(now);
408
+ }
409
+ now.mark.element.blur();
410
+ stopTyping();
411
+ }, true);
412
+ let tools = null;
413
+ // The section the bar is for: the one the pointer was last in, and it stays while the pointer is on the bar itself.
414
+ let tooled = null;
415
+ // Lucide's drawings, as the lines they are made of: the bridge can import nothing.
416
+ const DRAWN = {
417
+ up: ['m5 12 7-7 7 7', 'M12 19V5'],
418
+ down: ['M12 5v14', 'm19 12-7 7-7-7'],
419
+ duplicate: ['M8 8h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2z', 'M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2'],
420
+ remove: ['M3 6h18', 'M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6', 'M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2', 'M10 11v6', 'M14 11v6'],
421
+ add: ['M5 12h14', 'M12 5v14'],
422
+ drag: ['M9 5h.01', 'M9 12h.01', 'M9 19h.01', 'M15 5h.01', 'M15 12h.01', 'M15 19h.01'],
423
+ };
424
+ const drawing = (name) => {
425
+ const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');
426
+ for (const [key, value] of Object.entries({ viewBox: '0 0 24 24', width: '16', height: '16', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }))
427
+ svg.setAttribute(key, value);
428
+ for (const line of DRAWN[name] ?? []) {
429
+ const path = doc.createElementNS('http://www.w3.org/2000/svg', 'path');
430
+ path.setAttribute('d', line);
431
+ svg.append(path);
432
+ }
433
+ return svg;
434
+ };
435
+ const FONT = 'system-ui, sans-serif';
436
+ const bar = doc.createElement('div');
437
+ bar.setAttribute('data-cms-tools', '');
438
+ Object.assign(bar.style, {
439
+ position: 'absolute',
440
+ display: 'none',
441
+ alignItems: 'center',
442
+ gap: '2px',
443
+ padding: '4px',
444
+ borderRadius: '8px',
445
+ background: 'CanvasText',
446
+ color: 'Canvas',
447
+ font: `500 12px/1 ${FONT}`,
448
+ boxShadow: '0 4px 12px rgb(0 0 0 / 0.25)',
449
+ pointerEvents: 'auto',
450
+ });
451
+ const grip = doc.createElement('span');
452
+ grip.setAttribute('data-cms-tool', 'drag');
453
+ Object.assign(grip.style, { display: 'grid', placeItems: 'center', width: '20px', height: '28px', cursor: 'grab' });
454
+ grip.append(drawing('drag'));
455
+ bar.append(grip);
456
+ const named = doc.createElement('span');
457
+ Object.assign(named.style, { padding: '0 8px 0 2px', cursor: 'grab', maxWidth: '12rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' });
458
+ bar.append(named);
459
+ const press = (button, action) => {
460
+ // The pointer going down must not take the caret from the page or start a selection.
461
+ button.addEventListener('mousedown', (event) => event.preventDefault());
462
+ button.addEventListener('click', () => {
463
+ const id = tooled?.dataset['cmsSection'];
464
+ if (id && !button.disabled)
465
+ say({ type: 'act', id, action });
466
+ });
467
+ };
468
+ const tool = (action) => {
469
+ const button = doc.createElement('button');
470
+ button.type = 'button';
471
+ // The bar is for a pointer: the same things are in the form for a keyboard and a screen reader.
472
+ button.tabIndex = -1;
473
+ button.setAttribute('data-cms-tool', action);
474
+ Object.assign(button.style, { display: 'grid', placeItems: 'center', width: '28px', height: '28px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
475
+ button.append(drawing(action));
476
+ press(button, action);
477
+ bar.append(button);
478
+ return button;
479
+ };
480
+ const buttons = { up: tool('up'), down: tool('down'), duplicate: tool('duplicate'), remove: tool('remove') };
481
+ const adder = (action) => {
482
+ const button = doc.createElement('button');
483
+ button.type = 'button';
484
+ button.tabIndex = -1;
485
+ button.setAttribute('data-cms-tool', action);
486
+ Object.assign(button.style, {
487
+ position: 'absolute',
488
+ display: 'none',
489
+ alignItems: 'center',
490
+ gap: '4px',
491
+ height: '28px',
492
+ padding: '0 12px 0 8px',
493
+ border: '0',
494
+ borderRadius: '14px',
495
+ background: ACCENT,
496
+ color: ACCENT_INK,
497
+ font: `600 12px/1 ${FONT}`,
498
+ boxShadow: '0 4px 12px rgb(0 0 0 / 0.25)',
499
+ transform: 'translate(-50%, -50%)',
500
+ whiteSpace: 'nowrap',
501
+ cursor: 'pointer',
502
+ pointerEvents: 'auto',
503
+ });
504
+ button.append(drawing('add'), doc.createElement('span'));
505
+ press(button, action);
506
+ layer.append(button);
507
+ return button;
508
+ };
509
+ const adders = { addBefore: adder('addBefore'), addAfter: adder('addAfter') };
510
+ layer.append(bar);
511
+ const word = (value) => (typeof value === 'string' ? value : '');
512
+ placeTools = () => {
513
+ const hide = () => {
514
+ bar.style.display = 'none';
515
+ adders.addBefore.style.display = 'none';
516
+ adders.addAfter.style.display = 'none';
517
+ };
518
+ // While words are typed, nothing sits over them.
519
+ const section = typing || drag?.moved ? null : tooled?.isConnected ? tooled : null;
520
+ const about = section && tools?.sections[section.dataset['cmsSection'] ?? ''];
521
+ if (!section || !tools || !about)
522
+ return hide();
523
+ const rect = section.getBoundingClientRect();
524
+ if (rect.bottom <= 0 || rect.top >= page.innerHeight || (rect.width === 0 && rect.height === 0))
525
+ return hide();
526
+ named.textContent = word(about.name);
527
+ const able = { up: about.up === true, down: about.down === true, duplicate: about.copy === true, remove: true };
528
+ for (const action of ['up', 'down', 'duplicate', 'remove']) {
529
+ const button = buttons[action];
530
+ button.title = word(tools.labels[action]);
531
+ button.disabled = !able[action];
532
+ button.style.opacity = able[action] ? '1' : '0.4';
533
+ button.style.cursor = able[action] ? 'pointer' : 'default';
534
+ }
535
+ // At the section's top corner, and at the top of the page while the section's own top is above it.
536
+ Object.assign(bar.style, { display: 'flex', top: `${Math.min(Math.max(rect.top, 0) + 12, Math.max(rect.bottom - 44, 0))}px`, left: 'auto', right: `${Math.max(page.innerWidth - rect.right, 0) + 12}px` });
537
+ for (const [action, edge] of [['addBefore', rect.top], ['addAfter', rect.bottom]]) {
538
+ const button = adders[action];
539
+ // An edge that is off the page, or a page that takes no more sections, has no button.
540
+ const shown = about.add === true && edge >= 14 && edge <= page.innerHeight - 14;
541
+ button.style.display = shown ? 'flex' : 'none';
542
+ if (!shown)
543
+ continue;
544
+ if (button.lastElementChild)
545
+ button.lastElementChild.textContent = word(tools.labels['add']);
546
+ button.title = word(tools.labels[action]);
547
+ Object.assign(button.style, { top: `${edge}px`, left: `${rect.left + rect.width / 2}px` });
548
+ }
549
+ };
550
+ // Dragging a section by its bar: a line shows where it would land, and letting go says so to the editor.
551
+ const line = doc.createElement('div');
552
+ line.setAttribute('data-cms-drop', '');
553
+ Object.assign(line.style, { position: 'absolute', display: 'none', left: '0', right: '0', height: '4px', marginTop: '-2px', borderRadius: '2px', background: ACCENT, boxShadow: '0 0 0 1px Canvas' });
554
+ layer.append(line);
555
+ let drag = null;
556
+ const movable = () => [...doc.querySelectorAll('[data-cms-section]')].filter((section) => tools?.sections[section.dataset['cmsSection'] ?? ''] !== undefined);
557
+ const aim = () => {
558
+ if (!drag)
559
+ return;
560
+ const sections = movable();
561
+ const at = sections.findIndex((section) => {
562
+ const rect = section.getBoundingClientRect();
563
+ return drag !== null && drag.y < rect.top + rect.height / 2;
564
+ });
565
+ const target = at < 0 ? undefined : sections[at];
566
+ const own = sections.findIndex((section) => section.dataset['cmsSection'] === drag?.id);
567
+ const to = at < 0 ? sections.length : at;
568
+ // Before itself, or before the one after it, is where it is already.
569
+ drag.before = own < 0 || to === own || to === own + 1 ? undefined : (target?.dataset['cmsSection'] ?? null);
570
+ const last = sections[sections.length - 1];
571
+ const edge = target ? target.getBoundingClientRect().top : (last?.getBoundingClientRect().bottom ?? 0);
572
+ Object.assign(line.style, { display: drag.before === undefined ? 'none' : 'block', top: `${Math.min(Math.max(edge, 2), page.innerHeight - 2)}px` });
573
+ };
574
+ const endDrag = (drop) => {
575
+ if (!drag)
576
+ return;
577
+ const { id, before, moved } = drag;
578
+ drag = null;
579
+ line.style.display = 'none';
580
+ Object.assign(layer.style, { pointerEvents: 'none', cursor: '' });
581
+ if (drop && moved && before !== undefined)
582
+ say({ type: 'move', id, before });
583
+ draw();
584
+ };
585
+ // Near the top or the bottom of the page, it scrolls to bring the rest within reach.
586
+ const creep = () => {
587
+ if (!drag)
588
+ return;
589
+ const by = drag.y < 72 ? -14 : drag.y > page.innerHeight - 72 ? 14 : 0;
590
+ if (by !== 0 && drag.moved) {
591
+ page.scrollBy(0, by);
592
+ aim();
593
+ }
594
+ page.setTimeout(creep, 16);
595
+ };
596
+ for (const handle of [grip, named]) {
597
+ handle.addEventListener('mousedown', (event) => {
598
+ const id = tooled?.dataset['cmsSection'];
599
+ if (event.button !== 0 || !id || movable().length < 2)
600
+ return;
601
+ event.preventDefault();
602
+ drag = { id, from: event.clientY, y: event.clientY, before: undefined, moved: false };
603
+ // The layer takes the pointer while it drags, so nothing on the page answers to it.
604
+ Object.assign(layer.style, { pointerEvents: 'auto', cursor: 'grabbing' });
605
+ page.setTimeout(creep, 16);
606
+ });
607
+ }
608
+ doc.addEventListener('mousemove', (event) => {
609
+ if (!drag)
610
+ return;
611
+ drag.y = event.clientY;
612
+ // A few pixels of give, so a press that was only a press moves nothing.
613
+ if (Math.abs(drag.y - drag.from) > 4)
614
+ drag.moved = true;
615
+ if (drag.moved)
616
+ aim();
617
+ }, true);
618
+ doc.addEventListener('mouseup', () => endDrag(true), true);
619
+ doc.documentElement.addEventListener('mouseleave', () => endDrag(false));
620
+ doc.addEventListener('keydown', (event) => {
621
+ if (drag && event.key === 'Escape')
622
+ endDrag(false);
623
+ }, true);
624
+ // Events.
625
+ doc.addEventListener('mouseover', (event) => {
626
+ // Over the layer's own bar and buttons, what they are for stays as it was.
627
+ if (isElement(event.target) && layer.contains(event.target))
628
+ return;
629
+ marks.over = markOf(event.target);
630
+ if (marks.over)
631
+ marks.over.element.style.cursor = runFor(marks.over) ? 'text' : 'pointer';
632
+ tooled = isElement(event.target) ? event.target.closest('[data-cms-section]') : null;
633
+ draw();
634
+ });
635
+ doc.documentElement.addEventListener('mouseleave', () => {
636
+ marks.over = null;
637
+ tooled = null;
638
+ draw();
639
+ });
640
+ // Nothing on the page goes anywhere: a click chooses what it is on.
641
+ doc.addEventListener('click', (event) => {
642
+ event.preventDefault();
643
+ // A press on the layer's own bar is that button's business.
644
+ if (isElement(event.target) && layer.contains(event.target))
645
+ return;
646
+ const mark = markOf(event.target);
647
+ if (!mark)
648
+ return;
649
+ marks.chosen = mark;
650
+ draw();
651
+ say({ type: 'section', id: mark.section, ...(mark.field !== undefined && { field: mark.field }) });
652
+ }, true);
653
+ doc.addEventListener('submit', (event) => event.preventDefault(), true);
654
+ page.addEventListener('message', (event) => {
655
+ if (event.origin !== origin || event.source !== page.parent || event.data?.source !== SOURCE)
656
+ return;
657
+ if (event.data.type === 'typable') {
658
+ const places = event.data.places;
659
+ typable = typeof places === 'object' && places !== null ? places : {};
660
+ return;
661
+ }
662
+ if (event.data.type === 'tools') {
663
+ const said = event.data;
664
+ const isRecord = (value) => typeof value === 'object' && value !== null;
665
+ tools = isRecord(said.labels) && isRecord(said.sections) ? { labels: said.labels, sections: said.sections } : null;
666
+ draw();
667
+ return;
668
+ }
669
+ if (event.data.type !== 'show' || typeof event.data.id !== 'string')
670
+ return;
671
+ // While words are typed into a section, the outline stays on the field they go into.
672
+ if (typing?.mark.section === event.data.id)
673
+ return;
674
+ const mark = find(event.data.id, typeof event.data.field === 'string' ? event.data.field : undefined);
675
+ if (!mark)
676
+ return;
677
+ marks.chosen = mark;
678
+ const rect = mark.element.getBoundingClientRect();
679
+ // What is already in view stays where it is: the page does not jump while someone types.
680
+ if (rect.bottom <= 0 || rect.top >= page.innerHeight) {
681
+ // Room for a header that stays at the top of the page.
682
+ mark.element.style.scrollMarginTop = '6rem';
683
+ mark.element.scrollIntoView({ block: 'start' });
684
+ }
685
+ draw();
686
+ });
687
+ // Scroll.
688
+ const key = `velocity-cms:scroll:${page.location.pathname}`;
689
+ try {
690
+ const kept = Number(page.sessionStorage.getItem(key));
691
+ if (kept > 0)
692
+ page.scrollTo({ top: kept, behavior: 'instant' });
693
+ page.addEventListener('pagehide', () => page.sessionStorage.setItem(key, String(page.scrollY)));
694
+ }
695
+ catch {
696
+ // A page that may not keep anything starts at the top.
697
+ }
698
+ say({ type: 'ready' });
699
+ }
700
+ /** The bridge as the page is sent it. */
701
+ export const PREVIEW_BRIDGE_SCRIPT = `(${previewBridge.toString()})(window);\n`;
702
+ //# sourceMappingURL=preview-bridge.js.map