@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.
@@ -7,6 +7,43 @@ import { loadStyleElements, STYLE_OPEN } from './style-load.js';
7
7
  import { fitViewport, inheritTokens, kitStyles, VIEWPORT_MARGIN } from './styles.js';
8
8
  /** Kit items a host can feature besides component tags (`tag`) and starters (`tag:template`). */
9
9
  export const FEATURED_ITEMS = ['text', 'picture', 'page-break'];
10
+ /**
11
+ * The toolbar's own layout: the text style; font and size; the marks and link; the colours; alignment and spacing; the
12
+ * lists and clear formatting; the inserts; the types' commands; the view switch; undo and redo.
13
+ */
14
+ export const DEFAULT_TOOLBAR_LAYOUT = [
15
+ ['style'],
16
+ ['font', 'size'],
17
+ ['bold', 'italic', 'underline', 'link'],
18
+ ['color', 'highlight'],
19
+ ['align', 'spacing'],
20
+ ['bulleted', 'numbered', 'clear'],
21
+ ['featured', 'elements', 'templates', 'layouts'],
22
+ ['wraps'],
23
+ ['views'],
24
+ ['undo', 'redo'],
25
+ ];
26
+ /** Every item of the toolbar, by name, in the default layout's order: the formats, then the actions. */
27
+ export const TOOLBAR_ITEMS = DEFAULT_TOOLBAR_LAYOUT.flat();
28
+ /** The formats, from the text style to clear formatting: on a phone a group of them alone scrolls in a row. */
29
+ const FORMATS = new Set(TOOLBAR_ITEMS.slice(0, TOOLBAR_ITEMS.indexOf('featured')));
30
+ const INSERTS = new Set(['featured', 'elements', 'templates', 'layouts']);
31
+ /** The items of one button each, whose id is their name. */
32
+ const SINGLE_ITEMS = TOOLBAR_ITEMS.filter((name) => name !== 'featured' && name !== 'wraps' && name !== 'views');
33
+ /** A button's part by its id: a starter's `:`, and anything else a CSS name cannot hold, becomes `_`. */
34
+ const partOf = (id) => `button-${id.replace(/[^A-Za-z0-9-]/g, '_')}`;
35
+ /**
36
+ * The part of every button a toolbar may draw (`button-<name>`) with these featured inserts, types with a command
37
+ * (their tags) and views, for an element that holds a toolbar and exports its parts.
38
+ */
39
+ export function toolbarButtonParts(options) {
40
+ return [
41
+ ...SINGLE_ITEMS,
42
+ ...options.featured.map((name) => `insert-${name}`),
43
+ ...options.wraps.map((tag) => `wrap-${tag}`),
44
+ ...options.views.map((name) => `view-${name}`),
45
+ ].map(partOf);
46
+ }
10
47
  const ICONS = {
11
48
  bold: svg `<path d="M6 4h5a3 3 0 0 1 0 6H6zm0 6h6a3 3 0 0 1 0 6H6z" stroke-width="2"/>`,
12
49
  italic: svg `<path d="M9 4h7M4 16h7M12.5 4l-5 12"/>`,
@@ -53,16 +90,18 @@ const openerOf = (popup) => (popup === 'panel' ? 'style' : popup);
53
90
  export const VIEW_PICKED = 'astl-toolbar-view';
54
91
  const NO_STATE = { active: [], enabled: [], href: null, undo: false, redo: false };
55
92
  /**
56
- * The bar: groups with a thin rule between them (each group's `separator`, a part a host can redraw), undo and redo at
57
- * 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
58
- * than a phone, the groups wrap into rows when they do not fit, so every button is on show. The groups sit in two
59
- * wrappers, the formats (`formats`: the text style to the lists) and the actions (`actions`: the inserts, the types'
60
- * commands, the view switch, undo and redo), which only a phone lays out: there the formats are one row that scrolls
61
- * sideways, as a mobile editor's (wrapped, they would push the text below the fold), and the actions wrap under it, so
62
- * none of them is ever out of sight. A shade at an edge of the formats says more buttons lie that way (the covers
63
- * scroll with the buttons and hide it at either end), and the arrow keys scroll the focused button into view. The
64
- * actions wrap button by button, without rules (a group that wrapped as a whole would take a row of its own): only the
65
- * view switch and undo with redo stay together.
93
+ * The bar: groups with a thin rule between them (each group's `separator`, a part a host can redraw), in the order of
94
+ * `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
95
+ * 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
96
+ * button is on show. Each run of groups of formats alone sits in a wrapper (`formats`) and each run of the others in
97
+ * another (`actions`: the inserts, the types' commands, the view switch, undo and redo), which only a phone lays out:
98
+ * there a run of formats is one row that scrolls sideways, as a mobile editor's (wrapped, they would push the text below
99
+ * 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
100
+ * buttons lie that way (the covers scroll with the buttons and hide it at either end), and the arrow keys scroll the
101
+ * focused button into view. The actions wrap button by button, without rules (a group that wrapped as a whole would
102
+ * take a row of its own): only the view switch and undo with redo stay together. The host's own elements (the `start`
103
+ * 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
104
+ * them, or take a row of their own beside a run of formats.
66
105
  */
67
106
  const barStyles = css `
68
107
  :host {
@@ -81,9 +120,13 @@ const barStyles = css `
81
120
  background: var(--astl-surface);
82
121
  }
83
122
  .formats,
84
- .actions {
123
+ .actions,
124
+ .host {
85
125
  display: contents;
86
126
  }
127
+ .host[hidden] {
128
+ display: none;
129
+ }
87
130
  .group {
88
131
  display: flex;
89
132
  flex-wrap: wrap;
@@ -91,7 +134,7 @@ const barStyles = css `
91
134
  gap: var(--astl-space-1);
92
135
  }
93
136
  .group + .group,
94
- .formats + .actions > .group:first-child {
137
+ :is(.formats, .actions) + :is(.formats, .actions) > .group:first-child {
95
138
  position: relative;
96
139
  margin-inline-start: calc(-1 * var(--astl-space-2) - var(--astl-outline-width));
97
140
  padding-inline-start: calc(var(--astl-space-2) + var(--astl-outline-width));
@@ -102,7 +145,7 @@ const barStyles = css `
102
145
  inset-inline-start: 0;
103
146
  border-inline-start: var(--astl-outline-width) solid var(--astl-line);
104
147
  }
105
- .group.history {
148
+ .group.history.end {
106
149
  margin-inline-start: auto;
107
150
  }
108
151
  @container (inline-size < 30rem) {
@@ -111,27 +154,35 @@ const barStyles = css `
111
154
  align-items: stretch;
112
155
  }
113
156
  .formats,
114
- .actions {
157
+ .actions,
158
+ .host {
115
159
  display: flex;
116
160
  align-items: center;
117
161
  }
118
- .actions {
162
+ .actions,
163
+ .host {
119
164
  flex-wrap: wrap;
120
165
  gap: var(--astl-space-1);
121
166
  }
122
- .actions > .group:not(.views, .history) {
167
+ .actions > .group:not(.views, .history),
168
+ .actions > .host:not([hidden]) {
123
169
  display: contents;
124
170
  }
125
- .actions .separator {
171
+ .actions .separator,
172
+ .formats > .group:first-child > .separator {
126
173
  display: none;
127
174
  }
128
- .actions > .group {
175
+ .actions > .group,
176
+ .formats > .group:first-child {
129
177
  margin-inline-start: 0;
130
178
  }
179
+ .formats > .group:first-child,
131
180
  .actions > .history {
132
- margin-inline-start: auto;
133
181
  padding-inline-start: 0;
134
182
  }
183
+ .actions > .history.end {
184
+ margin-inline-start: auto;
185
+ }
135
186
  .formats {
136
187
  --ring: calc(var(--astl-editor-focus-width, 2px) + var(--astl-editor-focus-offset, 1px));
137
188
  gap: var(--astl-space-1) calc(2 * var(--astl-space-2) + var(--astl-outline-width));
@@ -350,15 +401,16 @@ const popupStyles = css `
350
401
  }
351
402
  `;
352
403
  /**
353
- * `<astl-toolbar>`: a word processor's toolbar for the editor in `adapter`, one row while it fits. In order: the text
354
- * style (a menu: paragraph, heading, subheading), bold, italic, underline, link, the two lists; the host's `featured`
355
- * inserts as buttons, "Elements" (every component and content insert) and "Templates" (the named starters), menus with
356
- * a search over one `<astl-insert-menu>`; the types' commands on the selection (`EditorDescriptor.wrap`, "Mark
357
- * word"); the view switch (`views`, two or more: a segmented control of radios); undo and redo at the end. Controls
358
- * the adapter has no capability for are left out (`format`, `undo`, `wrap`). One tab stop: the arrow keys, Home and
359
- * End move along it. Format buttons show the state at the cursor: pressed, or unavailable (`aria-disabled`, still
360
- * focusable). A press never moves the editor's cursor: a pointer's leaves the focus in the editor, and a key's gives
361
- * it back.
404
+ * `<astl-toolbar>`: a word processor's toolbar for the editor in `adapter`, one row while it fits. By default, in order:
405
+ * the text style (a menu: paragraph, heading, subheading), bold, italic, underline, link, the two lists; the host's
406
+ * `featured` inserts as buttons, "Elements" (every component and content insert) and "Templates" (the named starters),
407
+ * menus with a search over one `<astl-insert-menu>`; the types' commands on the selection (`EditorDescriptor.wrap`,
408
+ * "Mark word"); the view switch (`views`, two or more: a segmented control of radios); undo and redo at the end.
409
+ * `layout` names the items and their order. Controls the adapter has no capability for are left out (`format`, `undo`,
410
+ * `wrap`). One tab stop: the arrow keys, Home and End move along it. Format buttons show the state at the cursor:
411
+ * pressed, or unavailable (`aria-disabled`, still focusable). A press never moves the editor's cursor: a pointer's
412
+ * leaves the focus in the editor, and a key's gives it back. Each button is a part, `button button-<name>`. The host's
413
+ * elements in the slots `start` and `end` sit at the bar's ends, each with its own tab stop.
362
414
  */
363
415
  export class AstlToolbar extends AuthoringElement {
364
416
  static properties = {
@@ -366,6 +418,7 @@ export class AstlToolbar extends AuthoringElement {
366
418
  featured: { attribute: false },
367
419
  views: { attribute: false },
368
420
  view: {},
421
+ layout: { attribute: false },
369
422
  };
370
423
  static styles = [
371
424
  kitStyles,
@@ -394,16 +447,29 @@ export class AstlToolbar extends AuthoringElement {
394
447
  item: (index) => this.renderRoot.querySelector(`.bar [data-item="${index}"]`),
395
448
  axis: 'inline',
396
449
  });
450
+ /** Whether the host's `start` and `end` slots have elements: an end is laid out only while its slot has. */
451
+ #slotted = { start: false, end: false };
452
+ /** Where Escape is heard: the toolbar's root (the shadow root of an editor around it) and the document. */
453
+ #heard = [];
397
454
  constructor() {
398
455
  super();
399
456
  this.featured = [];
400
457
  this.views = [];
401
458
  this.view = '';
459
+ this.layout = DEFAULT_TOOLBAR_LAYOUT;
402
460
  }
403
461
  /** The insert menu of "Elements" and "Templates": insert from it as a host would from `<astl-insert-menu>`. */
404
462
  get menu() {
405
463
  return this.renderRoot.querySelector('astl-insert-menu');
406
464
  }
465
+ /**
466
+ * Whether one of the toolbar's popups is open: the style menu, the link dialog, an insert menu, a style popup or the
467
+ * style panel. An Escape that closes one goes no further than the toolbar's root, so a keydown listener on an
468
+ * editor around it never hears it.
469
+ */
470
+ get popupOpen() {
471
+ return this.#popup !== null;
472
+ }
407
473
  /** Opens "Elements", "Templates" or "Layout" with its search, as its button does. */
408
474
  async openMenu(menu) {
409
475
  await this.#open(menu);
@@ -444,14 +510,21 @@ export class AstlToolbar extends AuthoringElement {
444
510
  super.connectedCallback();
445
511
  this.#follow();
446
512
  document.addEventListener('pointerdown', this.#outside, true);
447
- document.addEventListener('keydown', this.#escape);
513
+ // The root first: an Escape from inside an editor around the toolbar (its text, its card) passes it before it
514
+ // reaches the editor and the host's listeners there. The document hears the rest of the page.
515
+ const root = this.getRootNode();
516
+ this.#heard = root instanceof ShadowRoot ? [root, document] : [document];
517
+ for (const target of this.#heard)
518
+ target.addEventListener('keydown', this.#escape);
448
519
  window.addEventListener('resize', this.#replace);
449
520
  }
450
521
  disconnectedCallback() {
451
522
  super.disconnectedCallback();
452
523
  this.#follow();
453
524
  document.removeEventListener('pointerdown', this.#outside, true);
454
- document.removeEventListener('keydown', this.#escape);
525
+ for (const target of this.#heard)
526
+ target.removeEventListener('keydown', this.#escape);
527
+ this.#heard = [];
455
528
  window.removeEventListener('resize', this.#replace);
456
529
  }
457
530
  willUpdate(changed) {
@@ -473,6 +546,19 @@ export class AstlToolbar extends AuthoringElement {
473
546
  return;
474
547
  this.#off = { adapter, off: listen.call(adapter, () => this.requestUpdate()) };
475
548
  }
549
+ /**
550
+ * Whether an end has the host's elements: flattened, as an editor around the toolbar passes its own slot on, and it
551
+ * tells of changes there too (its event bubbles through this slot).
552
+ */
553
+ #slotChange = (event) => {
554
+ const slot = event.currentTarget;
555
+ const name = slot.name === 'end' ? 'end' : 'start';
556
+ const has = slot.assignedElements({ flatten: true }).length > 0;
557
+ if (this.#slotted[name] === has)
558
+ return;
559
+ this.#slotted[name] = has;
560
+ this.requestUpdate();
561
+ };
476
562
  /** A press outside the open popup and its button closes it. */
477
563
  #outside = (event) => {
478
564
  if (this.#popup === null)
@@ -488,15 +574,19 @@ export class AstlToolbar extends AuthoringElement {
488
574
  this.#close(false);
489
575
  };
490
576
  /**
491
- * The style panel is not modal: the focus can leave it, by Tab or to the surface after an undo, and it stays open
492
- * over what it covers. Escape closes it from there too; only from inside does the focus go back to its button.
577
+ * Escape closes the open popup, from inside it (the focus goes back to its button) or from anywhere else: the style
578
+ * panel is not modal, and the focus can leave it, by Tab or to the surface after an undo, while it stays open over
579
+ * what it covers. The key goes no further, so a host's listener on an editor around the toolbar hears only the
580
+ * Escapes no popup used: `defaultPrevented` cannot tell it, as ProseMirror claims every Escape in the text.
493
581
  */
494
582
  #escape = (event) => {
495
- if (this.#popup !== 'panel' || event.key !== 'Escape')
583
+ const open = this.#popup;
584
+ if (open === null || event.key !== 'Escape')
496
585
  return;
497
- const panel = this.renderRoot.querySelector('#panel');
498
- const inside = panel !== null && event.composedPath().includes(panel);
499
- // Inside, a field may have its own use for the key (a rename). ProseMirror claims every Escape, with no use for it.
586
+ const popup = this.renderRoot.querySelector(`#${popoverOf(open)}`);
587
+ const inside = popup !== null && event.composedPath().includes(popup);
588
+ event.stopPropagation();
589
+ // Inside, a field may have its own use for the key (a rename): the popup stays.
500
590
  if (inside && event.defaultPrevented)
501
591
  return;
502
592
  event.preventDefault();
@@ -642,11 +732,11 @@ export class AstlToolbar extends AuthoringElement {
642
732
  const known = this.authoring?.fonts.find((font) => font.stack === stack);
643
733
  return known?.name ?? (stack.split(',')[0] ?? '').replace(/"/g, '').trim();
644
734
  }
645
- /** The bar's style controls, by group (font and size; colours; alignment and spacing), and clear formatting. */
646
- #styleGroups() {
735
+ /** The bar's style controls (font, size, the colours, alignment, spacing) and clear formatting; their ids are names. */
736
+ #styleItems() {
647
737
  const styles = this.#styles;
648
738
  if (styles === null)
649
- return { fonts: [], colors: [], blocks: [], clear: [] };
739
+ return [];
650
740
  const { text, textEnabled, targets } = styles;
651
741
  const hasBlock = targets.some((target) => target.kind === 'block');
652
742
  const popupItem = (popup, label, enabled, icon, iconName) => ({
@@ -680,38 +770,33 @@ export class AstlToolbar extends AuthoringElement {
680
770
  : align === 'justify'
681
771
  ? 'align-justify'
682
772
  : 'align-start';
683
- return {
684
- fonts: [valued('font', 'toolbar.font', font), valued('size', 'toolbar.size', size)],
685
- colors: [
686
- {
687
- ...popupItem('color', this.t('toolbar.color'), textEnabled, ICONS.color, 'color'),
688
- bar: text.color ?? null,
689
- },
690
- {
691
- ...popupItem('highlight', this.t('toolbar.highlight'), textEnabled, ICONS.highlight, 'highlight'),
692
- bar: text['background-color'] ?? null,
693
- },
694
- ],
695
- blocks: [
696
- popupItem('align', this.t('toolbar.align'), hasBlock, ICONS[alignIcon], alignIcon),
697
- popupItem('spacing', this.t('toolbar.spacing'), hasBlock, ICONS.spacing, 'spacing'),
698
- ],
699
- clear: [
700
- {
701
- id: 'clear',
702
- label: this.t('toolbar.clear'),
703
- text: null,
704
- icon: ICONS.clear,
705
- iconName: 'clear',
706
- disabled: !textEnabled && !hasBlock,
707
- press: () => {
708
- this.adapter?.style?.clear();
709
- this.#done();
710
- this.requestUpdate();
711
- },
773
+ return [
774
+ valued('font', 'toolbar.font', font),
775
+ valued('size', 'toolbar.size', size),
776
+ {
777
+ ...popupItem('color', this.t('toolbar.color'), textEnabled, ICONS.color, 'color'),
778
+ bar: text.color ?? null,
779
+ },
780
+ {
781
+ ...popupItem('highlight', this.t('toolbar.highlight'), textEnabled, ICONS.highlight, 'highlight'),
782
+ bar: text['background-color'] ?? null,
783
+ },
784
+ popupItem('align', this.t('toolbar.align'), hasBlock, ICONS[alignIcon], alignIcon),
785
+ popupItem('spacing', this.t('toolbar.spacing'), hasBlock, ICONS.spacing, 'spacing'),
786
+ {
787
+ id: 'clear',
788
+ label: this.t('toolbar.clear'),
789
+ text: null,
790
+ icon: ICONS.clear,
791
+ iconName: 'clear',
792
+ disabled: !textEnabled && !hasBlock,
793
+ press: () => {
794
+ this.adapter?.style?.clear();
795
+ this.#done();
796
+ this.requestUpdate();
712
797
  },
713
- ],
714
- };
798
+ },
799
+ ];
715
800
  }
716
801
  async #insert(name) {
717
802
  const menu = this.menu;
@@ -792,12 +877,64 @@ export class AstlToolbar extends AuthoringElement {
792
877
  }
793
878
  return items;
794
879
  }
795
- /** The bar's buttons in order, by group (named for its class). */
880
+ /**
881
+ * The bar's groups, from `layout`: each name once, at its first place, with what the adapter can do; the view switch
882
+ * a group of its own; groups left empty go.
883
+ */
796
884
  #groups() {
885
+ const available = this.#available();
886
+ const seen = new Set();
887
+ const groups = [];
888
+ let continued = false;
889
+ const push = (items, names, views = false) => {
890
+ if (items.length === 0)
891
+ return;
892
+ groups.push({
893
+ items,
894
+ views,
895
+ continued,
896
+ format: names.every((name) => FORMATS.has(name)),
897
+ inserts: names.some((name) => INSERTS.has(name)),
898
+ });
899
+ continued = views;
900
+ };
901
+ for (const group of Array.isArray(this.layout) ? this.layout : []) {
902
+ if (!Array.isArray(group))
903
+ continue;
904
+ continued = false;
905
+ let items = [];
906
+ let names = [];
907
+ for (const name of group) {
908
+ const found = seen.has(name) ? undefined : available.get(name);
909
+ seen.add(name);
910
+ if (found === undefined)
911
+ continue;
912
+ if (name === 'views') {
913
+ push(items, names);
914
+ push(found, [name], true);
915
+ items = [];
916
+ names = [];
917
+ }
918
+ else {
919
+ items.push(...found);
920
+ if (found.length > 0)
921
+ names.push(name);
922
+ }
923
+ }
924
+ push(items, names);
925
+ }
926
+ return groups;
927
+ }
928
+ /** What the bar can show, by name of the layout: none where the adapter has no capability for it. */
929
+ #available() {
797
930
  const adapter = this.adapter;
798
931
  const authoring = this.authoring;
799
932
  const state = this.#state;
800
- const groups = [];
933
+ const available = new Map();
934
+ const add = (...items) => {
935
+ for (const item of items)
936
+ available.set(item.id, [item]);
937
+ };
801
938
  const formatItem = (format, popup) => ({
802
939
  id: format,
803
940
  label: this.t(`toolbar.${format}`),
@@ -820,32 +957,18 @@ export class AstlToolbar extends AuthoringElement {
820
957
  const named = this.#namedNow();
821
958
  const rule = named === null ? undefined : adapter.style?.rules().find((one) => one.name === named);
822
959
  const styleName = rule?.label ?? rule?.name ?? this.t(`toolbar.${current ?? 'paragraph'}`);
823
- const style = this.#styleGroups();
824
- groups.push([
825
- 'group',
826
- [
827
- {
828
- id: 'style',
829
- label: this.t('toolbar.style', { style: styleName }),
830
- text: styleName,
831
- icon: ICONS.chevron,
832
- iconName: 'chevron',
833
- menu: true,
834
- // A selected picture or component has no text style, but its style form is in this menu.
835
- disabled: !STYLES.some((one) => state.enabled.includes(one)) && (this.#styles?.targets.length ?? 0) === 0,
836
- popup: 'style',
837
- press: () => void this.#open('style'),
838
- },
839
- ],
840
- ]);
841
- if (style.fonts.length > 0)
842
- groups.push(['group', style.fonts]);
843
- groups.push(['group', [...MARKS.map((mark) => formatItem(mark)), formatItem('link', 'link')]]);
844
- if (style.colors.length > 0)
845
- groups.push(['group', style.colors]);
846
- if (style.blocks.length > 0)
847
- groups.push(['group', style.blocks]);
848
- groups.push(['group', [...LISTS.map((list) => formatItem(list)), ...style.clear]]);
960
+ add({
961
+ id: 'style',
962
+ label: this.t('toolbar.style', { style: styleName }),
963
+ text: styleName,
964
+ icon: ICONS.chevron,
965
+ iconName: 'chevron',
966
+ menu: true,
967
+ // A selected picture or component has no text style, but its style form is in this menu.
968
+ disabled: !STYLES.some((one) => state.enabled.includes(one)) && (this.#styles?.targets.length ?? 0) === 0,
969
+ popup: 'style',
970
+ press: () => void this.#open('style'),
971
+ }, ...MARKS.map((mark) => formatItem(mark)), formatItem('link', 'link'), ...LISTS.map((list) => formatItem(list)), ...this.#styleItems());
849
972
  }
850
973
  const menu = (popup, icon) => ({
851
974
  id: popup,
@@ -862,60 +985,49 @@ export class AstlToolbar extends AuthoringElement {
862
985
  void this.#open(popup);
863
986
  },
864
987
  });
865
- const starters = authoring?.descriptors.some((d) => (d.templates ?? []).length > 0) === true;
866
- groups.push([
867
- 'group inserts',
868
- [
869
- ...this.#featuredItems(),
870
- menu('elements', 'add'),
871
- ...(starters ? [menu('templates', 'templates')] : []),
872
- // Layouts are styles: a host without the style API has none to insert.
873
- ...(adapter?.style !== undefined ? [menu('layouts', 'layouts')] : []),
874
- ],
875
- ]);
988
+ available.set('featured', this.#featuredItems());
989
+ add(menu('elements', 'add'));
990
+ if (authoring?.descriptors.some((d) => (d.templates ?? []).length > 0) === true)
991
+ add(menu('templates', 'templates'));
992
+ // Layouts are styles: a host without the style API has none to insert.
993
+ if (adapter?.style !== undefined)
994
+ add(menu('layouts', 'layouts'));
876
995
  if (adapter?.wrap !== undefined && authoring !== null) {
877
- const wraps = authoring.descriptors.filter((d) => d.wrap !== undefined);
878
- if (wraps.length > 0) {
879
- groups.push([
880
- 'group',
881
- wraps.map((d) => {
882
- const label = authoring.t(d.manifest.messages, d.wrap?.label ?? '');
883
- return {
884
- id: `wrap-${d.manifest.tag}`,
885
- label,
886
- text: label,
887
- icon: ICONS.wrap,
888
- iconName: 'wrap',
889
- data: { wrap: d.manifest.tag },
890
- press: () => {
891
- this.adapter?.wrap?.(d.manifest.tag);
892
- this.#done();
893
- },
894
- };
895
- }),
896
- ]);
897
- }
996
+ available.set('wraps', authoring.descriptors
997
+ .filter((d) => d.wrap !== undefined)
998
+ .map((d) => {
999
+ const label = authoring.t(d.manifest.messages, d.wrap?.label ?? '');
1000
+ return {
1001
+ id: `wrap-${d.manifest.tag}`,
1002
+ label,
1003
+ text: label,
1004
+ icon: ICONS.wrap,
1005
+ iconName: 'wrap',
1006
+ data: { wrap: d.manifest.tag },
1007
+ press: () => {
1008
+ this.adapter?.wrap?.(d.manifest.tag);
1009
+ this.#done();
1010
+ },
1011
+ };
1012
+ }));
898
1013
  }
899
1014
  // A switch needs two views at least.
900
1015
  if (this.views.length > 1) {
901
- groups.push([
902
- 'group views',
903
- this.views.map((view) => ({
904
- id: `view-${view.name}`,
905
- label: view.label,
906
- text: view.label,
907
- icon: null,
908
- iconName: '',
909
- checked: view.name === this.view,
910
- ...(view.description === undefined ? {} : { description: view.description }),
911
- press: () => {
912
- if (view.name === this.view)
913
- return;
914
- const detail = { view: view.name };
915
- this.dispatchEvent(new CustomEvent(VIEW_PICKED, { detail, bubbles: true, composed: true }));
916
- },
917
- })),
918
- ]);
1016
+ available.set('views', this.views.map((view) => ({
1017
+ id: `view-${view.name}`,
1018
+ label: view.label,
1019
+ text: view.label,
1020
+ icon: null,
1021
+ iconName: '',
1022
+ checked: view.name === this.view,
1023
+ ...(view.description === undefined ? {} : { description: view.description }),
1024
+ press: () => {
1025
+ if (view.name === this.view)
1026
+ return;
1027
+ const detail = { view: view.name };
1028
+ this.dispatchEvent(new CustomEvent(VIEW_PICKED, { detail, bubbles: true, composed: true }));
1029
+ },
1030
+ })));
919
1031
  }
920
1032
  if (adapter?.undo !== undefined && adapter.redo !== undefined) {
921
1033
  const history = (name) => ({
@@ -932,12 +1044,17 @@ export class AstlToolbar extends AuthoringElement {
932
1044
  this.#done();
933
1045
  },
934
1046
  });
935
- groups.push(['group history', [history('undo'), history('redo')]]);
1047
+ add(history('undo'), history('redo'));
936
1048
  }
937
- return groups;
1049
+ return available;
1050
+ }
1051
+ /** The bar's own button an event came from: never a host's element in a slot, nor one of its ancestors. */
1052
+ #buttonOf(event) {
1053
+ const button = event.target.closest('[data-item]');
1054
+ return button !== null && button.getRootNode() === this.renderRoot ? button : null;
938
1055
  }
939
1056
  #keydown(event) {
940
- const target = event.target.closest('[data-item]');
1057
+ const target = this.#buttonOf(event);
941
1058
  if (target === null)
942
1059
  return;
943
1060
  const index = Number(target.dataset.item);
@@ -953,8 +1070,10 @@ export class AstlToolbar extends AuthoringElement {
953
1070
  }
954
1071
  #button(item, index) {
955
1072
  const unavailable = item.disabled === true;
956
- // The parts: every button; an icon-only one is also an `icon-button`, and an option of the view switch a `view`.
957
- const part = item.checked !== undefined ? 'button view' : item.text === null ? 'button icon-button' : 'button';
1073
+ // The parts: every button, and each by its name; an icon-only one is also an `icon-button`, and an option of the
1074
+ // view switch a `view`.
1075
+ const kind = item.checked !== undefined ? 'button view' : item.text === null ? 'button icon-button' : 'button';
1076
+ const part = `${kind} ${partOf(item.id)}`;
958
1077
  return html `<button
959
1078
  type="button"
960
1079
  part=${part}
@@ -994,7 +1113,7 @@ export class AstlToolbar extends AuthoringElement {
994
1113
  : html `<span class="color-mark" data-color=${item.bar}></span>`}`}
995
1114
  </button>`;
996
1115
  }
997
- /** The arrows, Home and End along a menu's buttons; Escape closes it, back on its button; Tab goes on. */
1116
+ /** The arrows, Home and End along a menu's buttons; Tab goes on (Escape: `#escape`). */
998
1117
  #menuKeydown = (event) => {
999
1118
  const buttons = [...event.currentTarget.querySelectorAll('button')];
1000
1119
  const at = buttons.indexOf(event.target);
@@ -1007,10 +1126,6 @@ export class AstlToolbar extends AuthoringElement {
1007
1126
  event.preventDefault();
1008
1127
  buttons[event.key === 'Home' ? 0 : buttons.length - 1]?.focus();
1009
1128
  }
1010
- else if (event.key === 'Escape') {
1011
- event.preventDefault();
1012
- this.#close(true);
1013
- }
1014
1129
  else if (event.key === 'Tab')
1015
1130
  this.#close(false);
1016
1131
  };
@@ -1175,11 +1290,7 @@ export class AstlToolbar extends AuthoringElement {
1175
1290
  aria-label=${this.t('toolbar.link')}
1176
1291
  part="link"
1177
1292
  @keydown=${(event) => {
1178
- if (event.key === 'Escape') {
1179
- event.preventDefault();
1180
- this.#close(true);
1181
- }
1182
- else if (event.key === 'Enter' && event.target.localName === 'input') {
1293
+ if (event.key === 'Enter' && event.target.localName === 'input') {
1183
1294
  event.preventDefault();
1184
1295
  apply();
1185
1296
  }
@@ -1220,12 +1331,6 @@ export class AstlToolbar extends AuthoringElement {
1220
1331
  role="dialog"
1221
1332
  aria-label=${this.t(`toolbar.${this.#menu}`)}
1222
1333
  part="insert"
1223
- @keydown=${(event) => {
1224
- if (event.key === 'Escape') {
1225
- event.preventDefault();
1226
- this.#close(true);
1227
- }
1228
- }}
1229
1334
  @focusout=${(event) => {
1230
1335
  const next = event.relatedTarget;
1231
1336
  if (next !== null && !event.currentTarget.contains(next))
@@ -1270,22 +1375,39 @@ export class AstlToolbar extends AuthoringElement {
1270
1375
  const { lang, dir } = this.ui;
1271
1376
  // Out of the editing view (the first), only the switch works.
1272
1377
  const away = this.views.length > 0 && this.view !== this.views[0]?.name;
1273
- const groups = this.#groups().map(([name, items]) => [
1274
- name,
1275
- away
1276
- ? items.map((item) => (item.checked === undefined ? { ...item, disabled: true } : item))
1277
- : items,
1278
- ]);
1279
- this.#items = groups.flatMap(([, items]) => items);
1378
+ const groups = this.#groups().map((group) => away
1379
+ ? {
1380
+ ...group,
1381
+ items: group.items.map((item) => item.checked === undefined ? { ...item, disabled: true } : item),
1382
+ }
1383
+ : group);
1384
+ this.#items = groups.flatMap((group) => group.items);
1280
1385
  let index = 0;
1281
- const group = ([name, items], at) => html `<div class=${name} role=${name === 'group views' ? 'radiogroup' : 'presentation'}
1282
- part=${name === 'group views' ? 'views' : nothing}
1283
- aria-label=${name === 'group views' ? this.t('toolbar.view') : nothing}>
1284
- ${at === 0 || name === 'group views' ? nothing : html `<span class="separator" part="separator" aria-hidden="true"></span>`}
1285
- ${items.map((item) => this.#button(item, index++))}
1386
+ const last = groups.length - 1;
1387
+ const group = (g, at) => {
1388
+ const history = g.items.every((item) => item.id === 'undo' || item.id === 'redo');
1389
+ // Undo and redo at the end of the bar go to the end of their row, as in a word processor.
1390
+ const name = `group${g.inserts ? ' inserts' : ''}${g.views ? ' views' : ''}${history ? ` history${at === last ? ' end' : ''}` : ''}`;
1391
+ return html `<div class=${name} role=${g.views ? 'radiogroup' : 'presentation'}
1392
+ part=${g.views ? 'views' : nothing}
1393
+ aria-label=${g.views ? this.t('toolbar.view') : nothing}>
1394
+ ${at === 0 || g.views || g.continued ? nothing : html `<span class="separator" part="separator" aria-hidden="true"></span>`}
1395
+ ${g.items.map((item) => this.#button(item, index++))}
1286
1396
  </div>`;
1287
- // The formats come first, up to the inserts: on a phone they scroll in a row of their own (barStyles).
1288
- const split = Math.max(0, groups.findIndex(([name]) => name === 'group inserts'));
1397
+ };
1398
+ // Runs of groups of formats alone, and of the others: on a phone a run of formats scrolls in a row (barStyles).
1399
+ const runs = [];
1400
+ groups.forEach((g, at) => {
1401
+ const run = runs.at(-1);
1402
+ if (run?.format === g.format)
1403
+ run.groups.push(g);
1404
+ else
1405
+ runs.push({ format: g.format, groups: [g], start: at });
1406
+ });
1407
+ const host = (name) => html `<div class="host" ?hidden=${!this.#slotted[name]}><slot name=${name} @slotchange=${this.#slotChange}></slot></div>`;
1408
+ // Beside a run of actions, the host's elements wrap with it on a phone, rather than taking a row of their own.
1409
+ const first = runs[0]?.format === false;
1410
+ const final = runs.at(-1)?.format === false;
1289
1411
  // The picture dialog is outside the popovers: a picture asked for from a menu or a featured button shows while
1290
1412
  // they are closed.
1291
1413
  return html `<div
@@ -1296,14 +1418,13 @@ export class AstlToolbar extends AuthoringElement {
1296
1418
  lang=${lang}
1297
1419
  dir=${dir}
1298
1420
  @mousedown=${(event) => {
1299
- // A press keeps the editor's focus and selection.
1300
- if (event.target.closest('button') !== null)
1421
+ // A press keeps the editor's focus and selection; the host's elements in the slots are the host's.
1422
+ if (this.#buttonOf(event) !== null)
1301
1423
  event.preventDefault();
1302
1424
  }}
1303
1425
  @keydown=${(event) => this.#keydown(event)}
1304
1426
  >
1305
- ${split === 0 ? nothing : html `<div class="formats">${groups.slice(0, split).map((g, at) => group(g, at))}</div>`}
1306
- <div class="actions">${groups.slice(split).map((g, at) => group(g, split + at))}</div>
1427
+ ${first ? nothing : host('start')}${runs.map((run, at) => 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>`)}${final ? nothing : host('end')}
1307
1428
  </div>
1308
1429
  <div lang=${lang} dir=${dir}>
1309
1430
  ${this.#styleMenu()} ${this.#linkPopup()} ${this.#insertPopup()} ${this.#stylePopup()}