@astl/editor 0.0.0 → 0.1.1

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 (161) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +202 -0
  3. package/README.md +43 -0
  4. package/dist/authoring.d.ts +284 -0
  5. package/dist/authoring.d.ts.map +1 -0
  6. package/dist/authoring.js +566 -0
  7. package/dist/authoring.js.map +1 -0
  8. package/dist/define.d.ts +8 -0
  9. package/dist/define.d.ts.map +1 -0
  10. package/dist/define.js +35 -0
  11. package/dist/define.js.map +1 -0
  12. package/dist/edit.d.ts +45 -0
  13. package/dist/edit.d.ts.map +1 -0
  14. package/dist/edit.js +150 -0
  15. package/dist/edit.js.map +1 -0
  16. package/dist/elements/base.d.ts +31 -0
  17. package/dist/elements/base.d.ts.map +1 -0
  18. package/dist/elements/base.js +75 -0
  19. package/dist/elements/base.js.map +1 -0
  20. package/dist/elements/color-control.d.ts +25 -0
  21. package/dist/elements/color-control.d.ts.map +1 -0
  22. package/dist/elements/color-control.js +139 -0
  23. package/dist/elements/color-control.js.map +1 -0
  24. package/dist/elements/help-form.d.ts +31 -0
  25. package/dist/elements/help-form.d.ts.map +1 -0
  26. package/dist/elements/help-form.js +371 -0
  27. package/dist/elements/help-form.js.map +1 -0
  28. package/dist/elements/insert-menu.d.ts +79 -0
  29. package/dist/elements/insert-menu.d.ts.map +1 -0
  30. package/dist/elements/insert-menu.js +362 -0
  31. package/dist/elements/insert-menu.js.map +1 -0
  32. package/dist/elements/inspector.d.ts +24 -0
  33. package/dist/elements/inspector.d.ts.map +1 -0
  34. package/dist/elements/inspector.js +846 -0
  35. package/dist/elements/inspector.js.map +1 -0
  36. package/dist/elements/issue-list.d.ts +18 -0
  37. package/dist/elements/issue-list.d.ts.map +1 -0
  38. package/dist/elements/issue-list.js +85 -0
  39. package/dist/elements/issue-list.js.map +1 -0
  40. package/dist/elements/issues.d.ts +24 -0
  41. package/dist/elements/issues.d.ts.map +1 -0
  42. package/dist/elements/issues.js +81 -0
  43. package/dist/elements/issues.js.map +1 -0
  44. package/dist/elements/picture-dialog.d.ts +40 -0
  45. package/dist/elements/picture-dialog.d.ts.map +1 -0
  46. package/dist/elements/picture-dialog.js +433 -0
  47. package/dist/elements/picture-dialog.js.map +1 -0
  48. package/dist/elements/picture-field.d.ts +33 -0
  49. package/dist/elements/picture-field.d.ts.map +1 -0
  50. package/dist/elements/picture-field.js +692 -0
  51. package/dist/elements/picture-field.js.map +1 -0
  52. package/dist/elements/preview.d.ts +34 -0
  53. package/dist/elements/preview.d.ts.map +1 -0
  54. package/dist/elements/preview.js +165 -0
  55. package/dist/elements/preview.js.map +1 -0
  56. package/dist/elements/style-form.d.ts +30 -0
  57. package/dist/elements/style-form.d.ts.map +1 -0
  58. package/dist/elements/style-form.js +640 -0
  59. package/dist/elements/style-form.js.map +1 -0
  60. package/dist/elements/style-load.d.ts +26 -0
  61. package/dist/elements/style-load.d.ts.map +1 -0
  62. package/dist/elements/style-load.js +50 -0
  63. package/dist/elements/style-load.js.map +1 -0
  64. package/dist/elements/style-popups.d.ts +39 -0
  65. package/dist/elements/style-popups.d.ts.map +1 -0
  66. package/dist/elements/style-popups.js +173 -0
  67. package/dist/elements/style-popups.js.map +1 -0
  68. package/dist/elements/style-rules.d.ts +21 -0
  69. package/dist/elements/style-rules.d.ts.map +1 -0
  70. package/dist/elements/style-rules.js +274 -0
  71. package/dist/elements/style-rules.js.map +1 -0
  72. package/dist/elements/styles.d.ts +9 -0
  73. package/dist/elements/styles.d.ts.map +1 -0
  74. package/dist/elements/styles.js +161 -0
  75. package/dist/elements/styles.js.map +1 -0
  76. package/dist/elements/toolbar.d.ts +65 -0
  77. package/dist/elements/toolbar.d.ts.map +1 -0
  78. package/dist/elements/toolbar.js +1270 -0
  79. package/dist/elements/toolbar.js.map +1 -0
  80. package/dist/help.d.ts +33 -0
  81. package/dist/help.d.ts.map +1 -0
  82. package/dist/help.js +111 -0
  83. package/dist/help.js.map +1 -0
  84. package/dist/index.d.ts +32 -0
  85. package/dist/index.d.ts.map +1 -0
  86. package/dist/index.js +17 -0
  87. package/dist/index.js.map +1 -0
  88. package/dist/inspect.d.ts +251 -0
  89. package/dist/inspect.d.ts.map +1 -0
  90. package/dist/inspect.js +428 -0
  91. package/dist/inspect.js.map +1 -0
  92. package/dist/messages/en.json +252 -0
  93. package/dist/messages/help/en.json +18 -0
  94. package/dist/messages/help/pl.json +18 -0
  95. package/dist/messages/pl.json +252 -0
  96. package/dist/messages/style/en.json +67 -0
  97. package/dist/messages/style/pl.json +67 -0
  98. package/dist/messages.d.ts +5 -0
  99. package/dist/messages.d.ts.map +1 -0
  100. package/dist/messages.js +9 -0
  101. package/dist/messages.js.map +1 -0
  102. package/dist/pages.d.ts +28 -0
  103. package/dist/pages.d.ts.map +1 -0
  104. package/dist/pages.js +147 -0
  105. package/dist/pages.js.map +1 -0
  106. package/dist/scan.d.ts +82 -0
  107. package/dist/scan.d.ts.map +1 -0
  108. package/dist/scan.js +329 -0
  109. package/dist/scan.js.map +1 -0
  110. package/dist/style-messages.d.ts +7 -0
  111. package/dist/style-messages.d.ts.map +1 -0
  112. package/dist/style-messages.js +12 -0
  113. package/dist/style-messages.js.map +1 -0
  114. package/dist/style-model.d.ts +50 -0
  115. package/dist/style-model.d.ts.map +1 -0
  116. package/dist/style-model.js +76 -0
  117. package/dist/style-model.js.map +1 -0
  118. package/dist/style-placing.d.ts +38 -0
  119. package/dist/style-placing.d.ts.map +1 -0
  120. package/dist/style-placing.js +98 -0
  121. package/dist/style-placing.js.map +1 -0
  122. package/dist/textarea.d.ts +17 -0
  123. package/dist/textarea.d.ts.map +1 -0
  124. package/dist/textarea.js +175 -0
  125. package/dist/textarea.js.map +1 -0
  126. package/package.json +54 -4
  127. package/src/authoring.ts +896 -0
  128. package/src/define.ts +34 -0
  129. package/src/edit.ts +195 -0
  130. package/src/elements/base.ts +93 -0
  131. package/src/elements/color-control.ts +159 -0
  132. package/src/elements/help-form.ts +404 -0
  133. package/src/elements/insert-menu.ts +481 -0
  134. package/src/elements/inspector.ts +941 -0
  135. package/src/elements/issue-list.ts +103 -0
  136. package/src/elements/issues.ts +89 -0
  137. package/src/elements/picture-dialog.ts +461 -0
  138. package/src/elements/picture-field.ts +770 -0
  139. package/src/elements/preview.ts +186 -0
  140. package/src/elements/style-form.ts +751 -0
  141. package/src/elements/style-load.ts +64 -0
  142. package/src/elements/style-popups.ts +257 -0
  143. package/src/elements/style-rules.ts +294 -0
  144. package/src/elements/styles.ts +162 -0
  145. package/src/elements/toolbar.ts +1386 -0
  146. package/src/help.ts +156 -0
  147. package/src/index.ts +81 -0
  148. package/src/inspect.ts +774 -0
  149. package/src/messages/en.json +252 -0
  150. package/src/messages/help/en.json +18 -0
  151. package/src/messages/help/pl.json +18 -0
  152. package/src/messages/pl.json +252 -0
  153. package/src/messages/style/en.json +67 -0
  154. package/src/messages/style/pl.json +67 -0
  155. package/src/messages.ts +11 -0
  156. package/src/pages.ts +158 -0
  157. package/src/scan.ts +382 -0
  158. package/src/style-messages.ts +13 -0
  159. package/src/style-model.ts +125 -0
  160. package/src/style-placing.ts +117 -0
  161. package/src/textarea.ts +182 -0
@@ -0,0 +1,1386 @@
1
+ import type {
2
+ EditorAdapter,
3
+ EditorFormat,
4
+ EditorFormatState,
5
+ EditorStyleChanges,
6
+ EditorStyleRule,
7
+ EditorStyleState,
8
+ EditorStyleTarget,
9
+ EditorStyleTargetKind,
10
+ } from '@astl/core';
11
+ import { RovingFocus } from '@astl/player/interaction';
12
+ import {
13
+ type CSSResult,
14
+ type CSSResultGroup,
15
+ css,
16
+ html,
17
+ nothing,
18
+ type PropertyDeclarations,
19
+ type PropertyValues,
20
+ type SVGTemplateResult,
21
+ svg,
22
+ type TemplateResult,
23
+ } from 'lit';
24
+ import { styleMapOf } from '../style-model.js';
25
+ import { AuthoringElement } from './base.js';
26
+ import { type AstlInsertMenu, GLYPHS, type Glyph, type InsertGroup, TYPE_GLYPHS } from './insert-menu.js';
27
+ import { loadStyleElements, STYLE_OPEN, type StyleOpen } from './style-load.js';
28
+ import type { StylePopup } from './style-popups.js';
29
+ import { inheritTokens, kitStyles } from './styles.js';
30
+
31
+ /** Kit items a host can feature besides component tags (`tag`) and starters (`tag:template`). */
32
+ export const FEATURED_ITEMS: readonly string[] = ['text', 'picture', 'page-break'];
33
+
34
+ const ICONS = {
35
+ bold: svg`<path d="M6 4h5a3 3 0 0 1 0 6H6zm0 6h6a3 3 0 0 1 0 6H6z" stroke-width="2"/>`,
36
+ italic: svg`<path d="M9 4h7M4 16h7M12.5 4l-5 12"/>`,
37
+ underline: svg`<path d="M6 3v6a4 4 0 0 0 8 0V3M5 17h10"/>`,
38
+ link: svg`<path d="M8.5 11.5l3-3M7.5 9.5l-2 2a2.8 2.8 0 0 0 4 4l2-2M12.5 10.5l2-2a2.8 2.8 0 0 0-4-4l-2 2"/>`,
39
+ bulleted: svg`<path d="M8 5h9M8 10h9M8 15h9"/><circle cx="4" cy="5" r="1.3"/><circle cx="4" cy="10" r="1.3"/><circle cx="4" cy="15" r="1.3"/>`,
40
+ numbered: svg`<path d="M9 5h8M9 10h8M9 15h8M3 3.5h1.5V8M2.5 12.2c.4-.8 2.5-.9 2.5.4 0 1-2.5 2-2.5 3.4H5" stroke-width="1.5"/>`,
41
+ undo: svg`<path d="M7.5 5L4 8.5 7.5 12M4 8.5h8a4 4 0 0 1 0 8H9"/>`,
42
+ redo: svg`<path d="M12.5 5L16 8.5 12.5 12M16 8.5H8a4 4 0 0 0 0 8h3"/>`,
43
+ text: svg`<path d="M4 5V4h12v1M10 4v12M7.5 16h5"/>`,
44
+ add: svg`<path d="M10 4v12M4 10h12"/>`,
45
+ layouts: GLYPHS.columns,
46
+ templates: svg`<rect x="3" y="3" width="14" height="14" rx="1.5"/><path d="M3 8h14M8 8v9"/>`,
47
+ wrap: svg`<path d="M3 6h14M3 10h6M11 10h6M3 14h14" stroke-width="1.6"/><rect x="8" y="8" width="4" height="4" rx="1" stroke-width="1.4"/>`,
48
+ chevron: svg`<path d="M6 8l4 4 4-4"/>`,
49
+ color: svg`<path d="M5.5 13L10 3l4.5 10M7 10h6" stroke-width="1.8"/>`,
50
+ highlight: svg`<path d="M12.5 3.5l4 4-7.5 7.5H5v-4zM3.5 16.5h6" stroke-width="1.6"/>`,
51
+ 'align-start': svg`<path d="M3.5 5h13M3.5 9h8M3.5 13h13M3.5 17h8"/>`,
52
+ 'align-center': svg`<path d="M3.5 5h13M6 9h8M3.5 13h13M6 17h8"/>`,
53
+ 'align-end': svg`<path d="M3.5 5h13M8.5 9h8M3.5 13h13M8.5 17h8"/>`,
54
+ 'align-justify': svg`<path d="M3.5 5h13M3.5 9h13M3.5 13h13M3.5 17h13"/>`,
55
+ spacing: svg`<path d="M9 5h8M9 10h8M9 15h8M4.5 4v12M2.5 6l2-2 2 2M2.5 14l2 2 2-2"/>`,
56
+ clear: svg`<path d="M5 5V4h10v1M10 4l-1.5 7M4 16h7M13 11.5l4 4M17 11.5l-4 4"/>`,
57
+ } satisfies Readonly<Record<string, SVGTemplateResult>>;
58
+
59
+ /** The formats with a button of their own (the text styles are in a menu). */
60
+ type Toggle = 'bold' | 'italic' | 'underline' | 'link' | 'bulleted' | 'numbered';
61
+
62
+ const STYLES: readonly EditorFormat[] = ['paragraph', 'heading', 'subheading'];
63
+ const ELEMENT_GROUPS: readonly InsertGroup[] = ['components', 'content'];
64
+ const TEMPLATE_GROUPS: readonly InsertGroup[] = ['exercises'];
65
+ const LAYOUT_GROUPS: readonly InsertGroup[] = ['layouts'];
66
+ const MENU_GROUPS: Readonly<Record<InsertMenu, readonly InsertGroup[]>> = {
67
+ elements: ELEMENT_GROUPS,
68
+ templates: TEMPLATE_GROUPS,
69
+ layouts: LAYOUT_GROUPS,
70
+ };
71
+ const INSERT_MENUS: ReadonlySet<string> = new Set(Object.keys(MENU_GROUPS));
72
+ const MARKS: readonly Toggle[] = ['bold', 'italic', 'underline'];
73
+ const LISTS: readonly Toggle[] = ['bulleted', 'numbered'];
74
+
75
+ const STYLE_POPUPS: ReadonlySet<string> = new Set(['font', 'size', 'color', 'highlight', 'align', 'spacing']);
76
+
77
+ /** `panel`: the style form or the rules, the default of a request nobody else took (`astl-style-open`). */
78
+ type Popup = 'style' | 'link' | 'panel' | InsertMenu | StylePopup;
79
+
80
+ /** The toolbar's insert menus: every component and content insert, the named starters, or the layouts. */
81
+ export type InsertMenu = 'elements' | 'templates' | 'layouts';
82
+
83
+ const isMenu = (popup: Popup): popup is InsertMenu => INSERT_MENUS.has(popup);
84
+ /** The popover a popup opens: the insert menus share one. */
85
+ const popoverOf = (popup: Popup) => (isMenu(popup) ? 'insert' : popup);
86
+ /** The button a popup hangs from: the panel, reached from the style menu, hangs from that. */
87
+ const openerOf = (popup: Popup) => (popup === 'panel' ? 'style' : popup);
88
+
89
+ /** A view the toolbar's view switch offers (`AstlToolbar.views`). */
90
+ export interface ToolbarView {
91
+ readonly name: string;
92
+ readonly label: string;
93
+ }
94
+
95
+ /** The event the view switch fires when an author picks a view; `detail.view` is its name. */
96
+ export const VIEW_PICKED = 'astl-toolbar-view';
97
+
98
+ /** One button of the bar, in tab order. */
99
+ interface Item {
100
+ readonly id: string;
101
+ readonly label: string;
102
+ /** Shown beside the icon; null: the icon alone (its name is `label`). */
103
+ readonly text: string | null;
104
+ readonly icon: TemplateResult | SVGTemplateResult | null;
105
+ /** The icon's name, for `::part(icon-<name>)`. */
106
+ readonly iconName: string;
107
+ readonly pressed?: boolean;
108
+ /** A view of the view switch: whether it is the current one. */
109
+ readonly checked?: boolean;
110
+ readonly disabled?: boolean;
111
+ readonly popup?: Popup;
112
+ /** A button that says its value (the text style, the font, the size): a chevron after its text. */
113
+ readonly menu?: boolean;
114
+ /** A bar under the icon in this colour (the colour now). */
115
+ readonly bar?: string | null;
116
+ readonly data?: Readonly<Record<string, string>>;
117
+ press(): void;
118
+ }
119
+
120
+ const NO_STATE: EditorFormatState = { active: [], enabled: [], href: null, undo: false, redo: false };
121
+
122
+ /**
123
+ * The bar: one row of groups with a thin rule between them (each group's `separator`, a part a host can redraw), undo
124
+ * and redo at 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
125
+ * show. Wider than a phone, the groups wrap into rows
126
+ * when they do not fit, so every button is on show; on a phone the bar is one row that scrolls sideways, as a mobile
127
+ * editor's:
128
+ * wrapped, it would push the text below the fold. A shade at an edge says more buttons lie that way (the covers scroll
129
+ * with the buttons and hide it at either end), and the arrow keys scroll the focused button into view.
130
+ */
131
+ const barStyles: CSSResult = css`
132
+ :host {
133
+ display: block;
134
+ container-type: inline-size;
135
+ }
136
+ .bar {
137
+ box-sizing: border-box;
138
+ display: flex;
139
+ flex-wrap: wrap;
140
+ align-items: center;
141
+ gap: var(--astl-space-1) calc(2 * var(--astl-space-2) + var(--astl-outline-width));
142
+ padding: var(--astl-space-2);
143
+ border: var(--astl-outline-width) solid var(--astl-line);
144
+ border-radius: var(--astl-radius-l);
145
+ background: var(--astl-surface);
146
+ }
147
+ .group {
148
+ display: flex;
149
+ flex-wrap: wrap;
150
+ align-items: center;
151
+ gap: var(--astl-space-1);
152
+ }
153
+ .group + .group {
154
+ position: relative;
155
+ margin-inline-start: calc(-1 * var(--astl-space-2) - var(--astl-outline-width));
156
+ padding-inline-start: calc(var(--astl-space-2) + var(--astl-outline-width));
157
+ }
158
+ .separator {
159
+ position: absolute;
160
+ inset-block: 0;
161
+ inset-inline-start: 0;
162
+ border-inline-start: var(--astl-outline-width) solid var(--astl-line);
163
+ }
164
+ .group.history {
165
+ margin-inline-start: auto;
166
+ }
167
+ @container (inline-size < 30rem) {
168
+ .bar {
169
+ flex-wrap: nowrap;
170
+ overflow-x: auto;
171
+ scrollbar-width: thin;
172
+ background:
173
+ linear-gradient(90deg, var(--astl-surface) 50%, #0000) left / 1.5rem no-repeat local,
174
+ linear-gradient(-90deg, var(--astl-surface) 50%, #0000) right / 1.5rem no-repeat local,
175
+ radial-gradient(farthest-side at 0, var(--astl-outline), #0000) left / 0.5rem no-repeat,
176
+ radial-gradient(farthest-side at 100%, var(--astl-outline), #0000) right / 0.5rem no-repeat,
177
+ var(--astl-surface);
178
+ }
179
+ .group {
180
+ flex: none;
181
+ flex-wrap: nowrap;
182
+ }
183
+ }
184
+ `;
185
+
186
+ /** The buttons: hovered, pressed. */
187
+ const buttonStyles: CSSResult = css`
188
+ .bar button {
189
+ justify-content: center;
190
+ padding-inline: var(--astl-space-2);
191
+ border-color: transparent;
192
+ background: transparent;
193
+ white-space: nowrap;
194
+ }
195
+ .bar button.labelled {
196
+ padding-inline: var(--astl-space-2) var(--astl-space-3);
197
+ }
198
+ .bar button:hover {
199
+ border-color: var(--astl-line);
200
+ background: var(--astl-accent-soft);
201
+ }
202
+ .bar button[aria-pressed='true'] {
203
+ border-color: var(--astl-accent);
204
+ background: var(--astl-accent-soft);
205
+ color: var(--astl-ink);
206
+ }
207
+ .group.views {
208
+ gap: 0;
209
+ padding: calc(2 * var(--astl-outline-width));
210
+ border: var(--astl-outline-width) solid var(--astl-outline);
211
+ border-radius: var(--astl-radius-m);
212
+ }
213
+ .bar .views [aria-checked='true'] {
214
+ background: var(--astl-accent);
215
+ color: var(--astl-on-accent);
216
+ font-weight: 600;
217
+ }
218
+ `;
219
+
220
+ /**
221
+ * Unavailable here: dimmed and dashed (not by colour alone), still reachable by the arrow keys. Then the icons (shapes
222
+ * stroked here) and the popups: the text style menu, the link and the insert menus. Popups are compact: little
223
+ * padding, items without a frame (the hover's fill shows them; a disabled entry keeps its dashed one), the target kept
224
+ * (`--astl-target-min`). An insert menu has no visible title: the button that opened it names it, and the title is
225
+ * still the section's name.
226
+ */
227
+ const popupStyles: CSSResult = css`
228
+ .bar button[aria-disabled='true'] {
229
+ border-color: var(--astl-line);
230
+ border-style: dashed;
231
+ background: transparent;
232
+ color: var(--astl-ink-muted);
233
+ cursor: not-allowed;
234
+ }
235
+ .bar button[aria-expanded='true'] {
236
+ border-color: var(--astl-outline);
237
+ }
238
+ .icon {
239
+ fill: none;
240
+ stroke: currentColor;
241
+ stroke-width: 1.8;
242
+ stroke-linecap: round;
243
+ stroke-linejoin: round;
244
+ }
245
+ .icon circle {
246
+ fill: currentColor;
247
+ stroke: none;
248
+ }
249
+ .chevron {
250
+ inline-size: 1rem;
251
+ block-size: 1rem;
252
+ }
253
+ [popover] {
254
+ box-sizing: border-box;
255
+ position: fixed;
256
+ inset: auto;
257
+ margin: 0;
258
+ padding: var(--astl-space-2);
259
+ border: var(--astl-outline-width) solid var(--astl-line);
260
+ border-radius: var(--astl-radius-m);
261
+ background: var(--astl-surface);
262
+ color: var(--astl-ink);
263
+ box-shadow: 0 0.5rem 1.5rem rgb(0 0 0 / 0.2);
264
+ overflow: auto;
265
+ }
266
+ [popover]:not(:popover-open) {
267
+ display: none;
268
+ }
269
+ .menu {
270
+ display: flex;
271
+ flex-direction: column;
272
+ gap: 2px;
273
+ min-inline-size: 12rem;
274
+ max-block-size: calc(100dvh - 2 * var(--astl-space-4));
275
+ }
276
+ .menu button {
277
+ justify-content: flex-start;
278
+ padding: var(--astl-space-1) var(--astl-space-2);
279
+ border-color: transparent;
280
+ }
281
+ .menu button[aria-checked='true'] {
282
+ border-color: var(--astl-accent);
283
+ background: var(--astl-accent-soft);
284
+ font-weight: 600;
285
+ }
286
+ .insert {
287
+ inline-size: min(26rem, calc(100vw - 2 * var(--astl-space-4)));
288
+ max-block-size: min(32rem, calc(100vh - 2 * var(--astl-space-4)));
289
+ padding: 0;
290
+ }
291
+ .insert .search {
292
+ position: sticky;
293
+ inset-block-start: 0;
294
+ z-index: 1;
295
+ padding: var(--astl-space-2);
296
+ border-block-end: var(--astl-outline-width) solid var(--astl-line);
297
+ background: var(--astl-surface);
298
+ }
299
+ .insert astl-insert-menu::part(root) {
300
+ padding: var(--astl-space-2);
301
+ border: 0;
302
+ border-radius: 0;
303
+ }
304
+ .insert astl-insert-menu::part(title) {
305
+ display: none;
306
+ }
307
+ .insert astl-insert-menu::part(button) {
308
+ padding-inline: var(--astl-space-2);
309
+ }
310
+ .insert astl-insert-menu::part(button):enabled {
311
+ border-color: transparent;
312
+ }
313
+ .link {
314
+ display: flex;
315
+ flex-direction: column;
316
+ inline-size: min(22rem, calc(100vw - 2 * var(--astl-space-4)));
317
+ }
318
+ .menu .menu-section {
319
+ display: contents;
320
+ }
321
+ .menu .menu-group {
322
+ margin-block: var(--astl-space-2) 0;
323
+ padding-inline: var(--astl-space-2);
324
+ color: var(--astl-ink-muted);
325
+ font-size: var(--astl-size-small);
326
+ font-weight: 600;
327
+ }
328
+ .menu hr {
329
+ inline-size: 100%;
330
+ margin-block: var(--astl-space-1);
331
+ border: 0;
332
+ border-block-start: var(--astl-outline-width) solid var(--astl-line);
333
+ }
334
+ .bar button .value {
335
+ max-inline-size: 8rem;
336
+ overflow: hidden;
337
+ text-overflow: ellipsis;
338
+ }
339
+ .color-mark {
340
+ position: absolute;
341
+ inset-inline: 25%;
342
+ inset-block-end: var(--astl-space-1);
343
+ block-size: 0.2rem;
344
+ border: var(--astl-outline-width) solid var(--astl-outline);
345
+ forced-color-adjust: none;
346
+ }
347
+ .bar button[data-popup='color'],
348
+ .bar button[data-popup='highlight'] {
349
+ position: relative;
350
+ }
351
+ .link > * + * {
352
+ margin-block-start: var(--astl-space-2);
353
+ }
354
+ .link > [role='alert']:empty {
355
+ margin-block-start: 0;
356
+ }
357
+ .link label {
358
+ font-weight: 600;
359
+ }
360
+ .link .buttons {
361
+ display: flex;
362
+ flex-wrap: wrap;
363
+ gap: var(--astl-space-2);
364
+ }
365
+ .link .error {
366
+ margin: 0;
367
+ padding: var(--astl-space-2);
368
+ border-inline-start: var(--astl-space-1) solid var(--astl-danger);
369
+ background: var(--astl-danger-soft);
370
+ }
371
+ @media (forced-colors: active) {
372
+ .bar button:is([aria-pressed='true'], [aria-checked='true']) {
373
+ border-color: Highlight;
374
+ }
375
+ .bar button[aria-disabled='true'] {
376
+ color: GrayText;
377
+ }
378
+ }
379
+ `;
380
+
381
+ /**
382
+ * `<astl-toolbar>`: a word processor's toolbar for the editor in `adapter`, one row while it fits. In order: the text
383
+ * style (a menu: paragraph, heading, subheading), bold, italic, underline, link, the two lists; the host's `featured`
384
+ * inserts as buttons, "Elements" (every component and content insert) and "Templates" (the named starters), menus with
385
+ * a search over one `<astl-insert-menu>`; the types' commands on the selection (`EditorDescriptor.wrap`, "Mark
386
+ * word"); the view switch (`views`, a segmented control of radios); undo and redo at the end. Controls the adapter has
387
+ * no capability for are left out (`format`, `undo`, `wrap`). One tab stop: the arrow keys, Home and End move along it.
388
+ * Format buttons show the state at the cursor: pressed, or unavailable (`aria-disabled`, still focusable). A press
389
+ * never moves the editor's cursor: a pointer's leaves the focus in the editor, and a key's gives it back.
390
+ */
391
+ export class AstlToolbar extends AuthoringElement {
392
+ static override properties: PropertyDeclarations = {
393
+ ...AuthoringElement.properties,
394
+ featured: { attribute: false },
395
+ views: { attribute: false },
396
+ view: {},
397
+ };
398
+
399
+ static override styles: CSSResultGroup = [
400
+ kitStyles,
401
+ inheritTokens('astl-insert-menu, astl-picture-dialog, astl-style-form, astl-style-rules'),
402
+ barStyles,
403
+ buttonStyles,
404
+ popupStyles,
405
+ ];
406
+
407
+ /**
408
+ * The inserts shown as buttons, in order: component tags (their default template), `tag:template` for a named
409
+ * starter, and the kit items `text` (an empty paragraph after the cursor's block), `picture` and `page-break`.
410
+ * Unknown names are skipped. Default: none (everything is under "Elements" and "Templates").
411
+ */
412
+ declare featured: readonly string[];
413
+ /**
414
+ * The views of the view switch, in order; the first is the one the adapter edits, and in any other only the switch
415
+ * works. A pick fires `astl-toolbar-view` (bubbles, composed) with the view's name in `detail.view`; the host then
416
+ * sets `view`. Empty (default): no switch.
417
+ */
418
+ declare views: readonly ToolbarView[];
419
+ /** The name of the current view. */
420
+ declare view: string;
421
+
422
+ #state: EditorFormatState = NO_STATE;
423
+ #styles: EditorStyleState | null = null;
424
+ #popup: Popup | null = null;
425
+ /** The popups of the style controls, once one was asked for. */
426
+ #stylePopupsModule: typeof import('./style-popups.js') | null = null;
427
+ /** What the panel shows. */
428
+ #panel: StyleOpen['target'] = 'block';
429
+ /** A typed colour was refused, in the open colours popup. */
430
+ #colorError = false;
431
+ /** The insert menu shown last: its groups stay while closed. */
432
+ #menu: InsertMenu = 'elements';
433
+ #query = '';
434
+ #linkError = false;
435
+ #off: { readonly adapter: EditorAdapter; readonly off: () => void } | null = null;
436
+ #items: readonly Item[] = [];
437
+ readonly #roving = new RovingFocus(this, {
438
+ count: () => this.#items.length,
439
+ item: (index) => this.renderRoot.querySelector<HTMLElement>(`.bar [data-item="${index}"]`),
440
+ axis: 'inline',
441
+ });
442
+
443
+ constructor() {
444
+ super();
445
+ this.featured = [];
446
+ this.views = [];
447
+ this.view = '';
448
+ }
449
+
450
+ /** The insert menu of "Elements" and "Templates": insert from it as a host would from `<astl-insert-menu>`. */
451
+ get menu(): AstlInsertMenu | null {
452
+ return this.renderRoot.querySelector<AstlInsertMenu>('astl-insert-menu');
453
+ }
454
+
455
+ /** Opens "Elements", "Templates" or "Layout" with its search, as its button does. */
456
+ async openMenu(menu: InsertMenu): Promise<void> {
457
+ await this.#open(menu);
458
+ }
459
+
460
+ /**
461
+ * Asks for the style form of a target at the cursor, or the rules, as the style menu does: fires `astl-style-open`,
462
+ * and unless a host cancels it, shows them in a popup (they load now).
463
+ */
464
+ async openStyle(target: StyleOpen['target']): Promise<void> {
465
+ const detail: StyleOpen = { target };
466
+ this.#close(false);
467
+ const event = new CustomEvent(STYLE_OPEN, { detail, bubbles: true, composed: true, cancelable: true });
468
+ if (!this.dispatchEvent(event)) return;
469
+ await loadStyleElements();
470
+ this.#panel = target;
471
+ await this.#open('panel');
472
+ }
473
+
474
+ /** Loads the popups of the style controls and their styles, once; false if that failed (it says so in the console). */
475
+ async #loadStylePopups(): Promise<boolean> {
476
+ if (this.#stylePopupsModule !== null) return true;
477
+ try {
478
+ const module = await import('./style-popups.js');
479
+ const root = this.renderRoot as ShadowRoot;
480
+ const sheet = module.stylePopupStyles.styleSheet;
481
+ if (this.#stylePopupsModule === null && sheet !== undefined)
482
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
483
+ this.#stylePopupsModule = module;
484
+ return true;
485
+ } catch (error) {
486
+ console.error(error);
487
+ return false;
488
+ }
489
+ }
490
+
491
+ override connectedCallback(): void {
492
+ super.connectedCallback();
493
+ this.#follow();
494
+ document.addEventListener('pointerdown', this.#outside, true);
495
+ document.addEventListener('keydown', this.#escape);
496
+ }
497
+
498
+ override disconnectedCallback(): void {
499
+ super.disconnectedCallback();
500
+ this.#follow();
501
+ document.removeEventListener('pointerdown', this.#outside, true);
502
+ document.removeEventListener('keydown', this.#escape);
503
+ }
504
+
505
+ protected override willUpdate(changed: PropertyValues<this>): void {
506
+ super.willUpdate(changed);
507
+ if (changed.has('adapter')) this.#follow();
508
+ this.#state = this.adapter?.formatState?.() ?? NO_STATE;
509
+ this.#styles = this.adapter?.style?.state() ?? null;
510
+ }
511
+
512
+ /** Follows the cursor of the adapter: every move may change the state at it. */
513
+ #follow(): void {
514
+ const adapter = this.isConnected ? this.adapter : null;
515
+ if ((this.#off?.adapter ?? null) === adapter) return;
516
+ this.#off?.off();
517
+ this.#off = null;
518
+ const listen = adapter?.onCursorChange;
519
+ if (adapter === null || listen === undefined) return;
520
+ this.#off = { adapter, off: listen.call(adapter, () => this.requestUpdate()) };
521
+ }
522
+
523
+ /** A press outside the open popup and its button closes it. */
524
+ #outside = (event: Event): void => {
525
+ if (this.#popup === null) return;
526
+ const path = event.composedPath();
527
+ const popup = this.renderRoot.querySelector(`#${popoverOf(this.#popup)}`);
528
+ const opener = this.renderRoot.querySelector(`[data-popup="${openerOf(this.#popup)}"]`);
529
+ if ((popup !== null && path.includes(popup)) || (opener !== null && path.includes(opener))) return;
530
+ // The picture dialog of an insert menu sits outside the popover in the top layer, above it.
531
+ if (path.some((node) => node instanceof Element && node.localName === 'astl-picture-dialog')) return;
532
+ this.#close(false);
533
+ };
534
+
535
+ /**
536
+ * The style panel is not modal: the focus can leave it, by Tab or to the surface after an undo, and it stays open
537
+ * over what it covers. Escape closes it from there too; only from inside does the focus go back to its button.
538
+ */
539
+ #escape = (event: KeyboardEvent): void => {
540
+ if (this.#popup !== 'panel' || event.key !== 'Escape') return;
541
+ const panel = this.renderRoot.querySelector('#panel');
542
+ const inside = panel !== null && event.composedPath().includes(panel);
543
+ // Inside, a field may have its own use for the key (a rename). ProseMirror claims every Escape, with no use for it.
544
+ if (inside && event.defaultPrevented) return;
545
+ event.preventDefault();
546
+ this.#close(inside);
547
+ };
548
+
549
+ async #open(popup: Popup): Promise<void> {
550
+ if ((popup === 'panel' || STYLE_POPUPS.has(popup)) && !(await this.#loadStylePopups())) return;
551
+ if (this.#popup !== null && this.#popup !== popup) this.#close(false);
552
+ this.#popup = popup;
553
+ this.#linkError = false;
554
+ this.#colorError = false;
555
+ if (isMenu(popup)) {
556
+ this.#query = '';
557
+ this.#menu = popup;
558
+ }
559
+ this.requestUpdate();
560
+ await this.updateComplete;
561
+ const element = this.renderRoot.querySelector<HTMLElement>(`#${popoverOf(popup)}`);
562
+ const opener = this.renderRoot.querySelector<HTMLElement>(`[data-popup="${openerOf(popup)}"]`);
563
+ if (element === null || opener === null) return;
564
+ if (!element.matches(':popover-open')) element.showPopover();
565
+ // Its descriptions load now (`menuMessages`), not with the editor.
566
+ this.menu?.requestUpdate();
567
+ this.#place(element, opener);
568
+ const first =
569
+ popup === 'style' || STYLE_POPUPS.has(popup)
570
+ ? (element.querySelector<HTMLElement>('[aria-checked="true"], [aria-pressed="true"]') ??
571
+ element.querySelector('button'))
572
+ : popup === 'panel'
573
+ ? element
574
+ : element.querySelector<HTMLElement>('input');
575
+ first?.focus();
576
+ }
577
+
578
+ /** Closes the open popup; the focus goes back to its button with `back`. */
579
+ #close(back: boolean): void {
580
+ const popup = this.#popup;
581
+ if (popup === null) return;
582
+ this.#popup = null;
583
+ const element = this.renderRoot.querySelector<HTMLElement>(`#${popoverOf(popup)}`);
584
+ if (element?.matches(':popover-open') === true) element.hidePopover();
585
+ if (back) this.renderRoot.querySelector<HTMLElement>(`[data-popup="${openerOf(popup)}"]`)?.focus();
586
+ this.requestUpdate();
587
+ }
588
+
589
+ /** Puts a popup below its button, its start edge on the button's, inside the viewport. */
590
+ #place(popup: HTMLElement, opener: HTMLElement): void {
591
+ const rect = opener.getBoundingClientRect();
592
+ const rtl = getComputedStyle(opener).direction === 'rtl';
593
+ const width = popup.offsetWidth;
594
+ const room = document.documentElement.clientWidth;
595
+ const start = rtl ? room - rect.right : rect.left;
596
+ const inset = Math.max(8, Math.min(start, room - width - 8));
597
+ popup.style.setProperty('inset-inline-start', `${inset}px`);
598
+ // Below the button, or as low as it fits: a tall popup (the style form) from a bar far down the page.
599
+ const below = document.documentElement.clientHeight - popup.offsetHeight - 8;
600
+ popup.style.setProperty('inset-block-start', `${Math.max(8, Math.min(rect.bottom + 4, below))}px`);
601
+ }
602
+
603
+ /** After a command: the editor gets the focus back when a key pressed the button (a pointer never took it). */
604
+ #done(): void {
605
+ this.adapter?.focus?.();
606
+ }
607
+
608
+ #format(format: EditorFormat, href?: string): void {
609
+ if (!this.#state.enabled.includes(format)) return;
610
+ this.adapter?.format?.(format, href);
611
+ this.#done();
612
+ this.requestUpdate();
613
+ }
614
+
615
+ /** A style on the selected text (with only a cursor, on what is typed next), the popup closed. */
616
+ #setText(changes: EditorStyleChanges): void {
617
+ this.adapter?.style?.setText(changes);
618
+ this.#close(false);
619
+ this.#done();
620
+ this.requestUpdate();
621
+ }
622
+
623
+ /** A style on each text block of the selection, the popup closed. */
624
+ #setBlock(changes: EditorStyleChanges): void {
625
+ this.adapter?.style?.setTarget('block', changes);
626
+ this.#close(false);
627
+ this.#done();
628
+ this.requestUpdate();
629
+ }
630
+
631
+ /**
632
+ * Where a named style goes: on the selected text, and with only a cursor on what the cursor is in. A style of boxes
633
+ * (`box`) goes on what the cursor is in, words selected or not, as a paragraph style does in a word processor.
634
+ */
635
+ #namedTarget(box = false): 'text' | EditorStyleTargetKind | null {
636
+ const styles = this.#styles;
637
+ if (styles === null) return null;
638
+ return styles.hasSelection && !box ? 'text' : (styles.targets[0]?.kind ?? null);
639
+ }
640
+
641
+ /** The named style on that target. */
642
+ #namedNow(box = false): string | null {
643
+ const where = this.#namedTarget(box);
644
+ return where === 'text'
645
+ ? (this.#styles?.textClass ?? null)
646
+ : (this.#styles?.targets.find((target) => target.kind === where)?.className ?? null);
647
+ }
648
+
649
+ /** Whether a named style is a ready style of boxes: its rule in the document keeps that way of going on. */
650
+ #isBox(name: string): boolean {
651
+ return this.authoring?.styles.some((ready) => ready.name === name && ready.text !== true) ?? false;
652
+ }
653
+
654
+ /** Sets a named style, or takes it away when it is there; a ready style (`rule`) brings its rule in the same step. */
655
+ #setNamed(name: string, rule?: EditorStyleRule): void {
656
+ const box = this.#isBox(name);
657
+ const where = this.#namedTarget(box);
658
+ if (where !== null) {
659
+ if (rule === undefined)
660
+ this.adapter?.style?.setClass(where, this.#namedNow(box) === name ? null : name);
661
+ else this.adapter?.style?.setClass(where, name, rule);
662
+ }
663
+ this.#close(false);
664
+ this.#done();
665
+ this.requestUpdate();
666
+ }
667
+
668
+ /** The style at the cursor as a font's name: the host's, else the stack's first name; '' with none or a mix. */
669
+ #fontName(): string {
670
+ const stack = this.#styles?.text['font-family'];
671
+ if (stack === undefined) return '';
672
+ const known = this.authoring?.fonts.find((font) => font.stack === stack);
673
+ return known?.name ?? (stack.split(',')[0] ?? '').replace(/"/g, '').trim();
674
+ }
675
+
676
+ /** The bar's style controls, by group (font and size; colours; alignment and spacing), and clear formatting. */
677
+ #styleGroups(): { fonts: Item[]; colors: Item[]; blocks: Item[]; clear: Item[] } {
678
+ const styles = this.#styles;
679
+ if (styles === null) return { fonts: [], colors: [], blocks: [], clear: [] };
680
+ const { text, textEnabled, targets } = styles;
681
+ const hasBlock = targets.some((target) => target.kind === 'block');
682
+ const popupItem = (
683
+ popup: StylePopup,
684
+ label: string,
685
+ enabled: boolean,
686
+ icon: SVGTemplateResult,
687
+ iconName: string,
688
+ ): Item => ({
689
+ id: popup,
690
+ label,
691
+ text: null,
692
+ icon,
693
+ iconName,
694
+ disabled: !enabled,
695
+ popup,
696
+ press: () => {
697
+ if (this.#popup === popup) this.#close(true);
698
+ else void this.#open(popup);
699
+ },
700
+ });
701
+ const font = this.#fontName();
702
+ const size = /^(\d+(?:\.\d+)?)px$/.exec(text['font-size'] ?? '')?.[1] ?? text['font-size'] ?? '';
703
+ const valued = (popup: StylePopup, label: string, value: string): Item => ({
704
+ ...popupItem(
705
+ popup,
706
+ this.t(label, { value: value === '' ? this.t('toolbar.default') : value }),
707
+ textEnabled,
708
+ ICONS.chevron,
709
+ 'chevron',
710
+ ),
711
+ text: value === '' ? this.t(`toolbar.${popup}.name`) : value,
712
+ menu: true,
713
+ });
714
+ const blockStyle = targets.find((target) => target.kind === 'block')?.style ?? '';
715
+ const align = styleMapOf(blockStyle).get('text-align');
716
+ const alignIcon =
717
+ align === 'right' || align === 'end'
718
+ ? 'align-end'
719
+ : align === 'center'
720
+ ? 'align-center'
721
+ : align === 'justify'
722
+ ? 'align-justify'
723
+ : 'align-start';
724
+ return {
725
+ fonts: [valued('font', 'toolbar.font', font), valued('size', 'toolbar.size', size)],
726
+ colors: [
727
+ {
728
+ ...popupItem('color', this.t('toolbar.color'), textEnabled, ICONS.color, 'color'),
729
+ bar: text.color ?? null,
730
+ },
731
+ {
732
+ ...popupItem('highlight', this.t('toolbar.highlight'), textEnabled, ICONS.highlight, 'highlight'),
733
+ bar: text['background-color'] ?? null,
734
+ },
735
+ ],
736
+ blocks: [
737
+ popupItem('align', this.t('toolbar.align'), hasBlock, ICONS[alignIcon], alignIcon),
738
+ popupItem('spacing', this.t('toolbar.spacing'), hasBlock, ICONS.spacing, 'spacing'),
739
+ ],
740
+ clear: [
741
+ {
742
+ id: 'clear',
743
+ label: this.t('toolbar.clear'),
744
+ text: null,
745
+ icon: ICONS.clear,
746
+ iconName: 'clear',
747
+ disabled: !textEnabled && !hasBlock,
748
+ press: () => {
749
+ this.adapter?.style?.clear();
750
+ this.#done();
751
+ this.requestUpdate();
752
+ },
753
+ },
754
+ ],
755
+ };
756
+ }
757
+
758
+ async #insert(name: string): Promise<void> {
759
+ const menu = this.menu;
760
+ const adapter = this.adapter;
761
+ if (menu === null || adapter === null) return;
762
+ if (name === 'text') {
763
+ adapter.insert('<p></p>');
764
+ this.#done();
765
+ return;
766
+ }
767
+ if (name === 'picture') await menu.insertPicture();
768
+ else if (name === 'page-break') menu.insertPageBreak();
769
+ else {
770
+ const [tag = '', template] = name.split(':');
771
+ await menu.add(tag, template);
772
+ }
773
+ this.#done();
774
+ }
775
+
776
+ /** The featured names this editor can insert, as buttons. */
777
+ #featuredItems(): Item[] {
778
+ const authoring = this.authoring;
779
+ if (authoring === null) return [];
780
+ const disabled = this.adapter === null;
781
+ const items: Item[] = [];
782
+ for (const name of this.featured) {
783
+ if (name === 'text' || name === 'picture') {
784
+ const label = this.t(name === 'text' ? 'insert.text' : 'insert.picture');
785
+ items.push({
786
+ id: `insert-${name}`,
787
+ label,
788
+ text: label,
789
+ icon: name === 'text' ? ICONS.text : GLYPHS.picture,
790
+ iconName: name === 'text' ? 'text' : 'image',
791
+ disabled,
792
+ data: { content: name },
793
+ press: () => void this.#insert(name),
794
+ });
795
+ continue;
796
+ }
797
+ if (name === 'page-break') {
798
+ if (this.adapter?.splitPage === undefined) continue;
799
+ const label = this.t('insert.pageBreak');
800
+ items.push({
801
+ id: 'insert-page-break',
802
+ label,
803
+ text: label,
804
+ icon: GLYPHS.page,
805
+ iconName: 'files',
806
+ data: { content: name },
807
+ press: () => void this.#insert(name),
808
+ });
809
+ continue;
810
+ }
811
+ const [tag = '', template] = name.split(':');
812
+ const descriptor = authoring.descriptor(tag);
813
+ if (descriptor === null) continue;
814
+ const starter = template === undefined ? null : authoring.templates(tag).find((t) => t.id === template);
815
+ if (starter === undefined) continue;
816
+ const label = authoring.t(descriptor.manifest.messages, starter?.label ?? descriptor.label);
817
+ const icon = starter?.icon ?? descriptor.icon;
818
+ items.push({
819
+ id: `insert-${name}`,
820
+ label,
821
+ text: label,
822
+ icon: TYPE_GLYPHS.get(icon) ?? GLYPHS[descriptor.manifest.display as Glyph],
823
+ iconName: icon,
824
+ disabled,
825
+ data: template === undefined ? { tag } : { tag, template },
826
+ press: () => void this.#insert(name),
827
+ });
828
+ }
829
+ return items;
830
+ }
831
+
832
+ /** The bar's buttons in order, by group (named for its class). */
833
+ #groups(): [string, Item[]][] {
834
+ const adapter = this.adapter;
835
+ const authoring = this.authoring;
836
+ const state = this.#state;
837
+ const groups: [string, Item[]][] = [];
838
+ const formatItem = (format: Toggle, popup?: Popup): Item => ({
839
+ id: format,
840
+ label: this.t(`toolbar.${format}`),
841
+ text: null,
842
+ icon: ICONS[format],
843
+ iconName: format,
844
+ pressed: state.active.includes(format),
845
+ disabled: !state.enabled.includes(format),
846
+ ...(popup === undefined ? {} : { popup }),
847
+ press: () => {
848
+ if (popup !== undefined) void this.#open(popup);
849
+ else this.#format(format);
850
+ },
851
+ });
852
+ if (adapter?.format !== undefined && adapter.formatState !== undefined) {
853
+ const current = STYLES.find((style) => state.active.includes(style));
854
+ // The named style on what the menu would change says more than the tag.
855
+ const named = this.#namedNow();
856
+ const rule = named === null ? undefined : adapter.style?.rules().find((one) => one.name === named);
857
+ const styleName = rule?.label ?? rule?.name ?? this.t(`toolbar.${current ?? 'paragraph'}`);
858
+ const style = this.#styleGroups();
859
+ groups.push([
860
+ 'group',
861
+ [
862
+ {
863
+ id: 'style',
864
+ label: this.t('toolbar.style', { style: styleName }),
865
+ text: styleName,
866
+ icon: ICONS.chevron,
867
+ iconName: 'chevron',
868
+ menu: true,
869
+ // A selected picture or component has no text style, but its style form is in this menu.
870
+ disabled:
871
+ !STYLES.some((one) => state.enabled.includes(one)) && (this.#styles?.targets.length ?? 0) === 0,
872
+ popup: 'style',
873
+ press: () => void this.#open('style'),
874
+ },
875
+ ],
876
+ ]);
877
+ if (style.fonts.length > 0) groups.push(['group', style.fonts]);
878
+ groups.push(['group', [...MARKS.map((mark) => formatItem(mark)), formatItem('link', 'link')]]);
879
+ if (style.colors.length > 0) groups.push(['group', style.colors]);
880
+ if (style.blocks.length > 0) groups.push(['group', style.blocks]);
881
+ groups.push(['group', [...LISTS.map((list) => formatItem(list)), ...style.clear]]);
882
+ }
883
+ const menu = (popup: InsertMenu, icon: 'add' | 'templates' | 'layouts'): Item => ({
884
+ id: popup,
885
+ label: this.t(`toolbar.${popup}`),
886
+ text: this.t(`toolbar.${popup}`),
887
+ icon: ICONS[icon],
888
+ iconName: icon,
889
+ disabled: adapter === null,
890
+ popup,
891
+ press: () => {
892
+ if (this.#popup === popup) this.#close(true);
893
+ else void this.#open(popup);
894
+ },
895
+ });
896
+ const starters = authoring?.descriptors.some((d) => (d.templates ?? []).length > 0) === true;
897
+ groups.push([
898
+ 'group inserts',
899
+ [
900
+ ...this.#featuredItems(),
901
+ menu('elements', 'add'),
902
+ ...(starters ? [menu('templates', 'templates')] : []),
903
+ // Layouts are styles: a host without the style API has none to insert.
904
+ ...(adapter?.style !== undefined ? [menu('layouts', 'layouts')] : []),
905
+ ],
906
+ ]);
907
+ if (adapter?.wrap !== undefined && authoring !== null) {
908
+ const wraps = authoring.descriptors.filter((d) => d.wrap !== undefined);
909
+ if (wraps.length > 0) {
910
+ groups.push([
911
+ 'group',
912
+ wraps.map((d) => {
913
+ const label = authoring.t(d.manifest.messages, d.wrap?.label ?? '');
914
+ return {
915
+ id: `wrap-${d.manifest.tag}`,
916
+ label,
917
+ text: label,
918
+ icon: ICONS.wrap,
919
+ iconName: 'wrap',
920
+ data: { wrap: d.manifest.tag },
921
+ press: () => {
922
+ this.adapter?.wrap?.(d.manifest.tag);
923
+ this.#done();
924
+ },
925
+ };
926
+ }),
927
+ ]);
928
+ }
929
+ }
930
+ if (this.views.length > 0) {
931
+ groups.push([
932
+ 'group views',
933
+ this.views.map((view) => ({
934
+ id: `view-${view.name}`,
935
+ label: view.label,
936
+ text: view.label,
937
+ icon: null,
938
+ iconName: '',
939
+ checked: view.name === this.view,
940
+ press: () => {
941
+ if (view.name === this.view) return;
942
+ const detail = { view: view.name };
943
+ this.dispatchEvent(new CustomEvent(VIEW_PICKED, { detail, bubbles: true, composed: true }));
944
+ },
945
+ })),
946
+ ]);
947
+ }
948
+ if (adapter?.undo !== undefined && adapter.redo !== undefined) {
949
+ const history = (name: 'undo' | 'redo'): Item => ({
950
+ id: name,
951
+ label: this.t(`toolbar.${name}`),
952
+ text: null,
953
+ icon: ICONS[name],
954
+ iconName: name,
955
+ disabled: !state[name],
956
+ press: () => {
957
+ if (!state[name]) return;
958
+ adapter[name]?.();
959
+ this.#done();
960
+ },
961
+ });
962
+ groups.push(['group history', [history('undo'), history('redo')]]);
963
+ }
964
+ return groups;
965
+ }
966
+
967
+ #keydown(event: KeyboardEvent): void {
968
+ const target = (event.target as HTMLElement).closest<HTMLElement>('[data-item]');
969
+ if (target === null) return;
970
+ const index = Number(target.dataset.item);
971
+ const item = this.#items[index];
972
+ const menu = item?.popup === 'style' || STYLE_POPUPS.has(item?.popup ?? '');
973
+ if (menu && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
974
+ event.preventDefault();
975
+ if (item?.disabled !== true && item?.popup !== undefined) void this.#open(item.popup);
976
+ return;
977
+ }
978
+ this.#roving.keydown(event, index);
979
+ }
980
+
981
+ #button(item: Item, index: number): TemplateResult {
982
+ const unavailable = item.disabled === true;
983
+ // The parts: every button; an icon-only one is also an `icon-button`, and an option of the view switch a `view`.
984
+ const part =
985
+ item.checked !== undefined ? 'button view' : item.text === null ? 'button icon-button' : 'button';
986
+ return html`<button
987
+ type="button"
988
+ part=${part}
989
+ class=${item.text === null ? 'icon-only' : 'labelled'}
990
+ data-item=${index}
991
+ data-id=${item.id}
992
+ data-tag=${item.data?.tag ?? nothing}
993
+ data-template=${item.data?.template ?? nothing}
994
+ data-content=${item.data?.content ?? nothing}
995
+ data-popup=${item.popup ?? nothing}
996
+ tabindex=${this.#roving.tabIndex(index)}
997
+ aria-label=${item.text === null || item.menu === true ? item.label : nothing}
998
+ title=${item.text === null ? item.label : nothing}
999
+ aria-pressed=${item.pressed === undefined ? nothing : String(item.pressed)}
1000
+ role=${item.checked === undefined ? nothing : 'radio'}
1001
+ aria-checked=${item.checked === undefined ? nothing : String(item.checked)}
1002
+ aria-disabled=${unavailable ? 'true' : nothing}
1003
+ aria-haspopup=${
1004
+ item.popup === undefined
1005
+ ? nothing
1006
+ : item.popup === 'style' || item.menu === true || item.popup === 'align' || item.popup === 'spacing'
1007
+ ? 'menu'
1008
+ : 'dialog'
1009
+ }
1010
+ aria-expanded=${item.popup === undefined ? nothing : String(this.#popup === item.popup)}
1011
+ aria-controls=${item.popup === undefined ? nothing : popoverOf(item.popup)}
1012
+ @click=${() => {
1013
+ this.#roving.focus(index);
1014
+ if (!unavailable) item.press();
1015
+ }}
1016
+ >
1017
+ ${
1018
+ item.menu === true
1019
+ ? html`<span class="value">${item.text}</span>
1020
+ <svg class="icon chevron" part="icon icon-chevron" viewBox="0 0 20 20" aria-hidden="true" focusable="false">${item.icon}</svg>`
1021
+ : html`${item.icon === null ? nothing : html`<svg class="icon" part="icon icon-${item.iconName}" data-icon=${item.iconName} viewBox="0 0 20 20" aria-hidden="true" focusable="false">${item.icon}</svg>`}
1022
+ ${item.text === null ? nothing : html`<span>${item.text}</span>`}${
1023
+ item.bar === undefined || item.bar === null
1024
+ ? nothing
1025
+ : html`<span class="color-mark" data-color=${item.bar}></span>`
1026
+ }`
1027
+ }
1028
+ </button>`;
1029
+ }
1030
+
1031
+ /** The arrows, Home and End along a menu's buttons; Escape closes it, back on its button; Tab goes on. */
1032
+ #menuKeydown = (event: KeyboardEvent): void => {
1033
+ const buttons = [...(event.currentTarget as HTMLElement).querySelectorAll<HTMLElement>('button')];
1034
+ const at = buttons.indexOf(event.target as HTMLElement);
1035
+ const step = event.key === 'ArrowDown' ? 1 : event.key === 'ArrowUp' ? -1 : 0;
1036
+ if (step !== 0) {
1037
+ event.preventDefault();
1038
+ buttons[(at + step + buttons.length) % buttons.length]?.focus();
1039
+ } else if (event.key === 'Home' || event.key === 'End') {
1040
+ event.preventDefault();
1041
+ buttons[event.key === 'Home' ? 0 : buttons.length - 1]?.focus();
1042
+ } else if (event.key === 'Escape') {
1043
+ event.preventDefault();
1044
+ this.#close(true);
1045
+ } else if (event.key === 'Tab') this.#close(false);
1046
+ };
1047
+
1048
+ /**
1049
+ * The rest of the style menu: the document's named styles, the ready styles it does not have yet, then the forms of
1050
+ * what the cursor is in.
1051
+ */
1052
+ #styleMenuMore(): TemplateResult | typeof nothing {
1053
+ const styles = this.#styles;
1054
+ if (styles === null) return nothing;
1055
+ const named = this.adapter?.style?.rules().filter((rule) => rule.name !== undefined) ?? [];
1056
+ const own = new Set(named.map((rule) => rule.name));
1057
+ const ready = (this.authoring?.styles ?? []).filter((preset) => !own.has(preset.name));
1058
+ const targets: readonly EditorStyleTarget[] = styles.targets;
1059
+ const group = (label: string, items: readonly TemplateResult[]) => html`<hr />
1060
+ <div class="menu-section" role="group" aria-label=${label}>
1061
+ <div class="menu-group" aria-hidden="true">${label}</div>
1062
+ ${items}
1063
+ </div>`;
1064
+ return html`${
1065
+ named.length === 0
1066
+ ? nothing
1067
+ : group(
1068
+ this.t('toolbar.myStyles'),
1069
+ named.map((rule) => {
1070
+ const name = rule.name ?? '';
1071
+ const box = this.#isBox(name);
1072
+ const none = this.#namedTarget(box) === null;
1073
+ return html`<button
1074
+ type="button"
1075
+ role="menuitemradio"
1076
+ tabindex="-1"
1077
+ data-named=${name}
1078
+ aria-checked=${String(this.#namedNow(box) === name)}
1079
+ aria-disabled=${none ? 'true' : nothing}
1080
+ @click=${() => {
1081
+ if (!none) this.#setNamed(name);
1082
+ }}
1083
+ >
1084
+ ${rule.label ?? name}
1085
+ </button>`;
1086
+ }),
1087
+ )
1088
+ }
1089
+ ${
1090
+ ready.length === 0
1091
+ ? nothing
1092
+ : group(
1093
+ this.t('toolbar.readyStyles'),
1094
+ ready.map(({ name, label, style, text }) => {
1095
+ const none = this.#namedTarget(text !== true) === null;
1096
+ return html`<button
1097
+ type="button"
1098
+ role="menuitem"
1099
+ tabindex="-1"
1100
+ data-ready=${name}
1101
+ aria-disabled=${none ? 'true' : nothing}
1102
+ @click=${() => {
1103
+ // Its label as the author reads it now: from here on it is a style of this exercise.
1104
+ if (!none) this.#setNamed(name, { name, label, style });
1105
+ }}
1106
+ >
1107
+ ${label}
1108
+ </button>`;
1109
+ }),
1110
+ )
1111
+ }
1112
+ <hr />
1113
+ ${targets.map(
1114
+ (target) => html`<button
1115
+ type="button"
1116
+ role="menuitem"
1117
+ tabindex="-1"
1118
+ data-style-target=${target.kind}
1119
+ @click=${() => void this.openStyle(target.kind)}
1120
+ >
1121
+ ${this.t('style.target.more', { target: this.t(`style.target.${target.kind}`) })}
1122
+ </button>`,
1123
+ )}
1124
+ <button
1125
+ type="button"
1126
+ role="menuitem"
1127
+ tabindex="-1"
1128
+ data-style-target="rules"
1129
+ @click=${() => void this.openStyle('rules')}
1130
+ >
1131
+ ${this.t('style.rules.open')}
1132
+ </button>`;
1133
+ }
1134
+
1135
+ /** The open popup of the style controls, from its module. */
1136
+ #stylePopup(): TemplateResult | typeof nothing {
1137
+ const module = this.#stylePopupsModule;
1138
+ const popup = this.#popup;
1139
+ const styles = this.#styles;
1140
+ if (module === null || styles === null || (popup !== 'panel' && !STYLE_POPUPS.has(popup ?? '')))
1141
+ return nothing;
1142
+ return module.stylePopup({
1143
+ popup: popup === 'panel' ? { panel: this.#panel } : (popup as StylePopup),
1144
+ styles,
1145
+ fonts: this.authoring?.fonts ?? [],
1146
+ colorError: this.#colorError,
1147
+ authoring: this.authoring,
1148
+ adapter: this.adapter,
1149
+ t: (key, params) => this.t(key, params),
1150
+ setText: (changes) => this.#setText(changes),
1151
+ setBlock: (changes) => this.#setBlock(changes),
1152
+ refuseColor: () => {
1153
+ this.#colorError = true;
1154
+ this.requestUpdate();
1155
+ },
1156
+ close: (back) => this.#close(back),
1157
+ menuKeydown: this.#menuKeydown,
1158
+ });
1159
+ }
1160
+
1161
+ #styleMenu(): TemplateResult {
1162
+ const state = this.#state;
1163
+ const choose = (style: EditorFormat) => {
1164
+ this.#close(false);
1165
+ if (!state.active.includes(style) || style === 'paragraph') this.#format(style);
1166
+ else this.#done();
1167
+ };
1168
+ return html`<div
1169
+ id="style"
1170
+ class="menu"
1171
+ popover="manual"
1172
+ role="menu"
1173
+ aria-label=${this.t('toolbar.style', { style: this.t(`toolbar.${STYLES.find((s) => state.active.includes(s)) ?? 'paragraph'}`) })}
1174
+ part="style-menu"
1175
+ @keydown=${this.#menuKeydown}
1176
+ >
1177
+ ${STYLES.map(
1178
+ (style) => html`<button
1179
+ type="button"
1180
+ role="menuitemradio"
1181
+ tabindex="-1"
1182
+ data-format=${style}
1183
+ aria-checked=${String(state.active.includes(style))}
1184
+ aria-disabled=${state.enabled.includes(style) ? nothing : 'true'}
1185
+ @click=${() => choose(style)}
1186
+ >
1187
+ ${this.t(`toolbar.${style}`)}
1188
+ </button>`,
1189
+ )}
1190
+ ${this.#styleMenuMore()}
1191
+ </div>`;
1192
+ }
1193
+
1194
+ #linkPopup(): TemplateResult {
1195
+ const state = this.#state;
1196
+ const apply = () => {
1197
+ const input = this.renderRoot.querySelector<HTMLInputElement>('#link-address');
1198
+ const href = input?.value.trim() ?? '';
1199
+ if (href === '') {
1200
+ this.#close(false);
1201
+ this.#format('link');
1202
+ return;
1203
+ }
1204
+ if (this.authoring?.urlPolicy(href, { tag: 'a', attribute: 'href' }) !== true) {
1205
+ this.#linkError = true;
1206
+ this.requestUpdate();
1207
+ input?.focus();
1208
+ return;
1209
+ }
1210
+ this.#close(false);
1211
+ this.#format('link', href);
1212
+ };
1213
+ return html`<div
1214
+ id="link"
1215
+ class="link"
1216
+ popover="manual"
1217
+ role="dialog"
1218
+ aria-label=${this.t('toolbar.link')}
1219
+ part="link"
1220
+ @keydown=${(event: KeyboardEvent) => {
1221
+ if (event.key === 'Escape') {
1222
+ event.preventDefault();
1223
+ this.#close(true);
1224
+ } else if (event.key === 'Enter' && (event.target as HTMLElement).localName === 'input') {
1225
+ event.preventDefault();
1226
+ apply();
1227
+ }
1228
+ }}
1229
+ >
1230
+ <label for="link-address">${this.t('toolbar.link.address')}</label>
1231
+ <input
1232
+ id="link-address"
1233
+ type="url"
1234
+ inputmode="url"
1235
+ .value=${this.#popup === 'link' ? (state.href ?? '') : ''}
1236
+ aria-invalid=${this.#linkError ? 'true' : nothing}
1237
+ aria-describedby=${this.#linkError ? 'link-error' : nothing}
1238
+ />
1239
+ <div role="alert">${this.#linkError ? html`<p class="error" id="link-error">${this.t('toolbar.link.blocked')}</p>` : nothing}</div>
1240
+ <div class="buttons">
1241
+ <button type="button" class="primary" @click=${apply}>${this.t('toolbar.link.apply')}</button>
1242
+ ${
1243
+ state.href === null
1244
+ ? nothing
1245
+ : html`<button
1246
+ type="button"
1247
+ @click=${() => {
1248
+ this.#close(false);
1249
+ this.#format('link');
1250
+ }}
1251
+ >
1252
+ ${this.t('toolbar.link.remove')}
1253
+ </button>`
1254
+ }
1255
+ </div>
1256
+ </div>`;
1257
+ }
1258
+
1259
+ #insertPopup(): TemplateResult {
1260
+ const authoring = this.authoring;
1261
+ return html`<div
1262
+ id="insert"
1263
+ class="insert"
1264
+ popover="manual"
1265
+ role="dialog"
1266
+ aria-label=${this.t(`toolbar.${this.#menu}`)}
1267
+ part="insert"
1268
+ @keydown=${(event: KeyboardEvent) => {
1269
+ if (event.key === 'Escape') {
1270
+ event.preventDefault();
1271
+ this.#close(true);
1272
+ }
1273
+ }}
1274
+ @focusout=${(event: FocusEvent) => {
1275
+ const next = event.relatedTarget as Node | null;
1276
+ if (next !== null && !(event.currentTarget as HTMLElement).contains(next)) this.#close(false);
1277
+ }}
1278
+ @astl-inserted=${() => {
1279
+ this.#close(false);
1280
+ this.#done();
1281
+ }}
1282
+ >
1283
+ <div class="search">
1284
+ <input
1285
+ type="search"
1286
+ aria-label=${this.t('toolbar.search')}
1287
+ placeholder=${this.t('toolbar.search')}
1288
+ .value=${this.#query}
1289
+ @input=${(event: Event) => {
1290
+ this.#query = (event.target as HTMLInputElement).value;
1291
+ this.requestUpdate();
1292
+ }}
1293
+ @keydown=${(event: KeyboardEvent) => {
1294
+ if (event.key !== 'Enter') return;
1295
+ event.preventDefault();
1296
+ const first = this.menu?.renderRoot.querySelector<HTMLButtonElement>(
1297
+ 'button.insert:not(:disabled)',
1298
+ );
1299
+ first?.click();
1300
+ }}
1301
+ />
1302
+ </div>
1303
+ <astl-insert-menu
1304
+ part="menu"
1305
+ .authoring=${authoring}
1306
+ .adapter=${this.adapter}
1307
+ .filter=${this.#query}
1308
+ .groups=${MENU_GROUPS[this.#menu]}
1309
+ ></astl-insert-menu>
1310
+ </div>`;
1311
+ }
1312
+
1313
+ protected override render(): TemplateResult | typeof nothing {
1314
+ if (this.authoring === null) return nothing;
1315
+ const { lang, dir } = this.ui;
1316
+ // Out of the editing view (the first), only the switch works.
1317
+ const away = this.views.length > 0 && this.view !== this.views[0]?.name;
1318
+ const groups = this.#groups().map(
1319
+ ([name, items]) =>
1320
+ [
1321
+ name,
1322
+ away
1323
+ ? items.map((item) => (item.checked === undefined ? { ...item, disabled: true } : item))
1324
+ : items,
1325
+ ] as const,
1326
+ );
1327
+ this.#items = groups.flatMap(([, items]) => items);
1328
+ let index = 0;
1329
+ // The picture dialog is outside the popovers: a picture asked for from a menu or a featured button shows while
1330
+ // they are closed.
1331
+ return html`<div
1332
+ class="bar"
1333
+ part="toolbar"
1334
+ role="toolbar"
1335
+ aria-label=${this.t('toolbar.label')}
1336
+ lang=${lang}
1337
+ dir=${dir}
1338
+ @mousedown=${(event: MouseEvent) => {
1339
+ // A press keeps the editor's focus and selection.
1340
+ if ((event.target as HTMLElement).closest('button') !== null) event.preventDefault();
1341
+ }}
1342
+ @keydown=${(event: KeyboardEvent) => this.#keydown(event)}
1343
+ >
1344
+ ${groups.map(
1345
+ (
1346
+ [name, items],
1347
+ at,
1348
+ ) => html`<div class=${name} role=${name === 'group views' ? 'radiogroup' : 'presentation'}
1349
+ part=${name === 'group views' ? 'views' : nothing}
1350
+ aria-label=${name === 'group views' ? this.t('toolbar.view') : nothing}>
1351
+ ${at === 0 || name === 'group views' ? nothing : html`<span class="separator" part="separator" aria-hidden="true"></span>`}
1352
+ ${items.map((item) => this.#button(item, index++))}
1353
+ </div>`,
1354
+ )}
1355
+ </div>
1356
+ <div lang=${lang} dir=${dir}>
1357
+ ${this.#styleMenu()} ${this.#linkPopup()} ${this.#insertPopup()} ${this.#stylePopup()}
1358
+ </div>
1359
+ <astl-picture-dialog .authoring=${this.authoring}></astl-picture-dialog>`;
1360
+ }
1361
+
1362
+ protected override updated(changed: PropertyValues<this>): void {
1363
+ super.updated(changed);
1364
+ const menu = this.menu;
1365
+ if (menu !== null) menu.dialog = this.renderRoot.querySelector('astl-picture-dialog');
1366
+ // Through the CSSOM: a strict Content Security Policy blocks a style attribute, which Lit's styleMap writes on its
1367
+ // first render.
1368
+ for (const mark of this.renderRoot.querySelectorAll<HTMLElement>('.color-mark')) {
1369
+ mark.style.background = mark.dataset.color ?? '';
1370
+ }
1371
+ for (const choice of this.renderRoot.querySelectorAll<HTMLElement>('[data-font]')) {
1372
+ choice.style.fontFamily = choice.dataset.font ?? '';
1373
+ }
1374
+ // Popups stay where their buttons are while the page scrolls or the bar wraps.
1375
+ if (this.#popup === null) return;
1376
+ const element = this.renderRoot.querySelector<HTMLElement>(`#${popoverOf(this.#popup)}`);
1377
+ const opener = this.renderRoot.querySelector<HTMLElement>(`[data-popup="${openerOf(this.#popup)}"]`);
1378
+ if (element !== null && opener !== null && element.matches(':popover-open')) this.#place(element, opener);
1379
+ }
1380
+ }
1381
+
1382
+ declare global {
1383
+ interface HTMLElementTagNameMap {
1384
+ 'astl-toolbar': AstlToolbar;
1385
+ }
1386
+ }