@astl/editor-tiptap 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 (69) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/LICENSE +202 -0
  3. package/README.md +49 -0
  4. package/dist/adapter.d.ts +13 -0
  5. package/dist/adapter.d.ts.map +1 -0
  6. package/dist/adapter.js +421 -0
  7. package/dist/adapter.js.map +1 -0
  8. package/dist/blocks.d.ts +96 -0
  9. package/dist/blocks.d.ts.map +1 -0
  10. package/dist/blocks.js +460 -0
  11. package/dist/blocks.js.map +1 -0
  12. package/dist/define.d.ts +64 -0
  13. package/dist/define.d.ts.map +1 -0
  14. package/dist/define.js +20 -0
  15. package/dist/define.js.map +1 -0
  16. package/dist/element.d.ts +91 -0
  17. package/dist/element.d.ts.map +1 -0
  18. package/dist/element.js +779 -0
  19. package/dist/element.js.map +1 -0
  20. package/dist/index.d.ts +11 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +3 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/layouts.d.ts +52 -0
  25. package/dist/layouts.d.ts.map +1 -0
  26. package/dist/layouts.js +198 -0
  27. package/dist/layouts.js.map +1 -0
  28. package/dist/nodes.d.ts +150 -0
  29. package/dist/nodes.d.ts.map +1 -0
  30. package/dist/nodes.js +2426 -0
  31. package/dist/nodes.js.map +1 -0
  32. package/dist/source-view.d.ts +26 -0
  33. package/dist/source-view.d.ts.map +1 -0
  34. package/dist/source-view.js +114 -0
  35. package/dist/source-view.js.map +1 -0
  36. package/dist/source.d.ts +8 -0
  37. package/dist/source.d.ts.map +1 -0
  38. package/dist/source.js +24 -0
  39. package/dist/source.js.map +1 -0
  40. package/dist/style.d.ts +16 -0
  41. package/dist/style.d.ts.map +1 -0
  42. package/dist/style.js +568 -0
  43. package/dist/style.js.map +1 -0
  44. package/dist/styles.d.ts +5 -0
  45. package/dist/styles.d.ts.map +1 -0
  46. package/dist/styles.js +921 -0
  47. package/dist/styles.js.map +1 -0
  48. package/dist/surface.d.ts +24 -0
  49. package/dist/surface.d.ts.map +1 -0
  50. package/dist/surface.js +90 -0
  51. package/dist/surface.js.map +1 -0
  52. package/dist/tiptap.d.ts +10 -0
  53. package/dist/tiptap.d.ts.map +1 -0
  54. package/dist/tiptap.js +9 -0
  55. package/dist/tiptap.js.map +1 -0
  56. package/package.json +63 -4
  57. package/src/adapter.ts +421 -0
  58. package/src/blocks.ts +577 -0
  59. package/src/define.ts +84 -0
  60. package/src/element.ts +988 -0
  61. package/src/index.ts +10 -0
  62. package/src/layouts.ts +220 -0
  63. package/src/nodes.ts +2690 -0
  64. package/src/source-view.ts +138 -0
  65. package/src/source.ts +27 -0
  66. package/src/style.ts +638 -0
  67. package/src/styles.ts +931 -0
  68. package/src/surface.ts +110 -0
  69. package/src/tiptap.ts +9 -0
@@ -0,0 +1,779 @@
1
+ /**
2
+ * `<astl-editor>`: the authoring kit (toolbar, inspector, issues, preview) around an editing surface. The surface is
3
+ * TipTap by default, imported on demand; any other editor plugs in through `adapter` and a `slot="surface"` child, and
4
+ * then TipTap is never loaded.
5
+ */
6
+ import { directionOf, negotiateLocale, PRACTICE_POLICY, } from '@astl/core';
7
+ import { createAuthoring, DEFAULT_FONTS, DEFAULT_STYLES, EDITOR_NAMESPACE, editorMessages, } from '@astl/editor';
8
+ import { createEngine } from '@astl/engine';
9
+ import { tokens, tokensCss } from '@astl/tokens';
10
+ import { css, html, LitElement, nothing, unsafeCSS, } from 'lit';
11
+ import { keyed } from 'lit/directives/keyed.js';
12
+ /**
13
+ * Every token as `inherit` on `selector`, for elements that redeclare the tokens on their own `:host` (the kit
14
+ * elements): a rule from the outer tree wins over `:host`, so tokens set on `<astl-editor>` reach them. The kit's
15
+ * preview forwards them to its player the same way.
16
+ */
17
+ function inheritTokens(selector) {
18
+ const names = [tokens.scale, tokens.themes.light, tokens.themeScale.light].flatMap(Object.keys);
19
+ const lines = ['color-scheme: inherit;', ...names.map((name) => `--astl-${name}: inherit;`)];
20
+ return unsafeCSS(`${selector} {\n${lines.join('\n')}\n}`);
21
+ }
22
+ /**
23
+ * The shadow root of `<astl-editor>`: tokens, the toolbar over the surface beside the kit, everything in one column
24
+ * when narrow. The surface's own stylesheet comes with the surface (`styles.ts`).
25
+ */
26
+ const editorStyles = [
27
+ // Tokens sit on :host so host pages can override any --astl-* property on <astl-editor> itself.
28
+ unsafeCSS(tokensCss(':host')),
29
+ inheritTokens('astl-toolbar, astl-inspector, astl-issues, astl-preview, astl-picture-dialog'),
30
+ css `
31
+ :host {
32
+ display: block;
33
+ container-type: inline-size;
34
+ color: var(--astl-ink);
35
+ font-family: var(--astl-font-body);
36
+ font-size: var(--astl-size-ui);
37
+ line-height: 1.4;
38
+ }
39
+ :host([hidden]) {
40
+ display: none;
41
+ }
42
+ `,
43
+ // The bands are a column of flex items, not a grid: the spec makes a grid item's containing block its grid area,
44
+ // which may hold a host's sticky toolbar (`::part(toolbar)`) to its own row; a flex item's is the whole column.
45
+ css `
46
+ .layout {
47
+ display: flex;
48
+ flex-direction: column;
49
+ gap: var(--astl-editor-layout-gap, var(--astl-space-4));
50
+ }
51
+ .work {
52
+ display: grid;
53
+ grid-template-columns: minmax(0, 1fr);
54
+ align-items: start;
55
+ gap: var(--astl-space-4);
56
+ }
57
+ .surface,
58
+ .side,
59
+ .start,
60
+ .end {
61
+ display: flex;
62
+ flex-direction: column;
63
+ gap: var(--astl-space-4);
64
+ min-inline-size: 0;
65
+ }
66
+ .surface {
67
+ position: relative;
68
+ }
69
+ ::slotted(*) {
70
+ box-sizing: border-box;
71
+ inline-size: 100%;
72
+ max-inline-size: 100%;
73
+ }
74
+ .status {
75
+ margin: 0;
76
+ padding: var(--astl-space-4);
77
+ border: var(--astl-outline-width) solid var(--astl-line);
78
+ border-radius: var(--astl-radius-l);
79
+ background: var(--astl-surface);
80
+ color: var(--astl-ink-muted);
81
+ }
82
+ `,
83
+ // The side column and the host's columns in another view, and a host column with nothing slotted: out of the way (the
84
+ // grid keeps no track and no gap for them). The notice line with nothing to say: out of sight, but still in the
85
+ // accessibility tree, so its next message is announced.
86
+ css `
87
+ .side[hidden],
88
+ .start[hidden],
89
+ .end[hidden] {
90
+ display: none;
91
+ }
92
+ .status.idle {
93
+ position: absolute;
94
+ inline-size: 1px;
95
+ block-size: 1px;
96
+ padding: 0;
97
+ border: 0;
98
+ overflow: hidden;
99
+ clip-path: inset(50%);
100
+ white-space: nowrap;
101
+ }
102
+ `,
103
+ // The status line under the toolbar: the counts in mono, then whether it is ready to share (in words, never the
104
+ // colour alone).
105
+ css `
106
+ .status-line {
107
+ display: flex;
108
+ flex-wrap: wrap;
109
+ justify-content: space-between;
110
+ gap: 0 var(--astl-space-3);
111
+ margin: 0;
112
+ color: var(--astl-ink-muted);
113
+ font-size: var(--astl-size-small);
114
+ }
115
+ .counts {
116
+ font-family: var(--astl-font-mono);
117
+ }
118
+ .counts span + span::before {
119
+ content: '\\00b7' / '';
120
+ margin-inline: var(--astl-space-1);
121
+ }
122
+ .ready {
123
+ color: var(--astl-success);
124
+ font-weight: 600;
125
+ }
126
+ .error {
127
+ color: var(--astl-danger);
128
+ }
129
+ `,
130
+ // Wide: one row, between the toolbar and the preview: the host's `start` column, the surface, the side column (3:2 with
131
+ // the surface, at least 18rem), the host's `end` column. A row, not a grid, so a column that is not there takes no
132
+ // track and no gap. The side column and the host's columns stay in view while the content scrolls, within the work
133
+ // row only (never over the preview), each scrolling on its own when taller than the window.
134
+ css `
135
+ @container (min-inline-size: 48rem) {
136
+ .work {
137
+ display: flex;
138
+ }
139
+ .surface {
140
+ flex: 3 1 0;
141
+ }
142
+ .side {
143
+ flex: 2 1 0;
144
+ min-inline-size: 18rem;
145
+ }
146
+ .start,
147
+ .end {
148
+ flex: none;
149
+ }
150
+ .side,
151
+ .start,
152
+ .end {
153
+ position: sticky;
154
+ inset-block-start: var(--astl-editor-sticky-top, var(--astl-space-4));
155
+ max-block-size: calc(100dvh - var(--astl-editor-sticky-top, var(--astl-space-4)) - var(--astl-space-4));
156
+ overflow-y: auto;
157
+ padding: var(--astl-focus-width);
158
+ margin: calc(-1 * var(--astl-focus-width));
159
+ }
160
+ }
161
+ `,
162
+ ];
163
+ /** The tag of a preview element: the one place that reads the shape of `elements`. */
164
+ const elementTag = (element) => 'load' in element ? element.tag : element.manifest.tag;
165
+ let secret = null;
166
+ /**
167
+ * The preview compiles in the browser, so its secret only keeps preview ids apart from published ones: a random one
168
+ * per page, never a known value.
169
+ */
170
+ function previewSecret() {
171
+ secret ??= Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join('');
172
+ return secret;
173
+ }
174
+ function engineOf(lists, components) {
175
+ return createEngine({
176
+ components,
177
+ secret: previewSecret(),
178
+ slotKinds: [...lists.slotKinds.values()],
179
+ profile: lists.profile,
180
+ catalogs: lists.catalogs,
181
+ styleTemplates: [...lists.styleTemplates.values()],
182
+ ...(lists.urlPolicy === null ? {} : { urlPolicy: lists.urlPolicy }),
183
+ ...(lists.groundColors === null ? {} : { groundColors: lists.groundColors }),
184
+ });
185
+ }
186
+ const EMPTY = {
187
+ components: new Map(),
188
+ editors: new Map(),
189
+ elements: new Map(),
190
+ styleTemplates: new Map(),
191
+ slotKinds: new Map(),
192
+ catalogs: [],
193
+ profile: {},
194
+ urlPolicy: null,
195
+ groundColors: null,
196
+ uploadAsset: null,
197
+ pickPicture: null,
198
+ fonts: DEFAULT_FONTS,
199
+ styles: DEFAULT_STYLES,
200
+ featured: [],
201
+ views: [],
202
+ menuMessages: null,
203
+ };
204
+ let registered = null;
205
+ /** Without `defineEditor` (the class defined by hand): nothing registered. */
206
+ function current() {
207
+ registered ??= { ...EMPTY, engine: engineOf(EMPTY, []), version: 0 };
208
+ return registered;
209
+ }
210
+ /** Connected editors: a registration re-renders them. */
211
+ const connected = new Set();
212
+ /** `items` added by key: the same object again is skipped, another object under a taken key throws. */
213
+ function added(into, items, key, what) {
214
+ const out = new Map(into);
215
+ for (const item of items ?? []) {
216
+ const name = key(item);
217
+ const taken = out.get(name);
218
+ if (taken !== undefined && taken !== item)
219
+ throw new Error(`${what} ${name} is already registered`);
220
+ out.set(name, item);
221
+ }
222
+ return out;
223
+ }
224
+ /** Adds to what every `<astl-editor>` offers (`defineEditor`). Checks everything before anything changes. */
225
+ export function register(options) {
226
+ const before = registered ?? { ...EMPTY, version: 0 };
227
+ const tag = (item) => item.manifest.tag;
228
+ const lists = {
229
+ components: added(before.components, options.components, tag, 'Component'),
230
+ editors: added(before.editors, options.editors, tag, 'Editor descriptor'),
231
+ elements: added(before.elements, options.elements, elementTag, 'Preview element'),
232
+ styleTemplates: added(before.styleTemplates, options.styleTemplates, (t) => t.name, 'Style template'),
233
+ slotKinds: added(before.slotKinds, options.slotKinds, (k) => k.kind, 'Slot kind'),
234
+ catalogs: [...new Set([...before.catalogs, ...(options.catalogs ?? [])])],
235
+ profile: { ...before.profile, ...options.profile },
236
+ urlPolicy: options.urlPolicy ?? before.urlPolicy,
237
+ groundColors: options.groundColors ?? before.groundColors,
238
+ uploadAsset: options.uploadAsset ?? before.uploadAsset,
239
+ pickPicture: options.pickPicture ?? before.pickPicture,
240
+ fonts: options.fonts ?? before.fonts,
241
+ styles: options.styles ?? before.styles,
242
+ featured: options.featured ?? before.featured,
243
+ views: options.views ?? before.views,
244
+ menuMessages: options.menuMessages ?? before.menuMessages,
245
+ };
246
+ // Nothing new (the same objects again): connected editors keep their surface, cursor and undo history.
247
+ const maps = ['components', 'editors', 'elements', 'styleTemplates', 'slotKinds'];
248
+ const profile = (p) => JSON.stringify(Object.entries(p).sort());
249
+ if (registered !== null &&
250
+ maps.every((list) => lists[list].size === before[list].size) &&
251
+ lists.catalogs.length === before.catalogs.length &&
252
+ lists.urlPolicy === before.urlPolicy &&
253
+ JSON.stringify(lists.groundColors) === JSON.stringify(before.groundColors) &&
254
+ lists.uploadAsset === before.uploadAsset &&
255
+ lists.pickPicture === before.pickPicture &&
256
+ lists.menuMessages === before.menuMessages &&
257
+ JSON.stringify(lists.fonts) === JSON.stringify(before.fonts) &&
258
+ JSON.stringify(lists.styles) === JSON.stringify(before.styles) &&
259
+ lists.featured.join(' ') === before.featured.join(' ') &&
260
+ JSON.stringify(lists.views) === JSON.stringify(before.views) &&
261
+ profile(lists.profile) === profile(before.profile)) {
262
+ return;
263
+ }
264
+ // The engine and the kit check definitions and descriptors now, not when an editor first renders.
265
+ const engine = engineOf(lists, [...lists.components.values()]);
266
+ createAuthoring({
267
+ engine,
268
+ descriptors: [...lists.editors.values()],
269
+ locale: 'en',
270
+ fonts: lists.fonts,
271
+ styles: lists.styles,
272
+ });
273
+ registered = { ...lists, engine, version: before.version + 1 };
274
+ for (const editor of connected)
275
+ editor.requestUpdate();
276
+ }
277
+ /** The authoring of one editor: every registered type, or those `allowed` names. */
278
+ function authoringFor(r, locale, allowed) {
279
+ const keep = (items) => [...items.entries()].filter(([tag]) => allowed === null || allowed.includes(tag)).map(([, item]) => item);
280
+ return createAuthoring({
281
+ engine: allowed === null ? r.engine : engineOf(r, keep(r.components)),
282
+ descriptors: keep(r.editors),
283
+ elements: keep(r.elements),
284
+ locale,
285
+ catalogs: r.catalogs,
286
+ styleTemplates: [...r.styleTemplates.values()],
287
+ fonts: r.fonts,
288
+ styles: r.styles,
289
+ ...(r.urlPolicy === null ? {} : { urlPolicy: r.urlPolicy }),
290
+ ...(r.uploadAsset === null ? {} : { uploadAsset: r.uploadAsset }),
291
+ ...(r.pickPicture === null ? {} : { pickPicture: r.pickPicture }),
292
+ ...(r.menuMessages === null ? {} : { menuMessages: r.menuMessages }),
293
+ });
294
+ }
295
+ const THEMES = ['light', 'dark', 'hc', 'auto'];
296
+ const CHANGE = 'astl-editor-change';
297
+ const READY = 'astl-editor-ready';
298
+ const VIEW = 'astl-editor-view';
299
+ /** The views of every editor: the surface, and the source as HTML. */
300
+ const OWN_VIEWS = ['visual', 'source'];
301
+ /** The status line counts this long after the last change, as the issues list does. */
302
+ const COUNT_DELAY_MS = 300;
303
+ /** The side panels, in the order `<astl-editor>` shows them by default. */
304
+ const PANELS = ['issues', 'inspector'];
305
+ /** A space-separated list attribute as a list (null when absent). */
306
+ const listAttribute = {
307
+ fromAttribute: (value) => value === null ? null : value.split(/\s+/).filter((tag) => tag !== ''),
308
+ };
309
+ /** The `views` attribute: a JSON list of `{ name, label }` (null when absent or not JSON). */
310
+ const viewsAttribute = {
311
+ fromAttribute: (value) => {
312
+ try {
313
+ return value === null ? null : JSON.parse(value);
314
+ }
315
+ catch {
316
+ return null;
317
+ }
318
+ },
319
+ };
320
+ /** The icon parts of the toolbar, forwarded so hosts can draw their own icons (`::part(icon-text-t)`). */
321
+ const KIT_ICONS = [
322
+ 'chevron',
323
+ 'bold',
324
+ 'italic',
325
+ 'underline',
326
+ 'link',
327
+ 'bulleted',
328
+ 'numbered',
329
+ 'undo',
330
+ 'redo',
331
+ 'wrap',
332
+ 'text',
333
+ 'image',
334
+ 'files',
335
+ 'add',
336
+ 'templates',
337
+ ];
338
+ /** The inspector's parts, forwarded so hosts can restyle its header, banners and fields (`::part(inspector-issue)`). */
339
+ const INSPECTOR_PARTS = 'header: inspector-header, id: inspector-id, actions: inspector-actions, issue: inspector-issue, field: inspector-field, label: inspector-label, style: inspector-style';
340
+ /** The built-in surface module, once imported. */
341
+ let surfaces = null;
342
+ /** The source view's module, once imported (when the view first opens). */
343
+ let sourceViews = null;
344
+ export class AstlEditor extends LitElement {
345
+ static properties = {
346
+ locale: {},
347
+ components: { converter: listAttribute },
348
+ featured: { converter: listAttribute },
349
+ panels: { converter: listAttribute },
350
+ view: {},
351
+ views: { converter: viewsAttribute },
352
+ theme: {},
353
+ previewPolicy: { attribute: false },
354
+ adapter: { attribute: false },
355
+ };
356
+ static styles = editorStyles;
357
+ /** A value set while there is no adapter to take it. */
358
+ #pending = null;
359
+ /** Whether this element uses the built-in surface: decided when it first connects. */
360
+ #builtIn = null;
361
+ #surface = null;
362
+ #opening = false;
363
+ #failed = false;
364
+ /**
365
+ * The status line's message until the next edit: why a pasted or dropped picture was not inserted (no upload), or
366
+ * the page an edit added or joined.
367
+ */
368
+ #notice = null;
369
+ /** The page or block the surface's edit changed, waiting for that edit's change event, which shows it. */
370
+ #pageNotice = null;
371
+ /** Counts notices: the same message again is a new one for screen readers. */
372
+ #notices = 0;
373
+ /** The adapter the last ready event was for. */
374
+ #readyFor = null;
375
+ #resolveReady = () => { };
376
+ #ready = new Promise((resolve) => {
377
+ this.#resolveReady = resolve;
378
+ });
379
+ /** What the surface asks about pictures: the picture dialog of this element. */
380
+ #pictures = {
381
+ ask: (request) => this.renderRoot.querySelector('astl-picture-dialog')?.ask(request) ??
382
+ Promise.resolve(null),
383
+ refuse: () => {
384
+ this.#notice = { key: 'picture.pasteRefused' };
385
+ this.requestUpdate();
386
+ },
387
+ style: (kind) => {
388
+ void this.renderRoot.querySelector('astl-toolbar')?.openStyle(kind);
389
+ },
390
+ };
391
+ /** What the surface tells of pages and blocks: a page added, joined or deleted, a block moved or deleted. */
392
+ #pages = (change) => {
393
+ this.#pageNotice = change;
394
+ };
395
+ /** Whether the host's `start` and `end` slots have elements: a column exists only while its slot does. */
396
+ #slotted = { start: false, end: false };
397
+ #slotChange = (event) => {
398
+ const slot = event.target;
399
+ const name = slot.name === 'end' ? 'end' : 'start';
400
+ const has = slot.assignedElements().length > 0;
401
+ if (this.#slotted[name] === has)
402
+ return;
403
+ this.#slotted[name] = has;
404
+ this.requestUpdate();
405
+ };
406
+ /**
407
+ * The source view: the value laid out for reading when it opened (null until it shows), the author's text once they
408
+ * type (null before), and the errors that kept it there.
409
+ */
410
+ #shown = null;
411
+ #draft = null;
412
+ #errors = [];
413
+ /** What the status line counts, a moment after each change. */
414
+ #outline = null;
415
+ #counting;
416
+ #authoring = null;
417
+ #subscription = null;
418
+ constructor() {
419
+ super();
420
+ this.locale = null;
421
+ this.components = null;
422
+ this.featured = null;
423
+ this.panels = null;
424
+ this.view = 'visual';
425
+ this.views = null;
426
+ this.theme = 'auto';
427
+ this.previewPolicy = null;
428
+ this.adapter = null;
429
+ // A value set before the element was defined is an own property that hides the accessor.
430
+ if (Object.hasOwn(this, 'value')) {
431
+ const value = this.value;
432
+ delete this.value;
433
+ if (typeof value === 'string')
434
+ this.value = value;
435
+ }
436
+ }
437
+ /** The source HTML (`<astl-doc>`): the adapter's, or a value waiting for it, or an empty document. */
438
+ get value() {
439
+ return (this.adapter?.getSource() ?? this.#pending ?? `<astl-doc lang="${this.authoring.locale}"></astl-doc>`);
440
+ }
441
+ set value(source) {
442
+ if (this.adapter === null)
443
+ this.#pending = source;
444
+ else
445
+ this.adapter.setSource(source);
446
+ }
447
+ /**
448
+ * Resolves when the editor is first ready: its surface loaded (or the host's `adapter` set) and the value in place,
449
+ * so `adapter`, `authoring` and `value` are usable. Each time an editor becomes ready (again after a swap or a
450
+ * reconnect, with a new `adapter`), `astl-editor-ready` fires (bubbles, composed).
451
+ */
452
+ get ready() {
453
+ return this.#ready;
454
+ }
455
+ /**
456
+ * Compiles the current value and plays it in the preview, as the preview's own button does. Resolves when it plays,
457
+ * or shows why it cannot.
458
+ */
459
+ async preview() {
460
+ await this.updateComplete;
461
+ await this.renderRoot.querySelector('astl-preview')?.refresh();
462
+ }
463
+ /** The kit's logic, built from the registrations, the UI locale and `components`. */
464
+ get authoring() {
465
+ const r = current();
466
+ const locale = this.#uiLocale(r);
467
+ // The property also takes the attribute's form, a space-separated string.
468
+ const given = this.components;
469
+ const allowed = typeof given === 'string' ? given.split(/\s+/).filter((tag) => tag !== '') : given;
470
+ const key = `${r.version}\n${locale}\n${allowed === null ? '*' : allowed.join(' ')}`;
471
+ if (this.#authoring?.key !== key)
472
+ this.#authoring = { key, authoring: authoringFor(r, locale, allowed) };
473
+ return this.#authoring.authoring;
474
+ }
475
+ connectedCallback() {
476
+ super.connectedCallback();
477
+ connected.add(this);
478
+ // Back in the document: the built-in surface again. The first decision waits for the first update, when Lit has
479
+ // applied the properties set before the element was defined (an `adapter`).
480
+ if (this.#builtIn === true)
481
+ void this.#open();
482
+ this.#subscribe();
483
+ }
484
+ disconnectedCallback() {
485
+ super.disconnectedCallback();
486
+ connected.delete(this);
487
+ clearTimeout(this.#counting);
488
+ this.#readyFor = null;
489
+ this.#subscribe();
490
+ // ProseMirror listens on the document: a removed editor is destroyed, its source kept for a reconnect.
491
+ const surface = this.#surface;
492
+ if (surface === null)
493
+ return;
494
+ this.#pending = surface.adapter.getSource();
495
+ surface.destroy();
496
+ this.#surface = null;
497
+ this.adapter = null;
498
+ }
499
+ /** The host's views: the element's, else the registered ones. */
500
+ #hostViews() {
501
+ const views = this.views ?? current().views;
502
+ return Array.isArray(views) ? views : [];
503
+ }
504
+ /** The view on show: `view` when it names one, else `visual`. */
505
+ #view() {
506
+ const names = [...OWN_VIEWS, ...this.#hostViews().map((v) => v.name)];
507
+ return names.includes(this.view) ? this.view : 'visual';
508
+ }
509
+ /**
510
+ * Applies the source view's text, unless it has errors: then they show and the editor stays there. Only text that
511
+ * says something else than what was shown is applied (laid out the same, it is the same document): looking changes
512
+ * nothing.
513
+ */
514
+ #leaveSource() {
515
+ const text = this.#draft ?? this.#shown ?? this.value;
516
+ const errors = this.authoring.validate(text).issues.filter((issue) => issue.severity === 'error');
517
+ this.#errors = errors;
518
+ if (errors.length > 0) {
519
+ this.#notice = { key: 'view.sourceErrors', params: { n: errors.length } };
520
+ this.#notices++;
521
+ return false;
522
+ }
523
+ if (this.#draft !== null && sourceViews?.formatHtml(this.#draft) !== this.#shown)
524
+ this.value = this.#draft;
525
+ this.#draft = null;
526
+ return true;
527
+ }
528
+ /** Counts the document for the status line, after `delay` ms. */
529
+ #count(delay) {
530
+ clearTimeout(this.#counting);
531
+ this.#counting = setTimeout(() => {
532
+ const adapter = this.adapter;
533
+ this.#outline = adapter === null ? null : this.authoring.outline(adapter.getSource());
534
+ this.requestUpdate();
535
+ }, delay);
536
+ }
537
+ willUpdate(changed) {
538
+ if (changed.has('theme'))
539
+ this.dataset.theme = this.#theme();
540
+ if (changed.has('view')) {
541
+ const before = changed.get('view');
542
+ if (before === 'source' && this.view !== 'source' && !this.#leaveSource())
543
+ this.view = 'source';
544
+ else if (this.view === 'source' && before !== 'source') {
545
+ this.#shown = this.#draft = null;
546
+ this.#errors = [];
547
+ if (sourceViews === null) {
548
+ import('./source-view.js').then((module) => {
549
+ sourceViews = module;
550
+ this.requestUpdate();
551
+ }, (error) => console.error(error));
552
+ }
553
+ }
554
+ }
555
+ const surface = this.#surface;
556
+ if (surface !== null && this.adapter !== surface.adapter) {
557
+ // Another editor plugged in, or none (null): the built-in one goes, keeping its document for a comeback.
558
+ if (this.adapter === null)
559
+ this.#pending = surface.adapter.getSource();
560
+ surface.destroy();
561
+ this.#surface = null;
562
+ }
563
+ if (this.adapter !== null && this.#surface === null) {
564
+ this.#builtIn = false;
565
+ if (this.#pending !== null)
566
+ this.adapter.setSource(this.#pending);
567
+ this.#pending = null;
568
+ }
569
+ else if (this.adapter === null && this.#surface === null) {
570
+ // The first update, or the host took its editor away: the built-in surface, unless one is in the slot.
571
+ if (this.isConnected && (this.#builtIn === null || changed.has('adapter')))
572
+ this.#decide();
573
+ }
574
+ else if (this.#surface !== null && surfaces !== null && this.#surface.authoring !== this.authoring) {
575
+ // Other labels or other types: the same document in a new editor.
576
+ const source = this.#surface.adapter.getSource();
577
+ this.#surface.destroy();
578
+ this.#surface = surfaces.createSurface(this, this.authoring, current().engine.manifests, source, this.#pictures, this.#pages);
579
+ this.adapter = this.#surface.adapter;
580
+ }
581
+ this.#subscribe();
582
+ }
583
+ updated(changed) {
584
+ // The preview reads its theme when it renders.
585
+ if (changed.has('theme'))
586
+ this.renderRoot.querySelector('astl-preview')?.requestUpdate();
587
+ const adapter = this.adapter;
588
+ if (adapter !== null && adapter !== this.#readyFor && this.isConnected) {
589
+ this.#readyFor = adapter;
590
+ this.#count(0);
591
+ this.#resolveReady();
592
+ this.dispatchEvent(new Event(READY, { bubbles: true, composed: true }));
593
+ }
594
+ const before = changed.get('view');
595
+ if (changed.has('view') && before !== undefined && before !== this.view) {
596
+ this.dispatchEvent(new CustomEvent(VIEW, { detail: { view: this.view }, bubbles: true, composed: true }));
597
+ }
598
+ }
599
+ #decide() {
600
+ // An element the HTML parser is still filling may not have its slot="surface" child yet.
601
+ if (document.readyState === 'loading') {
602
+ document.addEventListener('DOMContentLoaded', () => this.requestUpdate('adapter'), { once: true });
603
+ return;
604
+ }
605
+ this.#builtIn = this.querySelector(':scope > [slot="surface"]') === null;
606
+ if (this.#builtIn)
607
+ void this.#open();
608
+ }
609
+ async #open() {
610
+ if (this.#opening || this.#surface !== null)
611
+ return;
612
+ this.#opening = true;
613
+ this.#failed = false;
614
+ try {
615
+ surfaces ??= await import('./surface.js');
616
+ if (!this.isConnected || !this.#builtIn || this.adapter !== null || this.#surface !== null)
617
+ return;
618
+ this.#surface = surfaces.createSurface(this, this.authoring, current().engine.manifests, this.value, this.#pictures, this.#pages);
619
+ this.#pending = null;
620
+ this.adapter = this.#surface.adapter;
621
+ }
622
+ catch (error) {
623
+ // A failed chunk load is not cached by every browser: the next connect tries again.
624
+ this.#failed = true;
625
+ console.error(error);
626
+ }
627
+ finally {
628
+ this.#opening = false;
629
+ this.requestUpdate();
630
+ }
631
+ }
632
+ #subscribe() {
633
+ const adapter = this.isConnected ? this.adapter : null;
634
+ if ((this.#subscription?.adapter ?? null) === adapter)
635
+ return;
636
+ this.#subscription?.off();
637
+ this.#subscription =
638
+ adapter === null
639
+ ? null
640
+ : {
641
+ adapter,
642
+ off: adapter.onChange(() => {
643
+ const notice = this.#pageNotice;
644
+ this.#pageNotice = null;
645
+ if (this.#notice !== null || notice !== null) {
646
+ this.#notice = notice;
647
+ if (notice !== null)
648
+ this.#notices++;
649
+ this.requestUpdate();
650
+ }
651
+ this.#count(COUNT_DELAY_MS);
652
+ this.dispatchEvent(new Event(CHANGE, { bubbles: true, composed: true }));
653
+ }),
654
+ };
655
+ }
656
+ #uiLocale(r) {
657
+ const requested = this.locale
658
+ ? [this.locale]
659
+ : this.lang
660
+ ? [this.lang]
661
+ : [...(navigator.languages ?? []), navigator.language].filter((l) => !!l);
662
+ const available = [...editorMessages, ...r.catalogs]
663
+ .filter((c) => c.namespace === EDITOR_NAMESPACE)
664
+ .map((c) => c.locale);
665
+ return negotiateLocale(requested, [...new Set(available)], 'en');
666
+ }
667
+ #theme() {
668
+ const theme = this.theme;
669
+ return theme !== null && THEMES.includes(theme) ? theme : 'auto';
670
+ }
671
+ render() {
672
+ const { authoring, adapter } = this;
673
+ const theme = this.#theme();
674
+ const waiting = this.#failed
675
+ ? { key: 'surface.failed' }
676
+ : this.#builtIn && adapter === null
677
+ ? { key: 'surface.loading' }
678
+ : this.#notice;
679
+ const lang = authoring.locale;
680
+ // Given as a string (the attribute's form) or a list.
681
+ const list = (value) => typeof value === 'string' ? value.split(/\s+/).filter((name) => name !== '') : value;
682
+ const featured = list(this.featured) ?? current().featured;
683
+ const panels = (list(this.panels) ?? PANELS).filter((name) => PANELS.includes(name));
684
+ const icons = new Set([
685
+ ...KIT_ICONS,
686
+ ...authoring.descriptors.flatMap((d) => [d.icon, ...(d.templates ?? []).map((t) => t.icon ?? d.icon)]),
687
+ ]);
688
+ const exported = [
689
+ 'toolbar: toolbar-bar',
690
+ 'button: toolbar-button',
691
+ 'icon-button: toolbar-icon-button',
692
+ 'views: toolbar-views',
693
+ 'view: toolbar-view',
694
+ 'separator: toolbar-separator',
695
+ 'icon: toolbar-icon',
696
+ 'insert',
697
+ 'menu: insert-menu',
698
+ 'style-menu',
699
+ 'style-colors',
700
+ 'style-panel',
701
+ ]
702
+ .concat([...icons].map((name) => `icon-${name}`))
703
+ .join(', ');
704
+ const panel = (name) => name === 'issues'
705
+ ? html `<astl-issues part="issues" data-theme=${theme} .authoring=${authoring} .adapter=${adapter}></astl-issues>`
706
+ : html `<astl-inspector part="inspector" exportparts=${INSPECTOR_PARTS} data-theme=${theme} .authoring=${authoring} .adapter=${adapter}></astl-inspector>`;
707
+ const t = (key, params) => authoring.t(EDITOR_NAMESPACE, key, params);
708
+ const view = this.#view();
709
+ const views = [
710
+ ...OWN_VIEWS.map((name) => ({ name, label: t(`view.${name}`) })),
711
+ ...this.#hostViews(),
712
+ ];
713
+ // The toolbar spans the editor, as a word processor's: above the text and the side column.
714
+ // Another view takes the surface's place, without the side column; the notice line stays, the one live region.
715
+ const away = view !== 'visual';
716
+ return html `<div class=${panels.length === 0 || away ? 'layout solo' : 'layout'}>
717
+ <astl-toolbar part="toolbar" exportparts=${exported} data-theme=${theme} .authoring=${authoring}
718
+ .adapter=${adapter} .featured=${featured} .views=${views} .view=${view}
719
+ @astl-toolbar-view=${(event) => {
720
+ this.view = event.detail.view;
721
+ }}></astl-toolbar>
722
+ ${this.#statusLine()}
723
+ <div class="work" part="work">
724
+ <div class="start" part="start" ?hidden=${away || !this.#slotted.start}>
725
+ <slot name="start" @slotchange=${this.#slotChange}></slot>
726
+ </div>
727
+ <div class="surface" part="surface">
728
+ ${away ? nothing : html `<slot name="surface"></slot>`}
729
+ ${view === 'source' ? this.#source() : away ? html `<slot name="view-${view}"></slot>` : nothing}
730
+ <p class=${waiting === null ? 'status idle' : 'status'} role="status" lang=${lang} dir=${directionOf(lang)}
731
+ >${keyed(this.#notices, waiting === null ? '' : authoring.t(EDITOR_NAMESPACE, waiting.key, waiting.params))}</p>
732
+ <astl-picture-dialog data-theme=${theme} .authoring=${authoring}></astl-picture-dialog>
733
+ </div>
734
+ ${panels.length === 0 ? nothing : html `<div class="side" part="side" ?hidden=${away}>${panels.map(panel)}</div>`}
735
+ <div class="end" part="end" ?hidden=${away || !this.#slotted.end}>
736
+ <slot name="end" @slotchange=${this.#slotChange}></slot>
737
+ </div>
738
+ </div>
739
+ <astl-preview part="preview" data-theme=${theme} .authoring=${authoring} .adapter=${adapter}
740
+ .policy=${this.previewPolicy ?? PRACTICE_POLICY}></astl-preview>
741
+ </div>`;
742
+ }
743
+ /**
744
+ * The status line (`part="status-line"`): how many elements and points the document has, then "Ready to share" or
745
+ * its errors and warnings. Text to read, not a live region: the notice line stays the editor's one.
746
+ */
747
+ #statusLine() {
748
+ const outline = this.#outline;
749
+ if (outline === null)
750
+ return nothing;
751
+ const { authoring } = this;
752
+ const t = (key, params) => authoring.t(EDITOR_NAMESPACE, key, params);
753
+ const elements = outline.pages.reduce((n, page) => n + page.components.length, 0);
754
+ const ready = outline.errors === 0;
755
+ const lang = authoring.locale;
756
+ return html `<p class="status-line" part="status-line" lang=${lang} dir=${directionOf(lang)}>
757
+ <span class="counts"><span>${t('status.elements', { n: elements })}</span>${outline.points === null
758
+ ? nothing
759
+ : html `<span>${t('surface.points', { points: outline.points })}</span>`}</span>
760
+ <span class=${ready ? 'ready' : 'counts error'}>${ready
761
+ ? t('status.ready')
762
+ : html `<span>${t('status.errors', { n: outline.errors })}</span><span>${t('status.warnings', { n: outline.warnings })}</span>`}</span>
763
+ </p>`;
764
+ }
765
+ /**
766
+ * The source view (`source-view.ts`, nothing until its module has loaded), with the value laid out for reading once
767
+ * per opening.
768
+ */
769
+ #source() {
770
+ const views = sourceViews;
771
+ if (views === null)
772
+ return nothing;
773
+ this.#shown ??= views.formatHtml(this.value);
774
+ return views.renderSource(this.renderRoot, this.authoring, this.#draft ?? this.#shown, this.#errors, (text) => {
775
+ this.#draft = text;
776
+ });
777
+ }
778
+ }
779
+ //# sourceMappingURL=element.js.map