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

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 (131) hide show
  1. package/app-dist/assets/{RichTextEditor-BiKJJtkz.js → RichTextEditor-D-0hJngm.js} +1 -1
  2. package/app-dist/assets/index-C2SsRclY.js +80 -0
  3. package/app-dist/assets/index-D8x7A_Xo.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 +97 -54
  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 +2 -0
  13. package/dist/client/queries.d.ts.map +1 -1
  14. package/dist/client/queries.js +42 -7
  15. package/dist/client/queries.js.map +1 -1
  16. package/dist/fields/BlocksControl.d.ts +6 -0
  17. package/dist/fields/BlocksControl.d.ts.map +1 -1
  18. package/dist/fields/BlocksControl.js +303 -89
  19. package/dist/fields/BlocksControl.js.map +1 -1
  20. package/dist/fields/SiteImagePicker.d.ts +22 -0
  21. package/dist/fields/SiteImagePicker.d.ts.map +1 -0
  22. package/dist/fields/SiteImagePicker.js +42 -0
  23. package/dist/fields/SiteImagePicker.js.map +1 -0
  24. package/dist/fields/block-icons.d.ts.map +1 -1
  25. package/dist/fields/block-icons.js +3 -1
  26. package/dist/fields/block-icons.js.map +1 -1
  27. package/dist/fields/carry.d.ts +19 -0
  28. package/dist/fields/carry.d.ts.map +1 -0
  29. package/dist/fields/carry.js +61 -0
  30. package/dist/fields/carry.js.map +1 -0
  31. package/dist/fields/controls.d.ts.map +1 -1
  32. package/dist/fields/controls.js +82 -58
  33. package/dist/fields/controls.js.map +1 -1
  34. package/dist/fields/field-control.d.ts +80 -0
  35. package/dist/fields/field-control.d.ts.map +1 -1
  36. package/dist/fields/field-control.js.map +1 -1
  37. package/dist/fields/page-focus.d.ts +32 -3
  38. package/dist/fields/page-focus.d.ts.map +1 -1
  39. package/dist/fields/page-focus.js +55 -1
  40. package/dist/fields/page-focus.js.map +1 -1
  41. package/dist/lib/open-site.d.ts +6 -0
  42. package/dist/lib/open-site.d.ts.map +1 -0
  43. package/dist/lib/open-site.js +8 -0
  44. package/dist/lib/open-site.js.map +1 -0
  45. package/dist/lib/rich-from-html.d.ts +9 -0
  46. package/dist/lib/rich-from-html.d.ts.map +1 -0
  47. package/dist/lib/rich-from-html.js +129 -0
  48. package/dist/lib/rich-from-html.js.map +1 -0
  49. package/dist/lib/sittings.d.ts +16 -0
  50. package/dist/lib/sittings.d.ts.map +1 -0
  51. package/dist/lib/sittings.js +29 -0
  52. package/dist/lib/sittings.js.map +1 -0
  53. package/dist/lib/use-command-key.d.ts +16 -0
  54. package/dist/lib/use-command-key.d.ts.map +1 -0
  55. package/dist/lib/use-command-key.js +30 -0
  56. package/dist/lib/use-command-key.js.map +1 -0
  57. package/dist/lib/use-history.d.ts +24 -0
  58. package/dist/lib/use-history.d.ts.map +1 -0
  59. package/dist/lib/use-history.js +48 -0
  60. package/dist/lib/use-history.js.map +1 -0
  61. package/dist/lib/use-narrow.d.ts +5 -0
  62. package/dist/lib/use-narrow.d.ts.map +1 -0
  63. package/dist/lib/use-narrow.js +19 -0
  64. package/dist/lib/use-narrow.js.map +1 -0
  65. package/dist/lib/use-save-key.d.ts +15 -0
  66. package/dist/lib/use-save-key.d.ts.map +1 -0
  67. package/dist/lib/use-save-key.js +27 -0
  68. package/dist/lib/use-save-key.js.map +1 -0
  69. package/dist/lib/use-undo-keys.d.ts +14 -0
  70. package/dist/lib/use-undo-keys.d.ts.map +1 -0
  71. package/dist/lib/use-undo-keys.js +46 -0
  72. package/dist/lib/use-undo-keys.js.map +1 -0
  73. package/dist/messages/en.d.ts +72 -2
  74. package/dist/messages/en.d.ts.map +1 -1
  75. package/dist/messages/en.js +72 -2
  76. package/dist/messages/en.js.map +1 -1
  77. package/dist/page-bridge/preview-bridge.d.ts +3 -3
  78. package/dist/page-bridge/preview-bridge.d.ts.map +1 -1
  79. package/dist/page-bridge/preview-bridge.js +1145 -33
  80. package/dist/page-bridge/preview-bridge.js.map +1 -1
  81. package/dist/screens/Contact/ContactScreen.js +1 -1
  82. package/dist/screens/Contact/ContactScreen.js.map +1 -1
  83. package/dist/screens/Contacts/ContactsScreen.js +2 -2
  84. package/dist/screens/Contacts/ContactsScreen.js.map +1 -1
  85. package/dist/screens/Contacts/StagesDialog.d.ts.map +1 -1
  86. package/dist/screens/Contacts/StagesDialog.js +4 -1
  87. package/dist/screens/Contacts/StagesDialog.js.map +1 -1
  88. package/dist/screens/ContentList/ContentListScreen.d.ts.map +1 -1
  89. package/dist/screens/ContentList/ContentListScreen.js +11 -4
  90. package/dist/screens/ContentList/ContentListScreen.js.map +1 -1
  91. package/dist/screens/ContentList/EntryPeek.d.ts +13 -0
  92. package/dist/screens/ContentList/EntryPeek.d.ts.map +1 -0
  93. package/dist/screens/ContentList/EntryPeek.js +32 -0
  94. package/dist/screens/ContentList/EntryPeek.js.map +1 -0
  95. package/dist/screens/ContentType/ContentTypeScreen.js +1 -1
  96. package/dist/screens/ContentType/ContentTypeScreen.js.map +1 -1
  97. package/dist/screens/Deals/DealsScreen.js +27 -3
  98. package/dist/screens/Deals/DealsScreen.js.map +1 -1
  99. package/dist/screens/EntryEditor/EntryEditorScreen.d.ts.map +1 -1
  100. package/dist/screens/EntryEditor/EntryEditorScreen.js +5 -3
  101. package/dist/screens/EntryEditor/EntryEditorScreen.js.map +1 -1
  102. package/dist/screens/EntryEditor/EntryForm.d.ts +2 -0
  103. package/dist/screens/EntryEditor/EntryForm.d.ts.map +1 -1
  104. package/dist/screens/EntryEditor/EntryForm.js +165 -19
  105. package/dist/screens/EntryEditor/EntryForm.js.map +1 -1
  106. package/dist/screens/EntryEditor/HistoryDialog.d.ts +2 -1
  107. package/dist/screens/EntryEditor/HistoryDialog.d.ts.map +1 -1
  108. package/dist/screens/EntryEditor/HistoryDialog.js +24 -5
  109. package/dist/screens/EntryEditor/HistoryDialog.js.map +1 -1
  110. package/dist/screens/EntryEditor/PagePane.d.ts +12 -2
  111. package/dist/screens/EntryEditor/PagePane.d.ts.map +1 -1
  112. package/dist/screens/EntryEditor/PagePane.js +54 -19
  113. package/dist/screens/EntryEditor/PagePane.js.map +1 -1
  114. package/dist/screens/EntryEditor/SectionOutline.d.ts +11 -0
  115. package/dist/screens/EntryEditor/SectionOutline.d.ts.map +1 -0
  116. package/dist/screens/EntryEditor/SectionOutline.js +46 -0
  117. package/dist/screens/EntryEditor/SectionOutline.js.map +1 -0
  118. package/dist/screens/EntryEditor/ThemeCard.d.ts +32 -0
  119. package/dist/screens/EntryEditor/ThemeCard.d.ts.map +1 -0
  120. package/dist/screens/EntryEditor/ThemeCard.js +67 -0
  121. package/dist/screens/EntryEditor/ThemeCard.js.map +1 -0
  122. package/dist/screens/Home/HomeScreen.d.ts +1 -1
  123. package/dist/screens/Home/HomeScreen.d.ts.map +1 -1
  124. package/dist/screens/Home/HomeScreen.js +54 -16
  125. package/dist/screens/Home/HomeScreen.js.map +1 -1
  126. package/dist/testing/admin-client-contract.d.ts.map +1 -1
  127. package/dist/testing/admin-client-contract.js +6 -0
  128. package/dist/testing/admin-client-contract.js.map +1 -1
  129. package/package.json +5 -5
  130. package/app-dist/assets/index-BgVjqwy6.js +0 -80
  131. 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,11 @@ 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'],
591
+ reorder: ['m21 16-4 4-4-4', 'M17 20V4', 'm3 8 4-4 4 4', 'M7 4v16'],
422
592
  drag: ['M9 5h.01', 'M9 12h.01', 'M9 19h.01', 'M15 5h.01', 'M15 12h.01', 'M15 19h.01'],
423
593
  };
424
594
  const drawing = (name) => {
@@ -433,7 +603,21 @@ export function previewBridge(page) {
433
603
  return svg;
434
604
  };
435
605
  const FONT = 'system-ui, sans-serif';
436
- const bar = doc.createElement('div');
606
+ /** Where what a site keeps at the top of its window ends (a header that stays as the page scrolls), or 0. */
607
+ const kept = () => {
608
+ if (typeof doc.elementFromPoint !== 'function')
609
+ return 0;
610
+ for (let element = doc.elementFromPoint(page.innerWidth / 2, 2); element && element !== doc.body && element !== doc.documentElement; element = element.parentElement) {
611
+ const position = page.getComputedStyle(element).position;
612
+ if (position !== 'fixed' && position !== 'sticky')
613
+ continue;
614
+ const rect = element.getBoundingClientRect();
615
+ // Only a strip at the top counts: something that covers the window is no header.
616
+ return rect.top <= 2 && rect.bottom < page.innerHeight / 3 ? rect.bottom : 0;
617
+ }
618
+ return 0;
619
+ };
620
+ const bar = grows(doc.createElement('div'));
437
621
  bar.setAttribute('data-cms-tools', '');
438
622
  Object.assign(bar.style, {
439
623
  position: 'absolute',
@@ -478,8 +662,87 @@ export function previewBridge(page) {
478
662
  return button;
479
663
  };
480
664
  const buttons = { up: tool('up'), down: tool('down'), duplicate: tool('duplicate'), remove: tool('remove') };
481
- const adder = (action) => {
482
- const button = doc.createElement('button');
665
+ // Adding is on the bar too, for a section whose edges are off the page.
666
+ const more = doc.createElement('button');
667
+ more.type = 'button';
668
+ more.tabIndex = -1;
669
+ more.setAttribute('data-cms-tool', 'addBelow');
670
+ Object.assign(more.style, { display: 'grid', placeItems: 'center', width: '28px', height: '28px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
671
+ more.append(drawing('add'));
672
+ press(more, 'addAfter');
673
+ bar.append(more);
674
+ // The page's sections by name, to put in another order.
675
+ const sorter = doc.createElement('button');
676
+ sorter.type = 'button';
677
+ sorter.tabIndex = -1;
678
+ sorter.setAttribute('data-cms-tool', 'reorder');
679
+ Object.assign(sorter.style, { display: 'none', placeItems: 'center', width: '28px', height: '28px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
680
+ sorter.append(drawing('reorder'));
681
+ sorter.addEventListener('mousedown', (event) => event.preventDefault());
682
+ sorter.addEventListener('click', () => openStack(null, true, 0));
683
+ bar.append(sorter);
684
+ // Swatches: a look of the section chosen among a few of the site's colours has a dot for each
685
+ // choice on the bar. The page changes nothing: it says which was pressed.
686
+ const dots = doc.createElement('span');
687
+ dots.setAttribute('data-cms-swatches', '');
688
+ 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)' });
689
+ bar.append(dots);
690
+ // One bar for everything: what can be done to the thing the pointer was last on (a picture, a
691
+ // link, an item of a list) is at its end, in the editor's orange, as the thing's own outline is.
692
+ const forThing = doc.createElement('span');
693
+ forThing.setAttribute('data-cms-about', '');
694
+ Object.assign(forThing.style, { display: 'none', alignItems: 'center', gap: '4px', paddingLeft: '8px', marginLeft: '4px', borderLeft: '1px solid color-mix(in srgb, currentColor 25%, transparent)' });
695
+ bar.append(forThing);
696
+ // A colour and nothing else: a sample is never an address to fetch.
697
+ const COLOUR = /^(?:#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(?:oklch|oklab|rgb|hsl)\([0-9.%,/ -]+\))$/i;
698
+ let dotted = '';
699
+ const drawDots = (about, id) => {
700
+ const sets = Array.isArray(about.swatches) ? about.swatches : [];
701
+ const key = `${id}:${JSON.stringify(sets)}`;
702
+ if (key === dotted)
703
+ return;
704
+ dotted = key;
705
+ dots.replaceChildren();
706
+ for (const set of sets) {
707
+ if (typeof set.field !== 'string' || !Array.isArray(set.choices))
708
+ continue;
709
+ for (const choice of set.choices) {
710
+ if (typeof choice.value !== 'string' || typeof choice.colour !== 'string' || choice.colour.length > 64 || !COLOUR.test(choice.colour))
711
+ continue;
712
+ const { field } = set;
713
+ const { value } = choice;
714
+ const dot = doc.createElement('button');
715
+ dot.type = 'button';
716
+ dot.tabIndex = -1;
717
+ dot.setAttribute('data-cms-swatch', `${field}:${value}`);
718
+ dot.title = [word(set.name), word(choice.name)].filter(Boolean).join(': ');
719
+ const isChosen = set.chosen === value;
720
+ if (isChosen)
721
+ dot.setAttribute('data-cms-chosen', '');
722
+ Object.assign(dot.style, {
723
+ boxSizing: 'border-box',
724
+ width: '18px',
725
+ height: '18px',
726
+ padding: '0',
727
+ borderRadius: '50%',
728
+ border: '1px solid color-mix(in srgb, currentColor 45%, transparent)',
729
+ background: choice.colour,
730
+ outline: isChosen ? `2px solid ${ACCENT}` : 'none',
731
+ outlineOffset: '1px',
732
+ cursor: isChosen ? 'default' : 'pointer',
733
+ });
734
+ dot.addEventListener('mousedown', (event) => event.preventDefault());
735
+ dot.addEventListener('click', () => {
736
+ if (!isChosen)
737
+ say({ type: 'swatch', id, field, value });
738
+ });
739
+ dots.append(dot);
740
+ }
741
+ }
742
+ dots.style.display = dots.childElementCount > 0 ? 'flex' : 'none';
743
+ };
744
+ const adder = (action, acts = true) => {
745
+ const button = grows(doc.createElement('button'));
483
746
  button.type = 'button';
484
747
  button.tabIndex = -1;
485
748
  button.setAttribute('data-cms-tool', action);
@@ -502,21 +765,469 @@ export function previewBridge(page) {
502
765
  pointerEvents: 'auto',
503
766
  });
504
767
  button.append(drawing('add'), doc.createElement('span'));
505
- press(button, action);
768
+ if (acts)
769
+ press(button, action);
770
+ else
771
+ button.addEventListener('mousedown', (event) => event.preventDefault());
506
772
  layer.append(button);
507
773
  return button;
508
774
  };
775
+ // A line along each edge of the section the bar is on, with the button that adds a section there.
776
+ const seam = () => {
777
+ const drawn = doc.createElement('div');
778
+ drawn.setAttribute('data-cms-seam', '');
779
+ Object.assign(drawn.style, { position: 'absolute', display: 'none', height: '2px', marginTop: '-1px', background: ACCENT });
780
+ layer.append(drawn);
781
+ return drawn;
782
+ };
783
+ const seams = { addBefore: seam(), addAfter: seam() };
509
784
  const adders = { addBefore: adder('addBefore'), addAfter: adder('addAfter') };
785
+ // An empty place inside a section (a column with nothing in it yet) has a button that adds the first.
786
+ const slotOf = (element) => element.dataset['cmsSlot'] ?? '';
787
+ const fillers = new Map();
788
+ const placeFillers = (isShown) => {
789
+ const wanted = new Map();
790
+ if (isShown && tools?.slots) {
791
+ for (const slot of doc.querySelectorAll('[data-cms-slot]')) {
792
+ const about = tools.slots[slotOf(slot)];
793
+ const rect = slot.getBoundingClientRect();
794
+ if (about?.empty === true && about.full !== true && rect.bottom > 14 && rect.top < page.innerHeight - 14 && rect.width > 0)
795
+ wanted.set(slotOf(slot), rect);
796
+ }
797
+ }
798
+ for (const [key, button] of fillers) {
799
+ if (wanted.has(key))
800
+ continue;
801
+ button.remove();
802
+ fillers.delete(key);
803
+ }
804
+ for (const [key, rect] of wanted) {
805
+ let button = fillers.get(key);
806
+ if (!button) {
807
+ button = adder('fill', false);
808
+ button.setAttribute('data-cms-fill', key);
809
+ button.addEventListener('click', () => {
810
+ const at = key.indexOf(':');
811
+ say({ type: 'slot', id: key.slice(0, at), field: key.slice(at + 1) });
812
+ });
813
+ fillers.set(key, button);
814
+ }
815
+ if (button.lastElementChild)
816
+ button.lastElementChild.textContent = word(tools?.labels['add']);
817
+ const middle = Math.min(Math.max(rect.top + rect.height / 2, 16), page.innerHeight - 16);
818
+ Object.assign(button.style, { display: 'flex', top: at(middle), left: at(rect.left + rect.width / 2) });
819
+ }
820
+ };
510
821
  layer.append(bar);
511
822
  const word = (value) => (typeof value === 'string' ? value : '');
823
+ // What the editor can change from the page has a button of its own on the bar once the pointer
824
+ // has been on it: a picture, and a link or a button. The pointer may be on something the
825
+ // template lays over it, so it is found by where it is.
826
+ const chip = (name) => {
827
+ const button = doc.createElement('button');
828
+ button.type = 'button';
829
+ button.tabIndex = -1;
830
+ button.setAttribute('data-cms-tool', name);
831
+ Object.assign(button.style, {
832
+ display: 'none',
833
+ alignItems: 'center',
834
+ gap: '6px',
835
+ height: '28px',
836
+ padding: '0 10px 0 8px',
837
+ border: '0',
838
+ borderRadius: '6px',
839
+ background: ACCENT,
840
+ color: ACCENT_INK,
841
+ font: `600 12px/1 ${FONT}`,
842
+ whiteSpace: 'nowrap',
843
+ cursor: 'pointer',
844
+ });
845
+ button.append(drawing(name), doc.createElement('span'));
846
+ button.addEventListener('mousedown', (event) => event.preventDefault());
847
+ forThing.append(button);
848
+ return button;
849
+ };
850
+ let pictured = null;
851
+ const pictureBox = outline('picture', '2px');
852
+ const linkBox = outline('link', '2px');
853
+ const changer = chip('picture');
854
+ changer.addEventListener('click', () => {
855
+ if (pictured?.field !== undefined)
856
+ say({ type: 'picture', id: pictured.section, field: pictured.field });
857
+ });
858
+ let linked = null;
859
+ const linker = chip('link');
860
+ linker.addEventListener('click', () => {
861
+ if (linked?.field !== undefined)
862
+ say({ type: 'link', id: linked.section, field: linked.field });
863
+ });
864
+ // Of those that lie over one another, the smallest is the one meant.
865
+ const smallestAt = (marks, x, y) => {
866
+ let found = null;
867
+ let least = Infinity;
868
+ for (const mark of marks) {
869
+ const rect = mark.element.getBoundingClientRect();
870
+ if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom)
871
+ continue;
872
+ const size = rect.width * rect.height;
873
+ if (size < least)
874
+ [found, least] = [mark, size];
875
+ }
876
+ return found;
877
+ };
878
+ const pictureAt = (x, y) => {
879
+ const id = tooled?.dataset['cmsSection'] ?? '';
880
+ const paths = tools?.sections[id]?.pictures;
881
+ if (!tooled || !Array.isArray(paths))
882
+ return null;
883
+ return smallestAt(paths.flatMap((path) => {
884
+ const mark = typeof path === 'string' ? find(id, path) : null;
885
+ return mark?.field === undefined ? [] : [mark];
886
+ }), x, y);
887
+ };
888
+ // A link shows no words of its own: it is found by where it leads. Two addresses that lead to
889
+ // one place read the same here, whatever a preview added to one and however it ends.
890
+ const leadsTo = (href) => {
891
+ if (typeof href !== 'string' || href === '')
892
+ return null;
893
+ try {
894
+ const to = new URL(href, page.location.href);
895
+ to.searchParams.delete('preview');
896
+ return `${to.origin}${to.pathname.replace(/\/$/, '')}${to.search}${to.hash}`;
897
+ }
898
+ catch {
899
+ return null;
900
+ }
901
+ };
902
+ // Where the site found each link to an entry to lead, by `<type>:<entry>`: it says so beside this script.
903
+ let leads = null;
904
+ const linksIn = new WeakMap();
905
+ const linksOf = (section, id, paths) => {
906
+ const said = paths.join('\n');
907
+ const known = linksIn.get(section);
908
+ if (known?.said === said)
909
+ return known.found;
910
+ const found = [];
911
+ linksIn.set(section, { said, found });
912
+ const held = new Map();
913
+ try {
914
+ if (leads === null) {
915
+ const table = JSON.parse(doc.querySelector('script[data-cms-links]')?.textContent ?? '{}');
916
+ leads = typeof table === 'object' && table !== null ? table : {};
917
+ }
918
+ const values = JSON.parse(section.dataset['cmsValues'] ?? '[]');
919
+ for (const value of Array.isArray(values) ? values : []) {
920
+ if (Array.isArray(value) && typeof value[0] === 'string' && typeof value[1] === 'string')
921
+ held.set(value[0], value[1]);
922
+ }
923
+ }
924
+ catch {
925
+ return found;
926
+ }
927
+ // Fields that lead to the same place share the links that go there, in order.
928
+ const wanted = new Map();
929
+ for (const path of paths) {
930
+ if (typeof path !== 'string')
931
+ continue;
932
+ const entry = held.get(`${path}.kind`) === 'entry' ? `${held.get(`${path}.type`) ?? ''}:${held.get(`${path}.entry`) ?? ''}` : null;
933
+ const to = leadsTo(entry === null ? (held.get(`${path}.href`) ?? held.get(path)) : leads?.[entry]);
934
+ if (to !== null)
935
+ wanted.set(to, [...(wanted.get(to) ?? []), path]);
936
+ }
937
+ const going = new Map();
938
+ for (const anchor of within(section, 'a[href]')) {
939
+ const to = leadsTo(anchor.getAttribute('href'));
940
+ if (to !== null && wanted.has(to))
941
+ going.set(to, [...(going.get(to) ?? []), anchor]);
942
+ }
943
+ for (const [to, fields] of wanted) {
944
+ const anchors = going.get(to) ?? [];
945
+ anchors.forEach((element, at) => {
946
+ const field = fields[Math.min(fields.length - 1, Math.floor((at * fields.length) / anchors.length))];
947
+ if (field !== undefined)
948
+ found.push({ element, section: id, field });
949
+ });
950
+ }
951
+ return found;
952
+ };
953
+ const linkAt = (x, y) => {
954
+ const id = tooled?.dataset['cmsSection'] ?? '';
955
+ const paths = tools?.sections[id]?.links;
956
+ return tooled && Array.isArray(paths) ? smallestAt(linksOf(tooled, id, paths), x, y) : null;
957
+ };
958
+ // Words chosen in text being written have a bar of their own: bold, italic, link. The browser
959
+ // shapes the words; where a link leads is asked of the editor, which has the words to ask with.
960
+ const formatBar = grows(doc.createElement('div'));
961
+ formatBar.setAttribute('data-cms-format', '');
962
+ Object.assign(formatBar.style, {
963
+ position: 'absolute',
964
+ display: 'none',
965
+ alignItems: 'center',
966
+ gap: '2px',
967
+ padding: '2px',
968
+ borderRadius: '8px',
969
+ background: 'CanvasText',
970
+ color: 'Canvas',
971
+ boxShadow: '0 4px 12px rgb(0 0 0 / 0.25)',
972
+ pointerEvents: 'auto',
973
+ });
974
+ const chosenWords = () => {
975
+ const selection = page.getSelection();
976
+ if (!writing || !selection || selection.rangeCount === 0 || selection.isCollapsed)
977
+ return null;
978
+ const range = selection.getRangeAt(0);
979
+ return writing.mark.element.contains(range.commonAncestorContainer) ? range : null;
980
+ };
981
+ const formatTool = (name, label, press) => {
982
+ const button = doc.createElement('button');
983
+ button.type = 'button';
984
+ button.tabIndex = -1;
985
+ button.setAttribute('data-cms-format-tool', name);
986
+ button.setAttribute('data-cms-label', label);
987
+ Object.assign(button.style, { display: 'grid', placeItems: 'center', width: '28px', height: '28px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
988
+ button.append(drawing(name));
989
+ // The pointer going down must not take the chosen words away.
990
+ button.addEventListener('mousedown', (event) => event.preventDefault());
991
+ button.addEventListener('click', () => {
992
+ const range = chosenWords();
993
+ if (writing && range)
994
+ press(writing, range);
995
+ });
996
+ formatBar.append(button);
997
+ return button;
998
+ };
999
+ const shape = (command, value) => {
1000
+ if (!writing)
1001
+ return;
1002
+ doc.execCommand(command, false, value);
1003
+ tellWriting(writing);
1004
+ };
1005
+ formatTool('bold', 'bold', () => shape('bold'));
1006
+ formatTool('italic', 'italic', () => shape('italic'));
1007
+ formatTool('link', 'textLink', (now, range) => {
1008
+ const start = isElement(range.startContainer) ? range.startContainer : range.startContainer.parentElement;
1009
+ const anchor = start?.closest('a[href]');
1010
+ asking = range.cloneRange();
1011
+ say({ type: 'linkAsk', id: now.mark.section, field: now.mark.field, href: anchor && now.mark.element.contains(anchor) ? withoutPreview(anchor.getAttribute('href') ?? '') : '' });
1012
+ placeFormat();
1013
+ });
1014
+ layer.append(formatBar);
1015
+ /** The editor's answer to where a link leads: an address, nothing to take the link away, or `null` to leave it. */
1016
+ const answerLink = (href) => {
1017
+ const range = asking;
1018
+ asking = null;
1019
+ if (!writing || !range)
1020
+ return;
1021
+ writing.mark.element.focus();
1022
+ const selection = page.getSelection();
1023
+ selection?.removeAllRanges();
1024
+ selection?.addRange(range);
1025
+ if (href === '')
1026
+ shape('unlink');
1027
+ else if (typeof href === 'string')
1028
+ shape('createLink', href);
1029
+ placeFormat();
1030
+ };
1031
+ placeFormat = () => {
1032
+ const range = asking ? null : chosenWords();
1033
+ if (!range) {
1034
+ formatBar.style.display = 'none';
1035
+ return;
1036
+ }
1037
+ for (const button of formatBar.querySelectorAll('button'))
1038
+ button.title = word(tools?.labels[button.getAttribute('data-cms-label') ?? '']);
1039
+ const rect = typeof range.getBoundingClientRect === 'function' ? range.getBoundingClientRect() : (writing?.mark.element.getBoundingClientRect() ?? null);
1040
+ if (!rect)
1041
+ return;
1042
+ // Above the chosen words, and under them where the page ends above.
1043
+ 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)) });
1044
+ };
1045
+ const itemsIn = new WeakMap();
1046
+ const itemsOf = (section, id) => {
1047
+ const about = tools?.sections[id];
1048
+ const lists = Array.isArray(about?.lists) ? about.lists : [];
1049
+ const links = Array.isArray(about?.links) ? about.links : [];
1050
+ const said = JSON.stringify([lists, links]);
1051
+ const known = itemsIn.get(section);
1052
+ if (known?.said === said)
1053
+ return known.found;
1054
+ const found = [];
1055
+ itemsIn.set(section, { said, found });
1056
+ // Every element known to show a field, by the field's place.
1057
+ const shown = [...guess(section)];
1058
+ for (const marked of within(section, '[data-cms-field]'))
1059
+ shown.push([marked.dataset['cmsField'] ?? '', marked]);
1060
+ for (const link of linksOf(section, id, links))
1061
+ shown.push([link.field ?? '', link.element]);
1062
+ for (const list of lists) {
1063
+ if (typeof list !== 'object' || list === null)
1064
+ continue;
1065
+ const { field, count, full } = list;
1066
+ if (typeof field !== 'string' || typeof count !== 'number')
1067
+ continue;
1068
+ const held = new Map();
1069
+ for (const [path, element] of shown) {
1070
+ if (!path.startsWith(`${field}.`))
1071
+ continue;
1072
+ const at = Number(path.slice(field.length + 1).split('.')[0]);
1073
+ if (Number.isInteger(at) && at >= 0 && at < count)
1074
+ held.set(at, [...(held.get(at) ?? []), element]);
1075
+ }
1076
+ for (const [at, elements] of held) {
1077
+ let element = elements[0];
1078
+ if (!element)
1079
+ continue;
1080
+ while (element !== section && !elements.every((inner) => element?.contains(inner)) && element.parentElement)
1081
+ element = element.parentElement;
1082
+ // As far out as it goes without taking in another item, so the whole card is the item.
1083
+ const others = [...held].filter(([other]) => other !== at).flatMap(([, theirs]) => theirs);
1084
+ if (others.some((other) => element?.contains(other)))
1085
+ continue;
1086
+ while (others.length > 0 && element.parentElement && element.parentElement !== section && !others.some((other) => element?.parentElement?.contains(other)))
1087
+ element = element.parentElement;
1088
+ if (element !== section)
1089
+ found.push({ element, section: id, field: `${field}.${at}`, list: field, at, count, full: full === true });
1090
+ }
1091
+ }
1092
+ return found;
1093
+ };
1094
+ let itemed = null;
1095
+ /** Where the item the bar is about will be on the page drawn next. */
1096
+ let next;
1097
+ /** What the bar was on when the page was last drawn: it is on it again, with no move of the pointer. */
1098
+ let again = null;
1099
+ let forget = () => undefined;
1100
+ const itemAt = (x, y) => {
1101
+ const id = tooled?.dataset['cmsSection'] ?? '';
1102
+ if (!tooled || !tools)
1103
+ return null;
1104
+ const items = itemsOf(tooled, id);
1105
+ const mark = smallestAt(items, x, y);
1106
+ return items.find((item) => item.element === mark?.element && item.field === mark.field) ?? null;
1107
+ };
1108
+ const itemBox = outline('item', '2px');
1109
+ itemBox.style.borderStyle = 'dashed';
1110
+ const itemBar = doc.createElement('div');
1111
+ itemBar.setAttribute('data-cms-item-tools', '');
1112
+ 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 });
1113
+ const itemTool = (action) => {
1114
+ const button = doc.createElement('button');
1115
+ button.type = 'button';
1116
+ button.tabIndex = -1;
1117
+ button.setAttribute('data-cms-item-tool', action);
1118
+ Object.assign(button.style, { display: 'grid', placeItems: 'center', width: '26px', height: '26px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', cursor: 'pointer' });
1119
+ button.append(drawing(action));
1120
+ button.addEventListener('mousedown', (event) => event.preventDefault());
1121
+ button.addEventListener('click', () => {
1122
+ if (!itemed || button.disabled)
1123
+ return;
1124
+ // Where the item will be once the page is drawn again, so the bar is still about it.
1125
+ next = action === 'remove' ? undefined : itemed.at + (action === 'up' ? -1 : action === 'down' ? 1 : 0);
1126
+ say({ type: 'item', id: itemed.section, field: itemed.list, at: itemed.at, action });
1127
+ });
1128
+ itemBar.append(button);
1129
+ return button;
1130
+ };
1131
+ const itemButtons = { up: itemTool('up'), down: itemTool('down'), duplicate: itemTool('duplicate'), remove: itemTool('remove') };
1132
+ forThing.append(itemBar);
1133
+ const placeItem = () => {
1134
+ const rect = shownRect(itemed);
1135
+ if (!rect || !tools || !itemed) {
1136
+ itemBar.style.display = 'none';
1137
+ itemBox.style.display = 'none';
1138
+ return;
1139
+ }
1140
+ place(itemBox, itemed);
1141
+ // Items side by side are moved sideways, and the arrows say so.
1142
+ const beside = itemsOf(tooled ?? itemed.element, itemed.section).find((other) => other.list === itemed?.list && other.at !== itemed.at);
1143
+ const sideways = beside !== undefined && Math.abs(beside.element.getBoundingClientRect().top - rect.top) < rect.height / 2;
1144
+ const able = { up: itemed.at > 0, down: itemed.at < itemed.count - 1, duplicate: !itemed.full, remove: true };
1145
+ for (const action of ['up', 'down', 'duplicate', 'remove']) {
1146
+ const button = itemButtons[action];
1147
+ button.title = word(tools.labels[`item${action.charAt(0).toUpperCase()}${action.slice(1)}`]);
1148
+ button.disabled = !able[action];
1149
+ button.style.opacity = able[action] ? '1' : '0.4';
1150
+ button.style.cursor = able[action] ? 'pointer' : 'default';
1151
+ if (action === 'up' || action === 'down')
1152
+ button.firstElementChild?.style.setProperty('transform', sideways ? 'rotate(-90deg)' : 'none');
1153
+ }
1154
+ itemBar.style.display = 'flex';
1155
+ };
1156
+ const shownRect = (mark) => {
1157
+ const rect = !typing && !writing && !drag?.moved && mark?.element.isConnected ? mark.element.getBoundingClientRect() : null;
1158
+ return !rect || !tools || rect.bottom <= 0 || rect.top >= page.innerHeight || (rect.width === 0 && rect.height === 0) ? null : rect;
1159
+ };
1160
+ const placeChips = () => {
1161
+ const picture = shownRect(pictured);
1162
+ changer.style.display = picture && tools ? 'flex' : 'none';
1163
+ if (picture && tools && changer.lastElementChild)
1164
+ changer.lastElementChild.textContent = word(tools.labels['picture']);
1165
+ place(pictureBox, picture ? pictured : null);
1166
+ const link = shownRect(linked);
1167
+ linker.style.display = link && tools ? 'flex' : 'none';
1168
+ if (link && tools && linker.lastElementChild)
1169
+ linker.lastElementChild.textContent = word(tools.labels['link']);
1170
+ place(linkBox, link ? linked : null);
1171
+ placeItem();
1172
+ forThing.style.display = changer.style.display === 'none' && linker.style.display === 'none' && itemBar.style.display === 'none' ? 'none' : 'flex';
1173
+ placeFormat();
1174
+ };
1175
+ // What the bar is about stays as it was while the pointer travels: over nothing, and across
1176
+ // other things on its way to the bar. It turns to another thing once the pointer rests on it.
1177
+ const REST = 140;
1178
+ let resting;
1179
+ const sameThing = (one, other) => one?.element === other?.element && one?.field === other?.field;
1180
+ const pointed = (x, y, isNow) => {
1181
+ page.clearTimeout(resting);
1182
+ resting = undefined;
1183
+ const picture = pictureAt(x, y);
1184
+ const link = linkAt(x, y);
1185
+ const item = itemAt(x, y);
1186
+ if (!picture && !link && !item)
1187
+ return;
1188
+ // Less of the same thing (the card, off its picture) is no reason to take a button away.
1189
+ if ((!picture || sameThing(picture, pictured)) && (!link || sameThing(link, linked)) && (!item || sameThing(item, itemed)))
1190
+ return;
1191
+ const turn = () => {
1192
+ resting = undefined;
1193
+ pictured = picture;
1194
+ linked = link;
1195
+ itemed = item;
1196
+ placeTools();
1197
+ };
1198
+ if (isNow || (!pictured && !linked && !itemed))
1199
+ turn();
1200
+ else
1201
+ resting = page.setTimeout(turn, REST);
1202
+ };
1203
+ forget = () => {
1204
+ page.clearTimeout(resting);
1205
+ resting = undefined;
1206
+ pictured = null;
1207
+ linked = null;
1208
+ itemed = null;
1209
+ };
1210
+ doc.addEventListener('mousemove', (event) => {
1211
+ // On the layer's own buttons, what they are for stays as it was.
1212
+ if (isElement(event.target) && layer.contains(event.target)) {
1213
+ page.clearTimeout(resting);
1214
+ resting = undefined;
1215
+ return;
1216
+ }
1217
+ pointed(event.clientX, event.clientY, false);
1218
+ }, true);
512
1219
  placeTools = () => {
1220
+ placeChips();
1221
+ placeFillers(!typing && !writing && !drag?.moved);
513
1222
  const hide = () => {
514
1223
  bar.style.display = 'none';
515
1224
  adders.addBefore.style.display = 'none';
516
1225
  adders.addAfter.style.display = 'none';
1226
+ seams.addBefore.style.display = 'none';
1227
+ seams.addAfter.style.display = 'none';
517
1228
  };
518
1229
  // While words are typed, nothing sits over them.
519
- const section = typing || drag?.moved ? null : tooled?.isConnected ? tooled : null;
1230
+ const section = typing || writing || drag?.moved ? null : tooled?.isConnected ? tooled : null;
520
1231
  const about = section && tools?.sections[section.dataset['cmsSection'] ?? ''];
521
1232
  if (!section || !tools || !about)
522
1233
  return hide();
@@ -524,6 +1235,7 @@ export function previewBridge(page) {
524
1235
  if (rect.bottom <= 0 || rect.top >= page.innerHeight || (rect.width === 0 && rect.height === 0))
525
1236
  return hide();
526
1237
  named.textContent = word(about.name);
1238
+ drawDots(about, section.dataset['cmsSection'] ?? '');
527
1239
  const able = { up: about.up === true, down: about.down === true, duplicate: about.copy === true, remove: true };
528
1240
  for (const action of ['up', 'down', 'duplicate', 'remove']) {
529
1241
  const button = buttons[action];
@@ -532,19 +1244,28 @@ export function previewBridge(page) {
532
1244
  button.style.opacity = able[action] ? '1' : '0.4';
533
1245
  button.style.cursor = able[action] ? 'pointer' : 'default';
534
1246
  }
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` });
1247
+ // At the section's top corner, and at the top of the page while the section's own top is above it:
1248
+ // under what the site keeps there, so the bar never covers the site's own header.
1249
+ sorter.title = word(tools.labels['reorder']);
1250
+ sorter.style.display = word(about.list) === '' && pageOrder().length > 1 ? 'grid' : 'none';
1251
+ more.title = word(tools.labels['addAfter']);
1252
+ more.style.display = about.add === true ? 'grid' : 'none';
1253
+ 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) });
1254
+ // A bar wider than the room to its left (a narrow column) starts at the page's edge instead.
1255
+ if (bar.offsetWidth > 0 && bar.getBoundingClientRect().left < 4)
1256
+ Object.assign(bar.style, { left: at(4), right: 'auto' });
537
1257
  for (const [action, edge] of [['addBefore', rect.top], ['addAfter', rect.bottom]]) {
538
1258
  const button = adders[action];
539
1259
  // An edge that is off the page, or a page that takes no more sections, has no button.
540
1260
  const shown = about.add === true && edge >= 14 && edge <= page.innerHeight - 14;
541
1261
  button.style.display = shown ? 'flex' : 'none';
1262
+ Object.assign(seams[action].style, { display: shown ? 'block' : 'none', top: `${edge}px`, left: `${rect.left}px`, width: `${rect.width}px` });
542
1263
  if (!shown)
543
1264
  continue;
544
1265
  if (button.lastElementChild)
545
1266
  button.lastElementChild.textContent = word(tools.labels['add']);
546
1267
  button.title = word(tools.labels[action]);
547
- Object.assign(button.style, { top: `${edge}px`, left: `${rect.left + rect.width / 2}px` });
1268
+ Object.assign(button.style, { top: at(edge), left: at(rect.left + rect.width / 2) });
548
1269
  }
549
1270
  };
550
1271
  // Dragging a section by its bar: a line shows where it would land, and letting go says so to the editor.
@@ -557,29 +1278,56 @@ export function previewBridge(page) {
557
1278
  const aim = () => {
558
1279
  if (!drag)
559
1280
  return;
560
- const sections = movable();
1281
+ const { id, x, y } = drag;
1282
+ const all = movable();
1283
+ const listOf = (section) => word(tools?.sections[section.dataset['cmsSection'] ?? '']?.list);
1284
+ const home = word(tools?.sections[id]?.list);
1285
+ const group = word(tools?.sections[id]?.group);
1286
+ const dragged = all.find((section) => section.dataset['cmsSection'] === id);
1287
+ // It lands among the sections it is with, or in another place the pointer is over that takes
1288
+ // the same blocks: the smallest such place, and never one inside the section itself.
1289
+ let into = home;
1290
+ let place;
1291
+ for (const slot of doc.querySelectorAll('[data-cms-slot]')) {
1292
+ const about = tools?.slots?.[slotOf(slot)];
1293
+ if (!about || about.group !== group || dragged?.contains(slot) || (slotOf(slot) !== home && about.full === true))
1294
+ continue;
1295
+ const rect = slot.getBoundingClientRect();
1296
+ if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom)
1297
+ continue;
1298
+ if (place && place.width * place.height <= rect.width * rect.height)
1299
+ continue;
1300
+ into = slotOf(slot);
1301
+ place = rect;
1302
+ }
1303
+ const sections = all.filter((section) => listOf(section) === into);
561
1304
  const at = sections.findIndex((section) => {
562
1305
  const rect = section.getBoundingClientRect();
563
- return drag !== null && drag.y < rect.top + rect.height / 2;
1306
+ return y < rect.top + rect.height / 2;
564
1307
  });
565
1308
  const target = at < 0 ? undefined : sections[at];
566
- const own = sections.findIndex((section) => section.dataset['cmsSection'] === drag?.id);
1309
+ const own = sections.findIndex((section) => section.dataset['cmsSection'] === id);
567
1310
  const to = at < 0 ? sections.length : at;
568
1311
  // 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);
1312
+ const stays = into === home && (own < 0 || to === own || to === own + 1);
1313
+ drag.before = stays ? undefined : (target?.dataset['cmsSection'] ?? null);
1314
+ drag.into = into === home ? undefined : into;
570
1315
  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` });
1316
+ const beside = target?.getBoundingClientRect() ?? last?.getBoundingClientRect() ?? place;
1317
+ const edge = target ? target.getBoundingClientRect().top : (last?.getBoundingClientRect().bottom ?? (place ? place.top + 2 : 0));
1318
+ // Across the page for the page's own sections, and as wide as its neighbours inside a section.
1319
+ const across = into === '' || !beside ? { left: '0', right: '0', width: 'auto' } : { left: `${beside.left}px`, right: 'auto', width: `${beside.width}px` };
1320
+ Object.assign(line.style, { display: stays ? 'none' : 'block', top: `${Math.min(Math.max(edge, 2), page.innerHeight - 2)}px`, ...across });
573
1321
  };
574
1322
  const endDrag = (drop) => {
575
1323
  if (!drag)
576
1324
  return;
577
- const { id, before, moved } = drag;
1325
+ const { id, before, into, moved } = drag;
578
1326
  drag = null;
579
1327
  line.style.display = 'none';
580
1328
  Object.assign(layer.style, { pointerEvents: 'none', cursor: '' });
581
1329
  if (drop && moved && before !== undefined)
582
- say({ type: 'move', id, before });
1330
+ say({ type: 'move', id, before, ...(into !== undefined && { into }) });
583
1331
  draw();
584
1332
  };
585
1333
  // Near the top or the bottom of the page, it scrolls to bring the rest within reach.
@@ -599,7 +1347,7 @@ export function previewBridge(page) {
599
1347
  if (event.button !== 0 || !id || movable().length < 2)
600
1348
  return;
601
1349
  event.preventDefault();
602
- drag = { id, from: event.clientY, y: event.clientY, before: undefined, moved: false };
1350
+ drag = { id, from: event.clientY, x: event.clientX, y: event.clientY, into: undefined, before: undefined, moved: false };
603
1351
  // The layer takes the pointer while it drags, so nothing on the page answers to it.
604
1352
  Object.assign(layer.style, { pointerEvents: 'auto', cursor: 'grabbing' });
605
1353
  page.setTimeout(creep, 16);
@@ -608,10 +1356,18 @@ export function previewBridge(page) {
608
1356
  doc.addEventListener('mousemove', (event) => {
609
1357
  if (!drag)
610
1358
  return;
1359
+ drag.x = event.clientX;
611
1360
  drag.y = event.clientY;
612
1361
  // A few pixels of give, so a press that was only a press moves nothing.
613
1362
  if (Math.abs(drag.y - drag.from) > 4)
614
1363
  drag.moved = true;
1364
+ // A section of the page itself is moved among the page's sections by name.
1365
+ if (drag.moved && word(tools?.sections[drag.id]?.list) === '') {
1366
+ const { id } = drag;
1367
+ endDrag(false);
1368
+ openStack(id, false, event.clientY);
1369
+ return;
1370
+ }
615
1371
  if (drag.moved)
616
1372
  aim();
617
1373
  }, true);
@@ -621,6 +1377,255 @@ export function previewBridge(page) {
621
1377
  if (drag && event.key === 'Escape')
622
1378
  endDrag(false);
623
1379
  }, true);
1380
+ const ROW = 44;
1381
+ const STEP = 50;
1382
+ let stacked = null;
1383
+ let stackWords = { names: {}, title: '', done: '', up: '', down: '' };
1384
+ let shift = 0;
1385
+ const stackKey = `velocity-cms:stack:${page.location.pathname}`;
1386
+ const pageOrder = () => movable().filter((section) => word(tools?.sections[section.dataset['cmsSection'] ?? '']?.list) === '').map((section) => section.dataset['cmsSection'] ?? '');
1387
+ const stack = doc.createElement('div');
1388
+ stack.setAttribute('data-cms-stack', '');
1389
+ Object.assign(stack.style, { position: 'absolute', inset: '0', display: 'none', overflow: 'hidden', background: 'rgb(14 14 16 / 0.82)', backdropFilter: 'blur(6px)', color: '#fff', font: `500 14px/1 ${FONT}`, pointerEvents: 'auto', userSelect: 'none' });
1390
+ // The rows are as large on the person's screen as the bar is, so their places are counted in their own size.
1391
+ const column = grows(doc.createElement('div'));
1392
+ Object.assign(column.style, { position: 'absolute', top: '0', left: '50%', width: 'min(26rem, calc(100% - 32px))' });
1393
+ stack.append(column);
1394
+ layer.append(stack);
1395
+ const headOf = (now) => (now.stays ? 56 : 0);
1396
+ /** Which row the held one would land before: as many as there are rows for after the last. */
1397
+ const landing = (now) => Math.min(Math.max(Math.round(((now.y - shift) / grow - headOf(now)) / STEP), 0), now.order.length);
1398
+ const drawStack = () => {
1399
+ const now = stacked;
1400
+ stack.style.display = now ? 'block' : 'none';
1401
+ if (!now)
1402
+ return;
1403
+ const head = headOf(now);
1404
+ const dragging = now.held !== null && now.moved;
1405
+ const own = now.held === null ? -1 : now.order.indexOf(now.held);
1406
+ const to = landing(now);
1407
+ column.replaceChildren();
1408
+ Object.assign(column.style, { height: `${head + now.order.length * STEP}px`, transform: `translate(-50%, ${shift / grow}px)` });
1409
+ if (now.stays) {
1410
+ const top = doc.createElement('div');
1411
+ Object.assign(top.style, { position: 'absolute', top: '0', left: '0', right: '0', height: '40px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', font: `600 15px/1 ${FONT}` });
1412
+ const title = doc.createElement('span');
1413
+ title.textContent = stackWords.title;
1414
+ const done = doc.createElement('button');
1415
+ done.type = 'button';
1416
+ done.tabIndex = -1;
1417
+ done.setAttribute('data-cms-stack-done', '');
1418
+ done.textContent = stackWords.done;
1419
+ Object.assign(done.style, { height: '32px', padding: '0 14px', border: '0', borderRadius: '8px', background: ACCENT, color: ACCENT_INK, font: `600 13px/1 ${FONT}`, cursor: 'pointer' });
1420
+ done.addEventListener('click', () => closeStack());
1421
+ top.append(title, done);
1422
+ column.append(top);
1423
+ }
1424
+ const rowLook = { position: 'absolute', left: '0', right: '0', height: `${ROW}px`, boxSizing: 'border-box', display: 'flex', alignItems: 'center', gap: '10px', padding: '0 8px 0 12px', borderRadius: '10px' };
1425
+ now.order.forEach((id, at) => {
1426
+ const row = doc.createElement('div');
1427
+ row.setAttribute('data-cms-stack-row', id);
1428
+ const isHeld = dragging && id === now.held;
1429
+ Object.assign(row.style, rowLook, {
1430
+ top: `${head + at * STEP}px`,
1431
+ background: isHeld ? 'transparent' : 'rgb(255 255 255 / 0.1)',
1432
+ border: isHeld ? '1px dashed rgb(255 255 255 / 0.35)' : '1px solid rgb(255 255 255 / 0.14)',
1433
+ color: isHeld ? 'rgb(255 255 255 / 0.35)' : '#fff',
1434
+ cursor: now.stays ? 'grab' : 'grabbing',
1435
+ });
1436
+ const count = doc.createElement('span');
1437
+ count.textContent = String(at + 1);
1438
+ Object.assign(count.style, { width: '20px', textAlign: 'right', opacity: '0.55', font: `500 12px/1 ${FONT}` });
1439
+ const name = doc.createElement('span');
1440
+ name.textContent = stackWords.names[id] ?? '';
1441
+ Object.assign(name.style, { flex: '1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' });
1442
+ row.append(drawing('drag'), count, name);
1443
+ if (now.stays) {
1444
+ for (const [way, label, able] of [['up', stackWords.up, at > 0], ['down', stackWords.down, at < now.order.length - 1]]) {
1445
+ const nudge = doc.createElement('button');
1446
+ nudge.type = 'button';
1447
+ nudge.tabIndex = -1;
1448
+ nudge.title = label;
1449
+ nudge.disabled = !able;
1450
+ nudge.setAttribute('data-cms-stack-nudge', way);
1451
+ Object.assign(nudge.style, { display: 'grid', placeItems: 'center', width: '30px', height: '30px', padding: '0', border: '0', borderRadius: '6px', background: 'transparent', color: 'inherit', opacity: able ? '1' : '0.3', cursor: able ? 'pointer' : 'default' });
1452
+ nudge.append(drawing(way));
1453
+ nudge.addEventListener('mousedown', (event) => event.stopPropagation());
1454
+ nudge.addEventListener('click', () => {
1455
+ if (able)
1456
+ land(id, way === 'up' ? at - 1 : at + 2);
1457
+ });
1458
+ row.append(nudge);
1459
+ }
1460
+ row.addEventListener('mousedown', (event) => {
1461
+ if (event.button !== 0)
1462
+ return;
1463
+ event.preventDefault();
1464
+ Object.assign(now, { held: id, from: event.clientY, y: event.clientY, moved: false });
1465
+ });
1466
+ }
1467
+ column.append(row);
1468
+ });
1469
+ if (!dragging || now.held === null)
1470
+ return;
1471
+ // Where it would land: nowhere new before itself or before the one after it.
1472
+ if (to !== own && to !== own + 1) {
1473
+ const mark = doc.createElement('div');
1474
+ mark.setAttribute('data-cms-stack-line', String(to));
1475
+ Object.assign(mark.style, { position: 'absolute', left: '-10px', right: '-10px', top: `${head + to * STEP - 6}px`, height: '6px', borderRadius: '3px', background: ACCENT, boxShadow: `0 0 0 3px color-mix(in srgb, ${ACCENT} 30%, transparent)` });
1476
+ column.append(mark);
1477
+ }
1478
+ const ghost = doc.createElement('div');
1479
+ ghost.setAttribute('data-cms-stack-held', now.held);
1480
+ Object.assign(ghost.style, rowLook, { top: `${(now.y - shift) / grow - ROW / 2}px`, left: '40px', right: '-40px', background: ACCENT, color: ACCENT_INK, font: `600 14px/1 ${FONT}`, boxShadow: '0 12px 32px rgb(0 0 0 / 0.45)', transform: 'rotate(-1deg)', pointerEvents: 'none', cursor: 'grabbing' });
1481
+ const held = doc.createElement('span');
1482
+ held.textContent = stackWords.names[now.held] ?? '';
1483
+ Object.assign(held.style, { flex: '1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' });
1484
+ ghost.append(drawing('drag'), held);
1485
+ column.append(ghost);
1486
+ };
1487
+ const wordsNow = () => {
1488
+ if (!tools)
1489
+ return;
1490
+ const { labels, sections } = tools;
1491
+ stackWords = { names: Object.fromEntries(pageOrder().map((id) => [id, word(sections[id]?.name)])), title: word(labels['reorder']), done: word(labels['done']), up: word(labels['up']), down: word(labels['down']) };
1492
+ };
1493
+ const keepStack = () => {
1494
+ try {
1495
+ if (stacked?.stays)
1496
+ page.sessionStorage.setItem(stackKey, JSON.stringify({ order: stacked.order, words: stackWords }));
1497
+ else
1498
+ page.sessionStorage.removeItem(stackKey);
1499
+ }
1500
+ catch {
1501
+ // A page that may keep nothing opens the rows again from the bar.
1502
+ }
1503
+ };
1504
+ const closeStack = () => {
1505
+ stacked = null;
1506
+ keepStack();
1507
+ draw();
1508
+ drawStack();
1509
+ };
1510
+ /** The held section goes before the row at `to`, and the editor is told; the rows stay if they were opened to stay. */
1511
+ const land = (id, to) => {
1512
+ const now = stacked;
1513
+ if (!now)
1514
+ return false;
1515
+ const own = now.order.indexOf(id);
1516
+ if (own < 0 || to === own || to === own + 1)
1517
+ return false;
1518
+ const before = now.order[to] ?? null;
1519
+ const rest = now.order.filter((other) => other !== id);
1520
+ rest.splice(before === null ? rest.length : rest.indexOf(before), 0, id);
1521
+ now.order = rest;
1522
+ if (now.stays)
1523
+ keepStack();
1524
+ say({ type: 'move', id, before });
1525
+ drawStack();
1526
+ return true;
1527
+ };
1528
+ const openStack = (held, stays, y, order = pageOrder()) => {
1529
+ if (order.length < 2)
1530
+ return;
1531
+ wordsNow();
1532
+ stacked = { order, stays, held, from: y, y, moved: held !== null };
1533
+ const total = (headOf(stacked) + order.length * STEP) * grow;
1534
+ // Opened by a drag, the held section's own row is under the pointer; opened from the bar, the rows are in the middle.
1535
+ shift = held === null ? Math.max((page.innerHeight - total) / 2, 24) : y - (order.indexOf(held) * STEP + ROW / 2) * grow;
1536
+ tooled = null;
1537
+ forget();
1538
+ draw();
1539
+ drawStack();
1540
+ if (held !== null)
1541
+ page.setTimeout(creepStack, 16);
1542
+ };
1543
+ // Near the top or the bottom, rows out of sight come within reach.
1544
+ const creepStack = () => {
1545
+ const now = stacked;
1546
+ if (!now || now.held === null)
1547
+ return;
1548
+ const total = (headOf(now) + now.order.length * STEP) * grow;
1549
+ const by = now.y < 72 && shift < 24 ? 12 : now.y > page.innerHeight - 72 && shift + total > page.innerHeight - 24 ? -12 : 0;
1550
+ if (by !== 0 && now.moved) {
1551
+ shift += by;
1552
+ drawStack();
1553
+ }
1554
+ page.setTimeout(creepStack, 16);
1555
+ };
1556
+ doc.addEventListener('mousemove', (event) => {
1557
+ const now = stacked;
1558
+ if (!now || now.held === null)
1559
+ return;
1560
+ now.y = event.clientY;
1561
+ if (!now.moved && Math.abs(now.y - now.from) > 4) {
1562
+ now.moved = true;
1563
+ page.setTimeout(creepStack, 16);
1564
+ }
1565
+ if (now.moved)
1566
+ drawStack();
1567
+ }, true);
1568
+ const letGo = (drop) => {
1569
+ const now = stacked;
1570
+ if (!now || now.held === null)
1571
+ return;
1572
+ const { held, moved } = now;
1573
+ const to = landing(now);
1574
+ now.held = null;
1575
+ now.moved = false;
1576
+ const landed = drop && moved && land(held, to);
1577
+ if (now.stays)
1578
+ drawStack();
1579
+ // Dropped, the rows stay in their new order until the page drawn from it takes their place.
1580
+ else if (landed)
1581
+ page.setTimeout(() => stacked === now && closeStack(), 4000);
1582
+ else
1583
+ closeStack();
1584
+ };
1585
+ doc.addEventListener('mouseup', () => letGo(true), true);
1586
+ doc.documentElement.addEventListener('mouseleave', () => letGo(false));
1587
+ doc.addEventListener('keydown', (event) => {
1588
+ if (!stacked || event.key !== 'Escape')
1589
+ return;
1590
+ event.stopPropagation();
1591
+ if (stacked.held !== null && stacked.stays)
1592
+ letGo(false);
1593
+ else
1594
+ closeStack();
1595
+ }, true);
1596
+ // A press beside the rows closes them.
1597
+ stack.addEventListener('mousedown', (event) => {
1598
+ if (event.target === stack && stacked?.stays)
1599
+ closeStack();
1600
+ });
1601
+ stack.addEventListener('wheel', (event) => {
1602
+ const now = stacked;
1603
+ if (!now)
1604
+ return;
1605
+ event.preventDefault();
1606
+ const total = (headOf(now) + now.order.length * STEP) * grow;
1607
+ shift = Math.min(Math.max(shift - event.deltaY, Math.min(page.innerHeight - total - 24, 24)), 24);
1608
+ drawStack();
1609
+ }, { passive: false });
1610
+ // Rows that were open when a move drew the page again are open on it at once, in the new order.
1611
+ try {
1612
+ const read = JSON.parse(page.sessionStorage.getItem(stackKey) ?? 'null');
1613
+ const was = typeof read === 'object' && read !== null ? read : {};
1614
+ if (Array.isArray(was.order) && was.order.every((id) => typeof id === 'string') && typeof was.words === 'object' && was.words !== null) {
1615
+ const words = was.words;
1616
+ const names = typeof words.names === 'object' && words.names !== null ? words.names : {};
1617
+ stackWords = { names: Object.fromEntries(Object.entries(names).map(([id, name]) => [id, word(name)])), title: word(words.title), done: word(words.done), up: word(words.up), down: word(words.down) };
1618
+ const order = was.order;
1619
+ if (order.length > 1) {
1620
+ stacked = { order, stays: true, held: null, from: 0, y: 0, moved: false };
1621
+ shift = Math.max((page.innerHeight - (56 + order.length * STEP) * grow) / 2, 24);
1622
+ drawStack();
1623
+ }
1624
+ }
1625
+ }
1626
+ catch {
1627
+ // Nothing kept, or nothing that can be read: the rows are opened from the bar.
1628
+ }
624
1629
  // Events.
625
1630
  doc.addEventListener('mouseover', (event) => {
626
1631
  // Over the layer's own bar and buttons, what they are for stays as it was.
@@ -629,12 +1634,18 @@ export function previewBridge(page) {
629
1634
  marks.over = markOf(event.target);
630
1635
  if (marks.over)
631
1636
  marks.over.element.style.cursor = runFor(marks.over) ? 'text' : 'pointer';
632
- tooled = isElement(event.target) ? event.target.closest('[data-cms-section]') : null;
1637
+ // Over what is no section (a header, a gap), the bar stays with the section it was on.
1638
+ const section = isElement(event.target) ? event.target.closest('[data-cms-section]') : null;
1639
+ if (section && section !== tooled) {
1640
+ tooled = section;
1641
+ forget();
1642
+ }
633
1643
  draw();
634
1644
  });
635
1645
  doc.documentElement.addEventListener('mouseleave', () => {
636
1646
  marks.over = null;
637
1647
  tooled = null;
1648
+ forget();
638
1649
  draw();
639
1650
  });
640
1651
  // Nothing on the page goes anywhere: a click chooses what it is on.
@@ -643,14 +1654,20 @@ export function previewBridge(page) {
643
1654
  // A press on the layer's own bar is that button's business.
644
1655
  if (isElement(event.target) && layer.contains(event.target))
645
1656
  return;
1657
+ // A press, or a tap where there is no pointer to rest, says at once what the bar is about.
1658
+ pointed(event.clientX, event.clientY, true);
646
1659
  const mark = markOf(event.target);
647
1660
  if (!mark)
648
1661
  return;
649
1662
  marks.chosen = mark;
650
1663
  draw();
651
- say({ type: 'section', id: mark.section, ...(mark.field !== undefined && { field: mark.field }) });
1664
+ // A field that is not being typed into here, where it is, is one for the form.
1665
+ const here = typing?.mark.element === mark.element || writing?.mark.element === mark.element;
1666
+ say({ type: 'section', id: mark.section, ...(mark.field !== undefined && { field: mark.field, ...(!here && { form: true }) }) });
652
1667
  }, true);
653
1668
  doc.addEventListener('submit', (event) => event.preventDefault(), true);
1669
+ // True once the page is where it should be: the person scrolled it, or the editor asked for a part of it.
1670
+ let settled = false;
654
1671
  page.addEventListener('message', (event) => {
655
1672
  if (event.origin !== origin || event.source !== page.parent || event.data?.source !== SOURCE)
656
1673
  return;
@@ -659,42 +1676,137 @@ export function previewBridge(page) {
659
1676
  typable = typeof places === 'object' && places !== null ? places : {};
660
1677
  return;
661
1678
  }
1679
+ if (event.data.type === 'linkAnswer') {
1680
+ answerLink(event.data.href);
1681
+ return;
1682
+ }
1683
+ if (event.data.type === 'zoom') {
1684
+ // How much smaller than life the editor shows the page: between a tenth and life size.
1685
+ const scale = event.data.scale;
1686
+ const next = typeof scale === 'number' && scale >= 0.1 && scale < 1 ? 1 / scale : 1;
1687
+ if (next !== grow) {
1688
+ grow = next;
1689
+ for (const element of grown) {
1690
+ if (grow === 1)
1691
+ element.style.removeProperty('zoom');
1692
+ else
1693
+ element.style.setProperty('zoom', String(grow));
1694
+ }
1695
+ draw();
1696
+ placeFormat();
1697
+ }
1698
+ return;
1699
+ }
662
1700
  if (event.data.type === 'tools') {
663
1701
  const said = event.data;
664
1702
  const isRecord = (value) => typeof value === 'object' && value !== null;
665
- tools = isRecord(said.labels) && isRecord(said.sections) ? { labels: said.labels, sections: said.sections } : null;
1703
+ const slots = said.slots;
1704
+ tools = isRecord(said.labels) && isRecord(said.sections) ? { labels: said.labels, sections: said.sections, ...(isRecord(slots) && { slots: slots }) } : null;
1705
+ if (again && tools && !tooled) {
1706
+ const was = again;
1707
+ tooled = [...doc.querySelectorAll('[data-cms-section]')].find((section) => section.dataset['cmsSection'] === was.id) ?? null;
1708
+ if (tooled && was.list !== undefined)
1709
+ itemed = itemsOf(tooled, was.id).find((item) => item.list === was.list && item.at === was.at) ?? null;
1710
+ }
1711
+ if (tools)
1712
+ again = null;
1713
+ if (stacked && stacked.held === null && tools) {
1714
+ // The page as it is now says the order and the names.
1715
+ const order = pageOrder();
1716
+ if (order.length > 1)
1717
+ stacked.order = order;
1718
+ wordsNow();
1719
+ drawStack();
1720
+ }
666
1721
  draw();
667
1722
  return;
668
1723
  }
669
1724
  if (event.data.type !== 'show' || typeof event.data.id !== 'string')
670
1725
  return;
671
1726
  // While words are typed into a section, the outline stays on the field they go into.
672
- if (typing?.mark.section === event.data.id)
1727
+ if (typing?.mark.section === event.data.id || writing?.mark.section === event.data.id)
673
1728
  return;
674
1729
  const mark = find(event.data.id, typeof event.data.field === 'string' ? event.data.field : undefined);
675
1730
  if (!mark)
676
1731
  return;
677
1732
  marks.chosen = mark;
678
1733
  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) {
1734
+ // What is already in view stays where it is: the page does not jump while someone types. Nor
1735
+ // does a page drawn again, which is where the person left it: the editor says so (`still`).
1736
+ if (event.data.still !== true && (rect.bottom <= 0 || rect.top >= page.innerHeight)) {
681
1737
  // Room for a header that stays at the top of the page.
682
1738
  mark.element.style.scrollMarginTop = '6rem';
1739
+ settled = true;
683
1740
  mark.element.scrollIntoView({ block: 'start' });
684
1741
  }
685
1742
  draw();
686
1743
  });
687
1744
  // Scroll.
1745
+ // A page drawn again is where it was: by the section that was in the window and where in it, so
1746
+ // it stays put even when something above is taller or shorter now, and else by how far down it was.
688
1747
  const key = `velocity-cms:scroll:${page.location.pathname}`;
689
1748
  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)));
1749
+ let kept = {};
1750
+ try {
1751
+ const read = JSON.parse(page.sessionStorage.getItem(key) ?? 'null');
1752
+ kept = typeof read === 'number' ? { y: read } : typeof read === 'object' && read !== null ? read : {};
1753
+ }
1754
+ catch {
1755
+ // What was kept another way is as good as nothing kept.
1756
+ }
1757
+ if (kept.on === true && typeof kept.id === 'string')
1758
+ again = { id: kept.id, ...(typeof kept.list === 'string' && typeof kept.at === 'number' && { list: kept.list, at: kept.at }) };
1759
+ const back = () => {
1760
+ if (typeof kept.y !== 'number' || !(kept.y > 0))
1761
+ return;
1762
+ const section = [...doc.querySelectorAll('[data-cms-section]')].find((candidate) => candidate.dataset['cmsSection'] === kept.id);
1763
+ const to = section && typeof kept.top === 'number' ? page.scrollY + section.getBoundingClientRect().top - kept.top : kept.y;
1764
+ if (Math.abs(page.scrollY - to) > 1)
1765
+ page.scrollTo({ top: Math.max(to, 0), behavior: 'instant' });
1766
+ };
1767
+ back();
1768
+ // A page that is not as tall yet as it will be (photos, fonts) is put back again as it settles,
1769
+ // until the person scrolls it or the editor asks for another part of it.
1770
+ for (const sign of ['wheel', 'touchmove', 'keydown', 'mousedown'])
1771
+ page.addEventListener(sign, () => (settled = true), { once: true, capture: true, passive: true });
1772
+ let tries = 0;
1773
+ const settle = () => {
1774
+ if (settled)
1775
+ return;
1776
+ back();
1777
+ if (++tries < 20)
1778
+ page.setTimeout(settle, 100);
1779
+ };
1780
+ page.setTimeout(settle, 100);
1781
+ page.addEventListener('load', () => {
1782
+ if (!settled)
1783
+ back();
1784
+ });
1785
+ page.addEventListener('pagehide', () => {
1786
+ // The section being worked on, or else the first one in the window.
1787
+ const inView = (section) => {
1788
+ const rect = section?.isConnected ? section.getBoundingClientRect() : null;
1789
+ return rect !== null && rect.bottom > 0 && rect.top < page.innerHeight;
1790
+ };
1791
+ const section = inView(tooled) ? tooled : [...doc.querySelectorAll('[data-cms-section]')].find(inView);
1792
+ const item = section === tooled && itemed ? { list: itemed.list, at: next ?? itemed.at } : undefined;
1793
+ page.sessionStorage.setItem(key, JSON.stringify({ y: page.scrollY, ...(section && { id: section.dataset['cmsSection'], top: section.getBoundingClientRect().top, on: section === tooled, ...item }) }));
1794
+ });
694
1795
  }
695
1796
  catch {
696
1797
  // A page that may not keep anything starts at the top.
697
1798
  }
1799
+ // The page is drawn again in place: a template's fade from one page to the next is for visitors.
1800
+ // The turn itself is kept, since it holds the page as it was on screen until this one is ready,
1801
+ // and is made to take no time. The rule is the bridge's own sheet, not a change to the page's.
1802
+ try {
1803
+ const sheet = new page.CSSStyleSheet();
1804
+ sheet.replaceSync('::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; }');
1805
+ doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet];
1806
+ }
1807
+ catch {
1808
+ // A browser without such sheets shows the template's own turn.
1809
+ }
698
1810
  say({ type: 'ready' });
699
1811
  }
700
1812
  /** The bridge as the page is sent it. */