@astl/editor 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,6 +31,85 @@ import { fitViewport, inheritTokens, kitStyles, VIEWPORT_MARGIN } from './styles
31
31
  /** Kit items a host can feature besides component tags (`tag`) and starters (`tag:template`). */
32
32
  export const FEATURED_ITEMS: readonly string[] = ['text', 'picture', 'page-break'];
33
33
 
34
+ /**
35
+ * A name of the toolbar's items, for its layout (`ToolbarLayout`). `featured` stands for the featured inserts in their
36
+ * order, `wraps` for the types' commands on the selection ("Mark word") and `views` for the view switch.
37
+ */
38
+ export type ToolbarItem =
39
+ | 'style'
40
+ | 'font'
41
+ | 'size'
42
+ | 'bold'
43
+ | 'italic'
44
+ | 'underline'
45
+ | 'link'
46
+ | 'color'
47
+ | 'highlight'
48
+ | 'align'
49
+ | 'spacing'
50
+ | 'bulleted'
51
+ | 'numbered'
52
+ | 'clear'
53
+ | 'featured'
54
+ | 'elements'
55
+ | 'templates'
56
+ | 'layouts'
57
+ | 'wraps'
58
+ | 'views'
59
+ | 'undo'
60
+ | 'redo';
61
+
62
+ /** The toolbar's groups of items, in order: a rule parts each group from the one before. */
63
+ export type ToolbarLayout = readonly (readonly ToolbarItem[])[];
64
+
65
+ /**
66
+ * The toolbar's own layout: the text style; font and size; the marks and link; the colours; alignment and spacing; the
67
+ * lists and clear formatting; the inserts; the types' commands; the view switch; undo and redo.
68
+ */
69
+ export const DEFAULT_TOOLBAR_LAYOUT: ToolbarLayout = [
70
+ ['style'],
71
+ ['font', 'size'],
72
+ ['bold', 'italic', 'underline', 'link'],
73
+ ['color', 'highlight'],
74
+ ['align', 'spacing'],
75
+ ['bulleted', 'numbered', 'clear'],
76
+ ['featured', 'elements', 'templates', 'layouts'],
77
+ ['wraps'],
78
+ ['views'],
79
+ ['undo', 'redo'],
80
+ ];
81
+
82
+ /** Every item of the toolbar, by name, in the default layout's order: the formats, then the actions. */
83
+ export const TOOLBAR_ITEMS: readonly ToolbarItem[] = DEFAULT_TOOLBAR_LAYOUT.flat();
84
+
85
+ /** The formats, from the text style to clear formatting: on a phone a group of them alone scrolls in a row. */
86
+ const FORMATS: ReadonlySet<string> = new Set(TOOLBAR_ITEMS.slice(0, TOOLBAR_ITEMS.indexOf('featured')));
87
+ const INSERTS: ReadonlySet<string> = new Set(['featured', 'elements', 'templates', 'layouts']);
88
+ /** The items of one button each, whose id is their name. */
89
+ const SINGLE_ITEMS: readonly string[] = TOOLBAR_ITEMS.filter(
90
+ (name) => name !== 'featured' && name !== 'wraps' && name !== 'views',
91
+ );
92
+
93
+ /** A button's part by its id: a starter's `:`, and anything else a CSS name cannot hold, becomes `_`. */
94
+ const partOf = (id: string): string => `button-${id.replace(/[^A-Za-z0-9-]/g, '_')}`;
95
+
96
+ /**
97
+ * The part of every button a toolbar may draw (`button-<name>`) with these featured inserts, types with a command
98
+ * (their tags) and views, for an element that holds a toolbar and exports its parts.
99
+ */
100
+ export function toolbarButtonParts(options: {
101
+ readonly featured: readonly string[];
102
+ readonly wraps: readonly string[];
103
+ readonly views: readonly string[];
104
+ }): string[] {
105
+ return [
106
+ ...SINGLE_ITEMS,
107
+ ...options.featured.map((name) => `insert-${name}`),
108
+ ...options.wraps.map((tag) => `wrap-${tag}`),
109
+ ...options.views.map((name) => `view-${name}`),
110
+ ].map(partOf);
111
+ }
112
+
34
113
  const ICONS = {
35
114
  bold: svg`<path d="M6 4h5a3 3 0 0 1 0 6H6zm0 6h6a3 3 0 0 1 0 6H6z" stroke-width="2"/>`,
36
115
  italic: svg`<path d="M9 4h7M4 16h7M12.5 4l-5 12"/>`,
@@ -123,17 +202,32 @@ interface Item {
123
202
 
124
203
  const NO_STATE: EditorFormatState = { active: [], enabled: [], href: null, undo: false, redo: false };
125
204
 
205
+ /** A group of the bar, in its layout's order. */
206
+ interface Group {
207
+ readonly items: readonly Item[];
208
+ /** Formats alone: on a phone it scrolls in a row with the format groups beside it. */
209
+ readonly format: boolean;
210
+ /** The view switch, a radio group of its own. */
211
+ readonly views: boolean;
212
+ /** It holds inserts (a hook for tests and the class `inserts`). */
213
+ readonly inserts: boolean;
214
+ /** The rest of a layout's group the view switch parted: no rule before it. */
215
+ readonly continued: boolean;
216
+ }
217
+
126
218
  /**
127
- * The bar: groups with a thin rule between them (each group's `separator`, a part a host can redraw), undo and redo at
128
- * its end. A group that wraps to the start of a row has its rule on the bar's own border, where it does not show. Wider
129
- * than a phone, the groups wrap into rows when they do not fit, so every button is on show. The groups sit in two
130
- * wrappers, the formats (`formats`: the text style to the lists) and the actions (`actions`: the inserts, the types'
131
- * commands, the view switch, undo and redo), which only a phone lays out: there the formats are one row that scrolls
132
- * sideways, as a mobile editor's (wrapped, they would push the text below the fold), and the actions wrap under it, so
133
- * none of them is ever out of sight. A shade at an edge of the formats says more buttons lie that way (the covers
134
- * scroll with the buttons and hide it at either end), and the arrow keys scroll the focused button into view. The
135
- * actions wrap button by button, without rules (a group that wrapped as a whole would take a row of its own): only the
136
- * view switch and undo with redo stay together.
219
+ * The bar: groups with a thin rule between them (each group's `separator`, a part a host can redraw), in the order of
220
+ * `layout`; undo and redo, as its last group, at its end. A group that wraps to the start of a row has its rule on the
221
+ * bar's own border, where it does not show. Wider than a phone, the groups wrap into rows when they do not fit, so every
222
+ * button is on show. Each run of groups of formats alone sits in a wrapper (`formats`) and each run of the others in
223
+ * another (`actions`: the inserts, the types' commands, the view switch, undo and redo), which only a phone lays out:
224
+ * there a run of formats is one row that scrolls sideways, as a mobile editor's (wrapped, they would push the text below
225
+ * the fold), and the actions wrap, so none of them is ever out of sight. A shade at an edge of the formats says more
226
+ * buttons lie that way (the covers scroll with the buttons and hide it at either end), and the arrow keys scroll the
227
+ * focused button into view. The actions wrap button by button, without rules (a group that wrapped as a whole would
228
+ * take a row of its own): only the view switch and undo with redo stay together. The host's own elements (the `start`
229
+ * and `end` slots) sit at the bar's ends and wrap with its groups; on a phone they wrap with the run of actions beside
230
+ * them, or take a row of their own beside a run of formats.
137
231
  */
138
232
  const barStyles: CSSResult = css`
139
233
  :host {
@@ -152,9 +246,13 @@ const barStyles: CSSResult = css`
152
246
  background: var(--astl-surface);
153
247
  }
154
248
  .formats,
155
- .actions {
249
+ .actions,
250
+ .host {
156
251
  display: contents;
157
252
  }
253
+ .host[hidden] {
254
+ display: none;
255
+ }
158
256
  .group {
159
257
  display: flex;
160
258
  flex-wrap: wrap;
@@ -162,7 +260,7 @@ const barStyles: CSSResult = css`
162
260
  gap: var(--astl-space-1);
163
261
  }
164
262
  .group + .group,
165
- .formats + .actions > .group:first-child {
263
+ :is(.formats, .actions) + :is(.formats, .actions) > .group:first-child {
166
264
  position: relative;
167
265
  margin-inline-start: calc(-1 * var(--astl-space-2) - var(--astl-outline-width));
168
266
  padding-inline-start: calc(var(--astl-space-2) + var(--astl-outline-width));
@@ -173,7 +271,7 @@ const barStyles: CSSResult = css`
173
271
  inset-inline-start: 0;
174
272
  border-inline-start: var(--astl-outline-width) solid var(--astl-line);
175
273
  }
176
- .group.history {
274
+ .group.history.end {
177
275
  margin-inline-start: auto;
178
276
  }
179
277
  @container (inline-size < 30rem) {
@@ -182,27 +280,35 @@ const barStyles: CSSResult = css`
182
280
  align-items: stretch;
183
281
  }
184
282
  .formats,
185
- .actions {
283
+ .actions,
284
+ .host {
186
285
  display: flex;
187
286
  align-items: center;
188
287
  }
189
- .actions {
288
+ .actions,
289
+ .host {
190
290
  flex-wrap: wrap;
191
291
  gap: var(--astl-space-1);
192
292
  }
193
- .actions > .group:not(.views, .history) {
293
+ .actions > .group:not(.views, .history),
294
+ .actions > .host:not([hidden]) {
194
295
  display: contents;
195
296
  }
196
- .actions .separator {
297
+ .actions .separator,
298
+ .formats > .group:first-child > .separator {
197
299
  display: none;
198
300
  }
199
- .actions > .group {
301
+ .actions > .group,
302
+ .formats > .group:first-child {
200
303
  margin-inline-start: 0;
201
304
  }
305
+ .formats > .group:first-child,
202
306
  .actions > .history {
203
- margin-inline-start: auto;
204
307
  padding-inline-start: 0;
205
308
  }
309
+ .actions > .history.end {
310
+ margin-inline-start: auto;
311
+ }
206
312
  .formats {
207
313
  --ring: calc(var(--astl-editor-focus-width, 2px) + var(--astl-editor-focus-offset, 1px));
208
314
  gap: var(--astl-space-1) calc(2 * var(--astl-space-2) + var(--astl-outline-width));
@@ -424,15 +530,16 @@ const popupStyles: CSSResult = css`
424
530
  `;
425
531
 
426
532
  /**
427
- * `<astl-toolbar>`: a word processor's toolbar for the editor in `adapter`, one row while it fits. In order: the text
428
- * style (a menu: paragraph, heading, subheading), bold, italic, underline, link, the two lists; the host's `featured`
429
- * inserts as buttons, "Elements" (every component and content insert) and "Templates" (the named starters), menus with
430
- * a search over one `<astl-insert-menu>`; the types' commands on the selection (`EditorDescriptor.wrap`, "Mark
431
- * word"); the view switch (`views`, two or more: a segmented control of radios); undo and redo at the end. Controls
432
- * the adapter has no capability for are left out (`format`, `undo`, `wrap`). One tab stop: the arrow keys, Home and
433
- * End move along it. Format buttons show the state at the cursor: pressed, or unavailable (`aria-disabled`, still
434
- * focusable). A press never moves the editor's cursor: a pointer's leaves the focus in the editor, and a key's gives
435
- * it back.
533
+ * `<astl-toolbar>`: a word processor's toolbar for the editor in `adapter`, one row while it fits. By default, in order:
534
+ * the text style (a menu: paragraph, heading, subheading), bold, italic, underline, link, the two lists; the host's
535
+ * `featured` inserts as buttons, "Elements" (every component and content insert) and "Templates" (the named starters),
536
+ * menus with a search over one `<astl-insert-menu>`; the types' commands on the selection (`EditorDescriptor.wrap`,
537
+ * "Mark word"); the view switch (`views`, two or more: a segmented control of radios); undo and redo at the end.
538
+ * `layout` names the items and their order. Controls the adapter has no capability for are left out (`format`, `undo`,
539
+ * `wrap`). One tab stop: the arrow keys, Home and End move along it. Format buttons show the state at the cursor:
540
+ * pressed, or unavailable (`aria-disabled`, still focusable). A press never moves the editor's cursor: a pointer's
541
+ * leaves the focus in the editor, and a key's gives it back. Each button is a part, `button button-<name>`. The host's
542
+ * elements in the slots `start` and `end` sit at the bar's ends, each with its own tab stop.
436
543
  */
437
544
  export class AstlToolbar extends AuthoringElement {
438
545
  static override properties: PropertyDeclarations = {
@@ -440,6 +547,7 @@ export class AstlToolbar extends AuthoringElement {
440
547
  featured: { attribute: false },
441
548
  views: { attribute: false },
442
549
  view: {},
550
+ layout: { attribute: false },
443
551
  };
444
552
 
445
553
  static override styles: CSSResultGroup = [
@@ -464,6 +572,12 @@ export class AstlToolbar extends AuthoringElement {
464
572
  declare views: readonly ToolbarView[];
465
573
  /** The name of the current view. */
466
574
  declare view: string;
575
+ /**
576
+ * The items and their order: groups of item names (`TOOLBAR_ITEMS`), a rule between groups. An item that is not named
577
+ * is not drawn; an unknown name is skipped, a name given twice shows at its first place, and the view switch is a
578
+ * group of its own. Default: `DEFAULT_TOOLBAR_LAYOUT`.
579
+ */
580
+ declare layout: ToolbarLayout;
467
581
 
468
582
  #state: EditorFormatState = NO_STATE;
469
583
  #styles: EditorStyleState | null = null;
@@ -486,11 +600,17 @@ export class AstlToolbar extends AuthoringElement {
486
600
  axis: 'inline',
487
601
  });
488
602
 
603
+ /** Whether the host's `start` and `end` slots have elements: an end is laid out only while its slot has. */
604
+ #slotted = { start: false, end: false };
605
+ /** Where Escape is heard: the toolbar's root (the shadow root of an editor around it) and the document. */
606
+ #heard: readonly (Document | ShadowRoot)[] = [];
607
+
489
608
  constructor() {
490
609
  super();
491
610
  this.featured = [];
492
611
  this.views = [];
493
612
  this.view = '';
613
+ this.layout = DEFAULT_TOOLBAR_LAYOUT;
494
614
  }
495
615
 
496
616
  /** The insert menu of "Elements" and "Templates": insert from it as a host would from `<astl-insert-menu>`. */
@@ -498,6 +618,15 @@ export class AstlToolbar extends AuthoringElement {
498
618
  return this.renderRoot.querySelector<AstlInsertMenu>('astl-insert-menu');
499
619
  }
500
620
 
621
+ /**
622
+ * Whether one of the toolbar's popups is open: the style menu, the link dialog, an insert menu, a style popup or the
623
+ * style panel. An Escape that closes one goes no further than the toolbar's root, so a keydown listener on an
624
+ * editor around it never hears it.
625
+ */
626
+ get popupOpen(): boolean {
627
+ return this.#popup !== null;
628
+ }
629
+
501
630
  /** Opens "Elements", "Templates" or "Layout" with its search, as its button does. */
502
631
  async openMenu(menu: InsertMenu): Promise<void> {
503
632
  await this.#open(menu);
@@ -538,7 +667,11 @@ export class AstlToolbar extends AuthoringElement {
538
667
  super.connectedCallback();
539
668
  this.#follow();
540
669
  document.addEventListener('pointerdown', this.#outside, true);
541
- document.addEventListener('keydown', this.#escape);
670
+ // The root first: an Escape from inside an editor around the toolbar (its text, its card) passes it before it
671
+ // reaches the editor and the host's listeners there. The document hears the rest of the page.
672
+ const root = this.getRootNode();
673
+ this.#heard = root instanceof ShadowRoot ? [root, document] : [document];
674
+ for (const target of this.#heard) target.addEventListener('keydown', this.#escape as EventListener);
542
675
  window.addEventListener('resize', this.#replace);
543
676
  }
544
677
 
@@ -546,7 +679,8 @@ export class AstlToolbar extends AuthoringElement {
546
679
  super.disconnectedCallback();
547
680
  this.#follow();
548
681
  document.removeEventListener('pointerdown', this.#outside, true);
549
- document.removeEventListener('keydown', this.#escape);
682
+ for (const target of this.#heard) target.removeEventListener('keydown', this.#escape as EventListener);
683
+ this.#heard = [];
550
684
  window.removeEventListener('resize', this.#replace);
551
685
  }
552
686
 
@@ -568,6 +702,19 @@ export class AstlToolbar extends AuthoringElement {
568
702
  this.#off = { adapter, off: listen.call(adapter, () => this.requestUpdate()) };
569
703
  }
570
704
 
705
+ /**
706
+ * Whether an end has the host's elements: flattened, as an editor around the toolbar passes its own slot on, and it
707
+ * tells of changes there too (its event bubbles through this slot).
708
+ */
709
+ #slotChange = (event: Event): void => {
710
+ const slot = event.currentTarget as HTMLSlotElement;
711
+ const name = slot.name === 'end' ? 'end' : 'start';
712
+ const has = slot.assignedElements({ flatten: true }).length > 0;
713
+ if (this.#slotted[name] === has) return;
714
+ this.#slotted[name] = has;
715
+ this.requestUpdate();
716
+ };
717
+
571
718
  /** A press outside the open popup and its button closes it. */
572
719
  #outside = (event: Event): void => {
573
720
  if (this.#popup === null) return;
@@ -581,14 +728,18 @@ export class AstlToolbar extends AuthoringElement {
581
728
  };
582
729
 
583
730
  /**
584
- * The style panel is not modal: the focus can leave it, by Tab or to the surface after an undo, and it stays open
585
- * over what it covers. Escape closes it from there too; only from inside does the focus go back to its button.
731
+ * Escape closes the open popup, from inside it (the focus goes back to its button) or from anywhere else: the style
732
+ * panel is not modal, and the focus can leave it, by Tab or to the surface after an undo, while it stays open over
733
+ * what it covers. The key goes no further, so a host's listener on an editor around the toolbar hears only the
734
+ * Escapes no popup used: `defaultPrevented` cannot tell it, as ProseMirror claims every Escape in the text.
586
735
  */
587
736
  #escape = (event: KeyboardEvent): void => {
588
- if (this.#popup !== 'panel' || event.key !== 'Escape') return;
589
- const panel = this.renderRoot.querySelector('#panel');
590
- const inside = panel !== null && event.composedPath().includes(panel);
591
- // Inside, a field may have its own use for the key (a rename). ProseMirror claims every Escape, with no use for it.
737
+ const open = this.#popup;
738
+ if (open === null || event.key !== 'Escape') return;
739
+ const popup = this.renderRoot.querySelector(`#${popoverOf(open)}`);
740
+ const inside = popup !== null && event.composedPath().includes(popup);
741
+ event.stopPropagation();
742
+ // Inside, a field may have its own use for the key (a rename): the popup stays.
592
743
  if (inside && event.defaultPrevented) return;
593
744
  event.preventDefault();
594
745
  this.#close(inside);
@@ -737,10 +888,10 @@ export class AstlToolbar extends AuthoringElement {
737
888
  return known?.name ?? (stack.split(',')[0] ?? '').replace(/"/g, '').trim();
738
889
  }
739
890
 
740
- /** The bar's style controls, by group (font and size; colours; alignment and spacing), and clear formatting. */
741
- #styleGroups(): { fonts: Item[]; colors: Item[]; blocks: Item[]; clear: Item[] } {
891
+ /** The bar's style controls (font, size, the colours, alignment, spacing) and clear formatting; their ids are names. */
892
+ #styleItems(): Item[] {
742
893
  const styles = this.#styles;
743
- if (styles === null) return { fonts: [], colors: [], blocks: [], clear: [] };
894
+ if (styles === null) return [];
744
895
  const { text, textEnabled, targets } = styles;
745
896
  const hasBlock = targets.some((target) => target.kind === 'block');
746
897
  const popupItem = (
@@ -785,38 +936,33 @@ export class AstlToolbar extends AuthoringElement {
785
936
  : align === 'justify'
786
937
  ? 'align-justify'
787
938
  : 'align-start';
788
- return {
789
- fonts: [valued('font', 'toolbar.font', font), valued('size', 'toolbar.size', size)],
790
- colors: [
791
- {
792
- ...popupItem('color', this.t('toolbar.color'), textEnabled, ICONS.color, 'color'),
793
- bar: text.color ?? null,
794
- },
795
- {
796
- ...popupItem('highlight', this.t('toolbar.highlight'), textEnabled, ICONS.highlight, 'highlight'),
797
- bar: text['background-color'] ?? null,
798
- },
799
- ],
800
- blocks: [
801
- popupItem('align', this.t('toolbar.align'), hasBlock, ICONS[alignIcon], alignIcon),
802
- popupItem('spacing', this.t('toolbar.spacing'), hasBlock, ICONS.spacing, 'spacing'),
803
- ],
804
- clear: [
805
- {
806
- id: 'clear',
807
- label: this.t('toolbar.clear'),
808
- text: null,
809
- icon: ICONS.clear,
810
- iconName: 'clear',
811
- disabled: !textEnabled && !hasBlock,
812
- press: () => {
813
- this.adapter?.style?.clear();
814
- this.#done();
815
- this.requestUpdate();
816
- },
939
+ return [
940
+ valued('font', 'toolbar.font', font),
941
+ valued('size', 'toolbar.size', size),
942
+ {
943
+ ...popupItem('color', this.t('toolbar.color'), textEnabled, ICONS.color, 'color'),
944
+ bar: text.color ?? null,
945
+ },
946
+ {
947
+ ...popupItem('highlight', this.t('toolbar.highlight'), textEnabled, ICONS.highlight, 'highlight'),
948
+ bar: text['background-color'] ?? null,
949
+ },
950
+ popupItem('align', this.t('toolbar.align'), hasBlock, ICONS[alignIcon], alignIcon),
951
+ popupItem('spacing', this.t('toolbar.spacing'), hasBlock, ICONS.spacing, 'spacing'),
952
+ {
953
+ id: 'clear',
954
+ label: this.t('toolbar.clear'),
955
+ text: null,
956
+ icon: ICONS.clear,
957
+ iconName: 'clear',
958
+ disabled: !textEnabled && !hasBlock,
959
+ press: () => {
960
+ this.adapter?.style?.clear();
961
+ this.#done();
962
+ this.requestUpdate();
817
963
  },
818
- ],
819
- };
964
+ },
965
+ ];
820
966
  }
821
967
 
822
968
  async #insert(name: string): Promise<void> {
@@ -893,12 +1039,59 @@ export class AstlToolbar extends AuthoringElement {
893
1039
  return items;
894
1040
  }
895
1041
 
896
- /** The bar's buttons in order, by group (named for its class). */
897
- #groups(): [string, Item[]][] {
1042
+ /**
1043
+ * The bar's groups, from `layout`: each name once, at its first place, with what the adapter can do; the view switch
1044
+ * a group of its own; groups left empty go.
1045
+ */
1046
+ #groups(): Group[] {
1047
+ const available = this.#available();
1048
+ const seen = new Set<string>();
1049
+ const groups: Group[] = [];
1050
+ let continued = false;
1051
+ const push = (items: readonly Item[], names: readonly string[], views = false) => {
1052
+ if (items.length === 0) return;
1053
+ groups.push({
1054
+ items,
1055
+ views,
1056
+ continued,
1057
+ format: names.every((name) => FORMATS.has(name)),
1058
+ inserts: names.some((name) => INSERTS.has(name)),
1059
+ });
1060
+ continued = views;
1061
+ };
1062
+ for (const group of Array.isArray(this.layout) ? this.layout : []) {
1063
+ if (!Array.isArray(group)) continue;
1064
+ continued = false;
1065
+ let items: Item[] = [];
1066
+ let names: string[] = [];
1067
+ for (const name of group as readonly string[]) {
1068
+ const found = seen.has(name) ? undefined : available.get(name);
1069
+ seen.add(name);
1070
+ if (found === undefined) continue;
1071
+ if (name === 'views') {
1072
+ push(items, names);
1073
+ push(found, [name], true);
1074
+ items = [];
1075
+ names = [];
1076
+ } else {
1077
+ items.push(...found);
1078
+ if (found.length > 0) names.push(name);
1079
+ }
1080
+ }
1081
+ push(items, names);
1082
+ }
1083
+ return groups;
1084
+ }
1085
+
1086
+ /** What the bar can show, by name of the layout: none where the adapter has no capability for it. */
1087
+ #available(): ReadonlyMap<string, readonly Item[]> {
898
1088
  const adapter = this.adapter;
899
1089
  const authoring = this.authoring;
900
1090
  const state = this.#state;
901
- const groups: [string, Item[]][] = [];
1091
+ const available = new Map<string, readonly Item[]>();
1092
+ const add = (...items: Item[]) => {
1093
+ for (const item of items) available.set(item.id, [item]);
1094
+ };
902
1095
  const formatItem = (format: Toggle, popup?: Popup): Item => ({
903
1096
  id: format,
904
1097
  label: this.t(`toolbar.${format}`),
@@ -919,30 +1112,25 @@ export class AstlToolbar extends AuthoringElement {
919
1112
  const named = this.#namedNow();
920
1113
  const rule = named === null ? undefined : adapter.style?.rules().find((one) => one.name === named);
921
1114
  const styleName = rule?.label ?? rule?.name ?? this.t(`toolbar.${current ?? 'paragraph'}`);
922
- const style = this.#styleGroups();
923
- groups.push([
924
- 'group',
925
- [
926
- {
927
- id: 'style',
928
- label: this.t('toolbar.style', { style: styleName }),
929
- text: styleName,
930
- icon: ICONS.chevron,
931
- iconName: 'chevron',
932
- menu: true,
933
- // A selected picture or component has no text style, but its style form is in this menu.
934
- disabled:
935
- !STYLES.some((one) => state.enabled.includes(one)) && (this.#styles?.targets.length ?? 0) === 0,
936
- popup: 'style',
937
- press: () => void this.#open('style'),
938
- },
939
- ],
940
- ]);
941
- if (style.fonts.length > 0) groups.push(['group', style.fonts]);
942
- groups.push(['group', [...MARKS.map((mark) => formatItem(mark)), formatItem('link', 'link')]]);
943
- if (style.colors.length > 0) groups.push(['group', style.colors]);
944
- if (style.blocks.length > 0) groups.push(['group', style.blocks]);
945
- groups.push(['group', [...LISTS.map((list) => formatItem(list)), ...style.clear]]);
1115
+ add(
1116
+ {
1117
+ id: 'style',
1118
+ label: this.t('toolbar.style', { style: styleName }),
1119
+ text: styleName,
1120
+ icon: ICONS.chevron,
1121
+ iconName: 'chevron',
1122
+ menu: true,
1123
+ // A selected picture or component has no text style, but its style form is in this menu.
1124
+ disabled:
1125
+ !STYLES.some((one) => state.enabled.includes(one)) && (this.#styles?.targets.length ?? 0) === 0,
1126
+ popup: 'style',
1127
+ press: () => void this.#open('style'),
1128
+ },
1129
+ ...MARKS.map((mark) => formatItem(mark)),
1130
+ formatItem('link', 'link'),
1131
+ ...LISTS.map((list) => formatItem(list)),
1132
+ ...this.#styleItems(),
1133
+ );
946
1134
  }
947
1135
  const menu = (popup: InsertMenu, icon: 'add' | 'templates' | 'layouts'): Item => ({
948
1136
  id: popup,
@@ -957,23 +1145,18 @@ export class AstlToolbar extends AuthoringElement {
957
1145
  else void this.#open(popup);
958
1146
  },
959
1147
  });
960
- const starters = authoring?.descriptors.some((d) => (d.templates ?? []).length > 0) === true;
961
- groups.push([
962
- 'group inserts',
963
- [
964
- ...this.#featuredItems(),
965
- menu('elements', 'add'),
966
- ...(starters ? [menu('templates', 'templates')] : []),
967
- // Layouts are styles: a host without the style API has none to insert.
968
- ...(adapter?.style !== undefined ? [menu('layouts', 'layouts')] : []),
969
- ],
970
- ]);
1148
+ available.set('featured', this.#featuredItems());
1149
+ add(menu('elements', 'add'));
1150
+ if (authoring?.descriptors.some((d) => (d.templates ?? []).length > 0) === true)
1151
+ add(menu('templates', 'templates'));
1152
+ // Layouts are styles: a host without the style API has none to insert.
1153
+ if (adapter?.style !== undefined) add(menu('layouts', 'layouts'));
971
1154
  if (adapter?.wrap !== undefined && authoring !== null) {
972
- const wraps = authoring.descriptors.filter((d) => d.wrap !== undefined);
973
- if (wraps.length > 0) {
974
- groups.push([
975
- 'group',
976
- wraps.map((d) => {
1155
+ available.set(
1156
+ 'wraps',
1157
+ authoring.descriptors
1158
+ .filter((d) => d.wrap !== undefined)
1159
+ .map((d) => {
977
1160
  const label = authoring.t(d.manifest.messages, d.wrap?.label ?? '');
978
1161
  return {
979
1162
  id: `wrap-${d.manifest.tag}`,
@@ -988,13 +1171,12 @@ export class AstlToolbar extends AuthoringElement {
988
1171
  },
989
1172
  };
990
1173
  }),
991
- ]);
992
- }
1174
+ );
993
1175
  }
994
1176
  // A switch needs two views at least.
995
1177
  if (this.views.length > 1) {
996
- groups.push([
997
- 'group views',
1178
+ available.set(
1179
+ 'views',
998
1180
  this.views.map((view) => ({
999
1181
  id: `view-${view.name}`,
1000
1182
  label: view.label,
@@ -1009,7 +1191,7 @@ export class AstlToolbar extends AuthoringElement {
1009
1191
  this.dispatchEvent(new CustomEvent(VIEW_PICKED, { detail, bubbles: true, composed: true }));
1010
1192
  },
1011
1193
  })),
1012
- ]);
1194
+ );
1013
1195
  }
1014
1196
  if (adapter?.undo !== undefined && adapter.redo !== undefined) {
1015
1197
  const history = (name: 'undo' | 'redo'): Item => ({
@@ -1025,13 +1207,19 @@ export class AstlToolbar extends AuthoringElement {
1025
1207
  this.#done();
1026
1208
  },
1027
1209
  });
1028
- groups.push(['group history', [history('undo'), history('redo')]]);
1210
+ add(history('undo'), history('redo'));
1029
1211
  }
1030
- return groups;
1212
+ return available;
1213
+ }
1214
+
1215
+ /** The bar's own button an event came from: never a host's element in a slot, nor one of its ancestors. */
1216
+ #buttonOf(event: Event): HTMLElement | null {
1217
+ const button = (event.target as HTMLElement).closest<HTMLElement>('[data-item]');
1218
+ return button !== null && button.getRootNode() === this.renderRoot ? button : null;
1031
1219
  }
1032
1220
 
1033
1221
  #keydown(event: KeyboardEvent): void {
1034
- const target = (event.target as HTMLElement).closest<HTMLElement>('[data-item]');
1222
+ const target = this.#buttonOf(event);
1035
1223
  if (target === null) return;
1036
1224
  const index = Number(target.dataset.item);
1037
1225
  const item = this.#items[index];
@@ -1046,9 +1234,11 @@ export class AstlToolbar extends AuthoringElement {
1046
1234
 
1047
1235
  #button(item: Item, index: number): TemplateResult {
1048
1236
  const unavailable = item.disabled === true;
1049
- // The parts: every button; an icon-only one is also an `icon-button`, and an option of the view switch a `view`.
1050
- const part =
1237
+ // The parts: every button, and each by its name; an icon-only one is also an `icon-button`, and an option of the
1238
+ // view switch a `view`.
1239
+ const kind =
1051
1240
  item.checked !== undefined ? 'button view' : item.text === null ? 'button icon-button' : 'button';
1241
+ const part = `${kind} ${partOf(item.id)}`;
1052
1242
  return html`<button
1053
1243
  type="button"
1054
1244
  part=${part}
@@ -1094,7 +1284,7 @@ export class AstlToolbar extends AuthoringElement {
1094
1284
  </button>`;
1095
1285
  }
1096
1286
 
1097
- /** The arrows, Home and End along a menu's buttons; Escape closes it, back on its button; Tab goes on. */
1287
+ /** The arrows, Home and End along a menu's buttons; Tab goes on (Escape: `#escape`). */
1098
1288
  #menuKeydown = (event: KeyboardEvent): void => {
1099
1289
  const buttons = [...(event.currentTarget as HTMLElement).querySelectorAll<HTMLElement>('button')];
1100
1290
  const at = buttons.indexOf(event.target as HTMLElement);
@@ -1105,9 +1295,6 @@ export class AstlToolbar extends AuthoringElement {
1105
1295
  } else if (event.key === 'Home' || event.key === 'End') {
1106
1296
  event.preventDefault();
1107
1297
  buttons[event.key === 'Home' ? 0 : buttons.length - 1]?.focus();
1108
- } else if (event.key === 'Escape') {
1109
- event.preventDefault();
1110
- this.#close(true);
1111
1298
  } else if (event.key === 'Tab') this.#close(false);
1112
1299
  };
1113
1300
 
@@ -1284,10 +1471,7 @@ export class AstlToolbar extends AuthoringElement {
1284
1471
  aria-label=${this.t('toolbar.link')}
1285
1472
  part="link"
1286
1473
  @keydown=${(event: KeyboardEvent) => {
1287
- if (event.key === 'Escape') {
1288
- event.preventDefault();
1289
- this.#close(true);
1290
- } else if (event.key === 'Enter' && (event.target as HTMLElement).localName === 'input') {
1474
+ if (event.key === 'Enter' && (event.target as HTMLElement).localName === 'input') {
1291
1475
  event.preventDefault();
1292
1476
  apply();
1293
1477
  }
@@ -1331,12 +1515,6 @@ export class AstlToolbar extends AuthoringElement {
1331
1515
  role="dialog"
1332
1516
  aria-label=${this.t(`toolbar.${this.#menu}`)}
1333
1517
  part="insert"
1334
- @keydown=${(event: KeyboardEvent) => {
1335
- if (event.key === 'Escape') {
1336
- event.preventDefault();
1337
- this.#close(true);
1338
- }
1339
- }}
1340
1518
  @focusout=${(event: FocusEvent) => {
1341
1519
  const next = event.relatedTarget as Node | null;
1342
1520
  if (next !== null && !(event.currentTarget as HTMLElement).contains(next)) this.#close(false);
@@ -1381,29 +1559,42 @@ export class AstlToolbar extends AuthoringElement {
1381
1559
  const { lang, dir } = this.ui;
1382
1560
  // Out of the editing view (the first), only the switch works.
1383
1561
  const away = this.views.length > 0 && this.view !== this.views[0]?.name;
1384
- const groups = this.#groups().map(
1385
- ([name, items]) =>
1386
- [
1387
- name,
1388
- away
1389
- ? items.map((item) => (item.checked === undefined ? { ...item, disabled: true } : item))
1390
- : items,
1391
- ] as const,
1562
+ const groups = this.#groups().map((group) =>
1563
+ away
1564
+ ? {
1565
+ ...group,
1566
+ items: group.items.map((item) =>
1567
+ item.checked === undefined ? { ...item, disabled: true } : item,
1568
+ ),
1569
+ }
1570
+ : group,
1392
1571
  );
1393
- this.#items = groups.flatMap(([, items]) => items);
1572
+ this.#items = groups.flatMap((group) => group.items);
1394
1573
  let index = 0;
1395
- const group = ([name, items]: readonly [string, readonly Item[]], at: number) =>
1396
- html`<div class=${name} role=${name === 'group views' ? 'radiogroup' : 'presentation'}
1397
- part=${name === 'group views' ? 'views' : nothing}
1398
- aria-label=${name === 'group views' ? this.t('toolbar.view') : nothing}>
1399
- ${at === 0 || name === 'group views' ? nothing : html`<span class="separator" part="separator" aria-hidden="true"></span>`}
1400
- ${items.map((item) => this.#button(item, index++))}
1574
+ const last = groups.length - 1;
1575
+ const group = (g: Group, at: number) => {
1576
+ const history = g.items.every((item) => item.id === 'undo' || item.id === 'redo');
1577
+ // Undo and redo at the end of the bar go to the end of their row, as in a word processor.
1578
+ const name = `group${g.inserts ? ' inserts' : ''}${g.views ? ' views' : ''}${history ? ` history${at === last ? ' end' : ''}` : ''}`;
1579
+ return html`<div class=${name} role=${g.views ? 'radiogroup' : 'presentation'}
1580
+ part=${g.views ? 'views' : nothing}
1581
+ aria-label=${g.views ? this.t('toolbar.view') : nothing}>
1582
+ ${at === 0 || g.views || g.continued ? nothing : html`<span class="separator" part="separator" aria-hidden="true"></span>`}
1583
+ ${g.items.map((item) => this.#button(item, index++))}
1401
1584
  </div>`;
1402
- // The formats come first, up to the inserts: on a phone they scroll in a row of their own (barStyles).
1403
- const split = Math.max(
1404
- 0,
1405
- groups.findIndex(([name]) => name === 'group inserts'),
1406
- );
1585
+ };
1586
+ // Runs of groups of formats alone, and of the others: on a phone a run of formats scrolls in a row (barStyles).
1587
+ const runs: { readonly format: boolean; readonly groups: Group[]; readonly start: number }[] = [];
1588
+ groups.forEach((g, at) => {
1589
+ const run = runs.at(-1);
1590
+ if (run?.format === g.format) run.groups.push(g);
1591
+ else runs.push({ format: g.format, groups: [g], start: at });
1592
+ });
1593
+ const host = (name: 'start' | 'end') =>
1594
+ html`<div class="host" ?hidden=${!this.#slotted[name]}><slot name=${name} @slotchange=${this.#slotChange}></slot></div>`;
1595
+ // Beside a run of actions, the host's elements wrap with it on a phone, rather than taking a row of their own.
1596
+ const first = runs[0]?.format === false;
1597
+ const final = runs.at(-1)?.format === false;
1407
1598
  // The picture dialog is outside the popovers: a picture asked for from a menu or a featured button shows while
1408
1599
  // they are closed.
1409
1600
  return html`<div
@@ -1414,13 +1605,15 @@ export class AstlToolbar extends AuthoringElement {
1414
1605
  lang=${lang}
1415
1606
  dir=${dir}
1416
1607
  @mousedown=${(event: MouseEvent) => {
1417
- // A press keeps the editor's focus and selection.
1418
- if ((event.target as HTMLElement).closest('button') !== null) event.preventDefault();
1608
+ // A press keeps the editor's focus and selection; the host's elements in the slots are the host's.
1609
+ if (this.#buttonOf(event) !== null) event.preventDefault();
1419
1610
  }}
1420
1611
  @keydown=${(event: KeyboardEvent) => this.#keydown(event)}
1421
1612
  >
1422
- ${split === 0 ? nothing : html`<div class="formats">${groups.slice(0, split).map((g, at) => group(g, at))}</div>`}
1423
- <div class="actions">${groups.slice(split).map((g, at) => group(g, split + at))}</div>
1613
+ ${first ? nothing : host('start')}${runs.map(
1614
+ (run, at) =>
1615
+ html`<div class=${run.format ? 'formats' : 'actions'}>${at === 0 && first ? host('start') : nothing}${run.groups.map((g, i) => group(g, run.start + i))}${at === runs.length - 1 && final ? host('end') : nothing}</div>`,
1616
+ )}${final ? nothing : host('end')}
1424
1617
  </div>
1425
1618
  <div lang=${lang} dir=${dir}>
1426
1619
  ${this.#styleMenu()} ${this.#linkPopup()} ${this.#insertPopup()} ${this.#stylePopup()}