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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/app-dist/assets/{RichTextEditor-BiKJJtkz.js → RichTextEditor-BpltDhwX.js} +1 -1
  2. package/app-dist/assets/index-Bx7Xh90l.js +80 -0
  3. package/app-dist/assets/index-DLXIqdLb.css +2 -0
  4. package/app-dist/index.html +5 -3
  5. package/dist/app/AdminLayout.d.ts.map +1 -1
  6. package/dist/app/AdminLayout.js +1 -1
  7. package/dist/app/AdminLayout.js.map +1 -1
  8. package/dist/app/paths.d.ts +2 -0
  9. package/dist/app/paths.d.ts.map +1 -1
  10. package/dist/app/paths.js +2 -0
  11. package/dist/app/paths.js.map +1 -1
  12. package/dist/client/queries.d.ts.map +1 -1
  13. package/dist/client/queries.js +32 -7
  14. package/dist/client/queries.js.map +1 -1
  15. package/dist/fields/BlocksControl.d.ts +6 -0
  16. package/dist/fields/BlocksControl.d.ts.map +1 -1
  17. package/dist/fields/BlocksControl.js +301 -89
  18. package/dist/fields/BlocksControl.js.map +1 -1
  19. package/dist/fields/SiteImagePicker.d.ts +22 -0
  20. package/dist/fields/SiteImagePicker.d.ts.map +1 -0
  21. package/dist/fields/SiteImagePicker.js +42 -0
  22. package/dist/fields/SiteImagePicker.js.map +1 -0
  23. package/dist/fields/block-icons.d.ts.map +1 -1
  24. package/dist/fields/block-icons.js +3 -1
  25. package/dist/fields/block-icons.js.map +1 -1
  26. package/dist/fields/carry.d.ts +19 -0
  27. package/dist/fields/carry.d.ts.map +1 -0
  28. package/dist/fields/carry.js +61 -0
  29. package/dist/fields/carry.js.map +1 -0
  30. package/dist/fields/controls.d.ts.map +1 -1
  31. package/dist/fields/controls.js +82 -58
  32. package/dist/fields/controls.js.map +1 -1
  33. package/dist/fields/field-control.d.ts +80 -0
  34. package/dist/fields/field-control.d.ts.map +1 -1
  35. package/dist/fields/field-control.js.map +1 -1
  36. package/dist/fields/page-focus.d.ts +32 -3
  37. package/dist/fields/page-focus.d.ts.map +1 -1
  38. package/dist/fields/page-focus.js +55 -1
  39. package/dist/fields/page-focus.js.map +1 -1
  40. package/dist/lib/open-site.d.ts +6 -0
  41. package/dist/lib/open-site.d.ts.map +1 -0
  42. package/dist/lib/open-site.js +8 -0
  43. package/dist/lib/open-site.js.map +1 -0
  44. package/dist/lib/rich-from-html.d.ts +9 -0
  45. package/dist/lib/rich-from-html.d.ts.map +1 -0
  46. package/dist/lib/rich-from-html.js +129 -0
  47. package/dist/lib/rich-from-html.js.map +1 -0
  48. package/dist/lib/sittings.d.ts +16 -0
  49. package/dist/lib/sittings.d.ts.map +1 -0
  50. package/dist/lib/sittings.js +29 -0
  51. package/dist/lib/sittings.js.map +1 -0
  52. package/dist/lib/use-history.d.ts +24 -0
  53. package/dist/lib/use-history.d.ts.map +1 -0
  54. package/dist/lib/use-history.js +48 -0
  55. package/dist/lib/use-history.js.map +1 -0
  56. package/dist/lib/use-narrow.d.ts +5 -0
  57. package/dist/lib/use-narrow.d.ts.map +1 -0
  58. package/dist/lib/use-narrow.js +19 -0
  59. package/dist/lib/use-narrow.js.map +1 -0
  60. package/dist/lib/use-save-key.d.ts +15 -0
  61. package/dist/lib/use-save-key.d.ts.map +1 -0
  62. package/dist/lib/use-save-key.js +27 -0
  63. package/dist/lib/use-save-key.js.map +1 -0
  64. package/dist/lib/use-undo-keys.d.ts +14 -0
  65. package/dist/lib/use-undo-keys.d.ts.map +1 -0
  66. package/dist/lib/use-undo-keys.js +46 -0
  67. package/dist/lib/use-undo-keys.js.map +1 -0
  68. package/dist/messages/en.d.ts +29 -1
  69. package/dist/messages/en.d.ts.map +1 -1
  70. package/dist/messages/en.js +29 -1
  71. package/dist/messages/en.js.map +1 -1
  72. package/dist/page-bridge/preview-bridge.d.ts +3 -3
  73. package/dist/page-bridge/preview-bridge.d.ts.map +1 -1
  74. package/dist/page-bridge/preview-bridge.js +868 -33
  75. package/dist/page-bridge/preview-bridge.js.map +1 -1
  76. package/dist/screens/Contact/ContactScreen.js +1 -1
  77. package/dist/screens/Contact/ContactScreen.js.map +1 -1
  78. package/dist/screens/Contacts/ContactsScreen.js +2 -2
  79. package/dist/screens/Contacts/ContactsScreen.js.map +1 -1
  80. package/dist/screens/ContentList/ContentListScreen.d.ts.map +1 -1
  81. package/dist/screens/ContentList/ContentListScreen.js +5 -2
  82. package/dist/screens/ContentList/ContentListScreen.js.map +1 -1
  83. package/dist/screens/ContentType/ContentTypeScreen.js +1 -1
  84. package/dist/screens/ContentType/ContentTypeScreen.js.map +1 -1
  85. package/dist/screens/EntryEditor/EntryEditorScreen.d.ts.map +1 -1
  86. package/dist/screens/EntryEditor/EntryEditorScreen.js +5 -3
  87. package/dist/screens/EntryEditor/EntryEditorScreen.js.map +1 -1
  88. package/dist/screens/EntryEditor/EntryForm.d.ts +2 -0
  89. package/dist/screens/EntryEditor/EntryForm.d.ts.map +1 -1
  90. package/dist/screens/EntryEditor/EntryForm.js +164 -19
  91. package/dist/screens/EntryEditor/EntryForm.js.map +1 -1
  92. package/dist/screens/EntryEditor/HistoryDialog.d.ts +2 -1
  93. package/dist/screens/EntryEditor/HistoryDialog.d.ts.map +1 -1
  94. package/dist/screens/EntryEditor/HistoryDialog.js +24 -5
  95. package/dist/screens/EntryEditor/HistoryDialog.js.map +1 -1
  96. package/dist/screens/EntryEditor/PagePane.d.ts +12 -2
  97. package/dist/screens/EntryEditor/PagePane.d.ts.map +1 -1
  98. package/dist/screens/EntryEditor/PagePane.js +54 -19
  99. package/dist/screens/EntryEditor/PagePane.js.map +1 -1
  100. package/dist/screens/EntryEditor/ThemeCard.d.ts +32 -0
  101. package/dist/screens/EntryEditor/ThemeCard.d.ts.map +1 -0
  102. package/dist/screens/EntryEditor/ThemeCard.js +67 -0
  103. package/dist/screens/EntryEditor/ThemeCard.js.map +1 -0
  104. package/dist/screens/Home/HomeScreen.d.ts.map +1 -1
  105. package/dist/screens/Home/HomeScreen.js +8 -3
  106. package/dist/screens/Home/HomeScreen.js.map +1 -1
  107. package/package.json +5 -5
  108. package/app-dist/assets/index-BgVjqwy6.js +0 -80
  109. package/app-dist/assets/index-BvWFILf6.css +0 -2
@@ -8,9 +8,9 @@
8
8
  * - messaging: what the page and the editor say to each other, and to nobody else
9
9
  * - marks: which section, and which field of it, an element of the page belongs to
10
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
11
+ * - tools: a small bar on the section the pointer is in (move, copy, remove), a button at each
12
+ * of its edges that adds a section there, and a button on a picture or a link the editor can
13
+ * change, all in the layer and all said to the editor, which makes the change
14
14
  * - events: what a pointer over the page and a click on it mean
15
15
  * - typing: words typed straight into a field on the page, said to the editor as they are typed
16
16
  * - scroll: the page stays where it was when it is drawn again
@@ -46,6 +46,8 @@ export function previewBridge(page) {
46
46
  // Every run that shows a field, by section and field, so all of them follow what is typed in one.
47
47
  const shownIn = new WeakMap();
48
48
  const squeeze = (text) => (text ?? '').replace(/\s+/g, '');
49
+ // What a section holds itself: a section inside it (a column's) answers for its own.
50
+ const within = (section, selector) => [...section.querySelectorAll(selector)].filter((element) => element.closest('[data-cms-section]') === section);
49
51
  const guess = (section) => {
50
52
  const known = guesses.get(section);
51
53
  if (known)
@@ -80,7 +82,7 @@ export function previewBridge(page) {
80
82
  list.push(element);
81
83
  into.set(text, list);
82
84
  };
83
- for (const element of section.querySelectorAll('*')) {
85
+ for (const element of within(section, '*')) {
84
86
  if (element.closest('script, style, template, noscript'))
85
87
  continue;
86
88
  if (element.tagName === 'IMG')
@@ -99,7 +101,7 @@ export function previewBridge(page) {
99
101
  if (!Array.isArray(value) || typeof value[0] !== 'string' || typeof value[1] !== 'string')
100
102
  continue;
101
103
  const path = value[0];
102
- if ([...section.querySelectorAll('[data-cms-field]')].some((marked) => marked.dataset['cmsField'] === path))
104
+ if (within(section, '[data-cms-field]').some((marked) => marked.dataset['cmsField'] === path))
103
105
  continue;
104
106
  let text = value[1];
105
107
  if (value[2] === 'html') {
@@ -170,6 +172,9 @@ export function previewBridge(page) {
170
172
  const id = section?.dataset['cmsSection'];
171
173
  if (!section || !id)
172
174
  return null;
175
+ // Everything inside text being written is that text, whatever was written into it since.
176
+ if (writing?.mark.element.contains(target))
177
+ return writing.mark;
173
178
  guess(section);
174
179
  // A field counts only inside the section the pointer is in, and the nearest one is meant.
175
180
  for (let element = target; element && element !== section; element = element.parentElement) {
@@ -184,7 +189,7 @@ export function previewBridge(page) {
184
189
  if (!found)
185
190
  return null;
186
191
  if (field !== undefined) {
187
- const inner = [...found.querySelectorAll('[data-cms-field]')].find((candidate) => candidate.dataset['cmsField'] === field) ?? guess(found).get(field);
192
+ const inner = within(found, '[data-cms-field]').find((candidate) => candidate.dataset['cmsField'] === field) ?? guess(found).get(field);
188
193
  if (inner)
189
194
  return { element: inner, section, field };
190
195
  }
@@ -196,6 +201,19 @@ export function previewBridge(page) {
196
201
  // page looks like the editor, whatever the page's own colours are.
197
202
  const ACCENT = 'oklch(62.5% 0.22 38)';
198
203
  const ACCENT_INK = 'oklch(14% 0 0)';
204
+ // The editor may show the page smaller than it is, so a wide page fits a narrow pane. What the
205
+ // editor draws for a pointer (bars and buttons) is then drawn that much larger, so it is the
206
+ // size it always is on the person's screen. `grow` is how much, and a place for such a thing is
207
+ // written with `at`, since the growing takes its place along.
208
+ let grow = 1;
209
+ const at = (px) => `${px / grow}px`;
210
+ const grown = [];
211
+ const grows = (element) => {
212
+ grown.push(element);
213
+ if (grow !== 1)
214
+ element.style.setProperty('zoom', String(grow));
215
+ return element;
216
+ };
199
217
  const layer = doc.createElement('div');
200
218
  layer.setAttribute('data-cms-layer', '');
201
219
  layer.setAttribute('aria-hidden', 'true');
@@ -287,6 +305,7 @@ export function previewBridge(page) {
287
305
  if (typing?.mark.element === mark.element)
288
306
  return;
289
307
  stopTyping();
308
+ stopWriting();
290
309
  const text = run.nodeValue ?? '';
291
310
  const lead = /^[ \t\n\r]*/.exec(text)?.[0].length ?? 0;
292
311
  const trail = lead === text.length ? 0 : (/[ \t\n\r]*$/.exec(text)?.[0].length ?? 0);
@@ -409,6 +428,152 @@ export function previewBridge(page) {
409
428
  now.mark.element.blur();
410
429
  stopTyping();
411
430
  }, true);
431
+ let writing = null;
432
+ // The words a link's address is being asked for, while the editor asks.
433
+ let asking = null;
434
+ // A link as the field holds it: without what a preview adds to links that stay on the site.
435
+ const withoutPreview = (href) => /^[a-z][a-z0-9+.-]*:/i.test(href) ? href : href.replace(/([?&])preview=[^&#]*(&)?/, (_all, lead, more) => (more ? lead : ''));
436
+ const htmlOf = (element) => {
437
+ const copy = element.cloneNode(true);
438
+ for (const anchor of copy.querySelectorAll('a[href]'))
439
+ anchor.setAttribute('href', withoutPreview(anchor.getAttribute('href') ?? ''));
440
+ return copy.innerHTML;
441
+ };
442
+ /** The element that shows a field's formatted text exactly as it is held, where the editor lets it be written on the page. */
443
+ const holderFor = (mark) => {
444
+ if (!mark || mark.field === undefined || mark.element.hasAttribute('data-cms-field'))
445
+ return null;
446
+ const places = typable[mark.section];
447
+ if (!Array.isArray(places) || !places.includes(mark.field))
448
+ return null;
449
+ const section = mark.element.closest('[data-cms-section]');
450
+ if (!section)
451
+ return null;
452
+ let held = null;
453
+ try {
454
+ const values = JSON.parse(section.dataset['cmsValues'] ?? '[]');
455
+ const value = (Array.isArray(values) ? values : []).find((candidate) => Array.isArray(candidate) && candidate[0] === mark.field && candidate[2] === 'html');
456
+ if (typeof value?.[1] === 'string') {
457
+ // Read as a browser reads it, and never drawn: nothing in it runs.
458
+ const read = doc.createElement('template');
459
+ read.innerHTML = value[1];
460
+ held = read.innerHTML;
461
+ }
462
+ }
463
+ catch {
464
+ return null;
465
+ }
466
+ if (held === null)
467
+ return null;
468
+ for (let element = mark.element; element && element !== section; element = element.parentElement) {
469
+ if (htmlOf(element) === held)
470
+ return element.closest('button, input, textarea, select, [contenteditable="false"]') ? null : element;
471
+ }
472
+ return null;
473
+ };
474
+ let placeFormat = () => undefined;
475
+ const tellWriting = (now) => {
476
+ say({ type: 'words', id: now.mark.section, field: now.mark.field, words: htmlOf(now.mark.element) });
477
+ redraw();
478
+ };
479
+ const stopWriting = () => {
480
+ if (!writing)
481
+ return;
482
+ const { mark, was, outline } = writing;
483
+ writing = null;
484
+ asking = null;
485
+ mark.element.style.outline = outline;
486
+ if (was === null)
487
+ mark.element.removeAttribute('contenteditable');
488
+ else
489
+ mark.element.setAttribute('contenteditable', was);
490
+ redraw();
491
+ };
492
+ const startWriting = (mark) => {
493
+ if (writing?.mark.element === mark.element)
494
+ return;
495
+ stopTyping();
496
+ stopWriting();
497
+ writing = { mark, before: mark.element.innerHTML, was: mark.element.getAttribute('contenteditable'), outline: mark.element.style.outline };
498
+ mark.element.setAttribute('contenteditable', 'true');
499
+ mark.element.style.outline = 'none';
500
+ marks.chosen = mark;
501
+ redraw();
502
+ };
503
+ doc.addEventListener('mousedown', (event) => {
504
+ if (isElement(event.target) && (layer.contains(event.target) || writing?.mark.element.contains(event.target)))
505
+ return;
506
+ const mark = markOf(event.target);
507
+ const holder = holderFor(mark);
508
+ if (mark && holder && mark.field !== undefined)
509
+ startWriting({ element: holder, section: mark.section, field: mark.field });
510
+ else
511
+ stopWriting();
512
+ }, true);
513
+ doc.addEventListener('focusout', (event) => {
514
+ // While the editor asks where a link leads, the page is left and come back to.
515
+ if (writing && !asking && event.target === writing.mark.element)
516
+ stopWriting();
517
+ });
518
+ doc.addEventListener('beforeinput', (event) => {
519
+ // Nothing is dragged into the text from elsewhere on the page.
520
+ if (writing && isElement(event.target) && writing.mark.element.contains(event.target) && event.inputType === 'insertFromDrop')
521
+ event.preventDefault();
522
+ }, true);
523
+ doc.addEventListener('paste', (event) => {
524
+ if (!writing || !isElement(event.target) || !writing.mark.element.contains(event.target))
525
+ return;
526
+ // What is pasted goes in as words alone: the markup of wherever it came from stays there.
527
+ event.preventDefault();
528
+ const words = event.clipboardData?.getData('text/plain') ?? '';
529
+ if (words !== '')
530
+ doc.execCommand('insertText', false, words);
531
+ }, true);
532
+ doc.addEventListener('input', (event) => {
533
+ if (writing && isElement(event.target) && writing.mark.element.contains(event.target))
534
+ tellWriting(writing);
535
+ }, true);
536
+ doc.addEventListener('keydown', (event) => {
537
+ if (!writing || event.isComposing || event.key !== 'Escape')
538
+ return;
539
+ event.preventDefault();
540
+ const now = writing;
541
+ // Escape puts back what the field said when the writing began.
542
+ if (now.mark.element.innerHTML !== now.before) {
543
+ now.mark.element.innerHTML = now.before;
544
+ tellWriting(now);
545
+ }
546
+ stopWriting();
547
+ now.mark.element.blur();
548
+ }, true);
549
+ doc.addEventListener('selectionchange', () => placeFormat());
550
+ // Undo and redo are the form's: the page says the keys were pressed and takes nothing back
551
+ // itself. Formatted text being written is the browser's to take back, as it is to write.
552
+ doc.addEventListener('keydown', (event) => {
553
+ if (writing || event.isComposing || event.altKey || !(event.metaKey || event.ctrlKey))
554
+ return;
555
+ const key = event.key.toLowerCase();
556
+ const asked = key === 'z' ? (event.shiftKey ? 'redo' : 'undo') : key === 'y' && event.ctrlKey && !event.shiftKey ? 'redo' : null;
557
+ if (asked === null)
558
+ return;
559
+ // A field of a form on the page is the visitor's, and the browser's to take back.
560
+ if (!typing && isElement(event.target) && event.target.closest('input, textarea, select, [contenteditable]'))
561
+ return;
562
+ event.preventDefault();
563
+ if (typing) {
564
+ typing.mark.element.blur();
565
+ stopTyping();
566
+ }
567
+ say({ type: asked });
568
+ }, true);
569
+ // Saving is the form's too: the page says the keys were pressed, and the browser's own answer
570
+ // to them (saving the page as a file) is stopped. What is being typed is already in the form.
571
+ doc.addEventListener('keydown', (event) => {
572
+ if (event.isComposing || event.altKey || event.shiftKey || !(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== 's')
573
+ return;
574
+ event.preventDefault();
575
+ say({ type: 'save' });
576
+ }, true);
412
577
  let tools = null;
413
578
  // 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
579
  let tooled = null;
@@ -419,6 +584,10 @@ export function previewBridge(page) {
419
584
  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
585
  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
586
  add: ['M5 12h14', 'M12 5v14'],
587
+ picture: ['M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z', 'M11 9a2 2 0 1 1-4 0 2 2 0 0 1 4 0z', 'm21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21'],
588
+ link: ['M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71', 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'],
589
+ bold: ['M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8'],
590
+ italic: ['M19 4h-9', 'M14 20H5', 'M15 4 9 20'],
422
591
  drag: ['M9 5h.01', 'M9 12h.01', 'M9 19h.01', 'M15 5h.01', 'M15 12h.01', 'M15 19h.01'],
423
592
  };
424
593
  const drawing = (name) => {
@@ -433,7 +602,21 @@ export function previewBridge(page) {
433
602
  return svg;
434
603
  };
435
604
  const FONT = 'system-ui, sans-serif';
436
- const bar = doc.createElement('div');
605
+ /** Where what a site keeps at the top of its window ends (a header that stays as the page scrolls), or 0. */
606
+ const kept = () => {
607
+ if (typeof doc.elementFromPoint !== 'function')
608
+ return 0;
609
+ for (let element = doc.elementFromPoint(page.innerWidth / 2, 2); element && element !== doc.body && element !== doc.documentElement; element = element.parentElement) {
610
+ const position = page.getComputedStyle(element).position;
611
+ if (position !== 'fixed' && position !== 'sticky')
612
+ continue;
613
+ const rect = element.getBoundingClientRect();
614
+ // Only a strip at the top counts: something that covers the window is no header.
615
+ return rect.top <= 2 && rect.bottom < page.innerHeight / 3 ? rect.bottom : 0;
616
+ }
617
+ return 0;
618
+ };
619
+ const bar = grows(doc.createElement('div'));
437
620
  bar.setAttribute('data-cms-tools', '');
438
621
  Object.assign(bar.style, {
439
622
  position: 'absolute',
@@ -478,8 +661,77 @@ export function previewBridge(page) {
478
661
  return button;
479
662
  };
480
663
  const buttons = { up: tool('up'), down: tool('down'), duplicate: tool('duplicate'), remove: tool('remove') };
481
- const adder = (action) => {
482
- const button = doc.createElement('button');
664
+ // Adding is on the bar too, for a section whose edges are off the page.
665
+ const more = doc.createElement('button');
666
+ more.type = 'button';
667
+ more.tabIndex = -1;
668
+ more.setAttribute('data-cms-tool', 'addBelow');
669
+ Object.assign(more.style, { display: 'grid', placeItems: 'center', width: '28px', height: '28px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
670
+ more.append(drawing('add'));
671
+ press(more, 'addAfter');
672
+ bar.append(more);
673
+ // Swatches: a look of the section chosen among a few of the site's colours has a dot for each
674
+ // choice on the bar. The page changes nothing: it says which was pressed.
675
+ const dots = doc.createElement('span');
676
+ dots.setAttribute('data-cms-swatches', '');
677
+ Object.assign(dots.style, { display: 'none', alignItems: 'center', gap: '7px', padding: '0 6px 0 10px', marginLeft: '4px', borderLeft: '1px solid color-mix(in srgb, currentColor 25%, transparent)' });
678
+ bar.append(dots);
679
+ // One bar for everything: what can be done to the thing the pointer was last on (a picture, a
680
+ // link, an item of a list) is at its end, in the editor's orange, as the thing's own outline is.
681
+ const forThing = doc.createElement('span');
682
+ forThing.setAttribute('data-cms-about', '');
683
+ Object.assign(forThing.style, { display: 'none', alignItems: 'center', gap: '4px', paddingLeft: '8px', marginLeft: '4px', borderLeft: '1px solid color-mix(in srgb, currentColor 25%, transparent)' });
684
+ bar.append(forThing);
685
+ // A colour and nothing else: a sample is never an address to fetch.
686
+ const COLOUR = /^(?:#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(?:oklch|oklab|rgb|hsl)\([0-9.%,/ -]+\))$/i;
687
+ let dotted = '';
688
+ const drawDots = (about, id) => {
689
+ const sets = Array.isArray(about.swatches) ? about.swatches : [];
690
+ const key = `${id}:${JSON.stringify(sets)}`;
691
+ if (key === dotted)
692
+ return;
693
+ dotted = key;
694
+ dots.replaceChildren();
695
+ for (const set of sets) {
696
+ if (typeof set.field !== 'string' || !Array.isArray(set.choices))
697
+ continue;
698
+ for (const choice of set.choices) {
699
+ if (typeof choice.value !== 'string' || typeof choice.colour !== 'string' || choice.colour.length > 64 || !COLOUR.test(choice.colour))
700
+ continue;
701
+ const { field } = set;
702
+ const { value } = choice;
703
+ const dot = doc.createElement('button');
704
+ dot.type = 'button';
705
+ dot.tabIndex = -1;
706
+ dot.setAttribute('data-cms-swatch', `${field}:${value}`);
707
+ dot.title = [word(set.name), word(choice.name)].filter(Boolean).join(': ');
708
+ const isChosen = set.chosen === value;
709
+ if (isChosen)
710
+ dot.setAttribute('data-cms-chosen', '');
711
+ Object.assign(dot.style, {
712
+ boxSizing: 'border-box',
713
+ width: '18px',
714
+ height: '18px',
715
+ padding: '0',
716
+ borderRadius: '50%',
717
+ border: '1px solid color-mix(in srgb, currentColor 45%, transparent)',
718
+ background: choice.colour,
719
+ outline: isChosen ? `2px solid ${ACCENT}` : 'none',
720
+ outlineOffset: '1px',
721
+ cursor: isChosen ? 'default' : 'pointer',
722
+ });
723
+ dot.addEventListener('mousedown', (event) => event.preventDefault());
724
+ dot.addEventListener('click', () => {
725
+ if (!isChosen)
726
+ say({ type: 'swatch', id, field, value });
727
+ });
728
+ dots.append(dot);
729
+ }
730
+ }
731
+ dots.style.display = dots.childElementCount > 0 ? 'flex' : 'none';
732
+ };
733
+ const adder = (action, acts = true) => {
734
+ const button = grows(doc.createElement('button'));
483
735
  button.type = 'button';
484
736
  button.tabIndex = -1;
485
737
  button.setAttribute('data-cms-tool', action);
@@ -502,21 +754,469 @@ export function previewBridge(page) {
502
754
  pointerEvents: 'auto',
503
755
  });
504
756
  button.append(drawing('add'), doc.createElement('span'));
505
- press(button, action);
757
+ if (acts)
758
+ press(button, action);
759
+ else
760
+ button.addEventListener('mousedown', (event) => event.preventDefault());
506
761
  layer.append(button);
507
762
  return button;
508
763
  };
764
+ // A line along each edge of the section the bar is on, with the button that adds a section there.
765
+ const seam = () => {
766
+ const drawn = doc.createElement('div');
767
+ drawn.setAttribute('data-cms-seam', '');
768
+ Object.assign(drawn.style, { position: 'absolute', display: 'none', height: '2px', marginTop: '-1px', background: ACCENT });
769
+ layer.append(drawn);
770
+ return drawn;
771
+ };
772
+ const seams = { addBefore: seam(), addAfter: seam() };
509
773
  const adders = { addBefore: adder('addBefore'), addAfter: adder('addAfter') };
774
+ // An empty place inside a section (a column with nothing in it yet) has a button that adds the first.
775
+ const slotOf = (element) => element.dataset['cmsSlot'] ?? '';
776
+ const fillers = new Map();
777
+ const placeFillers = (isShown) => {
778
+ const wanted = new Map();
779
+ if (isShown && tools?.slots) {
780
+ for (const slot of doc.querySelectorAll('[data-cms-slot]')) {
781
+ const about = tools.slots[slotOf(slot)];
782
+ const rect = slot.getBoundingClientRect();
783
+ if (about?.empty === true && about.full !== true && rect.bottom > 14 && rect.top < page.innerHeight - 14 && rect.width > 0)
784
+ wanted.set(slotOf(slot), rect);
785
+ }
786
+ }
787
+ for (const [key, button] of fillers) {
788
+ if (wanted.has(key))
789
+ continue;
790
+ button.remove();
791
+ fillers.delete(key);
792
+ }
793
+ for (const [key, rect] of wanted) {
794
+ let button = fillers.get(key);
795
+ if (!button) {
796
+ button = adder('fill', false);
797
+ button.setAttribute('data-cms-fill', key);
798
+ button.addEventListener('click', () => {
799
+ const at = key.indexOf(':');
800
+ say({ type: 'slot', id: key.slice(0, at), field: key.slice(at + 1) });
801
+ });
802
+ fillers.set(key, button);
803
+ }
804
+ if (button.lastElementChild)
805
+ button.lastElementChild.textContent = word(tools?.labels['add']);
806
+ const middle = Math.min(Math.max(rect.top + rect.height / 2, 16), page.innerHeight - 16);
807
+ Object.assign(button.style, { display: 'flex', top: at(middle), left: at(rect.left + rect.width / 2) });
808
+ }
809
+ };
510
810
  layer.append(bar);
511
811
  const word = (value) => (typeof value === 'string' ? value : '');
812
+ // What the editor can change from the page has a button of its own on the bar once the pointer
813
+ // has been on it: a picture, and a link or a button. The pointer may be on something the
814
+ // template lays over it, so it is found by where it is.
815
+ const chip = (name) => {
816
+ const button = doc.createElement('button');
817
+ button.type = 'button';
818
+ button.tabIndex = -1;
819
+ button.setAttribute('data-cms-tool', name);
820
+ Object.assign(button.style, {
821
+ display: 'none',
822
+ alignItems: 'center',
823
+ gap: '6px',
824
+ height: '28px',
825
+ padding: '0 10px 0 8px',
826
+ border: '0',
827
+ borderRadius: '6px',
828
+ background: ACCENT,
829
+ color: ACCENT_INK,
830
+ font: `600 12px/1 ${FONT}`,
831
+ whiteSpace: 'nowrap',
832
+ cursor: 'pointer',
833
+ });
834
+ button.append(drawing(name), doc.createElement('span'));
835
+ button.addEventListener('mousedown', (event) => event.preventDefault());
836
+ forThing.append(button);
837
+ return button;
838
+ };
839
+ let pictured = null;
840
+ const pictureBox = outline('picture', '2px');
841
+ const linkBox = outline('link', '2px');
842
+ const changer = chip('picture');
843
+ changer.addEventListener('click', () => {
844
+ if (pictured?.field !== undefined)
845
+ say({ type: 'picture', id: pictured.section, field: pictured.field });
846
+ });
847
+ let linked = null;
848
+ const linker = chip('link');
849
+ linker.addEventListener('click', () => {
850
+ if (linked?.field !== undefined)
851
+ say({ type: 'link', id: linked.section, field: linked.field });
852
+ });
853
+ // Of those that lie over one another, the smallest is the one meant.
854
+ const smallestAt = (marks, x, y) => {
855
+ let found = null;
856
+ let least = Infinity;
857
+ for (const mark of marks) {
858
+ const rect = mark.element.getBoundingClientRect();
859
+ if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom)
860
+ continue;
861
+ const size = rect.width * rect.height;
862
+ if (size < least)
863
+ [found, least] = [mark, size];
864
+ }
865
+ return found;
866
+ };
867
+ const pictureAt = (x, y) => {
868
+ const id = tooled?.dataset['cmsSection'] ?? '';
869
+ const paths = tools?.sections[id]?.pictures;
870
+ if (!tooled || !Array.isArray(paths))
871
+ return null;
872
+ return smallestAt(paths.flatMap((path) => {
873
+ const mark = typeof path === 'string' ? find(id, path) : null;
874
+ return mark?.field === undefined ? [] : [mark];
875
+ }), x, y);
876
+ };
877
+ // A link shows no words of its own: it is found by where it leads. Two addresses that lead to
878
+ // one place read the same here, whatever a preview added to one and however it ends.
879
+ const leadsTo = (href) => {
880
+ if (typeof href !== 'string' || href === '')
881
+ return null;
882
+ try {
883
+ const to = new URL(href, page.location.href);
884
+ to.searchParams.delete('preview');
885
+ return `${to.origin}${to.pathname.replace(/\/$/, '')}${to.search}${to.hash}`;
886
+ }
887
+ catch {
888
+ return null;
889
+ }
890
+ };
891
+ // Where the site found each link to an entry to lead, by `<type>:<entry>`: it says so beside this script.
892
+ let leads = null;
893
+ const linksIn = new WeakMap();
894
+ const linksOf = (section, id, paths) => {
895
+ const said = paths.join('\n');
896
+ const known = linksIn.get(section);
897
+ if (known?.said === said)
898
+ return known.found;
899
+ const found = [];
900
+ linksIn.set(section, { said, found });
901
+ const held = new Map();
902
+ try {
903
+ if (leads === null) {
904
+ const table = JSON.parse(doc.querySelector('script[data-cms-links]')?.textContent ?? '{}');
905
+ leads = typeof table === 'object' && table !== null ? table : {};
906
+ }
907
+ const values = JSON.parse(section.dataset['cmsValues'] ?? '[]');
908
+ for (const value of Array.isArray(values) ? values : []) {
909
+ if (Array.isArray(value) && typeof value[0] === 'string' && typeof value[1] === 'string')
910
+ held.set(value[0], value[1]);
911
+ }
912
+ }
913
+ catch {
914
+ return found;
915
+ }
916
+ // Fields that lead to the same place share the links that go there, in order.
917
+ const wanted = new Map();
918
+ for (const path of paths) {
919
+ if (typeof path !== 'string')
920
+ continue;
921
+ const entry = held.get(`${path}.kind`) === 'entry' ? `${held.get(`${path}.type`) ?? ''}:${held.get(`${path}.entry`) ?? ''}` : null;
922
+ const to = leadsTo(entry === null ? (held.get(`${path}.href`) ?? held.get(path)) : leads?.[entry]);
923
+ if (to !== null)
924
+ wanted.set(to, [...(wanted.get(to) ?? []), path]);
925
+ }
926
+ const going = new Map();
927
+ for (const anchor of within(section, 'a[href]')) {
928
+ const to = leadsTo(anchor.getAttribute('href'));
929
+ if (to !== null && wanted.has(to))
930
+ going.set(to, [...(going.get(to) ?? []), anchor]);
931
+ }
932
+ for (const [to, fields] of wanted) {
933
+ const anchors = going.get(to) ?? [];
934
+ anchors.forEach((element, at) => {
935
+ const field = fields[Math.min(fields.length - 1, Math.floor((at * fields.length) / anchors.length))];
936
+ if (field !== undefined)
937
+ found.push({ element, section: id, field });
938
+ });
939
+ }
940
+ return found;
941
+ };
942
+ const linkAt = (x, y) => {
943
+ const id = tooled?.dataset['cmsSection'] ?? '';
944
+ const paths = tools?.sections[id]?.links;
945
+ return tooled && Array.isArray(paths) ? smallestAt(linksOf(tooled, id, paths), x, y) : null;
946
+ };
947
+ // Words chosen in text being written have a bar of their own: bold, italic, link. The browser
948
+ // shapes the words; where a link leads is asked of the editor, which has the words to ask with.
949
+ const formatBar = grows(doc.createElement('div'));
950
+ formatBar.setAttribute('data-cms-format', '');
951
+ Object.assign(formatBar.style, {
952
+ position: 'absolute',
953
+ display: 'none',
954
+ alignItems: 'center',
955
+ gap: '2px',
956
+ padding: '2px',
957
+ borderRadius: '8px',
958
+ background: 'CanvasText',
959
+ color: 'Canvas',
960
+ boxShadow: '0 4px 12px rgb(0 0 0 / 0.25)',
961
+ pointerEvents: 'auto',
962
+ });
963
+ const chosenWords = () => {
964
+ const selection = page.getSelection();
965
+ if (!writing || !selection || selection.rangeCount === 0 || selection.isCollapsed)
966
+ return null;
967
+ const range = selection.getRangeAt(0);
968
+ return writing.mark.element.contains(range.commonAncestorContainer) ? range : null;
969
+ };
970
+ const formatTool = (name, label, press) => {
971
+ const button = doc.createElement('button');
972
+ button.type = 'button';
973
+ button.tabIndex = -1;
974
+ button.setAttribute('data-cms-format-tool', name);
975
+ button.setAttribute('data-cms-label', label);
976
+ Object.assign(button.style, { display: 'grid', placeItems: 'center', width: '28px', height: '28px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
977
+ button.append(drawing(name));
978
+ // The pointer going down must not take the chosen words away.
979
+ button.addEventListener('mousedown', (event) => event.preventDefault());
980
+ button.addEventListener('click', () => {
981
+ const range = chosenWords();
982
+ if (writing && range)
983
+ press(writing, range);
984
+ });
985
+ formatBar.append(button);
986
+ return button;
987
+ };
988
+ const shape = (command, value) => {
989
+ if (!writing)
990
+ return;
991
+ doc.execCommand(command, false, value);
992
+ tellWriting(writing);
993
+ };
994
+ formatTool('bold', 'bold', () => shape('bold'));
995
+ formatTool('italic', 'italic', () => shape('italic'));
996
+ formatTool('link', 'textLink', (now, range) => {
997
+ const start = isElement(range.startContainer) ? range.startContainer : range.startContainer.parentElement;
998
+ const anchor = start?.closest('a[href]');
999
+ asking = range.cloneRange();
1000
+ say({ type: 'linkAsk', id: now.mark.section, field: now.mark.field, href: anchor && now.mark.element.contains(anchor) ? withoutPreview(anchor.getAttribute('href') ?? '') : '' });
1001
+ placeFormat();
1002
+ });
1003
+ layer.append(formatBar);
1004
+ /** The editor's answer to where a link leads: an address, nothing to take the link away, or `null` to leave it. */
1005
+ const answerLink = (href) => {
1006
+ const range = asking;
1007
+ asking = null;
1008
+ if (!writing || !range)
1009
+ return;
1010
+ writing.mark.element.focus();
1011
+ const selection = page.getSelection();
1012
+ selection?.removeAllRanges();
1013
+ selection?.addRange(range);
1014
+ if (href === '')
1015
+ shape('unlink');
1016
+ else if (typeof href === 'string')
1017
+ shape('createLink', href);
1018
+ placeFormat();
1019
+ };
1020
+ placeFormat = () => {
1021
+ const range = asking ? null : chosenWords();
1022
+ if (!range) {
1023
+ formatBar.style.display = 'none';
1024
+ return;
1025
+ }
1026
+ for (const button of formatBar.querySelectorAll('button'))
1027
+ button.title = word(tools?.labels[button.getAttribute('data-cms-label') ?? '']);
1028
+ const rect = typeof range.getBoundingClientRect === 'function' ? range.getBoundingClientRect() : (writing?.mark.element.getBoundingClientRect() ?? null);
1029
+ if (!rect)
1030
+ return;
1031
+ // Above the chosen words, and under them where the page ends above.
1032
+ Object.assign(formatBar.style, { display: 'flex', top: at(rect.top >= 40 * grow ? rect.top - 36 * grow : rect.bottom + 6), left: at(Math.max(rect.left, 4)) });
1033
+ };
1034
+ const itemsIn = new WeakMap();
1035
+ const itemsOf = (section, id) => {
1036
+ const about = tools?.sections[id];
1037
+ const lists = Array.isArray(about?.lists) ? about.lists : [];
1038
+ const links = Array.isArray(about?.links) ? about.links : [];
1039
+ const said = JSON.stringify([lists, links]);
1040
+ const known = itemsIn.get(section);
1041
+ if (known?.said === said)
1042
+ return known.found;
1043
+ const found = [];
1044
+ itemsIn.set(section, { said, found });
1045
+ // Every element known to show a field, by the field's place.
1046
+ const shown = [...guess(section)];
1047
+ for (const marked of within(section, '[data-cms-field]'))
1048
+ shown.push([marked.dataset['cmsField'] ?? '', marked]);
1049
+ for (const link of linksOf(section, id, links))
1050
+ shown.push([link.field ?? '', link.element]);
1051
+ for (const list of lists) {
1052
+ if (typeof list !== 'object' || list === null)
1053
+ continue;
1054
+ const { field, count, full } = list;
1055
+ if (typeof field !== 'string' || typeof count !== 'number')
1056
+ continue;
1057
+ const held = new Map();
1058
+ for (const [path, element] of shown) {
1059
+ if (!path.startsWith(`${field}.`))
1060
+ continue;
1061
+ const at = Number(path.slice(field.length + 1).split('.')[0]);
1062
+ if (Number.isInteger(at) && at >= 0 && at < count)
1063
+ held.set(at, [...(held.get(at) ?? []), element]);
1064
+ }
1065
+ for (const [at, elements] of held) {
1066
+ let element = elements[0];
1067
+ if (!element)
1068
+ continue;
1069
+ while (element !== section && !elements.every((inner) => element?.contains(inner)) && element.parentElement)
1070
+ element = element.parentElement;
1071
+ // As far out as it goes without taking in another item, so the whole card is the item.
1072
+ const others = [...held].filter(([other]) => other !== at).flatMap(([, theirs]) => theirs);
1073
+ if (others.some((other) => element?.contains(other)))
1074
+ continue;
1075
+ while (others.length > 0 && element.parentElement && element.parentElement !== section && !others.some((other) => element?.parentElement?.contains(other)))
1076
+ element = element.parentElement;
1077
+ if (element !== section)
1078
+ found.push({ element, section: id, field: `${field}.${at}`, list: field, at, count, full: full === true });
1079
+ }
1080
+ }
1081
+ return found;
1082
+ };
1083
+ let itemed = null;
1084
+ /** Where the item the bar is about will be on the page drawn next. */
1085
+ let next;
1086
+ /** What the bar was on when the page was last drawn: it is on it again, with no move of the pointer. */
1087
+ let again = null;
1088
+ let forget = () => undefined;
1089
+ const itemAt = (x, y) => {
1090
+ const id = tooled?.dataset['cmsSection'] ?? '';
1091
+ if (!tooled || !tools)
1092
+ return null;
1093
+ const items = itemsOf(tooled, id);
1094
+ const mark = smallestAt(items, x, y);
1095
+ return items.find((item) => item.element === mark?.element && item.field === mark.field) ?? null;
1096
+ };
1097
+ const itemBox = outline('item', '2px');
1098
+ itemBox.style.borderStyle = 'dashed';
1099
+ const itemBar = doc.createElement('div');
1100
+ itemBar.setAttribute('data-cms-item-tools', '');
1101
+ Object.assign(itemBar.style, { display: 'none', alignItems: 'center', gap: '0', padding: '0 2px', height: '28px', boxSizing: 'border-box', borderRadius: '6px', background: ACCENT, color: ACCENT_INK });
1102
+ const itemTool = (action) => {
1103
+ const button = doc.createElement('button');
1104
+ button.type = 'button';
1105
+ button.tabIndex = -1;
1106
+ button.setAttribute('data-cms-item-tool', action);
1107
+ Object.assign(button.style, { display: 'grid', placeItems: 'center', width: '26px', height: '26px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
1108
+ button.append(drawing(action));
1109
+ button.addEventListener('mousedown', (event) => event.preventDefault());
1110
+ button.addEventListener('click', () => {
1111
+ if (!itemed || button.disabled)
1112
+ return;
1113
+ // Where the item will be once the page is drawn again, so the bar is still about it.
1114
+ next = action === 'remove' ? undefined : itemed.at + (action === 'up' ? -1 : action === 'down' ? 1 : 0);
1115
+ say({ type: 'item', id: itemed.section, field: itemed.list, at: itemed.at, action });
1116
+ });
1117
+ itemBar.append(button);
1118
+ return button;
1119
+ };
1120
+ const itemButtons = { up: itemTool('up'), down: itemTool('down'), duplicate: itemTool('duplicate'), remove: itemTool('remove') };
1121
+ forThing.append(itemBar);
1122
+ const placeItem = () => {
1123
+ const rect = shownRect(itemed);
1124
+ if (!rect || !tools || !itemed) {
1125
+ itemBar.style.display = 'none';
1126
+ itemBox.style.display = 'none';
1127
+ return;
1128
+ }
1129
+ place(itemBox, itemed);
1130
+ // Items side by side are moved sideways, and the arrows say so.
1131
+ const beside = itemsOf(tooled ?? itemed.element, itemed.section).find((other) => other.list === itemed?.list && other.at !== itemed.at);
1132
+ const sideways = beside !== undefined && Math.abs(beside.element.getBoundingClientRect().top - rect.top) < rect.height / 2;
1133
+ const able = { up: itemed.at > 0, down: itemed.at < itemed.count - 1, duplicate: !itemed.full, remove: true };
1134
+ for (const action of ['up', 'down', 'duplicate', 'remove']) {
1135
+ const button = itemButtons[action];
1136
+ button.title = word(tools.labels[`item${action.charAt(0).toUpperCase()}${action.slice(1)}`]);
1137
+ button.disabled = !able[action];
1138
+ button.style.opacity = able[action] ? '1' : '0.4';
1139
+ button.style.cursor = able[action] ? 'pointer' : 'default';
1140
+ if (action === 'up' || action === 'down')
1141
+ button.firstElementChild?.style.setProperty('transform', sideways ? 'rotate(-90deg)' : 'none');
1142
+ }
1143
+ itemBar.style.display = 'flex';
1144
+ };
1145
+ const shownRect = (mark) => {
1146
+ const rect = !typing && !writing && !drag?.moved && mark?.element.isConnected ? mark.element.getBoundingClientRect() : null;
1147
+ return !rect || !tools || rect.bottom <= 0 || rect.top >= page.innerHeight || (rect.width === 0 && rect.height === 0) ? null : rect;
1148
+ };
1149
+ const placeChips = () => {
1150
+ const picture = shownRect(pictured);
1151
+ changer.style.display = picture && tools ? 'flex' : 'none';
1152
+ if (picture && tools && changer.lastElementChild)
1153
+ changer.lastElementChild.textContent = word(tools.labels['picture']);
1154
+ place(pictureBox, picture ? pictured : null);
1155
+ const link = shownRect(linked);
1156
+ linker.style.display = link && tools ? 'flex' : 'none';
1157
+ if (link && tools && linker.lastElementChild)
1158
+ linker.lastElementChild.textContent = word(tools.labels['link']);
1159
+ place(linkBox, link ? linked : null);
1160
+ placeItem();
1161
+ forThing.style.display = changer.style.display === 'none' && linker.style.display === 'none' && itemBar.style.display === 'none' ? 'none' : 'flex';
1162
+ placeFormat();
1163
+ };
1164
+ // What the bar is about stays as it was while the pointer travels: over nothing, and across
1165
+ // other things on its way to the bar. It turns to another thing once the pointer rests on it.
1166
+ const REST = 140;
1167
+ let resting;
1168
+ const sameThing = (one, other) => one?.element === other?.element && one?.field === other?.field;
1169
+ const pointed = (x, y, isNow) => {
1170
+ page.clearTimeout(resting);
1171
+ resting = undefined;
1172
+ const picture = pictureAt(x, y);
1173
+ const link = linkAt(x, y);
1174
+ const item = itemAt(x, y);
1175
+ if (!picture && !link && !item)
1176
+ return;
1177
+ // Less of the same thing (the card, off its picture) is no reason to take a button away.
1178
+ if ((!picture || sameThing(picture, pictured)) && (!link || sameThing(link, linked)) && (!item || sameThing(item, itemed)))
1179
+ return;
1180
+ const turn = () => {
1181
+ resting = undefined;
1182
+ pictured = picture;
1183
+ linked = link;
1184
+ itemed = item;
1185
+ placeTools();
1186
+ };
1187
+ if (isNow || (!pictured && !linked && !itemed))
1188
+ turn();
1189
+ else
1190
+ resting = page.setTimeout(turn, REST);
1191
+ };
1192
+ forget = () => {
1193
+ page.clearTimeout(resting);
1194
+ resting = undefined;
1195
+ pictured = null;
1196
+ linked = null;
1197
+ itemed = null;
1198
+ };
1199
+ doc.addEventListener('mousemove', (event) => {
1200
+ // On the layer's own buttons, what they are for stays as it was.
1201
+ if (isElement(event.target) && layer.contains(event.target)) {
1202
+ page.clearTimeout(resting);
1203
+ resting = undefined;
1204
+ return;
1205
+ }
1206
+ pointed(event.clientX, event.clientY, false);
1207
+ }, true);
512
1208
  placeTools = () => {
1209
+ placeChips();
1210
+ placeFillers(!typing && !writing && !drag?.moved);
513
1211
  const hide = () => {
514
1212
  bar.style.display = 'none';
515
1213
  adders.addBefore.style.display = 'none';
516
1214
  adders.addAfter.style.display = 'none';
1215
+ seams.addBefore.style.display = 'none';
1216
+ seams.addAfter.style.display = 'none';
517
1217
  };
518
1218
  // While words are typed, nothing sits over them.
519
- const section = typing || drag?.moved ? null : tooled?.isConnected ? tooled : null;
1219
+ const section = typing || writing || drag?.moved ? null : tooled?.isConnected ? tooled : null;
520
1220
  const about = section && tools?.sections[section.dataset['cmsSection'] ?? ''];
521
1221
  if (!section || !tools || !about)
522
1222
  return hide();
@@ -524,6 +1224,7 @@ export function previewBridge(page) {
524
1224
  if (rect.bottom <= 0 || rect.top >= page.innerHeight || (rect.width === 0 && rect.height === 0))
525
1225
  return hide();
526
1226
  named.textContent = word(about.name);
1227
+ drawDots(about, section.dataset['cmsSection'] ?? '');
527
1228
  const able = { up: about.up === true, down: about.down === true, duplicate: about.copy === true, remove: true };
528
1229
  for (const action of ['up', 'down', 'duplicate', 'remove']) {
529
1230
  const button = buttons[action];
@@ -532,19 +1233,26 @@ export function previewBridge(page) {
532
1233
  button.style.opacity = able[action] ? '1' : '0.4';
533
1234
  button.style.cursor = able[action] ? 'pointer' : 'default';
534
1235
  }
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` });
1236
+ // At the section's top corner, and at the top of the page while the section's own top is above it:
1237
+ // under what the site keeps there, so the bar never covers the site's own header.
1238
+ more.title = word(tools.labels['addAfter']);
1239
+ more.style.display = about.add === true ? 'grid' : 'none';
1240
+ Object.assign(bar.style, { display: 'flex', top: at(Math.min(Math.max(rect.top, kept()) + 12 * grow, Math.max(rect.bottom - 44 * grow, 0))), left: 'auto', right: at(Math.max(page.innerWidth - rect.right, 0) + 12 * grow) });
1241
+ // A bar wider than the room to its left (a narrow column) starts at the page's edge instead.
1242
+ if (bar.offsetWidth > 0 && bar.getBoundingClientRect().left < 4)
1243
+ Object.assign(bar.style, { left: at(4), right: 'auto' });
537
1244
  for (const [action, edge] of [['addBefore', rect.top], ['addAfter', rect.bottom]]) {
538
1245
  const button = adders[action];
539
1246
  // An edge that is off the page, or a page that takes no more sections, has no button.
540
1247
  const shown = about.add === true && edge >= 14 && edge <= page.innerHeight - 14;
541
1248
  button.style.display = shown ? 'flex' : 'none';
1249
+ Object.assign(seams[action].style, { display: shown ? 'block' : 'none', top: `${edge}px`, left: `${rect.left}px`, width: `${rect.width}px` });
542
1250
  if (!shown)
543
1251
  continue;
544
1252
  if (button.lastElementChild)
545
1253
  button.lastElementChild.textContent = word(tools.labels['add']);
546
1254
  button.title = word(tools.labels[action]);
547
- Object.assign(button.style, { top: `${edge}px`, left: `${rect.left + rect.width / 2}px` });
1255
+ Object.assign(button.style, { top: at(edge), left: at(rect.left + rect.width / 2) });
548
1256
  }
549
1257
  };
550
1258
  // Dragging a section by its bar: a line shows where it would land, and letting go says so to the editor.
@@ -557,29 +1265,56 @@ export function previewBridge(page) {
557
1265
  const aim = () => {
558
1266
  if (!drag)
559
1267
  return;
560
- const sections = movable();
1268
+ const { id, x, y } = drag;
1269
+ const all = movable();
1270
+ const listOf = (section) => word(tools?.sections[section.dataset['cmsSection'] ?? '']?.list);
1271
+ const home = word(tools?.sections[id]?.list);
1272
+ const group = word(tools?.sections[id]?.group);
1273
+ const dragged = all.find((section) => section.dataset['cmsSection'] === id);
1274
+ // It lands among the sections it is with, or in another place the pointer is over that takes
1275
+ // the same blocks: the smallest such place, and never one inside the section itself.
1276
+ let into = home;
1277
+ let place;
1278
+ for (const slot of doc.querySelectorAll('[data-cms-slot]')) {
1279
+ const about = tools?.slots?.[slotOf(slot)];
1280
+ if (!about || about.group !== group || dragged?.contains(slot) || (slotOf(slot) !== home && about.full === true))
1281
+ continue;
1282
+ const rect = slot.getBoundingClientRect();
1283
+ if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom)
1284
+ continue;
1285
+ if (place && place.width * place.height <= rect.width * rect.height)
1286
+ continue;
1287
+ into = slotOf(slot);
1288
+ place = rect;
1289
+ }
1290
+ const sections = all.filter((section) => listOf(section) === into);
561
1291
  const at = sections.findIndex((section) => {
562
1292
  const rect = section.getBoundingClientRect();
563
- return drag !== null && drag.y < rect.top + rect.height / 2;
1293
+ return y < rect.top + rect.height / 2;
564
1294
  });
565
1295
  const target = at < 0 ? undefined : sections[at];
566
- const own = sections.findIndex((section) => section.dataset['cmsSection'] === drag?.id);
1296
+ const own = sections.findIndex((section) => section.dataset['cmsSection'] === id);
567
1297
  const to = at < 0 ? sections.length : at;
568
1298
  // 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);
1299
+ const stays = into === home && (own < 0 || to === own || to === own + 1);
1300
+ drag.before = stays ? undefined : (target?.dataset['cmsSection'] ?? null);
1301
+ drag.into = into === home ? undefined : into;
570
1302
  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` });
1303
+ const beside = target?.getBoundingClientRect() ?? last?.getBoundingClientRect() ?? place;
1304
+ const edge = target ? target.getBoundingClientRect().top : (last?.getBoundingClientRect().bottom ?? (place ? place.top + 2 : 0));
1305
+ // Across the page for the page's own sections, and as wide as its neighbours inside a section.
1306
+ const across = into === '' || !beside ? { left: '0', right: '0', width: 'auto' } : { left: `${beside.left}px`, right: 'auto', width: `${beside.width}px` };
1307
+ Object.assign(line.style, { display: stays ? 'none' : 'block', top: `${Math.min(Math.max(edge, 2), page.innerHeight - 2)}px`, ...across });
573
1308
  };
574
1309
  const endDrag = (drop) => {
575
1310
  if (!drag)
576
1311
  return;
577
- const { id, before, moved } = drag;
1312
+ const { id, before, into, moved } = drag;
578
1313
  drag = null;
579
1314
  line.style.display = 'none';
580
1315
  Object.assign(layer.style, { pointerEvents: 'none', cursor: '' });
581
1316
  if (drop && moved && before !== undefined)
582
- say({ type: 'move', id, before });
1317
+ say({ type: 'move', id, before, ...(into !== undefined && { into }) });
583
1318
  draw();
584
1319
  };
585
1320
  // Near the top or the bottom of the page, it scrolls to bring the rest within reach.
@@ -599,7 +1334,7 @@ export function previewBridge(page) {
599
1334
  if (event.button !== 0 || !id || movable().length < 2)
600
1335
  return;
601
1336
  event.preventDefault();
602
- drag = { id, from: event.clientY, y: event.clientY, before: undefined, moved: false };
1337
+ drag = { id, from: event.clientY, x: event.clientX, y: event.clientY, into: undefined, before: undefined, moved: false };
603
1338
  // The layer takes the pointer while it drags, so nothing on the page answers to it.
604
1339
  Object.assign(layer.style, { pointerEvents: 'auto', cursor: 'grabbing' });
605
1340
  page.setTimeout(creep, 16);
@@ -608,6 +1343,7 @@ export function previewBridge(page) {
608
1343
  doc.addEventListener('mousemove', (event) => {
609
1344
  if (!drag)
610
1345
  return;
1346
+ drag.x = event.clientX;
611
1347
  drag.y = event.clientY;
612
1348
  // A few pixels of give, so a press that was only a press moves nothing.
613
1349
  if (Math.abs(drag.y - drag.from) > 4)
@@ -629,12 +1365,18 @@ export function previewBridge(page) {
629
1365
  marks.over = markOf(event.target);
630
1366
  if (marks.over)
631
1367
  marks.over.element.style.cursor = runFor(marks.over) ? 'text' : 'pointer';
632
- tooled = isElement(event.target) ? event.target.closest('[data-cms-section]') : null;
1368
+ // Over what is no section (a header, a gap), the bar stays with the section it was on.
1369
+ const section = isElement(event.target) ? event.target.closest('[data-cms-section]') : null;
1370
+ if (section && section !== tooled) {
1371
+ tooled = section;
1372
+ forget();
1373
+ }
633
1374
  draw();
634
1375
  });
635
1376
  doc.documentElement.addEventListener('mouseleave', () => {
636
1377
  marks.over = null;
637
1378
  tooled = null;
1379
+ forget();
638
1380
  draw();
639
1381
  });
640
1382
  // Nothing on the page goes anywhere: a click chooses what it is on.
@@ -643,14 +1385,20 @@ export function previewBridge(page) {
643
1385
  // A press on the layer's own bar is that button's business.
644
1386
  if (isElement(event.target) && layer.contains(event.target))
645
1387
  return;
1388
+ // A press, or a tap where there is no pointer to rest, says at once what the bar is about.
1389
+ pointed(event.clientX, event.clientY, true);
646
1390
  const mark = markOf(event.target);
647
1391
  if (!mark)
648
1392
  return;
649
1393
  marks.chosen = mark;
650
1394
  draw();
651
- say({ type: 'section', id: mark.section, ...(mark.field !== undefined && { field: mark.field }) });
1395
+ // A field that is not being typed into here, where it is, is one for the form.
1396
+ const here = typing?.mark.element === mark.element || writing?.mark.element === mark.element;
1397
+ say({ type: 'section', id: mark.section, ...(mark.field !== undefined && { field: mark.field, ...(!here && { form: true }) }) });
652
1398
  }, true);
653
1399
  doc.addEventListener('submit', (event) => event.preventDefault(), true);
1400
+ // True once the page is where it should be: the person scrolled it, or the editor asked for a part of it.
1401
+ let settled = false;
654
1402
  page.addEventListener('message', (event) => {
655
1403
  if (event.origin !== origin || event.source !== page.parent || event.data?.source !== SOURCE)
656
1404
  return;
@@ -659,42 +1407,129 @@ export function previewBridge(page) {
659
1407
  typable = typeof places === 'object' && places !== null ? places : {};
660
1408
  return;
661
1409
  }
1410
+ if (event.data.type === 'linkAnswer') {
1411
+ answerLink(event.data.href);
1412
+ return;
1413
+ }
1414
+ if (event.data.type === 'zoom') {
1415
+ // How much smaller than life the editor shows the page: between a tenth and life size.
1416
+ const scale = event.data.scale;
1417
+ const next = typeof scale === 'number' && scale >= 0.1 && scale < 1 ? 1 / scale : 1;
1418
+ if (next !== grow) {
1419
+ grow = next;
1420
+ for (const element of grown) {
1421
+ if (grow === 1)
1422
+ element.style.removeProperty('zoom');
1423
+ else
1424
+ element.style.setProperty('zoom', String(grow));
1425
+ }
1426
+ draw();
1427
+ placeFormat();
1428
+ }
1429
+ return;
1430
+ }
662
1431
  if (event.data.type === 'tools') {
663
1432
  const said = event.data;
664
1433
  const isRecord = (value) => typeof value === 'object' && value !== null;
665
- tools = isRecord(said.labels) && isRecord(said.sections) ? { labels: said.labels, sections: said.sections } : null;
1434
+ const slots = said.slots;
1435
+ tools = isRecord(said.labels) && isRecord(said.sections) ? { labels: said.labels, sections: said.sections, ...(isRecord(slots) && { slots: slots }) } : null;
1436
+ if (again && tools && !tooled) {
1437
+ const was = again;
1438
+ tooled = [...doc.querySelectorAll('[data-cms-section]')].find((section) => section.dataset['cmsSection'] === was.id) ?? null;
1439
+ if (tooled && was.list !== undefined)
1440
+ itemed = itemsOf(tooled, was.id).find((item) => item.list === was.list && item.at === was.at) ?? null;
1441
+ }
1442
+ if (tools)
1443
+ again = null;
666
1444
  draw();
667
1445
  return;
668
1446
  }
669
1447
  if (event.data.type !== 'show' || typeof event.data.id !== 'string')
670
1448
  return;
671
1449
  // While words are typed into a section, the outline stays on the field they go into.
672
- if (typing?.mark.section === event.data.id)
1450
+ if (typing?.mark.section === event.data.id || writing?.mark.section === event.data.id)
673
1451
  return;
674
1452
  const mark = find(event.data.id, typeof event.data.field === 'string' ? event.data.field : undefined);
675
1453
  if (!mark)
676
1454
  return;
677
1455
  marks.chosen = mark;
678
1456
  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) {
1457
+ // What is already in view stays where it is: the page does not jump while someone types. Nor
1458
+ // does a page drawn again, which is where the person left it: the editor says so (`still`).
1459
+ if (event.data.still !== true && (rect.bottom <= 0 || rect.top >= page.innerHeight)) {
681
1460
  // Room for a header that stays at the top of the page.
682
1461
  mark.element.style.scrollMarginTop = '6rem';
1462
+ settled = true;
683
1463
  mark.element.scrollIntoView({ block: 'start' });
684
1464
  }
685
1465
  draw();
686
1466
  });
687
1467
  // Scroll.
1468
+ // A page drawn again is where it was: by the section that was in the window and where in it, so
1469
+ // it stays put even when something above is taller or shorter now, and else by how far down it was.
688
1470
  const key = `velocity-cms:scroll:${page.location.pathname}`;
689
1471
  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)));
1472
+ let kept = {};
1473
+ try {
1474
+ const read = JSON.parse(page.sessionStorage.getItem(key) ?? 'null');
1475
+ kept = typeof read === 'number' ? { y: read } : typeof read === 'object' && read !== null ? read : {};
1476
+ }
1477
+ catch {
1478
+ // What was kept another way is as good as nothing kept.
1479
+ }
1480
+ if (kept.on === true && typeof kept.id === 'string')
1481
+ again = { id: kept.id, ...(typeof kept.list === 'string' && typeof kept.at === 'number' && { list: kept.list, at: kept.at }) };
1482
+ const back = () => {
1483
+ if (typeof kept.y !== 'number' || !(kept.y > 0))
1484
+ return;
1485
+ const section = [...doc.querySelectorAll('[data-cms-section]')].find((candidate) => candidate.dataset['cmsSection'] === kept.id);
1486
+ const to = section && typeof kept.top === 'number' ? page.scrollY + section.getBoundingClientRect().top - kept.top : kept.y;
1487
+ if (Math.abs(page.scrollY - to) > 1)
1488
+ page.scrollTo({ top: Math.max(to, 0), behavior: 'instant' });
1489
+ };
1490
+ back();
1491
+ // A page that is not as tall yet as it will be (photos, fonts) is put back again as it settles,
1492
+ // until the person scrolls it or the editor asks for another part of it.
1493
+ for (const sign of ['wheel', 'touchmove', 'keydown', 'mousedown'])
1494
+ page.addEventListener(sign, () => (settled = true), { once: true, capture: true, passive: true });
1495
+ let tries = 0;
1496
+ const settle = () => {
1497
+ if (settled)
1498
+ return;
1499
+ back();
1500
+ if (++tries < 20)
1501
+ page.setTimeout(settle, 100);
1502
+ };
1503
+ page.setTimeout(settle, 100);
1504
+ page.addEventListener('load', () => {
1505
+ if (!settled)
1506
+ back();
1507
+ });
1508
+ page.addEventListener('pagehide', () => {
1509
+ // The section being worked on, or else the first one in the window.
1510
+ const inView = (section) => {
1511
+ const rect = section?.isConnected ? section.getBoundingClientRect() : null;
1512
+ return rect !== null && rect.bottom > 0 && rect.top < page.innerHeight;
1513
+ };
1514
+ const section = inView(tooled) ? tooled : [...doc.querySelectorAll('[data-cms-section]')].find(inView);
1515
+ const item = section === tooled && itemed ? { list: itemed.list, at: next ?? itemed.at } : undefined;
1516
+ page.sessionStorage.setItem(key, JSON.stringify({ y: page.scrollY, ...(section && { id: section.dataset['cmsSection'], top: section.getBoundingClientRect().top, on: section === tooled, ...item }) }));
1517
+ });
694
1518
  }
695
1519
  catch {
696
1520
  // A page that may not keep anything starts at the top.
697
1521
  }
1522
+ // The page is drawn again in place: a template's fade from one page to the next is for visitors.
1523
+ // The turn itself is kept, since it holds the page as it was on screen until this one is ready,
1524
+ // and is made to take no time. The rule is the bridge's own sheet, not a change to the page's.
1525
+ try {
1526
+ const sheet = new page.CSSStyleSheet();
1527
+ sheet.replaceSync('::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; }');
1528
+ doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet];
1529
+ }
1530
+ catch {
1531
+ // A browser without such sheets shows the template's own turn.
1532
+ }
698
1533
  say({ type: 'ready' });
699
1534
  }
700
1535
  /** The bridge as the page is sent it. */